Playwright + Python · Lesson 27 of 37

0/37 done

Module 27: Test Lifecycle

27. Test Lifecycle Management, Teardown Guarantees & Scope

15 minlesson

Your task

Implement safe_context_runner(context_creator, test_fn):

  1. context = context_creator().
  2. In try block, call test_fn(context).
  3. In finally block, call context.close().

Write it in the editor, then press Check answer (Ctrl + Enter).

pytest yield Fixtures for Teardown

python
import pytest

@pytest.fixture
def api_client(playwright):
    # Setup:
    request_context = playwright.request.new_context(base_url="https://api.targetqa.com")
    yield request_context
    # Teardown:
    request_context.dispose()

Key Takeaways & Walkthrough Summary

Managing test execution lifecycles guarantees that failed tests do not leave unclosed files or video recordings behind. In this lesson, you will learn to structure pytest yield fixtures for clean setup and teardown. Let's master test lifecycles!

Part of the Playwright + Python course (Playwright with Python). Practice this concept live in the Playwright Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What is the difference between fixture scopes in pytest?

function (default: runs per test), class (runs per class), module (runs per file), and session (runs once per entire test suite).

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip