FactoryBoy / factory_boy

A test fixtures replacement for Python

Home Page:https://factoryboy.readthedocs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Factory for Django model linking to self referential field

Shodiev-Shokhrukh opened this issue · comments

Description

*I have a model class A which has parent field which referential for the same model . I want to create a factory for this but some error occured *

To Reproduce

*When writing a test class and using above factory for setup method this error occured *

Model / Factory code
class BaseOrganization(
    models.Model
):
    name = models.CharField(max_length=255, verbose_name="Nomlanishi", null=True)
    juridical_address = models.CharField(
        max_length=150, verbose_name="Yuridik manzili", null=True, blank=True
    )
    phone_number = models.CharField(
        max_length=150,
        verbose_name="Telefon raqami",
        null=True,
        blank=True,
        validators=[phone_regex],
    )
    parent = models.ForeignKey(
        "self",
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="%(class)s_children",
        verbose_name="Yuqori tashkilot",
    )


    class Meta:
        abstract = True

class BaseOrganizationFactory(factory.django.DjangoModelFactory):

    """Base organization factory"""
    name = factory.Faker("company")
    juridical_address = factory.Faker("address")
    phone_number = factory.Faker("phone_number")
    parent = factory.SubFactory(
        "myapp.tests.factories.BaseOrganizationFactory",
    )


@pytest.mark.django_db
class TestBaseOrganization:
    @pytest.fixture(autouse=True)
    def setup(self):
        self.base_organization = BaseOrganizationFactory(
            parent=None
        )
    
The issue

If i run the tests RecursionError: maximum recursion depth exceeded error occured

 self.base_organization = BaseOrganizationFactory(
            parent=None
        ) calling this factory is the main cause of this error

Notes

I did
self.base_organization = BaseOrganizationFactory(parent__parent__parent__parent=None) or parent = factory.SubFactory( "myapp.tests.factories.BaseOrganizationFactory", parent=None ) but none of them worked the same error happened

@Shodiev-Shokhrukh Pinging everyone when you open an issue is not very polite, we already receive a notification.

Your test case is relying on additional code in the base classes of your code; can you try to reduce it to a more minimal situation?

We already have automated tests for that situation, which are passing, see https://github.com/FactoryBoy/factory_boy/blob/master/tests/test_using.py#L2771

Thanks,

Sorry for mentioning all of you. How to minimize this situation. I provided only little part of my model code