FIXTURES & HOOKS ARCHITECTURE IN PYTHON

Master test lifecycle orchestration in Playwright with Python: Pytest fixture scoping (function, module, session), yield teardown mechanics, autouse fixtures, request introspection, test failure hooks, customized browser contexts, and trace attachments.

🪝 Lifecycle Control: Pytest Fixtures & Test Hooks

In enterprise test automation, managing preconditions (such as opening isolated browser contexts, configuring network interception, authenticating users, and seeding database entities) and postconditions (clearing cookies, capturing failure diagnostics, stopping traces, and tearing down resources) is critical. Pytest Fixtures and Hooks replace brittle, legacy setUp() and tearDown() methods with modular, dependency-injected execution pipelines. By combining Playwright with Pytest's fixture system, engineers gain precise control over resource lifecycles through yield teardown mechanics, multi-tier scoping (function, module, session), dynamic test introspection via the request fixture, and global lifecycle hooks via pytest_runtest_makereport.

1. Fixture Scope Hierarchy & Execution Pipeline
Pytest categorizes fixtures into distinct scopes. Understanding when a fixture initializes and when its teardown executes is fundamental to building high-speed, leak-free test suites.
Fixture Hierarchy Topology
PYTEST FIXTURE SCOPE CASCADE:
┌─────────────────────────────────────────────────────────────────────────────┐
│ 1. SESSION SCOPE (scope="session")                                          │
│    * Executes ONCE per worker process at test suite initialization          │
│    * Typical Use: Shared Browser instance, API client, global config        │
└─────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ 2. MODULE SCOPE (scope="module")                                            │
│    * Executes ONCE per test file (e.g. test_orders.py)                      │
│    * Typical Use: Persistent test database schema, module-level mock server │
└─────────────────────────────────────────────────────────────────────────────┘
                                       │
                                       ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ 3. FUNCTION SCOPE (scope="function" - Default)                              │
│    * Executes for EVERY test function independently                         │
│    * Setup (Before yield): Launches Page, sets context cookies              │
│    * Teardown (After yield): Collects failure trace, closes context         │
└─────────────────────────────────────────────────────────────────────────────┘
Architectural Standard: Heavy resources (browsers, database connections) live in session/module scope; isolated runtime states (pages, contexts, cookies) live strictly in function scope.
Real-Time Example 1: Setup & Teardown Mechanics via the yield Keyword
Pytest uses the yield statement to separate setup steps from teardown routines. Code preceding yield executes before the test, while code following yield executes reliably during teardown.
Python (Setup & Teardown Fixture Lifecycle)
# content of conftest.py
import pytest
from playwright.sync_api import Playwright, BrowserContext, Page

@pytest.fixture
def managed_page(playwright: Playwright) -> Page:
    """Fixture demonstrating explicit setup and guaranteed teardown execution."""
    # ── SETUP PHASE (Pre-test execution) ─────────────────────────
    print("\n[Setup] Launching Chromium browser...")
    browser = playwright.chromium.launch(headless=True)
    context: BrowserContext = browser.new_context(viewport={"width": 1280, "height": 720})
    page: Page = context.new_page()

    # ── YIELD VALUE TO TEST ─────────────────────────────────────
    yield page

    # ── TEARDOWN PHASE (Post-test execution guaranteed) ──────────
    print(f"\n[Teardown] Cleaning up resources for URL: '{page.url}'")
    context.close()
    browser.close()
    print("[Teardown] Browser and context successfully closed.")

# content of test_lifecycle.py
def test_verify_todo_title(managed_page: Page):
    managed_page.goto("https://demo.playwright.dev/todomvc/")
    assert "TodoMVC" in managed_page.title()
    print("Test body completed successfully.")
Output: [Setup] Launching Chromium browser... Test body completed successfully. PASSED test_lifecycle.py::test_verify_todo_title [Teardown] Cleaning up resources for URL: 'https://demo.playwright.dev/todomvc/' [Teardown] Browser and context successfully closed.
Real-Time Example 2: Automatic Lifecycle Hooks via autouse=True
Apply autouse=True on fixtures to run global setup or cleanup tasks (such as measuring execution duration or clearing browser cache) across all tests without declaring the fixture argument in every function.
Python (Global autouse Execution Timer)
# content of conftest.py
import time
import pytest
from playwright.sync_api import Page

