vendredi 11 septembre 2020

Django 3.1 not closing postgres db connection after tests

The following method is called as part of a test (the test tries to find an external api call in the DB and if it can't find it it will do a real API call)

    def _ask_transliterate(self, content):
        found = APITransliteration.objects.filter(
            source_text=content, from_lang=self.from_lang, to_lang=self.to_lang
        )
        if len(found) == 0:
            my_json = self._ask_actual_api(content, TRANSLIT_PATH, self.translit_params())
            my = APITransliteration(
                source_text=content, response_json=my_json, from_lang=self.from_lang, to_lang=self.to_lang
            )                                                                                                                                                           
            my.save()
            return my.response_json
        return found.first().response_json

When I just call the class that inherits from TestCase it runs fine, which I believe is because it doesn't find the value in the DB so follows the inner if. If I do a full run of the tests, django refuses to destroy the test database due to an open connection, and

SELECT * FROM pg_stat_activity;

Reports that it is the query that corresponds to the first() call. This would make sense because the method gets called with the same parameters by two tests, so would find the value for the second run (which is the last test that gets executed). What doesn't make so much sense to me is why the connection is in ClientRead and Idle after my successful complete test run.

Is it me that is doing something wrong here? How should I call this so it won't leave idle connections around that django doesn't know it needs to clean up?

Aucun commentaire:

Enregistrer un commentaire