Created
July 24, 2025 21:18
-
-
Save cgoldberg/128f2ea25644746712cc90cd2a6a8fe0 to your computer and use it in GitHub Desktop.
Python (pytest and selenium) - fixture for taking screenshots on test failures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example fixture for taking screenshots on test failures | |
# | |
# requires: | |
# - pytest | |
# - selenium | |
import time | |
import pytest | |
from selenium import webdriver | |
@pytest.fixture | |
def driver(request): | |
driver = webdriver.Chrome() | |
failed_before = request.session.testsfailed | |
yield driver | |
if request.session.testsfailed > failed_before: | |
filename = f"./screenshot_{int(time.time() * 1000)}.png" | |
driver.save_screenshot(filename) | |
driver.quit() | |
def test_fail(driver): | |
driver.get("https://example.com/") | |
assert "wrong text" in driver.title # fails and a screenshot is saved | |
def test_pass(driver): | |
driver.get("https://example.com/") | |
assert True # passes and no screenshot is saved |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment