0
0
PyTesttesting~5 mins

Database rollback fixtures in PyTest

Choose your learning style9 modes available
Introduction

Database rollback fixtures help keep tests clean by undoing database changes after each test. This stops tests from affecting each other.

When you want each test to start with the same database state.
When tests add or change data in the database.
When you want to avoid manual cleanup after tests.
When you run many tests that use the database.
When you want faster tests by avoiding full database resets.
Syntax
PyTest
import pytest

@pytest.fixture
def db_rollback_fixture(db_session):
    transaction = db_session.begin_nested()
    yield db_session
    transaction.rollback()

The fixture starts a nested transaction before the test.

After the test, it rolls back all changes made during the test.

Examples
This fixture starts a transaction and rolls it back after the test.
PyTest
import pytest

@pytest.fixture
def rollback(db):
    trans = db.begin()
    yield db
    trans.rollback()
Uses nested transactions to isolate test changes.
PyTest
import pytest

@pytest.fixture
def rollback_fixture(session):
    session.begin_nested()
    yield session
    session.rollback()
Sample Program

This example shows a fake database session with a rollback fixture. The first test adds data, which is rolled back after the test. The second test confirms the data is empty, showing rollback worked.

PyTest
import pytest

class FakeDBSession:
    def __init__(self):
        self.data = []
        self.transaction_active = False
    def begin_nested(self):
        self.transaction_active = True
        print('Transaction started')
    def rollback(self):
        if self.transaction_active:
            self.data.clear()
            self.transaction_active = False
            print('Transaction rolled back')

@pytest.fixture
def db_session():
    return FakeDBSession()

@pytest.fixture
def db_rollback_fixture(db_session):
    db_session.begin_nested()
    yield db_session
    db_session.rollback()

def test_add_data(db_rollback_fixture):
    db_rollback_fixture.data.append('test item')
    assert 'test item' in db_rollback_fixture.data

def test_data_is_clean(db_rollback_fixture):
    assert db_rollback_fixture.data == []
OutputSuccess
Important Notes

Use rollback fixtures to keep tests independent and reliable.

Nested transactions are common for rollback in tests.

Make sure your database supports transactions for rollback to work.

Summary

Rollback fixtures undo database changes after each test.

This keeps tests isolated and repeatable.

They make tests faster and easier to maintain.