0
0
Selenium Pythontesting~5 mins

Retry mechanism for flaky tests in Selenium Python

Choose your learning style9 modes available
Introduction

Sometimes tests fail randomly due to temporary issues. Retry mechanism helps run the test again automatically to check if it passes on retry.

When a test fails because of slow page loading or network delays.
When external services cause intermittent failures.
When UI elements take time to appear causing test failures.
When tests fail due to temporary environment glitches.
When you want to reduce false negatives in test reports.
Syntax
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.

Examples
This is a simple test function to check page title.
Selenium Python
def test_example():
    # test steps here
    assert driver.title == "Home Page"
This runs test_example up to 5 times, waiting 1 second between tries if it fails.
Selenium Python
retry_test(test_example, retries=5, delay=1)
Sample Program

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.

Selenium Python
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()
OutputSuccess
Important Notes

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.

Summary

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.