0
0
Selenium Pythontesting~15 mins

Retry mechanism for flaky tests in Selenium Python - Build an Automation Script

Choose your learning style9 modes available
Verify retry mechanism for flaky login test
Preconditions (2)
Step 1: Open the login page URL
Step 2: Enter 'testuser' in the username input field with id 'username'
Step 3: Enter 'Test@1234' in the password input field with id 'password'
Step 4: Click the login button with id 'loginBtn'
Step 5: Wait for the dashboard page to load
Step 6: Verify the URL is 'https://example.com/dashboard'
Step 7: If the verification fails, retry the entire login process up to 2 more times
✅ Expected Result: The test should pass if the dashboard URL is reached within 3 attempts. If all attempts fail, the test should fail.
Automation Requirements - Selenium with Python unittest
Assertions Needed:
Assert current URL equals 'https://example.com/dashboard' after login
Best Practices:
Use explicit waits to wait for page elements or URL changes
Implement retry logic using a loop or decorator
Use clear and maintainable locators (By.ID)
Keep test code readable and modular
Automated Solution
Selenium Python
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class TestLoginWithRetry(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(5)  # Implicit wait for element presence
        self.wait = WebDriverWait(self.driver, 10)  # Explicit wait

    def login(self):
        self.driver.get('https://example.com/login')
        username_input = self.wait.until(EC.presence_of_element_located((By.ID, 'username')))
        password_input = self.driver.find_element(By.ID, 'password')
        login_button = self.driver.find_element(By.ID, 'loginBtn')

        username_input.clear()
        username_input.send_keys('testuser')
        password_input.clear()
        password_input.send_keys('Test@1234')
        login_button.click()

        # Wait for URL to change to dashboard
        self.wait.until(EC.url_to_be('https://example.com/dashboard'))

    def test_login_with_retry(self):
        max_attempts = 3
        for attempt in range(1, max_attempts + 1):
            try:
                self.login()
                current_url = self.driver.current_url
                self.assertEqual(current_url, 'https://example.com/dashboard')
                print(f'Login succeeded on attempt {attempt}')
                break
            except (AssertionError, Exception) as e:
                print(f'Attempt {attempt} failed: {e}')
                if attempt == max_attempts:
                    self.fail(f'Login failed after {max_attempts} attempts')

    def tearDown(self):
        self.driver.quit()

if __name__ == '__main__':
    unittest.main()

This test script uses Python's unittest framework with Selenium WebDriver.

setUp: Initializes the Chrome browser and sets implicit and explicit waits.

login method: Opens the login page, fills username and password fields, clicks login, and waits explicitly for the dashboard URL.

test_login_with_retry: Tries to login up to 3 times. If the dashboard URL is reached, it passes. If not, it retries. After 3 failures, the test fails.

tearDown: Closes the browser after the test.

This approach uses explicit waits for reliability and a retry loop to handle flaky failures like slow page loads or temporary glitches.

Common Mistakes - 4 Pitfalls
{'mistake': 'Using time.sleep() instead of explicit waits', 'why_bad': 'Sleeping blindly wastes time and can cause flaky tests if the page loads slower or faster than expected.', 'correct_approach': "Use Selenium's explicit waits like WebDriverWait with expected conditions to wait only as long as needed."}
Hardcoding XPath locators that are brittle
Not catching exceptions during retries
{'mistake': 'Retrying only the assertion without re-running the login steps', 'why_bad': "If the login process failed, just re-checking the assertion won't fix the problem.", 'correct_approach': 'Retry the entire login process including navigation and input steps.'}
Bonus Challenge

Now add data-driven testing with 3 different sets of login credentials (valid and invalid) to verify retry mechanism works for each case.

Show Hint