import unittest
import time
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
from selenium.common.exceptions import TimeoutException
class TestLoginScreenshotOnFailure(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.get('https://example.com/login')
self.wait = WebDriverWait(self.driver, 10)
def test_invalid_login_screenshot_on_failure(self):
driver = self.driver
try:
email_input = self.wait.until(EC.presence_of_element_located((By.ID, 'email')))
email_input.clear()
email_input.send_keys('wronguser@example.com')
password_input = driver.find_element(By.ID, 'password')
password_input.clear()
password_input.send_keys('wrongpassword')
login_button = driver.find_element(By.ID, 'loginBtn')
login_button.click()
# Wait for error message
error_msg = self.wait.until(EC.visibility_of_element_located((By.ID, 'errorMsg')))
# Assert error message is displayed
self.assertTrue(error_msg.is_displayed(), 'Error message should be visible')
except (AssertionError, TimeoutException) as e:
timestamp = time.strftime('%Y%m%d-%H%M%S')
screenshot_name = f'screenshot_failure_{timestamp}.png'
driver.save_screenshot(screenshot_name)
raise e
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()This test uses unittest and Selenium WebDriver for Python.
setUp: Opens the browser and navigates to the login page.
test_invalid_login_screenshot_on_failure: Enters invalid credentials, clicks login, and waits for the error message.
If the error message is not visible or any assertion fails, it catches the exception, takes a screenshot with a timestamped filename, and then re-raises the error to fail the test.
tearDown: Closes the browser after the test.
This approach ensures that if the test fails, you get a screenshot to help understand what went wrong.