@pytest.fixture(autouse=True)
def track_test_runtime():
    """Automatically times every test in the suite without explicit parameter injection."""
    start_time = time.perf_counter()
    yield
    duration = time.perf_counter() - start_time
    print(f"\n[Performance Audit] Test executed in: {duration:.4f} seconds")

# content of test_autouse_demo.py
def test_sample_site_load(page: Page):
    page.goto("https://example.com")
    assert page.locator("h1").inner_text() == "Example Domain"

def test_httpbin_status_check(page: Page):
    page.goto("https://httpbin.org/status/200")
    assert page.locator("body").is_visible()
Output: test_autouse_demo.py::test_sample_site_load PASSED [Performance Audit] Test executed in: 0.3841 seconds test_autouse_demo.py::test_httpbin_status_check PASSED [Performance Audit] Test executed in: 0.4120 seconds
Real-Time Example 3: Test Introspection via the request Fixture
Use Pytest's built-in request fixture inside custom fixtures to inspect test metadata, such as the active test function name, custom markers, or configuration flags.
Python (request Introspection & Naming)
# content of conftest.py
import pytest
from playwright.sync_api import Browser, BrowserContext

@pytest.fixture
def custom_audited_context(request, browser: Browser) -> BrowserContext:
    """Uses request fixture to tag context traffic with test function name."""
    test_node_name = request.node.name
    test_file_name = request.node.fspath.basename

    print(f"\n[Context Initializer] Configuring context for: {test_file_name}::{test_node_name}")

    context = browser.new_context(
        extra_http_headers={
            "X-Test-Case-Name": test_node_name,
            "X-Test-Module": test_file_name
        }
    )
    yield context
    context.close()

# content of test_introspection.py
def test_user_billing_report(custom_audited_context: BrowserContext):
    page = custom_audited_context.new_page()
    page.goto("https://httpbin.org/headers")
    headers_json = page.inner_text("pre")
    assert "test_user_billing_report" in headers_json
    print("Test passed with audited request metadata transmitted in headers!")
Output: [Context Initializer] Configuring context for: test_introspection.py::test_user_billing_report Test passed with audited request metadata transmitted in headers! PASSED test_introspection.py::test_user_billing_report
Real-Time Example 4: Capturing Traces & Screenshots on Failure (pytest_runtest_makereport)
Implement the pytest_runtest_makereport hook wrapper in conftest.py to detect test failures and record full-page screenshots and Playwright Trace ZIP files automatically.
Python (Failure Hook & Diagnostic Artifacts)
# content of conftest.py
import os
import pytest
from playwright.sync_api import Browser, BrowserContext, Page

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
    """Inspects test outcomes and attaches failure indicators onto the test item."""
    outcome = yield
    report = outcome.get_result()
    # Store report on item for fixture access
    setattr(item, f"report_{report.when}", report)

@pytest.fixture
def tracing_page(request, browser: Browser) -> Page:
    """Starts Playwright Tracing and preserves trace/screenshot only upon failure."""
    context: BrowserContext = browser.new_context()
    context.tracing.start(screenshots=True, snapshots=True, sources=True)
    page: Page = context.new_page()

    yield page

    # Check if test failed during the 'call' phase
    call_report = getattr(request.node, "report_call", None)
    if call_report and call_report.failed:
        artifacts_dir = "test-results/diagnostic_artifacts"
        os.makedirs(artifacts_dir, exist_ok=True)

        trace_path = os.path.join(artifacts_dir, f"{request.node.name}_trace.zip")
        shot_path = os.path.join(artifacts_dir, f"{request.node.name}_error.png")

        context.tracing.stop(path=trace_path)
        page.screenshot(path=shot_path, full_page=True)
        print(f"\n[Failure Hook] Captured forensic trace: {trace_path}")
        print(f"[Failure Hook] Captured failure screenshot: {shot_path}")
    else:
        # Discard trace if test passed to save disk space
        context.tracing.stop()

    context.close()
