QA Graphic

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.

 

About

Welcome to Pytest Tips and Tricks, your go-to resource for mastering the art of testing with Pytest! Whether you're a seasoned developer or just dipping your toes into the world of Python testing, this blog is designed to help you unlock the full potential of Pytest - one of the most powerful and flexible testing frameworks out there. Here, I'll share a treasure trove of practical insights, clever techniques, and time-saving shortcuts that I've gathered from years of writing tests and debugging code.

Schedule

Tuesday 1 QA
Wednesday 2 Pytest
Thursday 3 PlayWright
Friday 4 Macintosh
Saturday 5 Internet Tools
Sunday 6 Misc
Monday 7 Media