0
0
PyTesttesting~10 mins

Database rollback fixtures in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses a pytest fixture to start a database transaction before the test and roll it back after the test finishes. It verifies that changes made during the test do not persist in the database.

Test Code - pytest
PyTest
import pytest
import sqlite3

@pytest.fixture
def db_connection():
    conn = sqlite3.connect(':memory:')
    cursor = conn.cursor()
    cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)')
    conn.commit()
    conn.execute('BEGIN')
    yield conn
    conn.rollback()
    conn.close()

def test_insert_user(db_connection):
    cursor = db_connection.cursor()
    cursor.execute("INSERT INTO users (name) VALUES ('Alice')")
    cursor.execute('SELECT COUNT(*) FROM users')
    count = cursor.fetchone()[0]
    assert count == 1

    # After test ends, rollback fixture will undo this insert
Execution Trace - 5 Steps
StepActionSystem StateAssertionResult
1Test starts and pytest calls the db_connection fixtureAn in-memory SQLite database is created with a 'users' table-PASS
2Test function test_insert_user runs and inserts a user named 'Alice'Database now has one row in 'users' table-PASS
3Test queries the count of users in the tableQuery returns count = 1Assert that count == 1PASS
4Test finishes, pytest resumes fixture teardownFixture calls rollback on the database connection-PASS
5Fixture closes the database connectionIn-memory database is discarded-PASS
Failure Scenario
Failing Condition: If the table 'users' does not exist or insert fails
Execution Trace Quiz - 3 Questions
Test your understanding
What does the fixture do after the test finishes?
ACommits the changes permanently
BDeletes the database file
CRolls back the database changes and closes the connection
DDoes nothing
Key Result
Using a rollback fixture ensures tests do not leave data behind, keeping the database clean and tests independent.