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

前端 未结 8 919
广开言路
广开言路 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:23

    In modern Django (>=1.8) it's well documented (it's also documented for 1.7) here, you have the method reset_queries instead of assigning connection.queries=[] which indeed is raising an error, something like that works on django>=1.8:

    class QueriesTests(django.test.TestCase):
        def test_queries(self):
            from django.conf import settings
            from django.db import connection, reset_queries
    
            try:
                settings.DEBUG = True
                # [... your ORM code ...]
                self.assertEquals(len(connection.queries), num_of_expected_queries)
            finally:
                settings.DEBUG = False
                reset_queries()
    

    You may also consider resetting queries on setUp/tearDown to ensure queries are reset for each test instead of doing it on finally clause, but this way is more explicit (although more verbose), or you can use reset_queries in the try clause as many times as you need to evaluate queries counting from 0.

提交回复
热议问题