pytest-metadata

3.1.1 · active · verified Sun Mar 29

pytest-metadata is a plugin for pytest that provides access to test session metadata. It collects system information, environment variables (especially from CI systems), and allows users to inject custom data. Currently at version 3.1.1, it is actively maintained by the pytest-dev team, with releases typically aligning with pytest compatibility and new feature additions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to add custom metadata using a `pytest_configure` hook in `conftest.py`, how to modify the final metadata using the `pytest_metadata` hook, and how to access the collected metadata within a test function via the `metadata` fixture. It also shows how to add metadata via command-line arguments.

import pytest
import os
from pytest_metadata.plugin import metadata_key

# conftest.py (or a pytest plugin)
@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
    # Initialize metadata_key if not already present (e.g., if pytest-html isn't loaded)
    if not hasattr(config.stash, metadata_key):
        config.stash[metadata_key] = {}

    # Add custom metadata before tests run
    config.stash[metadata_key]["project_name"] = "My Awesome Project"
    config.stash[metadata_key]["run_by_user"] = os.environ.get("USER", "unknown")

@pytest.hookimpl(optionalhook=True)
def pytest_metadata(metadata):
    # This hook modifies the final metadata dictionary that will be reported.
    # For example, remove 'Packages' to simplify the report.
    metadata.pop("Packages", None)
    metadata["custom_value_from_hook"] = "Hello from pytest_metadata hook!"

# test_example.py
def test_access_session_metadata(metadata):
    # The 'metadata' fixture provides access to the collected session metadata
    print(f"\n--- Test-specific Metadata ---")
    print(f"Project Name: {metadata.get('project_name')}")
    print(f"Run By User: {metadata.get('run_by_user')}")
    print(f"Python Version: {metadata.get('Python')}")
    print(f"Custom Value: {metadata.get('custom_value_from_hook')}")

    assert "project_name" in metadata
    assert metadata["project_name"] == "My Awesome Project"
    assert "Python" in metadata
    assert "custom_value_from_hook" in metadata

# To run this example:
# 1. Save the conftest.py and test_example.py files in the same directory.
# 2. Run from your terminal: 
#    pytest -v --metadata cli_key cli_value --metadata another_key another_value
# Expected output will include metadata in the header (due to -v) and in the test print statements.

view raw JSON →