Search code examples
python-3.xpytestpython-unittestcoverage.py

How to display the right coverage for unit-tests in python?


I am having trouble displaying the correct coverage info for unittest. I created a simple python file as such: simple.py that contains the following contents:

def multiply(x, y):
    return x * y

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def divide(x, y):
    return x / y

and a unittest as such called test_simple.py that i stored under the tests folder:

import unittest

import simple as si


class TestSimple(unittest.TestCase):
    def test_multiply(self):
        self.assertEqual(si.multiply(3, 4), 12)

Now, im. using pytest and coverage.py to run my coverage report. I ran the following statements:

pytest test_simple.py --cov=simple

and see the following:

coverage report -m

Name        Stmts   Miss  Cover   Missing
---------------------------------------------------------------------------------------------------------------
simple.py       8      3    62%   5, 8, 11
---------------------------------------------------------------------------------------------------------------
TOTAL           8      3    62%

Why would this show 62%? shouldn't it 25%? it seems its adding 100% from my test file and 25% from the file i want to see how much percent is covered, and taking the average of the two...which gives me 62.5%. is there anyway i can show the correct info which is 25%? thanks


Solution

  • Take a look at the HTML output (pytest --cov=simple --cov-report=html, then open htmlcov/index.html), and you may find the answer more obvious:

    enter image description here

    The metrics are reporting coverage based on the number of statements in your code. Not "number of functions". There are 8 statements in your code:

    • 4 def statements
    • 4 return statements

    Your tests execute all four def statements, because that's what happens when you import a file, and then one return statement (for the multiply function).

    >>> 5/8
    0.625