python3 如何在单元测试中设置测试通过
python3 how to set test passed in unittest
我有一个循环检查某些条件的测试。
如果条件为真,我希望这个循环中断并通过测试,否则我想在循环结束后将测试标记为失败。
这是代码
while time.time() < timeout:
if condition:
self.assertTrue(True)
self.fail()
但是这个解决方案不起作用,循环没有中断断言,为什么会这样?
断言只有在失败时才会中断测试。在您的原始代码段中,循环内的断言始终通过,因此测试不间断地继续进行。解决这类问题的一种方法是在循环外保留一个布尔值,并在循环终止时对其断言:
test_passed = False
while not test_passed and time.time() < timeout:
if condition:
test_passed = True
self.assertTrue(test_passed)
您可以在一个测试中有多个断言,因此一个断言不会中断循环或 return 函数。
这应该适合你:
while not condition and time.time() < timeout:
time.sleep(0.1)
self.assertTrue(condition)
我有一个循环检查某些条件的测试。
如果条件为真,我希望这个循环中断并通过测试,否则我想在循环结束后将测试标记为失败。
这是代码
while time.time() < timeout:
if condition:
self.assertTrue(True)
self.fail()
但是这个解决方案不起作用,循环没有中断断言,为什么会这样?
断言只有在失败时才会中断测试。在您的原始代码段中,循环内的断言始终通过,因此测试不间断地继续进行。解决这类问题的一种方法是在循环外保留一个布尔值,并在循环终止时对其断言:
test_passed = False
while not test_passed and time.time() < timeout:
if condition:
test_passed = True
self.assertTrue(test_passed)
您可以在一个测试中有多个断言,因此一个断言不会中断循环或 return 函数。
这应该适合你:
while not condition and time.time() < timeout:
time.sleep(0.1)
self.assertTrue(condition)