QA Graphic

Naming Screenshots Dynamically in Pytest

Automate Screenshot Naming in Pytest: Easily Identify Test Failures

When running UI tests, capturing screenshots can be an invaluable debugging tool. However, managing these screenshots can quickly become chaotic if they are not properly labeled. One effective way to make screenshots easier to organize and track is by incorporating the test name into the filename. This ensures that each screenshot can be traced back to the exact test that generated it.

Raw Pytest Name

Capturing the Current Test Name in Pytest

Pytest provides an environment variable called PYTEST_CURRENT_TEST, which contains information about the currently executing test. We can extract the test name from this variable and use it to generate meaningful screenshot filenames.

Here's an example of how to do this in a Selenium-based test:


import os
import time
from datetime import datetime
def test_full_page_screenshot_adv(browser):
    browser.set_window_size(1315, 2330)
    browser.get("https://www.cryan.com")  # Navigate to the test page
    # Extract the current test name
    mytestname = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0]
    # Create a timestamp for unique filenames
    log_date = datetime.now().strftime('%Y-%m-%d-%H-%M')
    # Define the screenshot path
    screenshot_path = f"{mytestname}-{log_date}.png"
    # Capture and save the screenshot
    browser.save_screenshot(screenshot_path)
    print(f"Screenshot saved as {screenshot_path}")

How It Works

  1. Retrieve the Current Test Name:
    • The environment variable PYTEST_CURRENT_TEST holds information about the currently running test.
    • Using .split(':')[-1], we extract the actual test name from the full test path.
    • Further splitting by spaces (split(' ')[0]) ensures we only get the function name.
  2. Generate a Timestamp:
    • The datetime.now().strftime('%Y-%m-%d-%H-%M') function creates a timestamp in the format YYYY-MM-DD-HH-MM to ensure unique filenames.
  3. Save the Screenshot:
    • The test name and timestamp are combined to form a filename.
    • The screenshot is saved using Selenium's save_screenshot() method.

Why This Matters

  • Easier Debugging: Knowing which test generated a screenshot makes debugging test failures much simpler.
  • Organized Test Artifacts: Each screenshot is uniquely named, reducing the chances of overwriting files.
  • Automated Report Integration: The structured filenames can be linked to test reports, making them more informative.

Final Thoughts

By incorporating the test name into the screenshot filename, you can quickly identify which test generated a particular screenshot. This small tweak can save time when reviewing test results, especially in large automation suites.

Try implementing this in your test framework and see how much easier it becomes to manage your UI test screenshots!

 

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

Saturday 15 Internet Tools
Sunday 16 Misc
Monday 17 Media
Tuesday 18 QA
Wednesday 19 Pytest
Thursday 20 PlayWright
Friday 21 Macintosh