0

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Hey even when I do from simple import multiply, it’s showing 4 def statements as being covered and 3 return statements as not being covered. Is there anyway I can show just the functions not being covered?
No. Importing a file executes all the top-level statements (function and class definitions and any other "bare code").
when I do from simple import multiply, you are telling me it’s importing the whole file even though I’m importing only one function?
That's correct. Python doesn't know what functions are declared in that file until after it has executed all the top-level statements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.