1

I am trying to use 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."

1
  • loop over range(5), try the assert, sleep 5 seconds would be one naive way... Commented Sep 7, 2018 at 18:27

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

Comments

3

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 ...

4 Comments

I have something similar written, I wanted to have a compact version of above loop because as you can see in above code only (A == B) changes for different conditions but rest of the code is same, unnecessarily makes the code redundant and big
Good idea; I left the logic "exploded" for understanding.
I think it should be failed = (A != B), isn't it?
@LongNguyen depends on what you actually consider a success in your specific case ;P

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.