Pytest Fixture With Isolated Database

Provide a pytest fixture that creates a fresh database per test and tears it down, so tests stay independent and order does not matter.

PythonData Integrity

Code

pythonsnippet
22 lines
import sqlite3
from typing import Iterator

import pytest


@pytest.fixture
def db() -> Iterator[sqlite3.Connection]:
    connection = sqlite3.connect(":memory:")
    connection.execute(
        "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"
    )
    try:
        yield connection
    finally:
        connection.close()


def test_insert_item(db: sqlite3.Connection) -> None:
    db.execute("INSERT INTO items (name) VALUES (?)", ("widget",))
    count = db.execute("SELECT COUNT(*) FROM items").fetchone()[0]
    assert count == 1

How it works

Count the functions db and test_insert_item as the entire surface area of Pytest Fixture With Isolated Database.

Everything borrowed from sqlite3 is visible in one line: Iterator.

What to watch for

  • Plan for an install step: sqlite3 and pytest are a real dependency, resolved by the package manager.

Putting it to use

The main signature reads def db() -> Iterator[sqlite3.Connection]

db is the public entry point; everything else in the file exists to support it.

Core lines

def test_insert_item(db: sqlite3.Connection) -> None:
    db.execute("INSERT INTO items (name) VALUES (?)", ("widget",))
    count = db.execute("SELECT COUNT(*) FROM items").fetchone()[0]
    assert count == 1
def db() -> Iterator[sqlite3.Connection]:
    connection = sqlite3.connect(":memory:")
    connection.execute(
        "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT NOT NULL)"
    )
    try:
        yield connection
    finally:
        connection.close()

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `sqlite3` and `pytest`. Without them the snippet will not load.