ghandic / jsf

Creates fake JSON files from a JSON schema
https://ghandic.github.io/jsf
Other
164 stars 36 forks source link

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

Open mjp4 opened 7 months ago

mjp4 commented 7 months ago

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 commented 5 months ago

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

ghandic commented 5 months ago

PR Welcome

ayushbindlish commented 5 months ago

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