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.
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
- 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.
- The environment variable
- Generate a Timestamp:
- The
datetime.now().strftime('%Y-%m-%d-%H-%M')
function creates a timestamp in the formatYYYY-MM-DD-HH-MM
to ensure unique filenames.
- The
- Save the Screenshot:
- The test name and timestamp are combined to form a filename.
- The screenshot is saved using Selenium's
save_screenshot()
method.
- The test name and timestamp are combined to form a filename.
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!