Capturing Screenshots in Fixture Teardown
Cool Trick with Teardown
Pytest has solidified its position as a go-to testing framework for Python developers due to its simplicity, extensibility, and powerful features. In this blog post, we'll dive deep into using Pytest, specifically focusing on its integration with Playwright for browser automation, and explore how to capture screenshots during fixture teardown for enhanced debugging and result analysis.
Capturing Screenshots in Fixture Teardown
To capture a screenshot before the browser closes, we can modify the page fixture to include a teardown phase. This will help make debugging a bit easier and a chance to look at automation to see if there's any weirdness.
Any code in the Fixture that appears after "yield page" will run at the conclusion of the test.
import pytest
from playwright.sync_api import sync_playwright
import os
@pytest.fixture
def page(request):
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
yield page
def fin():
screenshot_path = f"screenshots/{request.node.name}.png"
os.makedirs(os.path.dirname(screenshot_path), exist_ok=True)
page.screenshot(path=screenshot_path)
browser.close()
request.addfinalizer(fin)
def test_example_with_screenshot(page):
page.goto("https://www.cryan.com")
assert "cryan.com" in page.title()
def test_example_fail(page):
page.goto("https://www.cryan.com")
assert "Wrong Title" in page.title()
After running the tests, you'll find screenshots in the screenshots directory. These screenshots will help you understand the state of the browser at the end of each test, especially during failures.
Benefits of Screenshot Capture
Debugging: Quickly identify issues by visually inspecting the browser state. Reporting: Include screenshots in test reports for better documentation. Visual Validation: Verify UI elements and layout.