[PYTHON] AssertNumQueries is useful if you want to easily test N + 1 queries with django

AssertNumQueries is useful if you want to easily test N + 1 queries with django

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.

If you want to know the query issued within a specific range other than test

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

reference

Recommended Posts

AssertNumQueries is useful if you want to easily test N + 1 queries with django
[OpenCV] When you want to check if it is read properly with imread
If you want to enter the virtual environment with jupyter, nb_conda_kernels is recommended
When you want to filter with Django REST framework
If you want to become a data scientist, start with Kaggle
Don't write Python if you want to speed it up with Python
[TensorFlow] If you want to run TensorBoard, install it with pip
When you want to use it as it is when using it with lambda memo
If you want to include awsebcli with CircleCI, specify the python version
If you want to get multiple statistics with groupby in pandas v1
Isn't Qt the strongest library if you want to easily output SVG?
If you don't know how to draw the graph you want with matplotlib, it is convenient to look at the gallery.
If you want to display values using choices in a template in a Django model
5 Reasons Processing is Useful for Those Who Want to Get Started with Python
If you want to make a discord bot with python, let's use a framework
If you want to create a Word Cloud.
Sometimes you want to access View information from Serializer with DRF (Django REST Framework)
When the variable you want to superscript with matplotlib is two or more characters
Settings when you want to run python-mecab with travis
If you want to use Cython, also include python-dev
Links to do what you want with Sublime Text
Things to do when you start developing with Django
Useful operation when you want to solve all problems in multiple programming languages with Codewars
If you want to use field names with hyphens when updating firestore data in python
Solution when you want to use cv_bridge with python3 (virtualenv)
One liner to hit if you forget where today is
I want to initialize if the value is empty (python)
I want to use R functions easily with ipython notebook
[Python] If you suddenly want to create an inquiry form
I want to make a blog editor with django admin
Use aggdraw when you want to draw beautifully with pillow
What to do if you can't sort files with subscripts
When you want to register Django's initial data with relationships
If you want your colleagues to use the same language
[Django] What to do if the model you want to create has a large number of fields
[Django] Carefully explain the escape route if you really want to use the table of another application