pytest-flask-sqlalchemy

raw JSON →
1.1.0 verified Fri May 01 auth: no python

A pytest plugin that provides fixtures to preserve test isolation in Flask-SQLAlchemy by using database transactions. It simplifies testing Flask applications with SQLAlchemy by allowing tests to roll back changes automatically. Current version is 1.1.0, with a release cadence of irregular minor updates.

pip install pytest-flask-sqlalchemy
error ImportError: cannot import name 'pytest_flask_sqlalchemy' from 'pytest_flask_sqlalchemy'
cause Incorrect import path. Some users try to import from a submodule that doesn't exist.
fix
Use 'import pytest_flask_sqlalchemy' (the module itself provides fixtures).
error pytest.PytestUnknownMarkWarning: Unknown pytest.mark.flask_sqlalchemy - is this a typo?
cause Plugin does not provide a mark; users mistakenly use a mark that doesn't exist.
fix
Remove @pytest.mark.flask_sqlalchemy from tests; plugin works implicitly via conftest.
error AttributeError: module 'pytest_flask_sqlalchemy' has no attribute 'Fixtures'
cause Trying to access a non-existent class or fixture directly.
fix
Fixtures are automatically available (e.g., 'db_session'), no need to import them explicitly.
breaking Requires Flask-SQLAlchemy >=2.5 and SQLAlchemy >=1.3; incompatible with SQLAlchemy <1.3 and Flask-SQLAlchemy <2.5.
fix Update dependencies: pip install --upgrade flask-sqlalchemy sqlalchemy
breaking Drop of Python 3.6 support in v1.1.0. Python 3.7+ required.
fix Use Python 3.7 or later.
deprecated pytest <6.0.1 is no longer supported as of v1.1.0.
fix Upgrade pytest to >=6.0.1.
gotcha The plugin uses a transaction boundary per test; do not manually call db.session.commit() without rolling back, else test isolation may break.
fix Use db.session.rollback() or rely on plugin auto-rollback. Avoid explicit commit in tests.

Basic setup with custom app and db fixtures; plugin ensures transaction rollback after each test.

import pytest

@pytest.fixture
def app():
    from myapp import create_app
    app = create_app()
    app.config['TESTING'] = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
    return app

@pytest.fixture
def db(app):
    from myapp import db
    db.init_app(app)
    with app.app_context():
        db.create_all()
    yield db
    db.drop_all()

def test_something(db):
    # db.session is managed by plugin
    assert True