0
0
Selenium Pythontesting~10 mins

Confirmation alert handling in Selenium Python - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test opens a webpage with a confirmation alert, clicks a button to trigger the alert, accepts the alert, and verifies the confirmation message on the page.

Test Code - Selenium
Selenium Python
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
import unittest

class TestConfirmationAlert(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://example.com/confirmation-alert')

    def test_accept_confirmation_alert(self):
        driver = self.driver
        # Click the button that triggers the confirmation alert
        button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.ID, 'confirm-btn'))
        )
        button.click()

        # Wait for the alert to be present
        alert = WebDriverWait(driver, 10).until(EC.alert_is_present())

        # Accept the confirmation alert
        alert.accept()

        # Verify the confirmation message is displayed
        message = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.ID, 'confirm-message'))
        )
        self.assertEqual(message.text, 'You clicked OK!')

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

if __name__ == '__main__':
    unittest.main()
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test starts and opens Chrome browserBrowser window opens at URL https://example.com/confirmation-alert-PASS
2Waits until the button with ID 'confirm-btn' is clickablePage fully loaded with visible button 'confirm-btn'Button is clickablePASS
3Clicks the 'confirm-btn' button to trigger confirmation alertConfirmation alert appears on screen-PASS
4Waits for the confirmation alert to be presentAlert dialog is present and activeAlert is presentPASS
5Accepts the confirmation alert by clicking OKAlert disappears, page updates accordingly-PASS
6Waits for the confirmation message element with ID 'confirm-message' to be visibleConfirmation message 'You clicked OK!' is visible on the pageMessage text equals 'You clicked OK!'PASS
7Test ends and browser closesBrowser window closed-PASS
Failure Scenario
Failing Condition: The confirmation alert does not appear after clicking the button
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test do after clicking the button with ID 'confirm-btn'?
AWaits for and accepts the confirmation alert
BImmediately checks the confirmation message without waiting
CCloses the browser
DClicks the button again
Key Result
Always wait explicitly for alerts before interacting with them to avoid timing issues and ensure reliable test execution.