编程语言
首页 > 编程语言> > python – Flask测试 – 为什么coverage不包括import语句和装饰器?

python – Flask测试 – 为什么coverage不包括import语句和装饰器?

作者:互联网

我的测试清楚地执行每个函数,也没有未使用的导入.然而,根据覆盖率报告,62%的代码从未在以下文件中执行:

有人可以指出我可能做错了什么吗?

以下是我初始化测试套件和覆盖范围的方法:

    cov = coverage(branch=True, omit=['website/*', 'run_test_suite.py'])
    cov.start()

    try:
        unittest.main(argv=[sys.argv[0]])
    except:
        pass

    cov.stop()
    cov.save()

    print "\n\nCoverage Report:\n"
    cov.report()

    print "HTML version: " + os.path.join(BASEDIR, "tmp/coverage/index.html")
    cov.html_report(directory='tmp/coverage')
    cov.erase()

解决方法:

这是coverage.py FAQ中的第三个问题:

Q: Why do the bodies of functions (or classes) show as executed, but
the def lines do not?

This happens because coverage is started after the functions are
defined. The definition lines are executed without coverage
measurement, then coverage is started, then the function is called.
This means the body is measured, but the definition of the function
itself is not.

To fix this, start coverage earlier. If you use the command line to
run your program with coverage, then your entire program will be
monitored. If you are using the API, you need to call coverage.start()
before importing the modules that define your functions.

最简单的方法是在覆盖范围内运行测试:

$coverage run -m unittest discover

您的自定义测试脚本除了覆盖命令行之外没有做太多工作,使用命令行会更简单.

标签:python,testing,flask,coverage-py
来源: https://codeday.me/bug/20191005/1855088.html