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

Manoj Govindan picture Manoj Govindan · Aug 10, 2009 · Viewed 21.1k times · Source

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 do is track the number of SQL queries executed by the function so that I can see if there is any improvement after some refactoring.

def do_something_in_the_database():
    # Does something in the database
    # return result

class DoSomethingTests(django.test.TestCase):
    def test_function_returns_correct_values(self):
        self.assertEqual(n, <number of SQL queries executed>)

EDIT: I found out that there is a pending Django feature request for this. However the ticket is still open. In the meantime is there another way to go about this?

Answer

Mitar picture Mitar · Oct 11, 2011

Since Django 1.3 there is a assertNumQueries available exactly for this purpose.