Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does coverage.py measure the function and class definitions?

I am trying to achieve a 100% coverage for a basic python module. I use Ned Batchelder's coverage.py module to test it.

1 class account(object):
2   def __init__(self, initial_balance=0):
3     self.balance = initial_balance
4   def add_one(self):
5    self.balance = self.balance + 1

These are the tests.

class TestAccount(unittest.TestCase):
  def test_create_edit_account(self):
    a = account1.account()
    a.add_one()

Here is what the coverage report I get.

    COVERAGE REPORT =
    Name                    Stmts   Miss  Cover   Missing
   -----------------------------------------------------
   __init__                    1      1     0%   1
   account1                    5      3    40%   1-2, 4
   account2                    7      7     0%   1-7

As we can see, the lines 1-2 and 4 are not covered which are the defintions. The rest of the lines are executed.

like image 801
praveen Avatar asked Dec 26 '11 14:12

praveen


People also ask

What does coverage do Python?

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.

What is coverage in Django coverage?

2019-04-30. Code coverage is a simple tool for checking which lines of your application code are run by your test suite. 100% coverage is a laudable goal, as it means every line is run at least once. Coverage.py is the Python tool for measuring code coverage.


1 Answers

I think your problem is described in the 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.

like image 158
jcollado Avatar answered Sep 23 '22 09:09

jcollado