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

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

    If you have DEBUG set to True in your settings.py (presumably so in your test environment) then you can count queries executed in your test as follows:

    from django.db import connection
    
    class DoSomethingTests(django.test.TestCase):
        def test_something_or_other(self):
            num_queries_old = len(connection.queries)
            do_something_in_the_database()
            num_queries_new = len(connection.queries)
            self.assertEqual(n, num_queries_new - num_queries_old)
    
    0 讨论(0)
  • 2021-01-31 14:46

    If you are using pytest, pytest-django has django_assert_num_queries fixture for this purpose:

    def test_queries(django_assert_num_queries):
        with django_assert_num_queries(3):
            Item.objects.create('foo')
            Item.objects.create('bar')
            Item.objects.create('baz')
    
    0 讨论(0)
提交回复
热议问题