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

喜欢而已 提交于 2019-11-29 11:46:22

问题


My tests clearly execute each function, and there are no unused imports either. Yet, according to the coverage report, 62% of the code was never executed in the following file:

Can someone please point out what I might be doing wrong?

Here's how I initialise the test suite and the coverage:

    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()

回答1:


This is the third question in the 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.

The simplest thing to do is run you tests under coverage:

$ coverage run -m unittest discover

Your custom test script isn't doing much beyond what the coverage command line would do, it will be simpler just to use the command line.




回答2:


For excluding the imports statements, you can add the following lines to .coveragerc

[report]
exclude_lines =
    # Ignore imports
    from
    import

but when I tried to add '@' for decorators, the source code within the scope of decorators was excluded. The coverage rate was wrong. There may be some other ways to exclude decorators.



来源:https://stackoverflow.com/questions/29449285/flask-testing-why-does-coverage-exclude-import-statements-and-decorators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!