factory_boy icon indicating copy to clipboard operation
factory_boy copied to clipboard

Feat/add unique feature arg in faker factory

Open tlconnor opened this issue 2 years ago • 3 comments

This pull request follows on from the abandoned https://github.com/FactoryBoy/factory_boy/pull/820. The code is simplified and follows the same pattern used when specifying the locale for Faker.

Since Faker 4.9.0 there has been support to generate unique values. This is really helpful when dealing with unique constraint on a field generated by factory boy. The test can be flaky if you use faker without the "unique" feature on an ORM field with an unique constraint.

The usage with factory boy is simple as this:

class UserFactory(fatory.Factory):
            class Meta:
                model = User

            arrival = factory.Faker(
                'date_between_dates',
                date_start=datetime.date(2020, 1, 1),
                date_end=datetime.date(2020, 5, 31),
                unique=True  # The generated date is guaranteed to be unique inside the test execution.
            )

The unique keyword can be passed on every faker providers. If True the faker object passes through the Faker Unique Proxy, making sure the generated value has not been already generated before. Note that the default unique keyword value is False.

Credit goes to @arthurHamon2 for the idea and the original pull request.

tlconnor avatar Feb 02 '23 00:02 tlconnor

@tlconnor merge #999 into your branch to test your changes

kingbuzzman avatar Feb 06 '23 16:02 kingbuzzman

@tlconnor NM, its been merged to master. Sync.

kingbuzzman avatar Feb 08 '23 17:02 kingbuzzman

Hi. Is this PR ready to merge? I'd really love this feature to be present and I can help if it's needed

HosseyNJF avatar Dec 11 '23 12:12 HosseyNJF