Test Overview
This test uses a pytest fixture to set up a temporary database table before the test runs and cleans it up after. It verifies that data can be inserted and queried correctly within the test.
This test uses a pytest fixture to set up a temporary database table before the test runs and cleans it up after. It verifies that data can be inserted and queried correctly within the test.
import pytest import sqlite3 @pytest.fixture def db_connection(): # Setup: create in-memory SQLite database conn = sqlite3.connect(':memory:') cursor = conn.cursor() cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)') conn.commit() yield conn # Teardown: close connection conn.close() def test_insert_and_query(db_connection): cursor = db_connection.cursor() cursor.execute("INSERT INTO users (name) VALUES ('Alice')") db_connection.commit() cursor.execute('SELECT name FROM users WHERE id=1') result = cursor.fetchone() assert result[0] == 'Alice'
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and pytest identifies the db_connection fixture | No database connection exists yet | - | PASS |
| 2 | Fixture db_connection runs: creates in-memory SQLite database and users table | In-memory SQLite database with empty users table | - | PASS |
| 3 | Test function test_insert_and_query runs using db_connection fixture | Database connection active with users table | - | PASS |
| 4 | Insert a user named 'Alice' into users table | users table has one row with name 'Alice' | - | PASS |
| 5 | Query the users table for user with id=1 | Query returns ('Alice',) | Assert that fetched name is 'Alice' | PASS |
| 6 | Test completes successfully | Database connection still open | - | PASS |
| 7 | Fixture teardown: close the database connection | Database connection closed, resources cleaned | - | PASS |