jeancochrane / jeancochrane/pytest-flask-sqlalchemy

Detached instance errors - Instance is not bound to a session

Open
#27 2 comments 5 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
253
Forks
45
PR merge metrics
No merged PRs in 30d

Description

In a test suite that has nearly 2000 test, sometimes there are some tests failing because we get an DetachedInstance exception withing the test (after a call to a endpoint we want to test):

```
sqlalchemy.orm.exc.DetachedInstanceError: Instance is not bound to a Session; attribute refresh operation cannot proceed (Background on this error at: http://sqlalche.me/e/bhk3)

+.venv/lib/python3.6/site-packages/sqlalchemy/orm/loading.py:915: DetachedInstanceError
```

This bug is unpredictible, doesn't happen when executing one test alone and when using IPDB before the call to the endpoint it wouldn't happen.
After investigation, we realized that in some rare case, the db_session is closed by flask, so I guess that sometime this package fails to block a db_session closing.

Locally we got able to avoid it by removing the sqlalchemy shutdown_session function (which is set by flask-sqlalchemy) from app.teardown_appcontext_funcs and running it at the end of each test.

It's hard to reproduce, but here are some hints that I got able to spot:
It happens only in a test when we fetch an object, make the call to the endpoint and then try to access the attribute of the object.
Needs to be multiple test running, running only one doesn't cause any problem.
Most of the case, the test before validate that an exception has been raised and handled within the tested endpoint.
It happens more in a test that follows a test which is parametrized, by example:
`@pytest.mark.parametrize('expected_status', [429, 503, 504])`

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.