18

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.

praveen
  • 3,193
  • 2
  • 26
  • 30

2 Answers2

22

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.

jcollado
  • 39,419
  • 8
  • 102
  • 133
5

Following jcollado's answer:

I have this problem with Django nose which only covers lines used by tests.

For fix it I launch firstly manage.py with coverage and after I launch tests. .coverage file will contain both's reports.

My first command is a custom which prints my project settings. Example:

coverage run ./manage.py settings && ./manage.py test myapp
Zulu
  • 8,765
  • 9
  • 49
  • 56