[PYTHON] When writing a test using DB with django, you may be able to do it faster by using `setUpTestData ()`

When writing a test using DB with django, you may be able to do it faster by using setUpTestData ()

When writing a test using DB in django, you may be able to do it faster by using setUpTestData ().

setUpTestData()

setUpTestData () is usually setUp () for each method This is to perform model initialization etc. on a class-by-class basis. (It might be a little interesting if you take a look at the internal implementation.)

Of course, being initialized on a class-by-class basis means that it will only be called once, so you need to be careful about things that update their status.

Example

For example, suppose you write a test for a search for django.contrib.auth.models.User in Texto. (There is no particular reason to choose ʻUser`. It's just a mess of defining the model.)

Calling setUp () every time

In the following test cases, User models are generated for the number of test methods. slow.

class Tests(TestCase):
    def setUp(self):
        from django.contrib.auth.models import User
        for i in range(110):
            User.objects.create_superuser("admin{}".format(i), "myemail{}@example.com".format(i), '')

    def test_query(self):
        from django.contrib.auth.models import User
        with self.assertNumQueries(1):
            actual = User.objects.filter(username__startswith="admin1").count()
            self.assertEqual(actual, 11)

    def test_query1(self):
        from django.contrib.auth.models import User
        with self.assertNumQueries(1):
            actual = User.objects.filter(username__startswith="admin1").count()
            self.assertEqual(actual, 11)

    def test_query2(self):
        from django.contrib.auth.models import User
        with self.assertNumQueries(1):
            actual = User.objects.filter(username__startswith="admin1").count()
            self.assertEqual(actual, 11)

Using setUpTestData ()

class Tests(TestCase):
    @classmethod
    def setUpTestData(cls):
        from django.contrib.auth.models import User
        for i in range(100):
            User.objects.create_superuser("admin{}".format(i), "myemail{}@example.com".format(i), '')

    def test_query(self):
        from django.contrib.auth.models import User
        with self.assertNumQueries(1):
            actual = User.objects.filter(username__startswith="admin1").count()
            self.assertEqual(actual, 11)

    def test_query1(self):
        from django.contrib.auth.models import User
        with self.assertNumQueries(1):
            actual = User.objects.filter(username__startswith="admin1").count()
            self.assertEqual(actual, 11)

    def test_query2(self):
        from django.contrib.auth.models import User
        with self.assertNumQueries(1):
            actual = User.objects.filter(username__startswith="admin1").count()
            self.assertEqual(actual, 11)

Comparison of execution time

Let's compare the execution time. The more setUp () is called for the number of test methods, the slower it will be, and the ratio of results is not very meaningful. Since there are 3 test methods, it takes about 3 times longer to generate the data with setUp ().

setUp setUpTestData
Number of users 100 100
Number of test methods 3 3
elapsed time 11.7s 3.6s

If you want to try it out, you can check it with the following gist.

https://gist.github.com/podhmo/ffc6f96e4688dfb53810f4e4d6ba4d92

Recommended Posts

When writing a test using DB with django, you may be able to do it faster by using `setUpTestData ()`
Things to do when you start developing with Django
What to do when a video cannot be read by cv2.VideoCapture
What to do if you get a "Wrong Python Platform" warning when using Python with the NetBeans IDE
When you want to use it as it is when using it with lambda memo
When you want to replace a column with a missing value (NaN) column by column
It is more convenient to use csv-table when writing a table with python-sphinx
A story that required preparation when trying to do a Django tutorial with plain centos7
A beginner tried coloring line art with chainer. I was able to do it.
When you want to filter with Django REST framework
Did you forget the password for a PDF with a password? pdfcrack may do something about it
[Django] A memorandum when you want to communicate asynchronously [Python3]
[AWS] What to do when you want to pip with Lambda
How to resolve CSRF Protection when using AngularJS with Django
[For IT beginners] What to do when the rev command cannot be used with Git Bash
If you write go table driven test in python, it may be better to use subTest
When it is troublesome to copy what you built with vue
What to do if you get a UnicodeDecodeError with pip install
When you want to send an object with requests using flask
When you want to sort a multidimensional list by multiple lines
[Django] I wanted to test when POSTing a large file [TDD]
[Tips] How to do template extends when creating HTML with django
[Python] What to do if you get a ModuleNotFoundError when importing pandas using Jupyter Notebook in Anaconda