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.
Code
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 == 1How 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:
sqlite3andpytestare 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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What does this need from the package registry?
- These are real dependencies: `sqlite3` and `pytest`. Without them the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.