Why are queries not added to django db.connection.queries in tests?

I am trying to capture the queries that my code sends to the database by examining the contents of django.db.connection.queries . For some reason, despite the fact that after all automatically generated configuration requests are logged, no additional requests are logged from my own code. The following test case demonstrates 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 its launch:

 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 

Can anyone shed some light on this? Thanks.

+7
sql django testing
source share
3 answers

You will not see any requests after executing User.objects.all() . This can be expected. Cause? Querysets are lazy. If you do nothing with the request, the NO request will be launched. To test 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') 
+5
source share

You must explicitly install DEBUG . For example, see the Example 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 every test should definitely solve the problem. Take a look at DjangoTestSuiteRunner - it seems that DEBUG set to setup_test_environment False, which is called in run_tests , which continues to create a DjangoTestRunner and call it run method . Therefore, you need to undo this - based on a quick scan of the code, this may be enough to do in your setup .

+6
source share
+3
source share

All Articles