gpt4 book ai didi

Python unittest,仅在测试失败时才做某事

转载 作者:太空狗 更新时间:2023-10-29 21:07:06 27 4
gpt4 key购买 nike

当使用 python 3 中的 unittest 库时,我只想在测试失败时执行一些操作(但这应该在类级别上,所以我不必为每个都编写它测试)。例如,当使用 behave 时,会出现类似这样的情况:

def after_step(context, step):
if step.status == "failed":
...

unittest库是否有类似的东西?如果没有,做类似事情的最简单方法是什么?

最佳答案

我最近在尝试做类似的事情,我找到了出路:

import unittest

class MyTestResult(unittest.TestResult):
def addFailure(self, test, err):
# here you can do what you want to do when a test case fails
print('test failed!')
super(MyTestResult, self).addFailure(test, err)

def addError(self, test, err):
# here you can do what you want to do when a test case raises an error
super(MyTestResult, self).addError(test, err)

class MyUT(unittest.TestCase):
def test_fail(self):
self.assertEqual(1, 2, '123')
self.assertTrue("ABc".isupper())

if __name__ == '__main__':
unittest.main(testRunner=unittest.TextTestRunner(resultclass=MyTestResult))

如果想根据不同的测试用例类做不同的工作,可以这样实现:

import unittest

class MyUT(unittest.TestCase):
class TestResult(unittest.TestResult):
def addFailure(self, test, err):
print('do something when test case failed')
super(MyUT.TestResult, self).addFailure(test, err)
def addError(self, test, err):
print('test case error')
super(MyUT.TestResult, self).addError(test, err)

def test_fail(self):
self.assertEqual(1, 2, "1=2")

class MyUT2(unittest.TestCase):
class TestResult(unittest.TestResult):
def addFailure(self, test, err):
print('do something else when test case failed')
super(MyUT2.TestResult, self).addFailure(test, err)
def addError(self, test, err):
print('test case error')
super(MyUT2.TestResult, self).addError(test, err)

def test_fail(self):
self.assertEqual(1, 2, "1=2")

if __name__ == '__main__':
classes = [MyUT, MyUT2]
for c in classes:
suite = unittest.TestLoader().loadTestsFromTestCase(c)
unittest.TextTestRunner(resultclass=c.TestResult).run(suite)

关于Python unittest,仅在测试失败时才做某事,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30647772/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com