目标:只有在测试失败时才需要调用一堆步骤(因此是一个函数)。
我尝试了什么:
1)尝试传递函数没有参数。
观察:如果测试通过,则不会调用函数。但如果测试失败,我会收到错误。 (AssertionError: <bound method TestAuto.func1 of <test_fail.TestAuto testMethod=test_fail>>)
class TestAuto(unittest.TestCase):
def test_fail(self):
self.assertEqual(1, 1, self.func1)
def func1(self):
print 'We are inside'
if __name__ == '__main__':
unittest.main()
test_fail (test_fail.TestAuto) ... ok
----------------------------------------
Ran 1 test in 0.001s
OK
2)尝试使用参数调用函数。
class TestAuto(unittest.TestCase):
def test_fail(self):
self.assertEqual(1, 1, self.func1('message'))
def func1(self, msg):
print msg
观察:无论测试通过还是失败,都会调用函数。
结果:
test_fail(test_fail.TestAuto)...消息 确定
在0.001s中进行1次测试
行
答案 0 :(得分:2)
您可以使用序数try/except
声明:
from exceptions import AssertionError as AE
class TestAuto(unittest.TestCase):
def test_not_fail(self):
# won't call func1
try:
self.assertEqual(1, 1)
except AE:
self.func1()
raise
def test_fail(self):
# will call func1
try:
self.assertEqual(1, 9)
except AE:
self.func1()
raise
def func1(self):
print 'We are inside'
它可以作为装饰器实现,方便使用:
from exceptions import AssertionError as AE
def run_if_test_fails(call_on_fail):
def deco(f):
def inner(*args, **kwargs):
try:
f(*args, **kwargs)
except AE:
# test failed - run callback
call_on_fail()
# reraise Error to mark it in result
raise
return inner
return deco
def func1():
print('We are inside')
class TestAuto(unittest.TestCase):
@run_if_test_fails(func1)
def test_not_fail(self):
# won't call func1
self.assertEqual(1, 1)
@run_if_test_fails(func1)
def test_fail(self):
# will call func1
self.assertEqual(1, 9)
答案 1 :(得分:0)
&#34;消息&#34;各种断言的参数方法用作描述测试失败的字符串。在第一个示例中,您传递了一个函数。如果断言成功则不使用,如果测试失败则打印(因为消息发生了什么)。
在你的第二个例子中,你已经进行了一个函数调用以准备参数 - 这是在调用 assertEquals之前发生的。 &#39;消息&#39;打印是因为您打算在func1中打印。
答案 2 :(得分:0)
msg = None需要显示某些内容。因此,如果我们想要使用一个函数,我们需要返回一些东西。现在我只尝试使用字符串,它可以工作。
class TestAuto(unittest.TestCase):
def test_fail(self):
self.assertEqual(1, 1, msg=self.func1('2 msg'))
def func1(self, mesg=None):
if mesg:
return mesg
else:
return 'Just an error'
1)案例1:测试失败时
==============================================================
FAIL: test_fail (test_fail.TestAuto)
--------------------------------------------------------------
Traceback (most recent call last):
File "test_fail.py", line 5, in test_fail
self.assertEqual(1, 2, msg=self.func1('2 msg'))
AssertionError: 2 msg
--------------------------------------------------------------
Ran 1 test in 0.002s
FAILED (failures=1)
2)案例2:当测试通过时
self.assertEqual(1, 1, msg=self.func1('2 msg'))
test_fail (test_fail.TestAuto) ... ok
--------------------------------------------------------------
Ran 1 test in 0.001s
OK