model_bakery icon indicating copy to clipboard operation
model_bakery copied to clipboard

inconsistent behaviour between `gen_from_choices` and `gen_string` (and others)

Open syphar opened this issue 6 years ago • 0 comments

We're using model-bakery for our testing, and in relation with recipes we stumbled onto an inconsistency in the library. While gen_from_choices returns a callable that is then generates the random value when being called by baker.make_recipe, for example gen_string (and the others) directly return the random value.

Expected behavior

With the example Recipe as written here, I would expect one of the two behaviours:

everything returns a callable

MyModel = Recipe(
    'myapp.MyModel,
    first_name=gen_string(10),
    last_name=gen_string(10),
    user_type=gen_from_choices(USER_TYPES),
    is_staff=True, 
)

and each time I create a model instance with this recipe I get different values for first_name or last_name and also user_type.

everything returns a value

If I know everything returns a value, I would need to define the recipe in this way to achieve my goal of random values per creation:

MyModel = Recipe(
    'myapp.MyModel,
    first_name=lambda: gen_string(10),
    last_name=lambda: gen_string(10),
    user_type=lambda: gen_from_choices(USER_TYPES),
    is_staff=True, 
)

functools.partial also works.

Actual behavior

MyModel = Recipe(
    'myapp.MyModel,
    first_name=gen_string(10),
    last_name=gen_string(10),
    user_type=gen_from_choices(USER_TYPES),
    is_staff=True, 
)

With this recipe, what actually happens is:

  • first_name and last_name always have the same (random) value, since they are called on module-load
  • user_type has a random value generated per instance

Reproduction Steps

use the examples, add the imports, and use baker.make_recipe

Versions

Python: 3.6 / 3.7 Django: 2.2.8 Model Bakery: 1.0.2

syphar avatar Dec 09 '19 16:12 syphar