Introduction One of the first obstacles a developer faces when starting a project is setting up unit tests and establishing a basic set of unit tests. In projects that use databases, combining migrations with automated tests adds complexity. In this article, we present a practical approach to performing function-level migrations using SQLAlchemy, Alembic and Pytest, with recommendations designed for professional teams like those at Q2BSTUDIO.
Concept of function-level migrations Function-level migrations consist of organizing schema or data changes into small units associated with specific functions or features. Instead of having monolithic migrations that cover many changes, each migration can be a function or a file containing specific upgrade and downgrade operations. This facilitates isolated testing, code reviews and reverting specific changes in production.
Setting up Alembic and SQLAlchemy Alembic integrates with SQLAlchemy through an env.py and a versions folder where revisions are stored. A common workflow is to generate revisions with alembic revision --autogenerate -m revision_message and then edit the files to turn automatic changes into reusable functions. It is advisable to keep migration utilities in separate modules so that migration functions can be imported from unit tests and executed in a controlled manner.
Pattern for migration functions A useful practice is to define two clear functions in each migration file, upgrade and downgrade, that delegate to business functions described in a migrations_helpers module. For example, encapsulating table creation, column addition or data transformations in small functions that can be called by both Alembic and unit tests. This makes it easier to validate the effect of the migration without having to apply the entire chain of revisions.
Testing migrations with Pytest To test migrations, the usual approach is to create Pytest fixtures that create a temporary database, preferably one that replicates the production engine. For fast unit tests, sqlite:///:memory: can be used with limitations, or ephemeral containers with PostgreSQL or MySQL can be used for greater fidelity. An example fixture creates an engine with create_engine, a session with sessionmaker and returns an isolated session. In tests, the migration function can be applied directly or alembic upgrade head can be run programmatically using alembic.config and alembic.command.
Running migrations from tests There are two strategies: running the migration through the Alembic API to simulate the real deployment flow, or importing and running the upgrade function directly for unit tests on a controlled transaction. The second strategy is faster and allows precise assertions about the state of the database after the migration. For integration tests, it is advisable to apply alembic upgrade head on a temporary database and then run the integration tests.
Transaction handling and isolation To keep tests clean, use nested transactions with session.begin_nested and rollback at the end of the test. Setting expire_on_commit to false helps avoid unexpected ORM object behavior after intermediate commits. In databases that do not fully support DDL transactions, consider creating and destroying entire schemas or databases per test.
Data and transformation testing Many migrations not only modify the schema but also transform data. To verify these transformations, create fixtures with representative sample data and then invoke the migration function. Validate that the new fields contain the expected values, that business rules were applied correctly and that critical queries still work. Automating these checks reduces risk in production deployments.
Continuous integration and deployment In CI/CD pipelines, automate steps to install dependencies, run migrations on a staging database and launch the test suite with Pytest. If you use cloud services like AWS or Azure, integrate stages that launch temporary resources in those environments or use emulators and containers. Applying migrations in staging before production and having specific regression tests for migrations reduces incidents in hot deployments.
Advanced tools and recommendations For more realistic tests, consider testcontainers or similar frameworks that spin up real PostgreSQL or MySQL instances during testing. Use linters and automated reviews for migration files, document each migration function and maintain a clear naming strategy for versions. Keep rollback utilities and post-migration verification scripts.
Best practices Keep migrations small and focused, write tests that cover both structure and data, use reproducible fixtures and automate the execution of Alembic from test code when appropriate. Document each migration and maintain a testing policy that includes migrations in the CI/CD flow.
Why trust Q2BSTUDIO Q2BSTUDIO is a software development company specialized in custom applications and custom software. Our teams combine expertise in artificial intelligence and AI for businesses, cybersecurity, AWS and Azure cloud services and business intelligence services to offer complete solutions. We implement robust migration and testing practices that include AI agents, Power BI for visualization and secure cloud pipelines.
Key services of Q2BSTUDIO We offer custom application development, artificial intelligence consulting, AI agent integration, cybersecurity solutions, deployment on AWS and Azure cloud services, and business intelligence projects with Power BI. Our approach includes automated migration testing, data validation and controlled deployments to minimize risks in production.
Summary and next steps Implementing function-level migrations with SQLAlchemy, Alembic and Pytest improves the traceability and testability of database changes. Combine reusable migration functions with test fixtures and temporary environments to ensure quality. If you need help designing a migration flow, automating unit tests or deploying cloud solutions with AWS and Azure cloud services, the Q2BSTUDIO team can support you throughout the entire cycle, from custom software to artificial intelligence and cybersecurity solutions.



