Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I was working on the Coverage.py module and want to make a simple test to check how it works.

The sample.py file:

def sum(num1, num2):

    return num1 + num2

def sum_only_positive(num1, num2):

    if num1 > 0 and num2 > 0:

        return num1 + num2

    else:

        return None

The test.py: 

from sample import sum, sum_only_positive

def test_sum():

    assert sum(5, 5) == 10

def test_sum_positive_ok():

    assert sum_only_positive(2, 2) == 4

def test_sum_positive_fail():

    assert sum_only_positive(-1, 2) is None

As you see, all my code is incorporated with tests, and the py.test says all of them pass. I was expecting the Coverage.py to show 100% coverage but I am not getting that much coverage. Kindly guide me.

1 Answer

0 votes
by (108k points)

Kindly be informed that the coverage will check for the .coverage file to read and create that report for you. Py.test on its own will not e able to create the report. You need py.test plugin for coverage:

pip install pytest-cov

If it is there already then you can run both at once like this:

py.test test.py --cov=sample.py

The above code will run the test module test.py and then it will record or illustrate the coverage report on sample.py.

If you need to have many test runs and you have incorporated their recorded coverage and then it will display a final report, you can run it like this:

py.test test.py --cov=sample.py --cov-report=

py.test test.py --cov=sample2.py --cov-report=

py.test test.py --cov=sample3.py --cov-report=

Then the run test module that is test.py and record (only) coverage on sample.py - don't illustrate a report. Now you can run the coverage command separately for a complete report:

coverage report -m

The command above simply displays a formatted coverage report based on the accumulated .coverage data file from previous test runs. -m means show lines missed i.e. lines not covered by tests:

Name        Stmts   Miss  Cover   Missing

-----------------------------------------

sample.py       6      0   100%  

Coverage supports more switches like --include and --omit to include/exclude files using path patterns.

Join this Python Training course now if you want to gain more knowledge in Python.

Browse Categories

...