Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...