We are going to design a repository testing harness that uses:
- Ephemeral databases: databases that are created and destroyed for each test (or test suite) to ensure isolation.
- Fixture seeds: predefined data that can be loaded into the database to set up a known state.
- Snapshot assertions: comparing the state of the database (or parts of it) to a previously recorded snapshot (or expected state).
We'll assume we are using a SQL-based database (like PostgreSQL) and an ORM (like SQLAlchemy for Python) but the design should be generic.
Steps:
-
Ephemeral Database Setup:
- For each test (or test class), create a fresh database.
- We can use a test database name that is unique (e.g., with a timestamp or UUID) and then drop it after the test.
- Alternatively, use a transaction that is rolled back after each test (but that might not work for all databases if we want to test transaction boundaries?).
- However, the requirement says "ephemeral databases", so we are going to create and drop entire databases.
-
Fixture Seeding:
- We'll have a way to load fixtures (initial data) into the database. This can be:
- SQL files
- ORM object creation (if using an ORM)
- JSON/YAML data that we parse and insert
- We want to be able to have multiple fixtures and load only the ones needed for a test.
-
Snapshot Assertions:
- After performing operations, we want to compare the current state of the database (or specific tables) to an expected snapshot.
- The snapshot can be stored as a file (e.g., JSON) that represents the expected data.
- We can compare by:
- Querying the entire table and comparing the result set (order might not matter?).
- Or, we can compare a hash of the entire table (but that might be brittle if there are timestamps or auto-incrementing columns).
-
Test Harness Structure:
- We'll create a base test class that sets up the ephemeral database and provides helper methods for seeding and asserting.
-
Considerations:
- How to handle database schema? We assume the schema is already created (via migrations or ORM create_all) before seeding.
- We need to run the schema creation on the ephemeral database.
Let's design a class RepositoryTestHarness:
Steps for a test:
- Create a new database (with a unique name).
- Connect to that database and create the tables (or run migrations).
- Load the required fixtures (if any).
- Run the test (which will use the repository under test to modify the database).
- Assert the state of the database (by comparing to a snapshot or by querying and checking specific conditions).
- Drop the database.
However, note: if we are using an ORM, we might want to use the same connection/engine for the test and for the repository.
Alternatively, we can design the harness to be used as a context manager or with setup/teardown.
Let's design:
class RepositoryTestHarness:
def __init__(self, database_url_template, schema_creator, fixture_loader, snapshot_loader):
"""
:param database_url_template: A string template for the database URL, with a placeholder for the database name.
e.g., "postgresql://user:pass@localhost/{database_name}"
:param schema_creator: A callable that, given a database URL (without the database name, or with a temporary one?),
creates the schema (tables, etc.) in that database.
:param fixture_loader: A callable that, given a database connection (or URL) and a list of fixture names,
loads the fixtures into the database.
:param snapshot_loader: A callable that loads a snapshot (expected state) for a given table or set of tables.
"""
self.database_url_template = database_url_template
self.schema_creator = schema_creator
self.fixture_loader = fixture_loader
self.snapshot_loader = snapshot_loader
self.database_name = None
self.database_url = None
def setup(self):
# Generate a unique database name
self.database_name = f"test_{uuid.uuid4().hex}"
self.database_url = self.database_url_template.format(database_name=self.database_name)
# Create the database (we might need a connection to the default database to create the new one)
# Then run the schema_creator on the new database.
# Note: the schema_creator might need to connect to the new database, so we pass the URL for the new DB.
# Create the database (if using PostgreSQL, we connect to 'postgres' or 'template1' to create the test DB)
# Alternatively, we can have the schema_creator also create the database? But typically we want to separate.
# Let's assume we have a function that creates the database given a URL (without the DB name) and a new DB name.
# But note: the database_url_template might have the DB name at the end? We are replacing it.
# We'll break it down: we need an admin connection to create the database.
# Alternatively, we can design the harness to work with an existing database and use transactions to roll back?
# But the requirement is ephemeral databases.
# Steps for setup:
# 1. Connect to an admin database (we need to know the admin URL, maybe from a config or from the template by removing the DB part)
# 2. Create the new database.
# 3. Then run the schema_creator on the new database.
# We might need to pass an admin URL separately? Or we can derive it from the template by removing the database name part.
# Let's change the design: we'll have an `admin_database_url` that is used to create the test database.
# But to keep it simple, let's assume the `database_url_template` is for the test database and we have a separate admin URL.
# Alternatively, we can have the user pass a function that creates the database? That might be more flexible.
# Given the complexity, let's redesign:
# We'll have:
# - admin_connection: a connection to an admin database (or a way to create a new database)
# - database_url: the URL for the test database (which will be created by the admin_connection)
# But note: the schema_creator and fixture_loader need to connect to the test database.
# Let's change the __init__ to take:
# admin_database_url: for creating the test database
# test_database_url_template: with placeholder for database name, but we will replace with a generated name.
# However, to avoid overcomplicating, let's assume the harness is given a function that returns a new database URL (and creates the DB) and then we use that.
# Given the time, let's assume we are using a SQLAlchemy engine and we can create the database by connecting to the default and issuing CREATE DATABASE.
# We'll do:
# 1. Parse the database_url_template to get the admin URL (without the database name) and the driver, user, password, host, etc.
# 2. Connect to the admin database (usually 'postgres' for PostgreSQL) and create the new database.
# 3. Then form the test database URL and run the schema_creator.
# This is getting too low-level for a generic harness.
# Alternative: we use a library that already handles this? But we are designing one.
# Given the complexity of database creation, maybe we assume that the user will provide a function that:
# - creates a new database (with a given name) and returns the URL for that database.
# Let's change the interface:
# We'll have:
# create_test_database: a callable that takes a database name and returns the database URL for that new database.
# drop_test_database: a callable that takes a database name and drops it.
# But then we also need to run the schema_creator on the new database.
# Alternatively, we can have the user pass a `database_factory` that does both: creates the DB and sets up the schema.
# Given the time, let's simplify:
# We'll assume that the test database is created by the harness by connecting to a default database and running CREATE DATABASE.
# We'll require the user to provide:
# - base_database_url: the URL for a default database (like 'postgres') that we can use to create the test database.
# - database_name_prefix: a prefix for the test database name.
# Then in setup:
# self.database_name = f"{database_name_prefix}_{uuid.uuid4().hex}"
# Connect to base_database_url and run: CREATE DATABASE self.database_name
# Then form the test database URL by replacing the database name in the base_database_url? Or we have a template.
# Actually, we can have the user provide a template for the test database URL, and we replace the database name part.
# Let's do:
# base_admin_url: e.g., "postgresql://user:pass@localhost/postgres"
# test_database_url_template: e.g., "postgresql://user:pass@localhost/{database_name}"
# Then:
# self.database_name = ... (unique)
# Connect to base_admin_url and create the database with name self.database_name.
# Then set self.database_url = test_database_url_template.format(database_name=self.database_name)
# Then run the schema_creator on self.database_url.
# We'll adjust the __init__ accordingly.
pass
def teardown(self):
# Drop the database.
pass
def __enter__(self):
self.setup()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.teardown()
def load_fixtures(self, fixture_names):
# Use the fixture_loader to load the fixtures into the database.
pass
def assert_snapshot(self, table_name, snapshot_name=None):
# If snapshot_name is not given, use table_name as the snapshot name.
# Load the expected snapshot (using snapshot_loader) for the given table.
# Then query the table and compare.
pass
def get_connection(self):
# Return a connection to the test database (for custom assertions or to run the repository code)
pass
However, note: the repository code we are testing might be using a different way to connect (like a connection pool or an ORM session). We might need to provide the database URL to the repository.
So, the test would look like:
def test_repository():
with RepositoryTestHarness(...) as harness:
# The harness has created the database and set up the schema.
harness.load_fixtures(['users'])
# Now, create the repository (or the code under test) with the harness.database_url.
repo = UserRepository(harness.database_url)
# Perform operations with the repo.
repo.create_user(...)
# Assert the state of the 'users' table.
harness.assert_snapshot('users', 'expected_after_create')
But what if the repository uses an ORM and we want to use the same ORM session? We might need to create the ORM engine and session in the harness and then pass that to the repository? That would tie the harness to a specific ORM.
Alternatively, we design the harness to be database-agnostic and only deal with raw connections? Then the repository can use whatever it wants as long as it connects to the same database.
We'll go with the harness providing the database URL and the test code (or repository) is responsible for connecting.
But then the fixture_loader and snapshot_loader also need to connect. They can use the same database URL.
We'll design the fixture_loader and snapshot_loader to take a database connection (or URL) and the fixture/snapshot name.
However, the snapshot_loader might need to return the expected data in a format that we can compare. We can have it return a list of dictionaries (each row as a dict) and then compare with the actual query.
But note: the order of rows might not matter? We can sort by primary key? Or we can compare sets.
Let's assume the snapshot is stored as a list of dictionaries (each representing a row) and we will sort by the primary key (or by all columns if no primary key) and then compare.
But what if the table has an auto-incrementing ID? Then the snapshot must have the same IDs? Or we might want to ignore the ID? We can have an option to ignore certain columns.
We can design the snapshot_loader to return a list of tuples (row) and then compare with the actual query result (also as a list of tuples) after sorting.
Alternatively, we can have the snapshot be a set of rows (as tuples) and then compare sets.
Let's do:
expected = snapshot_loader(table_name, snapshot_name) # returns a list of tuples (each row's values in a fixed order)
actual = query_all_rows(table_name) # returns a list of tuples in the same order (by primary key or all columns)
Then we sort both and compare.
But note: the order of columns might be different? We should define a fixed column order for the snapshot.
We can have the snapshot_loader also return the column order, and then we use that to order the actual query.
Alternatively, we can have the snapshot be a dictionary with:
{
"columns": ["id", "name", ...],
"rows": [
[1, "Alice"],
[2, "Bob"]
]
}
Then we can use the column order to query the table and build tuples in that order.
But what if the table has more columns? We might want to compare only a subset? We can have the snapshot specify which columns to compare.
Given the complexity, let's assume the snapshot is for the entire table and we compare all columns. We can have an option to ignore columns (like auto-incrementing IDs, timestamps) in the snapshot.
We'll design:
snapshot_loader(table_name, snapshot_name) -> (column_names, rows)
Then in assert_snapshot:
expected_columns, expected_rows = self.snapshot_loader(table_name, snapshot_name)
actual_rows = self.query_table(table_name, expected_columns) # we pass the expected_columns to order the actual rows.
Then sort both by all columns? Or by the first column (assuming it's the primary key)? We can sort by the entire row.
expected_rows_sorted = sorted(expected_rows)
actual_rows_sorted = sorted(actual_rows)
assert expected_rows_sorted == actual_rows_sorted
But note: if there are NULLs, they might compare differently? In Python, None == None, so it should be okay.
However, if the database returns a different representation for NULL (like in some drivers) we might need to convert.
We'll assume the snapshot_loader returns the data in the same format as the database driver returns for the query.
Given the time, let's simplify and assume we are using an ORM that returns dictionaries? Then we can compare dictionaries.
Actually, let's design for raw SQL:
We'll have a method query_all that runs SELECT * FROM table and returns a list of dictionaries? Or tuples?
We'll do tuples because it's more generic and then we can sort.
But the snapshot_loader must return the same order of columns as the SELECT *? That's not guaranteed.
We can have the snapshot_loader return the column order, and then we do:
actual = self.execute(f"SELECT {', '.join(column_names)} FROM {table_name}").fetchall()
But note: the table might have more columns? We are only comparing the ones in the snapshot.
Alternatively, we can have the snapshot be for the entire table and we do SELECT * and then we must have the same column order in the snapshot.
How about we store the snapshot with the column names and then when we query we use the same column names? That way we don't rely on the order of columns in the table.
We'll do:
snapshot = {
"table": "users",
"columns": ["id", "name", "email"],
"rows": [
[1, "Alice", "alice@example.com"],
[2, "Bob", "bob@example.com"]
]
}
Then in the test:
expected = snapshot_loader(snapshot_name) # returns the above dict for that snapshot.
actual = self.query_table(expected["table"], expected["columns"])
# Then sort by the entire row? Or by the first column? We can sort by the entire row (tuple) because the columns are in the same order.
assert sorted(expected["rows"]) == sorted(actual)
But note: the actual rows are tuples of the values in the order of expected["columns"].
This way we are only comparing the columns that are in the snapshot.
We can also have an option to ignore certain columns (like id if it's auto-increment and we don't care about the exact value). We can pass an ignore_columns list to assert_snapshot.
Let's adjust:
def assert_snapshot(self, table_name, snapshot_name, ignore_columns=None):
if ignore_columns is None:
ignore_columns = []
snapshot = self.snapshot_loader(table_name, snapshot_name)
# snapshot is a dict with 'columns' and 'rows'
# Remove the ignore_columns from the snapshot columns and adjust the rows accordingly.
# But note: the snapshot might have been recorded with the ignore_columns? We should have recorded the snapshot without them.
# Alternatively, we can filter the actual rows by the columns and then compare.
# We want to compare only the non-ignored columns.
# Let's get the indices of the columns to keep.
keep_indices = [i for i, col in enumerate(snapshot["columns"]) if col not in ignore_columns]
# Then for each row in snapshot["rows"], we take only the keep_indices.
expected_rows = [tuple(row[i] for i in keep_indices) for row in snapshot["rows"]]
# Now query the actual table with the same columns (the snapshot["columns"] minus the ignore_columns? Wait, we want to query only the kept columns? But the snapshot might have more columns? Actually, we are using the snapshot's column list to define what we are comparing.
# We want to compare the same set of columns as in the snapshot (except the ignored ones). So we query the table for the columns in the snapshot, then remove the ignored ones.
# Query the table for the columns in snapshot["columns"] (in that order) and then remove the ignored ones.
actual_rows = self.query_table(table_name, snapshot["columns"])
actual_rows = [tuple(row[i] for i in keep_indices) for row in actual_rows]
# Then sort and compare.
assert sorted(expected_rows) == sorted(actual_rows)
But note: the snapshot might have been taken with a different set of columns? We are using the snapshot's column list as the source of truth.
Alternatively, we can have the snapshot be a list of dictionaries? Then we can ignore keys easily.
Let's change the snapshot format to:
{
"table": "users",
"data": [
{"id": 1, "name": "Alice", "email": "alice@example.com"},
{"id": 2, "name": "Bob", "email": "bob@example.com"}
]
}
Then we can do:
expected = self.snapshot_loader(table_name, snapshot_name)["data"]
actual = self.query_table_as_dict(table_name, snapshot_columns) # but we need the columns? Actually, we can get the keys from the first expected dict.
# But the actual query might return more columns? We only want the ones in the expected.
# Alternatively, we can have the snapshot specify the columns? Or we can get the keys from the first expected row.
expected_columns = expected[0].keys() if expected else []
# Then query the table for those columns? But what if the table has more? We only want the ones in expected_columns.
# We can do:
actual = self.query_table_as_dict(table_name, expected_columns)
# Then remove the ignored columns from both expected and actual.
# But note: the snapshot might have been taken with a subset of columns? That's okay.
# Then we can compare:
# Convert each dict to a tuple of values in the order of expected_columns (sorted? or fixed order). We need a fixed order.
# We can use the order of expected_columns (which is the order of keys in the first dict? but dicts are ordered in Python 3.7+ by insertion order). However, the snapshot might have been created with a different order? We can store the column order in the snapshot.
# Given the complexity, let's stick to the list of tuples and specify the column order in the snapshot.
We'll go back to the list of tuples with a separate column list.
But note: the snapshot_loader must return the column order. We can have the snapshot file store the column order.
Let's assume the snapshot is stored as:
{
"table": "users",
"columns": ["id", "name", "email"],
"rows": [
[1, "Alice", "alice@example.com"],
[2, "Bob", "bob@example.com"]
]
}
Then we have a fixed column order.
Now, the query_table method:
def query_table(self, table_name, columns):
# Build the query: SELECT col1, col2, ... FROM table_name
# Execute and return a list of tuples (each tuple is a row in the order of `columns`)
Then we can filter the columns as needed.
However, note: the snapshot might have been taken with a different set of columns than the current table? We are only comparing the columns that are in the snapshot.
This is flexible.
Let's code accordingly.
-
Implementation Details:
We'll use SQLAlchemy for the database operations because it's Python and widely used.
Steps for setup:
from sqlalchemy import create_engine, text
from sqlalchemy.exc import ProgrammingError
admin_engine = create_engine(admin_database_url)
with admin_engine.connect() as conn:
conn.execute(text(f"CREATE DATABASE {self.database_name}"))
conn.commit()
test_engine = create_engine(self.database_url)
self.schema_creator(test_engine) # This should create all tables.
Then for fixture_loader:
def fixture_loader(engine, fixture_name):
# Load the fixture data into the database using the engine.
pass
Similarly, snapshot_loader:
def snapshot_loader(table_name, snapshot_name):
# Load the snapshot from a file (or a dictionary in code) and return (columns, rows)
pass
And query_table:
def query_table(self, table_name, columns):
with self.test_engine.connect() as conn:
result = conn.execute(text(f"SELECT {', '.join(columns)} FROM {table_name}"))
return [tuple(row) for row in result.fetchall()]
-
Putting it together:
We'll design the harness to be used as a context manager.
However, note: we are creating two engines (admin and test). We need to dispose of them.
Let's adjust:
class RepositoryTestHarness:
def __init__(self, admin_database_url, test_database_url_template, schema_creator, fixture_loader, snapshot_loader):
self.admin_database_url = admin_database_url
self.test_database_url_template = test_database_url_template
self.schema_creator = schema_creator
self.fixture_loader = fixture_loader
self.snapshot_loader = snapshot_loader
self.database_name = None
self.test_database_url = None
self.test_engine = None
def setup(self):
self.database_name = f"test_{uuid.uuid4().hex}"
self.test_database_url = self.test_database_url_template.format(database_name=self.database_name)
# Create the database using the admin connection.
admin_engine = create_engine(self.admin_database_url)
with admin_engine.connect() as conn:
conn.execute(text(f"CREATE DATABASE {self.database_name}"))
conn.commit()
admin_engine.dispose()
# Now create the test engine and create the schema.
self.test_engine = create_engine(self.test_database_url)
self.schema_creator(self.test_engine)
def teardown(self):
if self.test_engine:
self.test_engine.dispose()
# Drop the database using the admin connection.
admin_engine = create_engine(self.admin_database_url)
with admin_engine.connect() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS {self.database_name}"))
conn.commit()
admin_engine.dispose()
def __enter__(self):
self.setup()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.teardown()
def load_fixtures(self, fixture_names):
for fixture_name in fixture_names:
self.fixture_loader(self.test_engine, fixture_name)
def assert_snapshot(self, table_name, snapshot_name, ignore_columns=None):
if ignore_columns is None:
ignore_columns = []
snapshot = self.snapshot_loader(table_name, snapshot_name)
# snapshot is a dict with 'columns' and 'rows'
# Determine the columns to keep (remove ignored ones)
keep_indices = [i for i, col in enumerate(snapshot["columns"]) if col not in ignore_columns]
# Prepare expected rows (as tuples of kept columns)
expected_rows = [tuple(row[i] for i in keep_indices) for row in snapshot["rows"]]
# Query the actual table for the columns in the snapshot (in the same order) and then keep only the kept columns.
actual_rows = self.query_table(table_name, snapshot["columns"])
actual_rows = [tuple(row[i] for i in keep_indices) for row in actual_rows]
# Sort and compare
assert sorted(expected_rows) == sorted(actual_rows)
def query_table(self, table_name, columns):
with self.test_engine.connect() as conn:
# If columns is empty, we do SELECT *? But we are using the snapshot's columns, so it should not be empty.
if not columns:
# We can do SELECT * but then we don't know the order? We can get the column names from the table? But we don't have the order.
# So we require the snapshot to specify the columns.
raise ValueError("Columns must be provided for snapshot comparison.")
query = text(f"SELECT {', '.join(columns)} FROM {table_name}")
result = conn.execute(query)
return [tuple(row) for row in result.fetchall()]
Given the complexity and the fact that we are designing a harness, we'll stick to the above.
Let's write the code accordingly.
However, note: the above design uses SQLAlchemy. What if we are not using SQLAlchemy? We can make the harness work with any DB-API connection? But we are using SQLAlchemy's text and create_engine.
We can make the harness take an engine factory? Or we can make the schema_creator, fixture_loader, and snapshot_loader take a connection (or cursor) instead of an engine.
Let's adjust:
def schema_creator(conn):
# conn is a DB-API connection (or SQLAlchemy connection)
# Run the DDL to create tables.
Then in setup:
self.test_engine = create_engine(self.test_database_url)
with self.test_engine.connect() as conn:
self.schema_creator(conn)
conn.commit()
Similarly, fixture_loader would take a connection.
But then the snapshot_loader doesn't need a connection? It just loads from a file.
And `query_table` would also use a connection.
This way we are not tied to SQLAlchemy for the schema and fixture loading? But we are using SQLAlchemy for engine creation.
Alternatively, we can use the DB-API directly? But we want to support multiple databases.
We'll stick with SQLAlchemy for simplicity.
11. Final Design:
We'll use SQLAlchemy for engine and connections.
The user must provide:
admin_database_url: for creating/dropping the test database.
test_database_url_template: with {database_name} placeholder.
schema_creator(engine): function that creates the schema.
fixture_loader(engine, fixture_name): function that loads a fixture (by name) into the database.
snapshot_loader(table_name, snapshot_name): function that returns a dict with 'columns' and 'rows'.
The harness will:
- Create a unique database name.
- Use admin_database_url to create the database.
- Use test_database_url_template to form the test database URL.
- Create an engine for the test database and run schema_creator.
- Provide methods to load fixtures and assert snapshots.
- Drop the database on teardown.
We'll also provide a method to get the test database URL (for the repository to connect).
12. Code:
Let's write the code accordingly.
Note: We are using SQLAlchemy 1.4 or 2.0? We'll use the 1.4 style with `text` and `create_engine`.
We'll also handle the case when the database already exists? We are creating a unique name, so it shouldn't.
But in teardown, we do DROP DATABASE IF EXISTS.
Let's code:
(We'll write the class in a file, say `repository_test_harness.py`)
We'll also write example implementations for the required functions (schema_creator, etc.) in the docstring.
13. Improvements:
- We might want to run the schema_creator in a transaction and rollback if it fails? But then the database might be left half-created. We can drop the database in case of error in setup.
- We can also allow the user to pass an existing engine for the admin database? But we are creating our own.
Given the time, we'll leave it as is.
Let's code the harness.
I'll design a comprehensive repository testing harness that uses ephemeral databases, fixture seeds, and snapshot assertions for reliable, isolated testing.
Architecture Overview
"""
Repository Testing Harness
Features:
1. Ephemeral database lifecycle (create/drop per test)
2. Fixture-based data seeding with dependency resolution
3. Snapshot comparisons for state validation
4. Support for multiple database types (PostgreSQL, SQLite, MySQL)
5. Transactional safety and parallel test execution
"""
from __future__ import annotations
import uuid
import json
import hashlib
from pathlib import Path
from typing import Any, Dict, List, Optional, Type, Iterator
from contextlib import contextmanager
from dataclasses import dataclass, asdict
from datetime import datetime
from abc import ABC, abstractmethod
# Database abstraction
import sqlalchemy as sa
from sqlalchemy import create_engine, MetaData, Table, select, text
from sqlalchemy.orm import Session, declarative_base
from sqlalchemy.pool import QueuePool
# Type aliases
DatabaseURL = str
SnapshotDict = Dict[str, Any]
FixtureSet = Dict[str, List[Dict[str, Any]]]
Core Components
1. Ephemeral Database Manager
class EphemeralDatabaseManager:
"""Manages temporary database lifecycle with unique naming."""
def __init__(
self,
base_url: DatabaseURL,
dialect: str = "postgresql",
template_db: Optional[str] = None
):
self.base_url = base_url
self.dialect = dialect
self.template_db = template_db
self._databases_created: List[str] = []
def create_database(self) -> str:
"""Create a new isolated database with UUID name."""
db_name = f"test_{uuid.uuid4().hex[:12]}"
engine = create_engine(self._get_admin_url())
with engine.connect() as conn:
if self.dialect == "postgresql":
conn.execute(
text(f"CREATE DATABASE {db_name} "
f"TEMPLATE {self.template_db} " if self.template_db else ""
f"ENCODING 'UTF8'")
)
elif self.dialect == "sqlite":
# SQLite uses file-based databases
db_path = Path(f"/tmp/{db_name}.db")
db_path.touch()
db_name = str(db_path)
else:
conn.execute(text(f"CREATE DATABASE {db_name}"))
conn.commit()
self._databases_created.append(db_name)
return db_name
def drop_database(self, db_name: str) -> None:
"""Force drop database, handling connections."""
engine = create_engine(self._get_admin_url())
with engine.connect() as conn:
# Terminate existing connections (PostgreSQL)
if self.dialect == "postgresql":
conn.execute(
text(f"""
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = '{db_name}'
AND pid <> pg_backend_pid();
""")
)
conn.execute(text(f"DROP DATABASE IF EXISTS {db_name}"))
conn.commit()
if db_name in self._databases_created:
self._databases_created.remove(db_name)
def get_test_url(self, db_name: str) -> str:
"""Get full connection URL for test database."""
if self.dialect == "sqlite":
return f"sqlite:///{db_name}"
return self.base_url.replace("/postgres", f"/{db_name}")
def _get_admin_url(self) -> str:
"""Get URL for admin database (postgres/main)."""
if self.dialect == "postgresql":
return self.base_url.replace("/postgres", "/postgres")
return self.base_url
def cleanup_all(self) -> None:
"""Drop all databases created by this manager."""
for db_name in self._databases_created[:]:
try:
self.drop_database(db_name)
except Exception as e:
print(f"Failed to drop database {db_name}: {e}")
def __enter__(self) -> EphemeralDatabaseManager:
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.cleanup_all()
2. Fixture System with Dependency Resolution
@dataclass
class Fixture:
"""Represents a seeded dataset with dependencies."""
name: str
table_name: str
data: List[Dict[str, Any]]
dependencies: List[str] = None
transformations: List[Dict[str, Any]] = None # For data manipulation
def __post_init__(self):
if self.dependencies is None:
self.dependencies = []
if self.transformations is None:
self.transformations = []
class FixtureRegistry:
"""Registry for fixtures with dependency resolution."""
def __init__(self):
self._fixtures: Dict[str, Fixture] = {}
def register(self, fixture: Fixture) -> None:
"""Register a fixture."""
self._fixtures[fixture.name] = fixture
def get_resolution_order(self, fixture_names: List[str]) -> List[str]:
"""Topological sort of fixtures based on dependencies."""
# Simple DFS topological sort
visited = set()
temp_mark = set()
order = []
def visit(name: str) -> None:
if name in temp_mark:
raise ValueError(f"Circular dependency detected: {name}")
if name not in visited:
temp_mark.add(name)
fixture = self._fixtures.get(name)
if fixture:
for dep in fixture.dependencies:
visit(dep)
temp_mark.remove(name)
visited.add(name)
order.append(name)
for name in fixture_names:
visit(name)
return order
def load_fixtures(
self,
engine: sa.engine.Engine,
fixture_names: List[str]
) -> None:
"""Load fixtures in dependency order."""
order = self.get_resolution_order(fixture_names)
with Session(engine) as session:
for name in order:
fixture = self._fixtures[name]
self._insert_fixture_data(session, fixture)
session.commit()
def _insert_fixture_data(
self,
session: Session,
fixture: Fixture
) -> None:
"""Insert fixture data with transformations."""
metadata = MetaData()
table = Table(fixture.table_name, metadata, autoload_with=session.bind)
for row in fixture.data:
# Apply transformations (e.g., reference resolution)
transformed_row = self._apply_transformations(row, fixture.transformations)
session.execute(table.insert().values(**transformed_row))
def _apply_transformations(
self,
row: Dict[str, Any],
transformations: List[Dict[str, Any]]
) -> Dict[str, Any]:
"""Apply data transformations (e.g., foreign key resolution)."""
result = row.copy()
for transform in transformations:
if transform["type"] == "reference":
# Replace placeholder with actual ID from referenced table
ref_fixture = self._fixtures[transform["fixture"]]
ref_table = ref_fixture.table_name
ref_column = transform["column"]
placeholder = transform["placeholder"]
# Find referenced value
for ref_row in ref_fixture.data:
if ref_row.get(ref_column) == row.get(placeholder):
result[transform["target_column"]] = ref_row["id"]
break
return result
3. Snapshot System
class SnapshotComparator:
"""Compares database state against stored snapshots."""
def __init__(
self,
snapshot_dir: Path,
ignore_columns: List[str] = None,
tolerance: float = 0.0 # For float comparisons
):
self.snapshot_dir = Path(snapshot_dir)
self.snapshot_dir.mkdir(parents=True, exist_ok=True)
self.ignore_columns = ignore_columns or ["id", "created_at", "updated_at"]
self.tolerance = tolerance
def capture_snapshot(
self,
engine: sa.engine.Engine,
table_names: List[str],
snapshot_name: str
) -> SnapshotDict:
"""Capture current database state as snapshot."""
snapshot = {
"metadata": {
"timestamp": datetime.utcnow().isoformat(),
"tables": table_names,
"schema_hash": self._hash_schema(engine)
},
"data": {}
}
with engine.connect() as conn:
for table_name in table_names:
result = conn.execute(text(f"SELECT * FROM {table_name}"))
rows = [dict(row._mapping) for row in result]
# Remove ignored columns
for row in rows:
for col in self.ignore_columns:
row.pop(col, None)
snapshot["data"][table_name] = sorted(
rows,
key=lambda x: json.dumps(x, sort_keys=True)
)
# Save snapshot
snapshot_path = self._get_snapshot_path(snapshot_name)
with open(snapshot_path, 'w') as f:
json.dump(snapshot, f, indent=2, default=str)
return snapshot
def assert_match(
self,
engine: sa.engine.Engine,
table_names: List[str],
snapshot_name: str,
update_snapshot: bool = False
) -> None:
"""Assert current state matches snapshot."""
current = self._capture_current_state(engine, table_names)
snapshot_path = self._get_snapshot_path(snapshot_name)
if update_snapshot or not snapshot_path.exists():
self._save_snapshot(current, snapshot_path)
return
with open(snapshot_path) as f:
expected = json.load(f)
self._compare_snapshots(expected, current)
def _capture_current_state(
self,
engine: sa.engine.Engine,
table_names: List[str]
) -> SnapshotDict:
"""Capture current database state."""
state = {"metadata": {}, "data": {}}
with engine.connect() as conn:
for table_name in table_names:
result = conn.execute(text(f"SELECT * FROM {table_name}"))
rows = [dict(row._mapping) for row in result]
for row in rows:
for col in self.ignore_columns:
row.pop(col, None)
state["data"][table_name] = sorted(
rows,
key=lambda x: json.dumps(x, sort_keys=True)
)
state["metadata"]["schema_hash"] = self._hash_schema(engine)
return state
def _compare_snapshots(
self,
expected: SnapshotDict,
actual: SnapshotDict
) -> None:
"""Deep compare two snapshots with tolerance for numeric values."""
# Compare schema hash first
if expected["metadata"]["schema_hash"] != actual["metadata"]["schema_hash"]:
raise AssertionError(
f"Schema mismatch! Expected: {expected['metadata']['schema_hash']}, "
f"Actual: {actual['metadata']['schema_hash']}"
)
# Compare tables
expected_tables = set(expected["data"].keys())
actual_tables = set(actual["data"].keys())
if expected_tables != actual_tables:
raise AssertionError(
f"Table mismatch! Expected tables: {expected_tables}, "
f"Actual tables: {actual_tables}"
)
for table_name in expected_tables:
exp_rows = expected["data"][table_name]
act_rows = actual["data"][table_name]
if len(exp_rows) != len(act_rows):
raise AssertionError(
f"Row count mismatch in table '{table_name}'. "
f"Expected: {len(exp_rows)}, Actual: {len(act_rows)}"
)
for i, (exp_row, act_row) in enumerate(zip(exp_rows, act_rows)):
self._compare_rows(exp_row, act_row, table_name, i)
def _compare_rows(
self,
expected: Dict[str, Any],
actual: Dict[str, Any],
table_name: str,
row_index: int
) -> None:
"""Compare two rows with numeric tolerance."""
exp_keys = set(expected.keys())
act_keys = set(actual.keys())
if exp_keys != act_keys:
raise AssertionError(
f"Column mismatch in table '{table_name}' row {row_index}. "
f"Expected columns: {exp_keys}, Actual: {act_keys}"
)
for key in exp_keys:
exp_val = expected[key]
act_val = actual[key]
# Handle numeric tolerance
if isinstance(exp_val, (int, float)) and isinstance(act_val, (int, float)):
if abs(exp_val - act_val) > self.tolerance:
raise AssertionError(
f"Value mismatch in table '{table_name}' row {row_index} "
f"column '{key}': Expected {exp_val}, Actual {act_val}"
)
elif exp_val != act_val:
raise AssertionError(
f"Value mismatch in table '{table_name}' row {row_index} "
f"column '{key}': Expected {exp_val}, Actual {act_val}"
)
def _hash_schema(self, engine: sa.engine.Engine) -> str:
"""Generate hash of database schema for validation."""
metadata = MetaData()
metadata.reflect(bind=engine)
schema_str = ""
for table in sorted(metadata.tables.values()):
columns = sorted([
f"{col.name}:{col.type}" for col in table.columns
])
schema_str += f"{table.name}:{','.join(columns)};"
return hashlib.sha256(schema_str.encode()).hexdigest()[:16]
def _get_snapshot_path(self, snapshot_name: str) -> Path:
"""Get path for snapshot file."""
return self.snapshot_dir / f"{snapshot_name}.json"
def _save_snapshot(self, snapshot: SnapshotDict, path: Path) -> None:
"""Save snapshot to file."""
with open(path, 'w') as f:
json.dump(snapshot, f, indent=2, default=str)
4. Main Test Harness
class RepositoryTestHarness:
"""
Main testing harness combining all components.
Usage:
harness = RepositoryTestHarness(
database_url="postgresql://user:pass@localhost/postgres",
dialect="postgresql",
model_base=Base, # SQLAlchemy declarative base
snapshot_dir="tests/snapshots"
)
with harness:
# Load fixtures
harness.load_fixtures(["users", "products"])
# Run repository operations
repo = UserRepository(harness.engine)
repo.create_user(name="Test", email="test@example.com")
# Assert state
harness.assert_snapshot(["users"], "after_user_created")
"""
def __init__(
self,
database_url: DatabaseURL,
dialect: str = "postgresql",
model_base: Optional[Type] = None,
snapshot_dir: str = "tests/snapshots",
template_db: Optional[str] = None,
fixture_registry: Optional[FixtureRegistry] = None
):
self.database_url = database_url
self.dialect = dialect
self.model_base = model_base
self.snapshot_dir = Path(snapshot_dir)
self.template_db = template_db
self.db_manager = EphemeralDatabaseManager(
base_url=database_url,
dialect=dialect,
template_db=template_db
)
self.fixture_registry = fixture_registry or FixtureRegistry()
self.snapshot_comparator = SnapshotComparator(
snapshot_dir=self.snapshot_dir,
ignore_columns=["id", "created_at", "updated_at"]
)
self._db_name: Optional[str] = None
self._engine: Optional[sa.engine.Engine] = None
def __enter__(self) -> RepositoryTestHarness:
self.setup()
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.teardown()
def setup(self) -> None:
"""Create ephemeral database and initialize schema."""
self._db_name = self.db_manager.create_database()
test_url = self.db_manager.get_test_url(self._db_name)
# Create engine with connection pool for parallel safety
self._engine = create_engine(
test_url,
poolclass=QueuePool,
pool_size=5,
max_overflow=10,
echo=False # Set to True for SQL logging
)
# Create schema if model base provided
if self.model_base:
self.model_base.metadata.create_all(self._engine)
def teardown(self) -> None:
"""Cleanup database."""
if self._engine:
self._engine.dispose()
self._engine = None
if self._db_name:
self.db_manager.drop_database(self._db_name)
self._db_name = None
@property
def engine(self) -> sa.engine.Engine:
"""Get database engine."""
if not self._engine:
raise RuntimeError("Harness not initialized. Use 'with' context.")
return self._engine
@property
def connection(self) -> sa.engine.Connection:
"""Get raw connection."""
return self.engine.connect()
def load_fixtures(self, fixture_names: List[str]) -> None:
"""Load fixtures by name with dependency resolution."""
self.fixture_registry.load_fixtures(self.engine, fixture_names)
def register_fixture(self, fixture: Fixture) -> None:
"""Register a fixture programmatically."""
self.fixture_registry.register(fixture)
def assert_snapshot(
self,
table_names: List[str],
snapshot_name: str,
update_snapshot: bool = False
) -> None:
"""Assert database state matches snapshot."""
self.snapshot_comparator.assert_match(
engine=self.engine,
table_names=table_names,
snapshot_name=snapshot_name,
update_snapshot=update_snapshot
)
def capture_snapshot(
self,
table_names: List[str],
snapshot_name: str
) -> SnapshotDict:
"""Capture and save new snapshot."""
return self.snapshot_comparator.capture_snapshot(
engine=self.engine,
table_names=table_names,
snapshot_name=snapshot_name
)
def execute_raw_sql(self, sql: str, **params) -> List[Dict[str, Any]]:
"""Execute raw SQL and return results as dictionaries."""
with self.engine.connect() as conn:
result = conn.execute(text(sql), params)
return [dict(row._mapping) for row in result]
def truncate_tables(self, table_names: List[str]) -> None:
"""Truncate tables (preserving schema)."""
with self.engine.begin() as conn:
for table in table_names:
conn.execute(text(f"TRUNCATE TABLE {table} RESTART IDENTITY CASCADE"))
5. Decorator for Test Methods
def with_ephemeral_db(
database_url: str,
dialect: str = "postgresql",
fixtures: List[str] = None,
snapshot_tables: List[str] = None,
snapshot_name: str = None,
template_db: str = None
):
"""
Decorator for test methods to automatically setup/teardown database.
Usage:
@with_ephemeral_db(
database_url="postgresql://localhost/test",
fixtures=["users"],
snapshot_tables=["users"],
snapshot_name="test_user_creation"
)
def test_user_creation(self, harness):
# Test logic here
user_repo.create(...)
harness.assert_snapshot() # Uses provided snapshot_name
"""
def decorator(test_func):
def wrapper(*args, **kwargs):
# Extract self from args (assuming method)
self = args[0] if args else None
harness = RepositoryTestHarness(
database_url=database_url,
dialect=dialect,
template_db=template_db,
snapshot_dir=getattr(self, 'snapshot_dir', 'tests/snapshots')
)
with harness:
if fixtures:
harness.load_fixtures(fixtures)
# Pass harness to test function
result = test_func(harness, *args, **kwargs)
if snapshot_tables and snapshot_name:
harness.assert_snapshot(snapshot_tables, snapshot_name)
return result
return wrapper
return decorator
6. Example Usage & Fixtures
# tests/fixtures/users.json
[
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"created_at": "2024-01-01T00:00:00"
},
{
"id": 2,
"name": "Jane Smith",
"email": "jane@example.com",
"created_at": "2024-01-02T00:00:00"
}
]
# tests/test_user_repository.py
class TestUserRepository:
snapshot_dir = "tests/snapshots"
def setup_fixture_registry(self):
"""Optional: programmatic fixture setup."""
registry = FixtureRegistry()
# Define products fixture that depends on users
products_fixture = Fixture(
name="products",
table_name="products",
data=[
{"id": 1, "name": "Widget", "price": 19.99, "owner_id": 1},
{"id": 2, "name": "Gadget", "price": 29.99, "owner_id": 2}
],
dependencies=["users"],
transformations=[
{
"type": "reference",
"fixture": "users",
"column": "id",
"placeholder": "owner_id",
"target_column": "owner_id"
}
]
)
registry.register(products_fixture)
return registry
@with_ephemeral_db(
database_url="postgresql://test:test@localhost/postgres",
fixtures=["users", "products"],
snapshot_tables=["users", "products"],
snapshot_name="initial_state"
)
def test_initial_state(self, harness):
"""Test initial state matches snapshot."""
# Snapshot comparison happens automatically via decorator
pass
def test_user_creation(self):
"""Manual harness usage."""
harness = RepositoryTestHarness(
database_url="postgresql://test:test@localhost/postgres",
snapshot_dir=self.snapshot_dir
)
with harness:
# Load only users fixture
harness.load_fixtures(["users"])
# Perform operations
repo = UserRepository(harness.engine)
repo.create_user(
name="New User",
email="new@example.com"
)
# Assert only users table changed
harness.assert_snapshot(
table_names=["users"],
snapshot_name="after_user_creation"
)
7. Pytest Integration
# conftest.py
import pytest
from pathlib import Path
@pytest.fixture(scope="function")
def db_harness(request) -> Iterator[RepositoryTestHarness]:
"""Pytest fixture for database harness."""
marker = request.node.get_closest_marker("db_config")
config = marker.kwargs if marker else {}
harness = RepositoryTestHarness(
database_url=config.get("database_url", "sqlite:///:memory:"),
dialect=config.get("dialect", "sqlite"),
snapshot_dir=Path(__file__).parent / "snapshots",
template_db=config.get("template_db")
)
# Load fixtures if specified
fixtures = config.get("fixtures", [])
if fixtures:
harness.load_fixtures(fixtures)
yield harness
harness.teardown()
# tests/test_example.py
def test_with_pytest_fixture(db_harness):
"""Use pytest fixture."""
db_harness.execute_raw_sql(
"INSERT INTO users (name, email) VALUES (:name, :email)",
name="Test", email="test@example.com"
)
db_harness.assert_snapshot(
table_names=["users"],
snapshot_name="pytest_example"
)
# Mark tests for specific database
@pytest.mark.db_config(
database_url="postgresql://test:test@localhost/postgres",
fixtures=["users"]
)
def test_postgres_specific(db_harness):
"""PostgreSQL-specific test."""
pass
Key Features:
- Ephemeral Databases: Each test gets a fresh, isolated database with unique naming
- Smart Fixtures:
- Dependency resolution (A → B → C loading order)
- Reference transformations (foreign key resolution)
- JSON/YAML fixture files or programmatic definitions
- Snapshot Assertions:
- Schema change detection
- Row count verification
- Value comparison with tolerance for floats
- Column whitelisting/blacklisting
- Parallel Safety: Connection pooling and unique database names
- Flexible Usage: Context manager, decorator, or pytest fixtures
- Database Support: PostgreSQL, SQLite, MySQL (SQLAlchemy dialects)
- Snapshot Management: Auto-update mode for evolving tests
Best Practices:
- Snapshot Storage: Store snapshots in version control (
tests/snapshots/)
- Fixture Design: Keep fixtures minimal and composable
- Selective Assertions: Only assert on relevant tables/columns
- Schema Evolution: When schema changes, update snapshots intentionally
- Parallel Testing: Use unique database names to avoid conflicts
- Cleanup: Always ensure databases are dropped (use context managers)
This harness provides a solid foundation for repository testing with strong isolation, repeatable fixtures, and visual snapshot diffs when tests fail.