[Answered ]-Why does Django/Postgres appear to save but doesn't, gives 'connection already closed'?

1👍

The error "psycopg2.InterfaceError: connection already closed" appears whenever there’s an error in the code being unit tested before it gets to the assertion check in the test. It’s not a psycopg2 error, per se. A non-intuitive message, to say the least.

I’m open to suggestions on how to do unit testing in Django in which such errors are exposed and their location given in the source code, not just in the tests. I found them by process of elimination: commenting out tests and stepping through code with pdb.

My test classes are all subclassed from django.test.TestCase since they query Models in places. From the django unit testing docs:

If your tests rely on database access such as creating or querying
models, be sure to create your test classes as subclasses of
django.test.TestCase rather than unittest.TestCase.

Using unittest.TestCase avoids the cost of running each test in a
transaction and flushing the database, but if your tests interact with
the database their behavior will vary based on the order that the test
runner executes them. This can lead to unit tests that pass when run
in isolation but fail when run in a suite.

👤Ron

Leave a comment