[PYTHON] Pin factory_boy seed value in Django

Conclusion

Create a custom class that inherits from TestCase and set the seed value insetUp (). Each app inherits a custom class and writes a test.

background

I wanted to ensure test reproducibility when using factory_boy with Django.

procedure

environment

factory-boy==2.12.0

BaseTestCase class definition

Define 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()

Inheritance of individual TestCase classes

Inherit 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)

Summary

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

Pin factory_boy seed value in Django
Models in Django
Forms in Django
Model changes in Django
Performance optimization in Django 3.xx
PHP var_dump in Django templates
Handle constants in Django templates
Implement follow functionality in Django
Rename table columns in Django3
Shapley value calculation in Python
Output table structure in Django
Show Django ManyToManyField in Template