SQLAlchemy: "catching classes that do not inherit from BaseException is not allowed" when testing in Pytest

Viewed 866

Recently, when running my tests in Pytest, I started to get a strange warning at the end of the test results; many many iterations of the following:

Exception ignored in: <function _ConnectionRecord.checkout.<locals>.<lambda> at 0x10eea07a0>
Traceback (most recent call last):
  File "/Users/username/appdev/scattr-api/venv/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 503, in <lambda>
  File "/Users/username/appdev/scattr-api/venv/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 710, in _finalize_fairy
  File "/Users/username/appdev/scattr-api/venv/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 528, in checkin
  File "/Users/username/appdev/scattr-api/venv/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 387, in _return_conn
  File "/Users/username/appdev/scattr-api/venv/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 106, in _do_return_conn
TypeError: catching classes that do not inherit from BaseException is not allowed

This started happening recently, regardless of whether tests pass or not. I don't understand why this warning started showing up, or what it means that it's "ignored," so I'm not sure what I should be doing about it, if anything. I haven't noticed any problems when running my actual application, it's just something that's happened when running the tests.

The fact that the last function in traceback is "_do_return_conn" makes me think it's something about the connection pool, but I'm still not sure how to make sense of it...

1 Answers

I determined that the issue arises from not explicitly closing a connection in pytest tests.

I'd been using custom connection to look up values in the database in the tests (to make sure correct values were inserted) and it's if this wasn't explicitly closed at the end that this cryptic error message appeared.

SQLAlchemy has garbage collection which will eventually return connections to the pool even if they're not explicitly closed. However, in the context of running pytest, this doesn't have time to happen during the duration of the test, resulting in the cryptic error message.

Related