Python的单元测试呼叫功能时断言失败
目的:我需要调用了一堆的步骤(因此函数)只有在测试失败。Python的单元测试呼叫功能时断言失败
我试了一下:
1)试图传递函数W/O参数。
观察:如果测试通过,功能不会被调用。但是如果测试失败,我会收到一个错误。 (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)...消息 确定
冉1次测试中0.001S
OK
的 “消息”各种断言的参数方法是用来描述测试失败的字符串。在你的第一个例子中,你传递一个函数。如果断言成功则不使用,如果测试失败则打印(因为这是消息发生的情况)。
在你的第二个例子中,你已经做了一个函数调用,以便准备参数 - 这发生在调用assertEquals之前之前。 'message'被打印出来,因为你的电话打印在func1中。
调用函数我同意你的观点。这解释了观察到的行为。我虽然找到了解决我的问题(张贴在这里)。告诉我,如果你同意。 –
在MSG =无希望的东西来显示。所以如果我们想使用一个函数,我们需要返回一些东西。现在我已经尝试过只使用字符串,它的工作原理。
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
'self.func1('2 msg')'将被调用,无论测试是否失败 –
@ GennadyKandaurov ..你说得对。我刚刚发现了。我试图捕捉测试的状态并在所谓的函数中使用它。 –
您可以使用顺序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'
它可以作为dec执行orator方便使用:
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等于1而导致第一个参数是消息,第一个参数是第二个消息。还有更多的:在第一个你不用 - >() – metmirr