3

I am using coverage.py to test my code coverage. My tests are passing, however, when I call

coverage run -- [script].py -m [test_script].py

and generate a report it indicates that

<line hits="1" number="5"/>
<line hits="0" number="6"/>
<line hits="0" number="7"/>
<line hits="0" number="8"/>

Where line 5,6,7 and 8 are as follows:

def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

For another example:

My test code:

def test_arb():
assert tree.inc(3) == 4

the function

def inc(x):
    return x+1

and the result on the report

<line hits="1" number="48"/>
<line hits="0" number="49"/>

I've spent days researching this and can't seem to find a straightforward answer. Would anyone be able to help? It may be an obvious fix but I am a beginner at Python and testing.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
  • 1
    Can you show your full test, how you are running it, and the complete output? It seems like your functions are not being called at all. – Daniel Roseman Sep 29 '18 at 11:51
  • The full test can be found here: https://github.com/sineadmcaleer/cs3012-1/blob/master/test_tree.py I am running using the following statement: coverage run -- tree.py -m test_tree.py and the out put is : Name Stmts Miss Cover ----------------------------- tree.py 28 22 21% – Sinead McAleer Sep 29 '18 at 12:52
  • 1
    The output you receive is correct - the line you're running doesn't execute any tests at all. You should notice that because no test output is displayed. Effectively, you are only running `tree.py` which only imports your classes and functions (this is what's reflected in the coverage report). You have to invoke `pytest` in order to run the tests. Example: `coverage run -m pytest test_tree.py` should give you a much better coverage results. – hoefling Sep 29 '18 at 13:38
  • 2
    However, `pytest` has a nice coverage collection plugin which uses `coverage` under the hood, so I'd suggest you use that instead. Install with `pip install pytest-cov`, run with `pytest test_tree.py --cov=.` to collect coverage over modules in current directory. It will also immediately print the coverage report table to the terminal. Various report formats are also supported, for example `pytest test_tree.py --cov=. --cov-report=xml` will write the report to `coverage.xml` without you needing to generate it yourself etc. – hoefling Sep 29 '18 at 13:42

1 Answers1

1

Based on your coverage command, if using unittest module, make sure your [test_script].py has

if __name__ == 'main':
    unittest.main()

(or its alternative in pytest)