API: Measure a single function

Issue #531 closed
space one created an issue

It would be nice if the docs contain a single code snipped for how to measure a single function. Might this be possible?

from coverage import Coverage
def my_target_function():
   return True
cov = Coverage()
cov.measure(my_target_function)
my_target_function()
cov.stop()
cov.report()

measure should be able to handle functions/classes/modules. I'm okay to give as second parameter the source-code-file (but I guess the function internally has a reference to it anywhere). (I think the source-code file is also only needed for the HTML report?!).

Comments (4)

  1. Loic Dachary

    Could you please explain why the proposed measure() function is better than doing the following (which is what the documentation proposes):

    from coverage import Coverage
    def my_target_function():
       return True
    cov = Coverage()
    cov.start()
    my_target_function()
    cov.stop()
    cov.report()
    

    When running the above you get:

    Name        Stmts   Miss  Cover
    -------------------------------
    sample.py       8      7    12%
    
  2. space one reporter

    Because I want to use this in unit tests. I want to use this in combination with https://bitbucket.org/ned/coveragepy/issues/503/get-coverage-as-percentage. With the example you posted I would need to 1. specify a source file in some configuration file for each unit test 2. I cannot use the default plaintext output (which you posted) as this doesn't show single functions but only files 3. i would then need to either parse the HTML output OR write an own reporting class (and watch out for API changes at every new release)

  3. Loic Dachary

    @space one thanks for clarifing the relationship between these two issues. I would not know how to implement that but at least I now understand what it is about ;-)

  4. Log in to comment