Output: FAILED test_checkout.py::test_inventory_checkout [Failure Hook] Captured forensic trace: test-results/diagnostic_artifacts/test_inventory_checkout_trace.zip [Failure Hook] Captured failure screenshot: test-results/diagnostic_artifacts/test_inventory_checkout_error.png
Real-Time Example 5: Parametrized Fixtures for Cross-Role & Cross-Viewport Testing
Supply the params argument to @pytest.fixture to run the exact same test case across multiple responsive viewport configurations automatically.
Python (Multi-Viewport Parametrized Fixture)
# content of conftest.py
import pytest
from playwright.sync_api import Browser, Page

VIEWPORT_PROFILES = [
    {"name": "Desktop_1080p", "width": 1920, "height": 1080},
    {"name": "Tablet_iPad",    "width": 768,  "height": 1024},
    {"name": "Mobile_Phone",   "width": 375,  "height": 667}
]

@pytest.fixture(params=VIEWPORT_PROFILES, ids=lambda p: p["name"])
def responsive_page(request, browser: Browser) -> Page:
    """Runs tests across Desktop, Tablet, and Mobile viewport configurations."""
    profile = request.param
    context = browser.new_context(viewport={"width": profile["width"], "height": profile["height"]})
    page = context.new_page()
    yield page
    context.close()

# content of test_responsive_layout.py
def test_navigation_header_responsiveness(responsive_page: Page):
    responsive_page.goto("https://demo.playwright.dev/todomvc/")
    vp = responsive_page.viewport_size
    print(f"\nTesting layout under viewport: {vp['width']}x{vp['height']}")
    assert responsive_page.locator("h1").is_visible()
Output: test_responsive_layout.py::test_navigation_header_responsiveness[Desktop_1080p] PASSED Testing layout under viewport: 1920x1080 test_responsive_layout.py::test_navigation_header_responsiveness[Tablet_iPad] PASSED Testing layout under viewport: 768x1024 test_responsive_layout.py::test_navigation_header_responsiveness[Mobile_Phone] PASSED Testing layout under viewport: 375x667 3 passed in 1.25s
Real-Time Example 6: Composing Hierarchical Fixtures (Chained Dependencies)
Build clean dependency chains where high-level fixtures consume lower-level fixtures (e.g. authenticated_user -> seeded_cart -> checkout_page) to construct test states cleanly.
Python (Chained Fixture Dependency Tree)
# content of conftest.py
import pytest
from playwright.sync_api import BrowserContext, Page

@pytest.fixture
def logged_in_context(context: BrowserContext) -> BrowserContext:
    """Level 1 Fixture: Injects authentication cookie into browser context."""
    context.add_cookies([{
        "name": "auth_token",
        "value": "SESSION_POOJA_9921",
        "domain": "example.com",
        "path": "/"
    }])
    return context

@pytest.fixture
def populated_cart_page(logged_in_context: BrowserContext) -> Page:
    """Level 2 Fixture: Consumes logged_in_context and injects items into localStorage."""
    page = logged_in_context.new_page()
    page.goto("https://example.com")
    page.evaluate("""() => {
        localStorage.setItem('cart_items', JSON.stringify(['SKU-OPTIC-1', 'SKU-RELAY-9']));
    }""")
    return page

# content of test_checkout_chain.py
def test_order_submission(populated_cart_page: Page):
    # Test receives fully authenticated, pre-populated page without setup code!
    cart_items = populated_cart_page.evaluate("() => JSON.parse(localStorage.getItem('cart_items'))")
    cookies = populated_cart_page.context.cookies("https://example.com")

    assert len(cart_items) == 2
    assert any(c["name"] == "auth_token" for c in cookies)
    print("Chained hierarchical fixture dependency tree resolved successfully!")
Output: Chained hierarchical fixture dependency tree resolved successfully! PASSED test_checkout_chain.py::test_order_submission
Real-Time Example 7: Custom Pytest CLI Flags via pytest_addoption
Add custom command-line flags (such as --env, --api-url, or --slowmo-delay) to your framework using pytest_addoption, consuming them inside fixtures via request.config.
Python (Custom CLI Options via pytest_addoption)
# content of conftest.py
import pytest

