SQLAlchemy related fixtures to handle connections and transactions with SQLAlchemy in tests.
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.
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
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'
To get going, in a checkout:
uv sync
You can then run the tests with:
uv run pytest