2016-11-07 106 views
1

我试图按照David Sale的Testing Python的第3章,但使用nose2而不是nosetests。到目前为止,我已经写了一个calculate.pyPython的nose2 -with-coverage显示测试本身的覆盖范围

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) 

,并在子目录test,一个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() 

如果我在主目录下运行nose2 --with-coverage,我得到

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

我不明白为什么要为测试程序test/test_calculate.py以及主程序计算覆盖率,calculate.py。有什么办法可以禁用这种行为吗?

回答

0

您可以使用--coverage参数来仅测量给定路径的覆盖范围。在你的榜样,你需要运行

nose2 --with-coverage --coverage calculate 

这会给你的预期输出:

.. 
---------------------------------------------------------------------- 
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% 
相关问题