🪝 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.
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 │
└─────────────────────────────────────────────────────────────────────────────┘
yield statement to separate setup steps from teardown routines. Code preceding yield executes before the test, while code following yield executes reliably during teardown.
# 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.")
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.
# 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()
request fixture inside custom fixtures to inspect test metadata, such as the active test function name, custom markers, or configuration flags.
# 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!")
pytest_runtest_makereport hook wrapper in conftest.py to detect test failures and record full-page screenshots and Playwright Trace ZIP files automatically.
# 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()
params argument to @pytest.fixture to run the exact same test case across multiple responsive viewport configurations automatically.
# 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()
authenticated_user -> seeded_cart -> checkout_page) to construct test states cleanly.
# 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!")
--env, --api-url, or --slowmo-delay) to your framework using pytest_addoption, consuming them inside fixtures via request.config.
# 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
# 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!")
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. │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