I am trying to find out the number of queries executed by a utility function. I have written a unit test for this function and the function is working well. What I would like to
Here is the working prototype of context manager withAssertNumQueriesLessThen
import json
from contextlib import contextmanager
from django.test.utils import CaptureQueriesContext
from django.db import connections
@contextmanager
def withAssertNumQueriesLessThen(self, value, using='default', verbose=False):
with CaptureQueriesContext(connections[using]) as context:
yield # your test will be run here
if verbose:
msg = "\r\n%s" % json.dumps(context.captured_queries, indent=4)
else:
msg = None
self.assertLess(len(context.captured_queries), value, msg=msg)
It can be simply used in your unit tests for example for checking the number of queries per Django REST API call
with self.withAssertNumQueriesLessThen(10):
response = self.client.get('contacts/')
self.assertEqual(response.status_code, 200)
Also you can provide exact DB using
and verbose
if you want to pretty-print list of actual queries to stdout