pytest-sqlalchemy¶
SQLAlchemy related fixtures to handle connections and transactions with SQLAlchemy in tests.
Fixtures¶
This plugin provides the following fixtures which gives access to the SQLAlchemy objects of the same name.
engine The engine used to connect to the database. Scope is “module”.
connection An open connection to the database. Scope is “module”.
See Working with Engines and Connections on how to use these fixtures.
transaction A started transaction on the connection. Transaction will be rolled back. No Scope.
See Using Transactions on how to use this fixtures
dbsession A sqlalchemy session not bound to any model. No scope.
See Session Basics to learn about how to use sessions.
Usage¶
The fixtures can be used in your tests like any other Pytest Fixtures.
Example:
import pytest
from pytest_sqlalchemy import connection
def test_connection(connection):
# Do fancy stuff with the connection.
# Note you will not need to close the connection. This is done
# automatically when the scope (module) of the fixtures ends.
assert connection
Invoke¶
You need to provide the connection URL for the engine when invoking the pytest command:
pytest --sqlalchemy-connect-url="postgresql://scott:tiger@localhost:5432/mydatabase"
Or override the sqlalchemy_connect_url fixture on your conftest.py file:
@pytest.fixture(scope="session")
def sqlalchemy_connect_url():
return 'postgresql://scott:tiger@localhost:5432/mydatabase'
Development¶
To get going, in a checkout:
uv sync
You can then run the tests with:
uv run pytest
Changes¶
0.3.0 (16.04.2025)¶
Now targeting Python 3.9+, SQLAlchemy 1.4+ and pytest 8+.
Moved to uv for environment management and Github Actions for CI.
Testing against sqlite, MySQL and Postgres, with 100% line coverage.
Fully type annotated and checked with mypy.
Formatted with ruff.
Documentation moved to Sphinx and published on Read the Docs
0.2.1 (13.03.2018)¶
Fix behaviour under multiprocessing by recreating
Engineinstance.
0.2.0 (22.02.2018)¶
Feature release. Thanks to Sebastian Buczyński.
Added option to create the database on each run by using
sqlalchemy-utils.Added option to run tests on multiple dynamically created databases (
pytest-xdist) likepytest-djangodoes.
0.1.1 (22.09.2017)¶
Initial release.