Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

enter image description here

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()
like image 409
Marlyyy Avatar asked Apr 04 '15 17:04

Marlyyy


People also ask

What is test_ client Flask?

Flask provides a test client that simulates requests to the application and returns the response data. You should test as much of your code as possible. Code in functions only runs when the function is called, and code in branches, such as if blocks, only runs when the condition is met.

Does coverage work with Pytest?

You can use Coverage.py with both unittest and Pytest.

How does Python code coverage work?

Coverage.py is a tool for measuring code coverage of Python programs. It monitors your program, noting which parts of the code have been executed, then analyzes the source to identify code that could have been executed but was not. Coverage measurement is typically used to gauge the effectiveness of tests.


1 Answers

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.

like image 192
Ned Batchelder Avatar answered Sep 20 '22 10:09

Ned Batchelder