In django 1.7 migration, assertNumQueries outputs the result of the query captured when it fails. It came to give me. So, if you write the following code, you will be able to understand the query of the DB issued in the part enclosed in with.
from django.test import TestCase
class Test(TestCase):
def _callFUT(self):
Model(name="foo").save()
return Model.objects.count()
def test_it(self):
with self.assertNumQueries(3):
self.assertEqual(self._callFUT(), 1)
For example, in the code above you can find out how many queries were executed in self._callFUT ()
.
Originally there are two cases, but I specified 3 in ʻassertNumQueries ()` and made it fail on purpose.
Execution result
Creating test database for alias 'default'...
F
======================================================================
FAIL: test_it (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "qr_34141zLt.py", line 46, in test_it
self.assertEqual(self._callFUT(), 1)
File "/home/podhmo/vboxshare/venvs/django/lib/python3.3/site-packages/django/test/testcases.py", line 90, in __exit__
query['sql'] for query in self.captured_queries
AssertionError: 2 != 3 : 2 queries executed, 3 expected
Captured queries were:
QUERY = 'INSERT INTO "model" ("name") VALUES (%s)' - PARAMS = ('foo',)
QUERY = 'SELECT COUNT(*) AS "__count" FROM "model"' - PARAMS = ()
----------------------------------------------------------------------
Ran 1 test in 0.005s
FAILED (failures=1)
Destroying test database for alias 'default'...
You will be able to see the issued query.
You may be able to use django.test.utils.CaptureQueriesContext
.
Please do your best with the following feeling
from django.test.utils import CaptureQueriesContext
from django.db import connections
with CaptureQueriesContext(connections["default"]):
do_something()
Wrote by PileMd