Test Overview
This test opens a webpage, tries to find a button, clicks it, and verifies the page title. If the test fails, it takes a screenshot to help diagnose the problem.
This test opens a webpage, tries to find a button, clicks it, and verifies the page title. If the test fails, it takes a screenshot to help diagnose the problem.
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException import unittest class TestScreenshotOnFailure(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.implicitly_wait(5) def test_click_button_and_check_title(self): driver = self.driver driver.get('https://example.com') try: button = driver.find_element(By.ID, 'submit-btn') button.click() self.assertEqual(driver.title, 'Expected Title') except Exception as e: driver.save_screenshot('failure_screenshot.png') raise e def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and WebDriver Chrome browser opens | Chrome browser window is open and ready | — | PASS |
| 2 | Browser navigates to 'https://example.com' | Page 'https://example.com' is loaded in browser | — | PASS |
| 3 | Find element with ID 'submit-btn' | Button with ID 'submit-btn' is present on the page | — | PASS |
| 4 | Click the 'submit-btn' button | Button is clicked, page may change | — | PASS |
| 5 | Check if page title equals 'Expected Title' | Page title is checked | Assert page title == 'Expected Title' | PASS |
| 6 | Test ends and browser closes | Browser window is closed | — | PASS |
save_screenshot().driver.save_screenshot('error.png') matches Selenium's API.try:
driver.find_element(By.ID, 'submit').click()
except Exception as e:
driver.save_screenshot('fail.png')
print('Screenshot saved on failure')try:
driver.find_element(By.NAME, 'login').click()
except:
driver.save_screenshot(failure.png)time.time() in filename ensures unique screenshot names.Pass the test and this pattern moves unknown