Django: is there a way to count SQL queries from an unit test?

前端 未结 8 933
广开言路
广开言路 2021-01-31 13:55

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

8条回答
  •  无人共我
    2021-01-31 14:22

    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

提交回复
热议问题