Open stabacco opened 2 years ago
Yeap, create_scoped_session
method has been replaced by _make_scoped_session
, see https://github.com/pallets-eco/flask-sqlalchemy/blob/2908083d0d0c918e1adce396d351da6fa3112692/src/flask_sqlalchemy/extension.py#L336, so that would need to be updated to that.
I believe a solution is to use SQLAlchemy directly:
from sqlalchemy.orm import sessionmaker, scoped_session
db.session = scoped_session(session_factory=sessionmaker(bind=db_connection))
Thanks @Midnighter ! If folks are looking for a workaround for now, this is the conftest.py I'm using with latest flask-sqlalchemy for similar purposes - not as comprehensive as this package, but works for a fake session:
https://github.com/pamelafox/flask-surveys-container-app/blob/main/backend/tests/conftest.py
I'm not sure exactly how this library works, but the way config, engines, and the session are managed did change significantly in Flask-SQLAlchemy 3.0. Just monkeypatching db.session
as suggested above might work for simple cases, but I have a feeling it will fail in weird ways.
The following code sets up transactions for each bind, then rolls them back after each test. This supports multiple binds, in case one request queries multiple databases.
@pytest.fixture
def db(app):
with app.app_context():
engines = db.engines
cleanup = []
for key, engine in engines.items():
c = engine.connect()
t = c.begin()
engines[key] = c
cleanup.append((key, engine, c, t))
yield db
for key, engine, c, t in cleanup:
t.rollback()
c.close()
engines[key] = engine
I'm not sure if this works in more complex situations, but it works in my project. https://github.com/Teachesworkspace/pytest-flask-sqlalchemy/commit/d6ae3d9e9292f2a61a3aa5bc988114a6ce36bf56
If anyone was like me and had problems migrating pytest from SQLAlchemy <= 1.4 to SQLAlchemy 2.0, I created a minimum working example and was able to backtrack through my own test suite to find out why transactional tests weren't working.
Looks like there has been a new major release for flask-sqlalchemy https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/changes/#version-3-0-0 and they have broken backwards compatibility in a few places.
For example :
Also the
create_scoped_session
method seems to have gone.