jeancochrane / pytest-flask-sqlalchemy

A pytest plugin for preserving test isolation in Flask-SQLAlchemy using database transactions.
MIT License
255 stars 45 forks source link

Disable session.remove on flask_sqlalchemy.SQLAlchemy #18

Open janbuchar opened 5 years ago

janbuchar commented 5 years ago

With Flask-SQLAlchemy 2.4.0, SQLAlchemy 1.3.3 and pytest-flask-sqlalchemy 1.0.2, I sometimes (non-deterministically) got DetachedInstanceError because the session instantiated in the flask_sqlalchemy.SQLAlchemy extension already terminated the session (https://github.com/pallets/flask-sqlalchemy/blob/master/flask_sqlalchemy/__init__.py#L849).

Adding something like this to conftest.py helped.

mocker.patch.object(sqla.session, "remove", lambda: None)
jeancochrane commented 5 years ago

Sorry it took me so long to get to this @Teyras! That seems like a pretty nasty race condition. I'd welcome a PR making this change if you've had some success with it. We'll have to be careful to preserve the remove() function somewhere, since we use it ourselves to tear down the session:

https://github.com/jeancochrane/pytest-flask-sqlalchemy/blob/7cb57c0c4e3ab18f1bf84f15769c4ece2fecee9e/pytest_flask_sqlalchemy/fixtures.py#L75-L78

But we should probably be able to get away with preserving the method the same way we do close(), commit(), and rollback():

https://github.com/jeancochrane/pytest-flask-sqlalchemy/blob/7cb57c0c4e3ab18f1bf84f15769c4ece2fecee9e/pytest_flask_sqlalchemy/fixtures.py#L130-L133