Sometimes tests fail randomly due to temporary issues. Retry mechanism helps run the test again automatically to check if it passes on retry.
Retry mechanism for flaky tests in Selenium Python
from selenium.common.exceptions import WebDriverException import time def retry_test(func, retries=3, delay=2): for attempt in range(1, retries + 1): try: func() print(f"Test passed on attempt {attempt}") break except (WebDriverException, AssertionError) as e: print(f"Attempt {attempt} failed: {e}") if attempt == retries: raise time.sleep(delay)
The retry_test function takes another function func which is the test to run.
You can set how many times to retry and how long to wait between tries.
def test_example(): # test steps here assert driver.title == "Home Page"
test_example up to 5 times, waiting 1 second between tries if it fails.retry_test(test_example, retries=5, delay=1)
This script opens a browser, runs a test to check the page title, and retries up to 3 times if the test fails. It prints which attempt passed or failed. Finally, it closes the browser.
from selenium import webdriver from selenium.common.exceptions import WebDriverException import time # Setup WebDriver (example with Chrome) driver = webdriver.Chrome() def test_title(): driver.get("https://example.com") assert driver.title == "Example Domain" def retry_test(func, retries=3, delay=2): for attempt in range(1, retries + 1): try: func() print(f"Test passed on attempt {attempt}") break except (WebDriverException, AssertionError) as e: print(f"Attempt {attempt} failed: {e}") if attempt == retries: raise time.sleep(delay) try: retry_test(test_title, retries=3, delay=1) finally: driver.quit()
Use retries carefully to avoid hiding real issues.
Keep delay enough to let temporary problems clear.
Catch only expected exceptions to retry, not all errors.
Retry mechanism helps reduce false failures in flaky tests.
It runs the test multiple times with delays between tries.
Use it to handle temporary issues like slow loading or network glitches.
Practice
Solution
Step 1: Understand flaky tests
Flaky tests fail sometimes due to temporary problems like slow page loads or network delays.Step 2: Purpose of retry mechanism
Retry mechanism reruns failed tests to check if failure was temporary, reducing false failures.Final Answer:
To rerun tests that fail due to temporary issues like slow loading -> Option CQuick Check:
Retry mechanism = rerun flaky tests [OK]
- Thinking retry speeds up tests
- Assuming retry ignores failures
- Confusing retry with logging
Solution
Step 1: Check retry decorator structure
def retry(func): def wrapper(): for _ in range(3): try: return func() except Exception: pass return wrapper defines a wrapper function that tries to run the test 3 times catching exceptions.Step 2: Verify retry logic correctness
def retry(func): def wrapper(): for _ in range(3): try: return func() except Exception: pass return wrapper retries on exception and returns on success, which is correct retry behavior.Final Answer:
def retry(func): def wrapper(): for _ in range(3): try: return func() except Exception: pass return wrapper -> Option BQuick Check:
Retry decorator = try 3 times with exception catch [OK]
- Not catching exceptions inside loop
- Infinite loops without exit
- Calling function multiple times without try-except
def retry(func):
def wrapper():
for i in range(2):
try:
return func()
except Exception:
print(f"Retry {i+1} failed")
print("All retries failed")
return wrapper
@retry
def test():
print("Running test")
raise Exception("Fail")
test()Solution
Step 1: Analyze retry loop
The wrapper tries to run test twice. Each time test() prints "Running test" then raises Exception.Step 2: Trace output
On first try, prints "Running test", then exception triggers "Retry 1 failed". Second try repeats same steps, then prints "Retry 2 failed". After loop ends, prints "All retries failed".Final Answer:
Running test Retry 1 failed Running test Retry 2 failed All retries failed -> Option AQuick Check:
Retry prints on each failure, then final failure message [OK]
- Missing repeated 'Running test' print
- Ignoring final 'All retries failed' print
- Assuming retry stops after first failure
def retry(func):
def wrapper():
for _ in range(3):
try:
func()
except Exception:
continue
return wrapperSolution
Step 1: Check retry logic
The wrapper calls func() but never returns its result or breaks loop on success.Step 2: Effect of missing return
Without return, wrapper always completes loop and returns None, so retry never stops on success.Final Answer:
The function does not return the result or stop retrying on success -> Option DQuick Check:
Missing return causes always 3 retries even on success [OK]
- Not returning function result inside try
- Misusing continue in except block
- Ignoring decorator metadata preservation
Solution
Step 1: Check retry count and delay
import time def retry(func): def wrapper(): for i in range(3): try: return func() except Exception: if i < 2: time.sleep(2) else: raise return wrapper retries 3 times with a 2-second sleep between tries except after last attempt.Step 2: Verify exception handling
import time def retry(func): def wrapper(): for i in range(3): try: return func() except Exception: if i < 2: time.sleep(2) else: raise return wrapper raises exception after last retry, correctly stopping retries on failure.Final Answer:
import time def retry(func): def wrapper(): for i in range(3): try: return func() except Exception: if i < 2: time.sleep(2) else: raise return wrapper -> Option AQuick Check:
Retry with delay and raise after last try [OK]
- Not raising exception after last retry
- Missing delay between retries
- Retrying infinitely without limit
Ready to prove it?
Pass the test and this pattern moves unknown
