Flask 测试 - 为什么覆盖范围不包括导入语句和装饰器?

Flask Testing - why does coverage exclude import statements and decorators?

我的测试清楚地执行了每个功能,也没有未使用的导入。然而,根据覆盖率报告,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

您的自定义测试脚本并没有超出 coverage 命令行的功能,使用命令行会更简单。

为了排除import语句,你可以在.coveragerc中添加以下行

[report]
exclude_lines =
    # Ignore imports
    from
    import

但是当我尝试为装饰器添加'@'时,装饰器范围内的源代码被排除在外。覆盖率是错误的。 可能还有其他一些排除装饰器的方法。