A pytest fixture supplies repeatable test context before a test runs and can clean it up afterward. It prevents tests from inheriting state left by earlier runs, a common risk when tests write ACH records into a shared database table. section 5.2.1
Define a fixture with @pytest.fixture. Put setup before yield, let the test run at yield, and put teardown after it. A test requests the fixture by naming it as a function parameter. section 5.2.1
Resetting ACH-record tests
A record-count test parses an ACH file and expects 41 rows. Without cleanup, repeated runs accumulate rows and produce counts such as 82 or 123. A setup_teardown_method fixture yields to the test, then runs TRUNCATE ach_files so the next test starts clean. section 5.2.1
Fixtures can also provide reusable objects rather than only database cleanup. In behavior-driven tests, a record fixture supplies the parsed record used by a step definition to assert its record type. section 2.4.4
Fixture scope and automatic use support different testing needs:
- Use a session-scoped browser fixture to launch Chromium once, yield it to tests, and close it after the session. section 9.2.4
- Use a function-scoped page fixture to create an isolated browser context and page for each test, then close that context. section 9.2.4
- Use autouse=True when every test needs preparation, such as clearing database tables and loading an ACH file before an integration test. section 9.2.4
Listing 9.17 Pytest fixtures for Playwright
@pytest.fixture(scope="session") #1
def browser(): #2
with sync_playwright() as p: #3
browser = p.chromium.launch(headless=False) #3
yield browser #3
browser.close() #4
#5
@pytest.fixture(scope="function")
def page(browser): #6
context = browser.new_context() #7
pages = context.pages #7
page = pages[0] if pages else context.new_page() #7
yield page #8
context.close() #9
The browser and page fixtures show two scopes, resource creation before yield, and deterministic cleanup after yield. section 9.2.4









