typestar

Fixtures in Python

A fixture builds what a test needs, and tears it down afterwards.

import pytest


class Session:
    def __init__(self):
        self.runs = []
        self.closed = False

    def record(self, tpm):
        self.runs.append(tpm)

    def close(self):
        self.closed = True


@pytest.fixture
def session():
    made = Session()
    yield made
    made.close()


@pytest.fixture(scope="module")
def target():
    return 90


def test_records_runs(session, target):
    session.record(104)
    assert session.runs == [104]
    assert session.runs[0] > target

How it works

  1. Requesting it by name is how a test asks for it.
  2. A yield fixture cleans up after the test returns.
  3. scope decides how often it is rebuilt.

Keywords and builtins used here

The run, in numbers

Lines
31
Characters to type
423
Tokens
117
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 1 of 2 in Fixtures, step 4 of 9 in Testing with pytest.

← Previous Next →