Skip to content

Open source assertExactQueries

We have implemented assertExactQueries in unit tests as a way to test SQL queries against a text file instead of only counting them with assertNumQueries. While it can work really well in simple situations, it can be quite a mess when Django prefetches are involved.

From the work I put in in !1306 (merged), I think it would be possible to put in more work and properly handle prefetches:

with self.assertExactQueries('file.sql') as ctx:
    ctx.add_param('id', element_id)
    ctx.add_prefetch('zone__image__server', expected_zone_ids)

    self.client.get()

The implementation could inspect Django models to resolve zone__image__server, use get_prefetcher to get the prefetch queryset, and compile it into SQL without running it which would give us the exact SQL we should be expecting. We can then look for the prefetches in the SQL queries and handle them separately without having to include them the SQL file.

This can be open-sourced as a Python lib that provides the AssertExactQueriesContext and the self.assertExactQueries in a mixin that one can add to any TestCase.

We can probably do two or three blog posts about how assertNumQueries works under the hood, as that was the first step that led to creating assertExactQueries, a first implementation of exact SQL assertion, the complexity of handling prefetches, and announce the library.