0Pricing
Python Academy · Lesson

Fixtures and Setup/Teardown

Use fixtures for shared test state and resource setup.

What Are Fixtures?

Fixtures are functions decorated with @pytest.fixture that provide test dependencies. pytest injects them by name.

import pytest

@pytest.fixture
def user():
    return {"name": "Alice", "age": 30}

def test_name(user):
    assert user["name"] == "Alice"

Setup and Teardown with yield

Yield the fixture value inside a fixture to separate setup (before yield) from teardown (after yield).

import pytest

@pytest.fixture
def db_connection():
    conn = create_connection()  # setup
    yield conn
    conn.close()                # teardown

def test_query(db_connection):
    result = db_connection.query("SELECT 1")
    assert result is not None

All lessons in this course

  1. Writing Your First pytest Tests
  2. Fixtures and Setup/Teardown
  3. Parametrize and Test Coverage
  4. Mocking with unittest.mock
← Back to Python Academy