Skip to content

Commit

Permalink
Add documentation on how to use the fixture name
Browse files Browse the repository at this point in the history
  • Loading branch information
mcosti committed May 1, 2024
1 parent 918fb90 commit 979048e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
35 changes: 35 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,41 @@ Sub-factory attribute points to the model fixture of the sub-factory.
Attributes of sub-factories are injected as dependencies to the model fixture and can be overridden_ via
the parametrization.

Django Model SubFactory with a custom fixture name
--------------------------------------------------

By default, the subfactory is retrieved by using the lowercase-underscore form of the Django model class name
and invoking that fixture from the pytest request.
If you want to use a different name, you must define it in the factory class Meta and use a custom DjangoModelFactory

.. code-block:: python
from factory.django import DjangoModelFactory, DjangoOptions
class CustomFixtureFactoryOptions(DjangoOptions):
"""Allow overriding the fixture name when referencing the factory via SubFactory/RelatedFactory."""
def _build_default_options(self):
return super()._build_default_options() + [
factory.base.OptionDefault("fixture_name", None),
]
class CustomFixtureDjangoModelFactory(DjangoModelFactory):
_options_class = CustomFixtureFactoryOptions
class Meta:
abstract = True
@register
class AuthorFactory(CustomFixtureDjangoModelFactory):
class Meta:
model = Author
fixture_name = "other_author"
name = "Charles Dickens"
Related Factory
---------------

Expand Down
2 changes: 1 addition & 1 deletion pytest_factoryboy/fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ def attr_fixture(request: SubRequest, value: T) -> T:

def subfactory_fixture(request: SubRequest, factory_class: FactoryType) -> Any:
"""SubFactory/RelatedFactory fixture implementation."""
overriden_fixture_name = getattr(factory_class._meta, "_fixture_name", None)
overriden_fixture_name = getattr(factory_class._meta, "fixture_name", None)
if overriden_fixture_name is not None:
return request.getfixturevalue(overriden_fixture_name)

Expand Down

0 comments on commit 979048e

Please sign in to comment.