AnC*_*AnC 12 python unit-testing
我在我的测试框架中使用以下代码:
testModules = ["test_foo", "test_bar"]
suite = unittest.TestLoader().loadTestsFromNames(testModules)
runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
results = runner.run(suite)
return results.wasSuccessful()
Run Code Online (Sandbox Code Playgroud)
有没有办法让报告(runner.run?)在第一次失败后中止以防止过多的冗长?
moi*_*ink 11
在问了问题九年后,这仍然是“ python单元测试过早失败”的最佳搜索结果之一,正如我在查看其他搜索结果时所发现的那样,这些答案不再适用于最新版本的单元测试模块。
unittest模块的文档https://docs.python.org/3/library/unittest.html#command-line-options和https://docs.python.org/2.7/library/unittest.html#command- line-options显示有一个参数failfast = True,可以将其添加到unittest.main中,或者等效地使用命令行选项-f或--failfast来停止对第一个错误或失败的测试。此选项是在2.7版中添加的。与其他答案中建议的先前必需的解决方法相比,使用该选项要容易得多。
也就是说,只需更改您的
unittest.main()
Run Code Online (Sandbox Code Playgroud)
至
unittest.main(failfast=True)
Run Code Online (Sandbox Code Playgroud)
根据Eugene的指导,我想出了以下内容:
class TestCase(unittest.TestCase):
def run(self, result=None):
if result.failures or result.errors:
print "aborted"
else:
super(TestCase, self).run(result)
Run Code Online (Sandbox Code Playgroud)
虽然这种方法运行得相当好,但每个单独的测试模块必须定义是否要使用此自定义类或默认类(命令行开关,类似于py.tests --exitfirst,将是理想的),这有点令人讨厌.
这是一个功能.如果要覆盖它,则需要子类TestCase和/或TestSuite类并覆盖run()方法中的逻辑.
PS:我认为你必须在类中继承unittest.TestCase和覆盖方法run():
def run(self, result=None):
if result is None: result = self.defaultTestResult()
result.startTest(self)
testMethod = getattr(self, self._testMethodName)
try:
try:
self.setUp()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
return
ok = False
try:
testMethod()
ok = True
except self.failureException:
result.addFailure(self, self._exc_info())
result.stop()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
result.stop()
try:
self.tearDown()
except KeyboardInterrupt:
raise
except:
result.addError(self, self._exc_info())
ok = False
if ok: result.addSuccess(self)
finally:
result.stopTest(self)
Run Code Online (Sandbox Code Playgroud)
(我添加了两个result.stop()默认run定义的调用).
然后你必须修改所有的测试用例,使它们成为这个新类的子类,而不是unittest.TestCase.
警告:我没有测试此代码.:)
| 归档时间: |
|
| 查看次数: |
4380 次 |
| 最近记录: |