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.
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.)
setUp ()
every timeIn 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)
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)
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