pytest-alembic
pytest-alembic is a pytest plugin designed to verify Alembic database migrations. It provides fixtures and test functions to ensure that migrations can be applied and reverted correctly, that the database schema remains consistent, and that the migration history is valid. The library is actively maintained, with frequent minor releases addressing compatibility and bug fixes, typically on a monthly or bi-monthly basis.
Warnings
- breaking Older versions of `pytest-alembic` (specifically prior to `0.11.0`) have fixture definition incompatibilities when used with `pytest` version `8.x.x` or higher.
- gotcha When using `pyproject.toml` for Alembic configuration (instead of `alembic.ini`), versions of `pytest-alembic` prior to `0.12.1` may not correctly parse the configuration.
- gotcha Early versions of `pytest-alembic` might have compatibility issues with SQLAlchemy 2.0's new API. While general support exists, specific edge cases could arise.
- gotcha In versions prior to `0.12.0`, `pytest-alembic` might not correctly handle branched revisions, potentially leading to errors when upgrading a database with a complex, branched migration history.
- deprecated The `--pytest-alembic-tests-folder` CLI option (or its programmatic equivalent) was removed/refactored in `v0.10.2`. Relying on it in older test setups may cause issues.
Install
-
pip install pytest-alembic
Imports
- Config
from alembic.config import Config
- create_engine
from sqlalchemy import create_engine
- AlembicRunner
from pytest_alembic.runner import AlembicRunner
- create_alembic_fixture
from pytest_alembic.util import create_alembic_fixture
Quickstart
import pytest
from alembic.config import Config
from sqlalchemy import create_engine
from pytest_alembic.runner import AlembicRunner
# conftest.py
# This file should be in your tests directory or root project directory
@pytest.fixture(scope="session")
def alembic_config():
"""Override this fixture to provide your alembic configuration."""
# Adjust 'alembic.ini' and 'migrations' to your project's paths
config = Config("alembic.ini")
config.set_main_option("script_location", "migrations")
return config
@pytest.fixture(scope="session")
def alembic_engine(alembic_config):
"""Override this fixture to provide your database engine."""
# Use an in-memory SQLite database for quick tests or a separate test database
# For real applications, consider a dedicated test database service.
return create_engine("sqlite:///:memory/")
# test_migrations.py
# This file would be in your tests directory
def test_alembic_history_consistent(alembic_runner: AlembicRunner):
"""Verify that the migration history is linear and consistent."""
alembic_runner.check_current_revision_is_linear()
def test_all_migrations_can_upgrade_and_downgrade(alembic_runner: AlembicRunner):
"""Verify that all migrations can be applied and reverted successfully."""
alembic_runner.upgrade_downgrade()