Reputation: 687
I have a test with a loop checking some condition.
I want this loop to break and test to be passed if condition is true, otherwise I want to mark test as failed after loop ended.
here is the code
while time.time() < timeout:
if condition:
self.assertTrue(True)
self.fail()
but this solution is not working, loop is not breaking with the assert, why so?
Upvotes: 2
Views: 192
Reputation: 312056
Assertions only break the test when they fail. In your original snippet, the assert inside the loop always passes, so the test continues uninterrupted. One approach to solve these types of problems is to keep a boolean outside the loop, and assert on it when the loop terminates:
test_passed = False
while not test_passed and time.time() < timeout:
if condition:
test_passed = True
self.assertTrue(test_passed)
Upvotes: 2
Reputation: 2054
You can have multiple asserts in a test, therefore an assert will not break a loop or return the function.
This should work for you:
while not condition and time.time() < timeout:
time.sleep(0.1)
self.assertTrue(condition)
Upvotes: 1