FactoryBoy / factory_boy

A test fixtures replacement for Python
https://factoryboy.readthedocs.io/
MIT License
3.52k stars 399 forks source link

Fix warning in 3.10 "DeprecationWarning: non-integer arguments to randrange()" #916

Closed nk9 closed 2 years ago

nk9 commented 2 years ago

Description

I am using the following code to generate fuzzy integers in a factory today:

import factory.fuzzy as fuzzy

#…
    obj_id = fuzzy.FuzzyInteger(4e6, 5e6)

After upgrading to Python 3.10, this results in a deprecation warning:

  /.venv/lib/python3.10/site-packages/factory/fuzzy.py:118: DeprecationWarning: non-integer arguments to randrange() have been deprecated since Python 3.10 and will be removed in a subsequent version
    return random.randgen.randrange(self.low, self.high + 1, self.step)

I have tried passing integers instead of floats (e.g. int(4e6) and 4000000), but neither fix the warning. And they're both kind of annoying to have to type anyway.

Notes

Presumably, the solution is to cast the variables using int() before passing them to randrange(). More info in this Python library bug.

stefan6419846 commented 2 years ago

As stated in the documentation of the fuzzy generators (https://factoryboy.readthedocs.io/en/stable/fuzzy.html), you should prefer migrating to factory.Faker instead. Your code should look something like this afterwards, see https://faker.readthedocs.io/en/master/providers/faker.providers.python.html#faker.providers.python.Provider.pyint:

   obj_id = factory.Faker('pyint', min_value=int(4e6), max_value=int(5e6))

You have to explicitly cast the values to int here as well, due to the function signature expecting int values.

nk9 commented 2 years ago

Thanks, I hadn't noticed that detail about the fuzzy generators. The new style is quite verbose, so I've wrapped it in my own function with positional arguments and it's working well.