Test the number of times you have thrown a query (sql) in django

I can't use TransactionTestCase.assertNumQueries obediently because I messed with the test DB connection. In case.

# coding: utf-8

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")

from django.conf import settings
from django.db import connections

import unittest, pprint
from collections import deque
from core.models import Kvs, Hoge


class TestKvs(unittest.TestCase):

    def setUp(self):
        settings.DEBUG = True

    def tearDown(self):
        # django.db. reset_queries are fine
        connections['default'].queries_log = deque()  
        settings.DEBUG = False

    def test_simple(self):
        hoge = list(Hoge.objects.all())[0]
        # select
        self.assertEqual(len(connections['default'].queries), 1)

        Kvs.set(hoge.id, hoge)
        # select, begin, update
        self.assertEqual(len(connections['default'].queries), 4)

        got = Kvs.get(hoge.id)
        # select
        self.assertEqual(got.id, hoge.id)
        self.assertEqual(len(connections['default'].queries), 5)


if __name__ == "__main__":
    unittest.main()

Reference: [Django: is there a way to count SQL queries from an unit test?](Http://stackoverflow.com/questions/1254170/django-is-there-a-way-to-count-sql-queries- from-an-unit-test)

Recommended Posts

Test the number of times you have thrown a query (sql) in django
Find the number of days in a month
How to count the number of elements in Django and output to a template
Get the number of specific elements in a python list
How to generate a query using the IN operator in Django
[Python] Programming to find the number of a in a character string that repeats a specified number of times.
The meaning of ".object" in Django
Get the query string (query string) in Django
Get the number of readers of a treatise on Mendeley in Python
If you want a singleton in python, think of the module as a singleton
Have Alexa run Python to give you a sense of the future
Count the number of times two values appear in a Python 3 iterator type element at the same time
Write the test in a python docstring
Generate a list packed with the number of days in the current month.
Check the in-memory bytes of a floating point number float in Python
Test & Debug Tips: Create a file of the specified size in Python
plot the coordinates of the processing (python) list and specify the number of times in draw ()
Set the number of elements in a NumPy one-dimensional array to a power of 2 (0 padded)
Create a BOT that displays the number of infected people in the new corona
You walk in a spiral in a world where the walls of the cross rise (simulation)
Visualize the timeline of the number of issues on GitHub assigned to you in Python
I didn't have to write a decorator in the class Thank you contextmanager
Output the number of CPU cores in Python
Get the caller of a function in Python
Make a copy of the list in Python
Output in the form of a python array
The story of viewing media files in Django
Until you create a new app in Django
If you define a method in a Ruby class and define a method in it, it becomes a method of the original class.
[Python] A program that finds the shortest number of steps in a game that crosses clouds
[Django] Let's try to clarify the part of Django that was somehow through in the test
Find out the maximum number of characters in multi-line text stored in a data frame
[Python] Representing the number of complaints from life insurance companies in a bar graph
Find a guideline for the number of processes / threads to set in the application server
Check if the string is a number in python
[Python] A program that counts the number of valleys
How to get the number of digits in Python
Count the number of parameters in the deep learning model
Get the size (number of elements) of UnionFind in Python
A reminder about the implementation of recommendations in Python
Make a note of what you want to do in the future with Raspberry Pi
VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
If you draw an Omikuji with a probability of 1% 100 times in a row, will you win once?
How to write when you want to put a number after the group number to be replaced with a regular expression in re.sub of Python
Maya | Find out the number of polygons in the selected object
A note on the default behavior of collate_fn in PyTorch
I participated in the translation activity of Django official documents
Find out the apparent width of a string in python
Examine the margin of error in the number of deaths from pneumonia
Django + MongoDB development environment maintenance (in the middle of writing)
Analyzing data on the number of corona patients in Japan
Have the equation graph of the linear function drawn in Python
The story of a Django model field disappearing from a class
Summary of stumbling blocks in Django for the first time
[Note] Import of a file in the parent directory in Python
[Homology] Count the number of holes in data with Python
To write a test in Go, first design the interface
Get the number of occurrences for each element in the list
Find the eigenvalues of a real symmetric matrix in Python
Record what you have learned in the four months of in-house software engineer training (* currently in progress)
Settings for running a test each time you save a file in the editor using watchmedo (watchdog)