pytest-alembic

0.12.1 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

To get started, define `alembic_config` and `alembic_engine` fixtures in your `conftest.py`. The `alembic_config` fixture should point to your Alembic configuration file and script location. The `alembic_engine` fixture should return a SQLAlchemy engine configured for a test database. Once these are set, you can write pytest functions that use the `alembic_runner` fixture to interact with and test your migrations. Run pytest with the plugin installed, and it will automatically discover tests.

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()

view raw JSON →