Reputation: 1098
I am trying to use pytest to create some sort of automation suite. The product suite I am trying to write around communicates over network interface. I am using assert statements like
assert A == B
The main issue I want to address is this:
B takes different amounts of time to reach the desired value (e.g.: sometimes 2 seconds, sometimes 5 seconds)
Is it possible to implement an assert statement which kind of executes the given condition for a certain number of times with a delay and then assert?
assert A == B, 5, 5.0, "Still it failed"
The above statement would mean: "try A == B
5 times with 5.0 second delay between each iteration and after that emit given error if it still fails."
Upvotes: 1
Views: 2718
Reputation: 12025
For a better and more readable code, you can use the retry
decorator on a inner function. Do pip install retry
to install the retry
module
from retry import retry
def test_abc():
# <my test code>
@retry(AssertionError, tries=5, delay=5.0)
def _check_something():
assert A == B, "Still failing even after 5 tries"
# Validate
_check_something()
Upvotes: 4
Reputation: 77900
No, but you can write a loop that does the same thing.
import time
failed = True
i = 0
while i < 5 and failed:
failed = (A == B)
time.sleep(5.0)
assert not failed, "Still it failed"
Wrap that into a function for readability ...
Upvotes: 3