def pytest_addoption(parser):
    """Registers proprietary command line switches with the Pytest parser."""
    parser.addoption(
        "--env",
        action="store",
        default="staging",
        help="Target test environment: dev, staging, or prod"
    )
    parser.addoption(
        "--api-timeout",
        action="store",
        default=5000,
        type=int,
        help="Default network timeout in milliseconds"
    )

@pytest.fixture(scope="session")
def base_test_url(request) -> str:
    """Resolves base URL based on CLI --env argument."""
    env = request.config.getoption("--env").lower()
    urls = {
        "dev": "https://dev.nikita-infotech.com",
        "staging": "https://staging.nikita-infotech.com",
        "prod": "https://nikita-infotech.com"
    }
    return urls.get(env, "https://staging.nikita-infotech.com")

# Execution CLI:
# pytest --env=prod
CLI Value: Switch environments across CI/CD pipelines effortlessly: pytest --env=dev vs. pytest --env=staging.
Real-Time Example 8: Managing Network Mocks via Fixtures
Package mock network routes into clean, reusable fixtures so individual tests can activate isolated mock endpoints simply by declaring the fixture name.
Python (Network Mocking Fixture Pattern)
# content of conftest.py
import json
import pytest
from playwright.sync_api import Page

@pytest.fixture
def mock_maintenance_mode(page: Page):
    """Fixture that intercepts system status API calls to simulate 503 maintenance."""
    def handle_status(route):
        route.fulfill(
            status=503,
            content_type="application/json",
            body=json.dumps({"status": "MAINTENANCE", "retry_after": 300})
        )

    page.route("**/api/v1/system-status", handle_status)
    yield
    page.unroute("**/api/v1/system-status")

# content of test_maintenance_banner.py
def test_maintenance_mode_banner(page: Page, mock_maintenance_mode):
    page.set_content("""
        
        
    """)

    banner = page.locator("#banner")
    banner.wait_for(state="visible")
    assert banner.inner_text() == "Site Under Maintenance"
    print("Mock fixture simulated 503 maintenance mode cleanly!")
Output: Mock fixture simulated 503 maintenance mode cleanly! PASSED test_maintenance_banner.py::test_maintenance_mode_banner
Real-Time Example 9: Pytest Fixtures & Hooks Reference Matrix
A comprehensive reference summary of fixture scopes, built-in Pytest hooks, yield mechanics, and best practices for Playwright Python test frameworks.
Fixtures & Hooks Architecture Matrix
FIXTURES & HOOKS ARCHITECTURE MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Hook / Fixture Element       │ Scope / Type                 │ Primary Description / Use Case                          │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ scope="function"             │ Per-Test (Default)           │ Isolates test state (fresh Page, clean context).        │
│ scope="module"               │ Per-File                     │ Shares state across single test module (e.g. DB schema).│
│ scope="session"              │ Per-Worker Run               │ Shared heavy resources (Browser process, API clients).  │
│ yield keyword                │ Split (Setup / Teardown)     │ Code before yield runs on setup; after runs on teardown.│
│ autouse=True                 │ Automatic Execution          │ Runs automatically without being requested in signature.│
│ request.node                 │ Fixture (Subrequest)         │ Introspects test name, markers, files, and config.      │
│ pytest_addoption(parser)     │ Pytest Hook (CLI)            │ Registers custom command line options (e.g. --env=qa).  │
│ pytest_runtest_makereport    │ Pytest Hook (Reporting)      │ Detects test failures to trigger screenshots & traces.  │
│ params=[...]                 │ Parametrization              │ Re-runs test across multiple inputs (e.g. viewports).   │
├──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┤
│ BEST PRACTICE GUIDELINES:                                                                                             │
│ * Store reusable fixtures centrally in conftest.py files for automated discovery.                                     │
│ * Always clean up resources (context.close(), page.close()) in the post-yield section.                                │
│ * Use pytest_runtest_makereport only for diagnostic capture; avoid modifying test outcomes inside hooks.              │
│ * Prefer chained fixtures over deep object inheritance hierarchies.                                                   │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
Engineering Best Practice: Centralize your test lifecycle inside conftest.py using yield fixtures. Never launch browser instances manually inside test methods; allow Pytest's dependency injection to supply pre-configured, audited page instances.