zerosleeps

Since 2010

Reproducing Django bug 34486

That Django bug I mentioned a few days ago is a slippery little devil. It’s related to the way a couple of methods available in Django’s contrib.postgres.search module construct their SQL statements. Something in the stack was assuming a connection to the database would be available earlier than is actually was, leading to an exception.

I won’t say it’s impossible to replicate the bug using Django’s test client, but I haven’t worked out a way to do so. Using the test client inside any of the test case classes which allow database interaction means a database connection is opened and maintained early enough. This doesn’t exercise the code path in question, so it never leads to that exception.

The solution I’ve come up with is to not use Django’s test client, instead using Python’s urllib. This means switching to LiveServerTestCase, but it more realistically mimics a fresh, cold, external request.

from django.test import LiveServerTestCase
import urllib.request


class SearchTestCase(LiveServerTestCase):
    def test_search_status(self):
        with urllib.request.urlopen(
            f"{self.live_server_url}/search/?query=foo"
        ) as request:
            self.assertEqual(request.status, 200)