以编程方式获取单元测试的结果 [英] Getting the results of a unittest programmatically

查看:29
本文介绍了以编程方式获取单元测试的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些单元测试"代码,它很棒.当我手动运行它时,我可以在 CLI 上看到它.

I wrote some 'unittest' code, and it's great. I can see it on the CLI when I run it manually.

现在我想将它连接起来作为合并到我的存储库上的主钩子的一部分自动运行.除了以编程方式获取单元测试结果的部分外,我已经使用虚拟代码设置了所有内容.

Now I want to hook it up to run automatically as part of a merge to master hook on my repository. I have everything set up with dummy code except for the part of grabbing the results of the unittest programmatically.

当我调用 unittest.main() 来运行它们时,它会抛出一个 SystemExit.我试过捕捉它并重新路由标准输出,但我无法让它工作,而且感觉我做错了.有没有更简单的方法来获取单元测试的结果,比如在 Python 行字符串列表中,甚至更复杂的结果对象?

When I call unittest.main() to run them all, it throws a SystemExit. I've tried catching it and rerouting the standard output, but I wasn't able to get it to work, and it also feels like I'm doing it wrong. Is there an easier way to get the results of the unittests, like in a Python list of line strings, or even a more complicated result object?

出于我的目的,我只对 100% 通过或失败感兴趣,然后在向 master 发出拉取请求时在存储库中显示该视觉效果,并附上指向完整单元测试结果的链接详情.

Really for my purposes, I'm only interested in 100% pass or fail, and then showing that visual in the repository on a pull request to master, with a link to the full unittest result details.

如果可以调用其他 Python 单元测试框架并轻松传递结果,我也不喜欢unittest".

I'm also not married to 'unittest' if some other Python unit test framework can be called and pass off results easily.

推荐答案

您可以将 exit=False 传递给 unittest.main,并捕获返回值.要从另一个脚本或交互式解释器运行它,您也可以指定目标 module.

You can pass exit=False to unittest.main, and capture the return value. To run it from another script, or the interactive interpreter, you can specify a target module as well.

这为我们提供了一个被执行的 TestCaseTestSuite 类的实例.内部 unittest 机制将生成一个 TestResult 对象在该对象的 result 属性中可用.

That gives us an instance of the TestCase or TestSuite class that was executed. The internal unittest machinery will make a TestResult object available in the result attribute of that object.

该对象将有一个 TestResult.wasSuccessful 提供您要查找的结果的方法.

That object will have a TestResult.wasSuccessful method that gives the result you're looking for.

假设你有一些文件 tests.py:

from unittest import main

test = main(module='tests', exit=False)
print(test.result.wasSuccessful())

这篇关于以编程方式获取单元测试的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