Opened 9 days ago

Closed 8 days ago

Last modified 8 days ago

#36327 closed New feature (wontfix)

Improve TestCase.assertNumQueries() to allow for multiple databases

Reported by: Javier Buzzi Owned by: Javier Buzzi
Component: Testing framework Version: dev
Severity: Normal Keywords: query count testcase assertNumQueries
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Javier Buzzi)

PR 19380

Relevant discussions:

The goal is to enhance the behavior of TestCase.assertNumQueries(). In large Django projects, the data structure is often split into multiple databases—for example, one for user data, another for business data, one for events, and even a dedicated one for certain monetary compliance logs. As a result, tests may need to validate query counts across several databases. For instance, you might have code that looks like this:

class TestThing(TestCase):
    databases = {"db1", "db2", "db3", "db4"}

    def test_thing(self):
        with self.assertNumQueries(4, using="db1"), self.assertNumQueries(0, using="db2"), self.assertNumQueries(1, using="db3"), self.assertNumQueries(0, using="db4"):
            thing()

The desired improvement is to simplify this syntax. Instead of writing a separate context manager for each database, you could pass multiple databases at once. For example:

class TestThing(TestCase):
    databases = {"db1", "db2", "db3", "db4"}

    def test_thing(self):
        with self.assertNumQueries(5, using={"db1", "db2", "db3", "db4"}):
            thing()

Alternatively, you might be able to use a special keyword like __all__ to achieve the same effect:

with self.assertNumQueries(5, using="__all__"):
    ...

This approach not only makes the test code more manageable but also helps improve clarity by consolidating query count assertions across all databases.

Change History (4)

comment:1 by Javier Buzzi, 9 days ago

Description: modified (diff)
Has patch: set

comment:2 by Javier Buzzi, 9 days ago

Owner: set to Javier Buzzi
Status: newassigned

comment:3 by Natalia Bidart, 8 days ago

Resolution: wontfix
Status: assignedclosed

As explained in the forum post, I'll close this as wontfix since a viable approach using subTest and assertNumQueries has been proposed in the related discussion, which covers the use case without requiring a framework change (to my best understanding).

comment:4 by Mariusz Felisiak, 8 days ago

I'm also skeptic. I'd prefer to explicitly assert the number of queries per database.

Note: See TracTickets for help on using tickets.
Back to Top