I could be wrong here, but I feel like when developers are asserting the number of queries that a code block makes, their true intention is to prevent it from exceeding a threshold.
With that being said, I think it would be more suitable to have anassertNumQueriesLte function.
Or a more flexible version could be assertNumQueriesBetween(min=None, max=None).
(The currentassertNumQueriesfunction can make tests annoyingly brittle - any optimization that reduces the number of queries requires you to update your tests, and sometimes that’s troublesome)
1 Like
I agree that it’s underpowered as a testing tool, but adding range support feels like a weak approach to me: it allows you to skip updating tests when you deliberately optimise code, but it also means tests will no longer catch when you inadvertently remove queries.
I’ve developed two packages providing improved query assertion tools, the most recent covered here: Django: Introducing inline-snapshot-django - Adam Johnson
Perhaps that will solve your problem better than making a change in django?
2 Likes
I think there’s room for improvement around limiting the checks on the specific models that are generating queries as well. I created GitHub - aspiredu/django-assert-model-queries: A utility to count the number of model queries in a Django application. as an exploration into that, but haven’t done a ton with it.
Example from the docs:
# Django TestCase example
from django.test import TestCase
from django_assert_model_queries import AssertModelQueries, ModelNumQueriesHelper
from testapp.models import Community
class TestDjangoIntegration(ModelNumQueriesHelper, TestCase):
def test_assert_model_num_queries_context(self):
with AssertModelQueries({"testapp.Community": 1}):
Community.objects.create(name="test")
with AssertModelQueries({"testapp.Community": 2, "testapp.Chapter": 1, "testapp.Community_topics": 1}):
Community.objects.all().delete()