Not a duplicate of Making random phone number xxx-xxx-xxxx
My project uses python-phonenumbers and django-phonenumber-field for phone number validation. Within the project are vast lists of custom validation rules, for which naive approach like this will not be sufficient:
>>> import functools
>>> import random
>>> a = functools.partial(random.randint, 0, 9)
>>> gen = lambda: "+{}-{}{}{}-{}{}{}-{}{}{}{}".format(a(), a(), a(), a(), a(), a(), a(), a(), a(), a(), a())
>>> gen()
'+2-758-702-0180' # Obviously wrong
>>> gen()
'+1-911-555-0180' # Obviously wrong, it has 911 in it
So, without resorting to a brute-force while loop that has no upper bound, and without introducing an upper bound for such trivial problems, what better ways are there to generate valid phone numbers accepted by the validator itself?
from phonenumber_field.validators import validate_international_phonenumber
from django.core.exceptions import ValidationError
def generate_valid_number():
while True: # While loops are not desired, even with an upper bound!
try:
number = gen()
validate_international_phonenumber(number)
return number
except ValidationError:
pass