pytest-dev / pytest-dev/pytest-factoryboy

ManyToMany PostGeneration class

Open
#59 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
400
Forks
44
Avg merge
6h 34m
Merged PRs (30d)
1

Description

Most m2m relation handling for factories in Django is pretty simple, is this of interest?

class ManyToManyPostGeneration(factory.PostGeneration):
    """
    Simplified factory post_generation for many-to-many relationships - sets values passed to the collection
    https://factoryboy.readthedocs.io/en/latest/recipes.html?highlight=many#simple-many-to-many-relationship

    Arguments:
        name: the name of the many-to-many relation

    Usage:
        You can pass the factory a list of model instances

        - article_factory.create(tags=LazyFixture(lambda tag: [tag])))

        Or you can use the parametrize decorator

        - @pytest.mark.parametrize('article__tags', [LazyFixture(lambda tag: [tag])])
    """
    def __init__(self, name):
        def func(self, create, extracted, **kwargs):
            if create and extracted:
                getattr(self, name).set(extracted)
        func.__name__ = name
        return super().__init__(func)

Makes basic m2m declarations as simple as

class ArticleFactory(factory.django.DjangoModelFactory):
    tags = ManyToManyPostGeneration('tags')

You can also define and use the inverse side too

class TagFactory(factory.django.DjangoModelFactory):
    articles = ManyToManyPostGeneration('articles')

I'd drop the string arg but I couldn't figure out how to know the relation name otherwise

Another thought was whether it should add or set – the examples provided use add but I figure given the whole list is passed in an explicit set is probably what is expected (i.e. clobber)

Any interest in something like this in pytest-factoryboy?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the proposed ManyToManyPostGeneration class and its DjangoModelFactory usage. Resolve whether the relation should use set or add, how the relation name is determined, and whether both sides are supported; the issue provides no repository files or tests to target.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
backend, testing
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.