如何使用 unittest 从测试或设置中停止所有测试? [英] How to stop all tests from inside a test or setUp using unittest?
问题描述
我正在扩展 python 2.7 unittest
框架来做一些功能测试.我想做的一件事是停止所有测试在测试内部和 setUpClass()
方法内部运行.有时,如果测试失败,程序已损坏,无法再继续测试,因此我想停止运行测试.
I'm extending the python 2.7 unittest
framework to do some function testing. One of the things I would like to do is to stop all the tests from running inside of a test, and inside of a setUpClass()
method. Sometimes if a test fails, the program is so broken it is no longer of any use to keep testing, so I want to stop the tests from running.
我注意到 TestResult 有一个 shouldStop
属性和一个 stop()
方法,但我不确定如何在测试中访问它.
I noticed that a TestResult has a shouldStop
attribute, and a stop()
method, but I'm not sure how to get access to that inside of a test.
有人有什么想法吗?有没有更好的办法?
Does anyone have any ideas? Is there a better way?
推荐答案
这是我在一段时间后想出的另一个答案:
Here's another answer I came up with after a while:
首先,我添加了一个新的例外:
First, I added a new exception:
class StopTests(Exception):
"""
Raise this exception in a test to stop the test run.
"""
pass
然后我在我的子测试类中添加了一个新的assert
:
then I added a new assert
to my child test class:
def assertStopTestsIfFalse(self, statement, reason=''):
try:
assert statement
except AssertionError:
result.addFailure(self, sys.exc_info())
最后我覆盖了 run
函数以将其包含在 testMethod()
调用的正下方:
and last I overrode the run
function to include this right below the testMethod()
call:
except StopTests:
result.addFailure(self, sys.exc_info())
result.stop()
我更喜欢这个,因为现在任何测试都可以停止所有测试,并且没有特定于 cpython 的代码.
I like this better since any test now has the ability to stop all the tests, and there is no cpython-specific code.
这篇关于如何使用 unittest 从测试或设置中停止所有测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!