Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come queries aren't being added to Django's db.connection.queries in tests?

I'm trying to capture the queries which my code submits to the database by examining the contents of django.db.connection.queries. For some reason though, after all the automatically produced setup queries are logged, no further queries are logged from my own code. The following test case demonstrates the behavior.

from django.test import TestCase
from django.db import reset_queries, connection
from django.contrib.auth.models import User
from django.conf import settings

class Test1(TestCase):
    def setUp(self):
        settings.DEBUG = True

    def test1(self):
        self.assert_(settings.DEBUG, 'DEBUG is False')
        reset_queries() #clears out all the setup queries
        User.objects.all()
        self.assert_(connection.queries, 'No queries')

And here are the results of running it:

Traceback (most recent call last):
  File "/Users/jacob/foo/bar_project/baz_application/tests.py", line 246, in test1
    self.assert_(connection.queries)
AssertionError: No queries

Would anyone be able to shed some light on this? Thanks.

like image 937
Jacob Avatar asked Sep 07 '10 22:09

Jacob


3 Answers

You have to explicitly set DEBUG. For example, see the sample usage section for these tests in the django documentation:

# Set up.
# The test runner sets settings.DEBUG to False, but we want to gather queries
# so we'll set it to True here and reset it at the end of the test suite.
>>> from django.conf import settings
>>> settings.DEBUG = True

UPDATE: I may be missing something, but doing it in each test should definitely fix the issue. Take a look at the DjangoTestSuiteRunner -- it seems that DEBUG is set False in the setup_test_environment, which is called in run_tests, which goes on to instantiate a DjangoTestRunner and call its run method. So you'll need to undo that -- based on a quick scan of the code, it might be sufficient to do this in your setup method.

like image 56
ars Avatar answered Nov 06 '22 19:11

ars


You will not see any queries after executing User.objects.all(). This is only to be expected. The reason? Querysets are lazy. Unless you do something with the queryset NO query will be triggered. To verify this hypothesis, try the following and see if the test passes.

class Test1(TestCase):
    def setUp(self):
        settings.DEBUG = True

    def test1(self):
        self.assert_(settings.DEBUG, 'DEBUG is False')
        reset_queries() #clears out all the setup queries
        print User.objects.all() # <============= Printing the queryset.
        self.assert_(connection.queries, 'No queries')
like image 45
Manoj Govindan Avatar answered Nov 06 '22 18:11

Manoj Govindan


When you run tests DEBUG is set to False explicitly by Django test framework.

like image 5
Davor Lucic Avatar answered Nov 06 '22 20:11

Davor Lucic