Skip to content
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

Generation of number type fails if no integer exists between minimum and maximum #101

Open
mjp4 opened this issue Feb 12, 2024 · 3 comments

Comments

@mjp4
Copy link

mjp4 commented Feb 12, 2024

If multipleOf is not set in the schema, then generating a number always attempts to use a step of 1, and throws an exception when no such valid number exists.

>>> from jsf import JSF
>>> JSF({"type": "number", "minimum": 0.1, "maximum": 0.9}).generate()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../lib/python3.8/site-packages/jsf/parser.py", line 251, in generate
    return self.root.generate(context=self.context)
  File ".../lib/python3.8/site-packages/jsf/schema_types/number.py", line 37, in generate
    step * random.randint(math.ceil(float(_min) / step), math.floor(float(_max) / step))
  File "/usr/lib/python3.8/random.py", line 248, in randint
    return self.randrange(a, b+1)
  File "/usr/lib/python3.8/random.py", line 226, in randrange
    raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (1, 1, 0)

I suggest a check that max - min is greater than step, and if not try a smaller step.

It is even worse when using exclusive Maximums and Minimums, when it is unable to find any value in a range from 0.1-2.9

>>> JSF({
        "type": "number",
        "minimum": 0.1,
        "maximum": 2.9,
        "exclusiveMinimum": True,
        "exclusiveMaximum": True
    }).generate()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../lib/python3.8/site-packages/jsf/parser.py", line 251, in generate
    return self.root.generate(context=self.context)
  File ".../lib/python3.8/site-packages/jsf/schema_types/number.py", line 37, in generate
    step * random.randint(math.ceil(float(_min) / step), math.floor(float(_max) / step))
  File "/usr/lib/python3.8/random.py", line 248, in randint
    return self.randrange(a, b+1)
  File "/usr/lib/python3.8/random.py", line 226, in randrange
    raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (2, 2, 0)
@ayushbindlish
Copy link

random.randint can be updated to random.uniform to fix this @ghandic

@ghandic
Copy link
Owner

ghandic commented Mar 19, 2024

PR Welcome

@ayushbindlish
Copy link

@mjp4 Could you provide a sample schema with which you are hitting this issue?

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

No branches or pull requests

3 participants