使用unittest
和Coverage.py,
def add_one(num: int):
num = num + 1
return num
from unittest import TestCase
from add_one import add_one
class TestAddOne(TestCase):
def test_add_one(self):
self.assertEqual(add_one(0), 1)
self.assertNotEqual(add_one(0), 2)
这里是报道:
如何测试整个文件?
答案 0 :(得分:1)
假设您的测试文件名为test_one.py
,请在同一目录中运行以下命令:
coverage run -m unittest test_one.py && coverage report
结果应类似于以下内容:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Name Stmts Miss Cover
---------------------------------
add_one.py 3 0 100%
test_one.py 6 0 100%
---------------------------------
TOTAL 9 0 100%
答案 1 :(得分:0)
您永远不会调用test_add_one
方法。
请注意如何执行函数定义,而不要执行主体。要运行测试,请添加__main__
和TestSuite
/ TextTestRunner
(https://docs.python.org/3/library/unittest.html)
from unittest import TestCase, TestSuite, TextTestRunner
from add_one import add_one
class TestAddOne(TestCase):
def test_add_one(self):
self.assertEqual(add_one(0), 1)
self.assertNotEqual(add_one(0), 2)
if __name__ == "__main__":
suite = TestSuite()
suite.addTest(TestAddOne("test_add_one"))
TextTestRunner().run(suite)
结果
coverage run <file.py>
coverage html
# OR
coverage report -m