如何使用覆盖率 API 运行单元测试
我正在尝试使用 coverage
-API (https://coverage.readthedocs.io/en/6.3.2/api.html#api)。
链接页面上描述的简单用例告诉我将执行的代码包装在他们提供的代码片段中。我正在使用 unittest.main()
来执行测试。下面的代码运行时没有错误,但既没有创建任何报告信息,也没有执行 print("Done.")
。
我猜 unittest.main()
在某个地方调用了 sys.exit()
?如何使用 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.")
I am trying to generate a coverage report using the 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. The below code runs without an error but neither is any report information created nor is print("Done.")
executed.
I guess unittest.main()
calls a sys.exit()
somewhere along the way? How does one use the API to execute all unittest-tests?
Example
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.")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,看起来unittest.main()正在调用sys.exit()。您确定需要使用覆盖率 API 吗?您可以跳过覆盖范围和大部分单元测试:
然后:
Yes, it looks like unittest.main() is calling sys.exit(). Are you sure you need to use the coverage API? You can skip coverage and most of unittest:
Then:
要使示例正常工作,您可以简单地将对
unittest.main()
的调用放在 try/ except 语句中,这样一旦单元测试已完成。这将根据需要运行,包括在最后打印
Done.
:HTML 覆盖率报告将在当前工作目录的
htmlcov
目录中创建。To get the example to work you can simply put the call to
unittest.main()
in a try/except statement so thecov.stop()
will be called once the unit test has completed.This will run as desired, including printing
Done.
at the end:The HTML coverage report will have been created in the
htmlcov
directory in the current working directory.