Skip to content

Fix Faker.random_number intermittent exceptions #1074 #1089

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 14, 2020

Conversation

Jengah
Copy link
Contributor

@Jengah Jengah commented Dec 29, 2019

What does this change

Uses self.random_digit_not_null() instead of self.random_digit() to generate a random max length of digits when none are passed to self.random_number() method.

Also, raise more aptly worded / obvious ValueError when digits param is less than 1 and fix_len param is set to True.

What was wrong

The use of self.random_digit() to generate a random max length of digits in a random number gives it a 10% chance of equaling 0 and failing with a ValueError when fix_len is set to True.

How this fixes it

Setting digits = self.random_digit_not_null() will always generate a number between 1 and 9 instead of 0 and 9, resolving the case where a user specifies fix_len=True and doesn't specify a digits param.

Fixes #1074

@@ -151,10 +151,15 @@ def random_number(self, digits=None, fix_len=False):
fixed length number
"""
if digits is None:
digits = self.random_digit()
digits = self.random_digit_not_null()
if digits < 0:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should also note that although it seems logical that this should be set to if digits <= 0:, this breaks test functionality for the python provider method for pyfloat.

Specifically this line:

assert 0 <= abs(provider.pyfloat(left_digits=0)) < 1

@fcurella
Copy link
Collaborator

Thank you!

@fcurella fcurella merged commit 24401dc into joke2k:master Jan 14, 2020
IlfirinPL pushed a commit to IlfirinPL/faker that referenced this pull request Apr 9, 2021
)

* ensure max number of digits generated in random_number is > -1 when param is not passed and > 0 when fix_len is True

* add additional tests for random_number functionality
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Faker.random_number raises exception randomly
2 participants