[英]How to run unittest tests using coverage API
I am trying to generate a coverage report using the coverage
-API ( https://coverage.readthedocs.io/en/6.3.2/api.html#api ).我正在尝试使用coverage
-API ( https://coverage.readthedocs.io/en/6.3.2/api.html#api ) 生成覆盖率报告。
The simple use-case described on the linked page tells me to wrap my executed code inside the snippet they provide.链接页面上描述的简单用例告诉我将执行的代码包装在他们提供的代码片段中。 I am using unittest.main()
to execute tests.我正在使用unittest.main()
来执行测试。 The below code runs without an error but neither is any report information created nor is print("Done.")
executed.下面的代码运行没有错误,但既没有创建任何报告信息,也没有执行print("Done.")
。
I guess unittest.main()
calls a sys.exit()
somewhere along the way?我猜unittest.main()
会在某个地方调用sys.exit()
吗? How does one use the API to execute all unittest-tests?如何使用 API 执行所有单元测试?
import coverage
import unittest
def func(input):
return input
class testInput(unittest.TestCase):
def test_func(self):
self.assertEqual(func(1), 1)
if __name__ == '__main__':
cov = coverage.Coverage()
cov.start()
unittest.main()
cov.stop()
cov.save()
cov.html_report()
print("Done.")
Yes, it looks like unittest.main() is calling sys.exit().是的,看起来 unittest.main() 正在调用 sys.exit()。 Are you sure you need to use the coverage API?您确定需要使用覆盖范围 API 吗? You can skip coverage and most of unittest:您可以跳过覆盖范围和大部分单元测试:
# foo.py
import unittest
def func(input):
return input
class testInput(unittest.TestCase):
def test_func(self):
self.assertEqual(func(1), 1)
Then:然后:
$ python -m coverage run -m unittest foo.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
$ python -m coverage report -m
Name Stmts Miss Cover Missing
--------------------------------------
foo.py 6 0 100%
--------------------------------------
TOTAL 6 0 100%
To get the example to work you can simply put the call to unittest.main()
in a try/except statement so the cov.stop()
will be called once the unit test has completed.要使示例正常运行,您只需将对unittest.main()
的调用放在 try/except 语句中,以便在单元测试完成后调用cov.stop()
。
# testInput.py
import coverage
import unittest
def func(input):
return input
class testInput(unittest.TestCase):
def test_func(self):
self.assertEqual(func(1), 1)
if __name__ == '__main__':
cov = coverage.Coverage()
cov.start()
try:
unittest.main()
except: # catch-all except clause
pass
cov.stop()
cov.save()
cov.html_report()
print("Done.")
This will run as desired, including printing Done.
这将按需要运行,包括打印Done.
at the end:在最后:
python3 testInput.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
Done.
The HTML coverage report will have been created in the htmlcov
directory in the current working directory. HTML 覆盖率报告将在当前工作目录的htmlcov
目录中创建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.