2

I'm trying to follow Chapter 3 of David Sale's Testing Python, but using nose2 instead of nosetests. So far I've written a calculate.py:

class Calculate(object):
    def add(self, x, y):
        if type(x) == int and type(y) == int:
            return x + y
        else:
            raise TypeError("Invalid type: {} and {}".format(type(x), type(y)))

if __name__ == '__main__':      # pragma: no cover
    calc = Calculate()
    result = calc.add(2, 2)
    print(result)

and, in a subdirectory test, a test_calculator.py:

import unittest
from calculate import Calculate

class TestCalculate(unittest.TestCase):
    def setUp(self):
        self.calc = Calculate()

    def test_add_method_returns_correct_result(self):
        self.assertEqual(4, self.calc.add(2,2))

    def test_add_method_raises_typeerror_if_not_ints(self):
        self.assertRaises(TypeError, self.calc.add, "Hello", "World")


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

If I run nose2 --with-coverage in the main directory, I get

..
----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK
----------- coverage: platform linux, python 3.5.2-final-0 -----------
Name                     Stmts   Miss  Cover
--------------------------------------------
calculate.py                 5      0   100%
test/test_calculate.py      11      1    91%
--------------------------------------------
TOTAL                       16      1    94%

I don't understand why a coverage is calculated for the testing program test/test_calculate.py as well as for the main program, calculate.py. Is there any way to disable this behavior?

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526

1 Answers1

0

You can use the --coverage parameter to measure coverage only for the given path. In your example, you need to run

nose2 --with-coverage --coverage calculate

This will give you the expected output:

..
----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK
----------- coverage: platform linux, python 3.5.2-final-0 -----------
Name           Stmts   Miss  Cover
----------------------------------
calculate.py       5      0   100%
s3rvac
  • 9,301
  • 9
  • 46
  • 74