Skip to content

Commit

Permalink
fix: constrained strings not deterministic with seed because urandom …
Browse files Browse the repository at this point in the history
…not seedable (#319)

* urandom not seedable

* compatibility python 3.8

* python 38 has getrandbits bug

---------

Co-authored-by: An De Rijdt <an.joanna.de.rijdt@ing.com>
  • Loading branch information
klimantje and An De Rijdt committed Aug 2, 2023
1 parent 5abe4b3 commit 3aeaa0c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
3 changes: 1 addition & 2 deletions polyfactory/value_generators/primitives.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

from binascii import hexlify
from decimal import Decimal
from os import urandom
from typing import TYPE_CHECKING

if TYPE_CHECKING:
Expand Down Expand Up @@ -80,7 +79,7 @@ def create_random_bytes(
max_length = min_length + 1 * 2

length = random.randint(min_length, max_length)
result = hexlify(urandom(length))
result = b"" if length == 0 else hexlify(random.getrandbits(length * 8).to_bytes(length, "little"))

if lower_case:
result = result.lower()
Expand Down
16 changes: 16 additions & 0 deletions tests/test_random_seed.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,19 @@ class FactoryWithNoneOptionals(ModelFactory):
ModelFactory.seed_random(seed)
second_build = [FactoryWithNoneOptionals.build() for _ in range(10)]
assert first_build == second_build


def test_deterministic_constrained_strings() -> None:
class MyModel(BaseModel):
id: int
special_id: str = Field(min_length=10, max_length=24)

class MyModelFactory(ModelFactory):
__model__ = MyModel

ModelFactory.seed_random(1651)

ins = MyModelFactory.build()

assert ins.id == 4
assert ins.special_id == "48489ab53c59b24acfe1"

0 comments on commit 3aeaa0c

Please sign in to comment.