Skip to content
This repository was archived by the owner on Jul 31, 2025. It is now read-only.

fix: ensure deterministic behavior for Use function with seeded random #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion polyfactory/factories/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,7 @@ def seed_random(cls, seed: int) -> None:
:returns: 'None'

"""
cls.__random__ = Random(seed)
cls.__random__.seed(seed)
cls.__faker__.seed_instance(seed)

@classmethod
Expand Down
19 changes: 19 additions & 0 deletions tests/test_random_seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from pydantic import VERSION, BaseModel, Field

from polyfactory.fields import Use
from polyfactory.factories.pydantic_factory import ModelFactory


Expand All @@ -26,6 +27,24 @@ class MyModelFactory(ModelFactory):
assert ins.special_id == "ID-515.943"


def test_deterministic_use_function_seeding():
class MyModel(BaseModel):
choice_value: str

choices = ["option1", "option2", "option3", "option4", "option5"]

class MyModelFactory(ModelFactory):
__model__ = MyModel
choice_value = Use(ModelFactory.__random__.choice, choices)

ModelFactory.seed_random(12345)
first_batch = [MyModelFactory.build().choice_value for _ in range(10)]

ModelFactory.seed_random(12345) # Seed random again with the same value
second_batch = [MyModelFactory.build().choice_value for _ in range(10)]

assert first_batch == second_batch

def test_deterministic_optionals_seeding() -> None:
class ModelWithOptionalValues(BaseModel):
name: Optional[str]
Expand Down