Create a custom class that inherits from TestCase and set the seed value insetUp ().
Each app inherits a custom class and writes a test.
I wanted to ensure test reproducibility when using factory_boy with Django.
factory-boy==2.12.0
BaseTestCase class definitionDefine a BaseTestCase class that fixes the seed value.
I write a base application and write abstract classes there.
python:./base/tests.py
from django.test import TestCase
import factory.random
class BaseTestCase(TestCase):
def setUp(self):
factory.random.reseed_random(0)
return super().setUp()
TestCase classesInherit the BaseTestCase class and define each test case.
python:./user/tests.py
from base.tests import BaseTestCase
from .models import User
from .factories import UserFactory
class UserTestCase(BaseTestCase):
def test_create_user(self):
user = UserFactory()
actual_user = User.objects.get(pk=user.pk)
self.assertEqual(user, actual_user)
Of course, when defining setUp (), also call the method of the parent class.
python:./user/tests.py
class UserTestCase(BaseTestCase):
def setUp(self):
super().setUp()
print("initialize")
def test_create_user(self):
user = UserFactory()
actual_user = User.objects.get(pk=user.pk)
self.assertEqual(user, actual_user)
By fixing the seed value, the test can be executed with the reproducibility guaranteed. This article is based on Django, but it should work for Django as well.
Recommended Posts