A test fixture is reusable setup for a test: data, state, or an environment prepared before the assertion runs. It keeps repeated setup—such as opening an in-memory database—out of every test, so a later change happens in one place rather than throughout the suite. section 8.4.2
In pytest, a fixture can create a resource, yield it to a test, then clean it up afterward. Tests request the fixture by naming it as a parameter, making their dependency on the prepared environment explicit. section 8.4.2
```python
import pytest
import sqlite3
@pytest.fixture
def db_connection():
# Setup: create the in-memory database connection
memory_conn = create_in_memory_db_from_existing('../data/questions.db')
yield memory_conn # This is where the testing happens
# Teardown: close the database connection
memory_conn.close()
def test_connection(db_connection):
db_connection.execute("SELECT * FROM questions")
def test_get_question(db_connection):
# Example test using the db_connection fixture
result = db_connection.execute("SELECT * FROM questions WHERE id = 1")
question = result.fetchone()
assert question is not None
```
This fixture builds an in-memory copy of a database, yields its connection to two tests, and closes the connection during teardown. Both tests reuse the same setup without recreating its implementation. section 8.4.2
Use the existing database fixture
A generated test initially used unittest and Mock. A focused revision asked for pytest and the existing in-memory-database fixture instead. The resulting test deletes rows, calls get_all_questions, and asserts that the result is an empty list. Reusing the fixture preserves the suite’s chosen test environment while keeping the test focused on behavior. section 8.4.3
Use fixtures deliberately in an AI-assisted test workflow:
- Generate the basic structure first, including fixtures and imports, then review whether the setup matches the code’s purpose. section 8.4.5
- Consolidate setup when several tests need the same environment, rather than duplicating connection or data-creation code. section 8.4.2 section 8.4.5
- Run and debug iteratively; generated fixtures and tests still need verification, corrections, and stronger coverage where needed. section 8.4.5 section 8.4.4
A fixture is helpful, not a substitute for test design. AI can generate scaffolding and common cases, but developers must verify assumptions, edge cases, assertions, ordering concerns, and whether an in-memory database faithfully serves the test’s goal. section 8.4.3 section 8.4.5









