0
0
Selenium Pythontesting~10 mins

Retry mechanism for flaky tests in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks a login button on a webpage. It uses a retry mechanism to handle flaky failures by trying the test up to 3 times before failing.

Test Code - unittest
Selenium Python
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
import time

class TestLoginButton(unittest.TestCase):
    MAX_RETRIES = 3

    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com/login')

    def test_login_button_present(self):
        retries = 0
        while retries < self.MAX_RETRIES:
            try:
                button = self.driver.find_element(By.ID, 'login-btn')
                self.assertTrue(button.is_displayed())
                break  # Test passed, exit retry loop
            except (NoSuchElementException, AssertionError):
                retries += 1
                if retries == self.MAX_RETRIES:
                    raise
                time.sleep(1)  # Wait before retrying

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

if __name__ == '__main__':
    unittest.main()
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and WebDriver opens Chrome browserBrowser window opens at https://example.com/login-PASS
2Test tries to find element with ID 'login-btn'Page loaded, looking for login button-FAIL
3Test catches NoSuchElementException, waits 1 second, retries (retry 1)Still on login page, retrying element search-PASS
4Test tries to find element with ID 'login-btn' againPage loaded, looking for login button-PASS
5Test asserts the login button is displayedLogin button found and visiblebutton.is_displayed() is TruePASS
6Test passes and browser closesBrowser closed-PASS
Failure Scenario
Failing Condition: Login button with ID 'login-btn' is not found after 3 retries
Execution Trace Quiz - 3 Questions
Test your understanding
What causes the test to retry finding the login button?
ANoSuchElementException or assertion failure
BSuccessful button click
CPage navigation to home
DTimeout waiting for page load
Key Result
Implementing a retry mechanism helps handle flaky tests caused by temporary issues like slow loading or element rendering delays, improving test reliability.