Skip to content

Commit abf38dd

Browse files
authored
Merge pull request #261 from azubieta/master
Handle float operation errors when using divmod
2 parents 47488cc + 06907b6 commit abf38dd

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

python_jsonschema_objects/validators.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import decimal
12
import logging
23

34
import six
@@ -40,8 +41,14 @@ def __call__(self, name):
4041

4142
@registry.register()
4243
def multipleOf(param, value, _):
43-
quot, rem = divmod(value, param)
44-
if rem != 0:
44+
# This conversion to string is intentional because floats are imprecise.
45+
# >>> decimal.Decimal(33.069)
46+
# Decimal('33.0690000000000026147972675971686840057373046875')
47+
# >>> decimal.Decimal('33.069')
48+
# Decimal('33.069')
49+
value = decimal.Decimal(str(value))
50+
divisor = decimal.Decimal(str(param))
51+
if value % divisor != 0:
4552
raise ValidationError("{0} is not a multiple of {1}".format(value, param))
4653

4754

test/test_pytest.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def test_schema_validation():
4141
"$id": "test",
4242
"type": "object",
4343
"properties": {
44-
"name": "string", # <-- this is invalid
44+
"name": "string", # <-- this is invalid
4545
"email": {"oneOf": [{"type": "string"}, {"type": "integer"}]},
4646
},
4747
"required": ["email"],
@@ -531,3 +531,24 @@ def test_justareference_example(markdown_examples):
531531
)
532532
ns = builder.build_classes()
533533
ns.JustAReference("Hello")
534+
535+
536+
def test_number_multiple_of_validation():
537+
schema = {
538+
"$schema": "http://json-schema.org/schema#",
539+
"$id": "test",
540+
"type": "object",
541+
"title": "Base",
542+
"properties": {
543+
"sample": {
544+
"type": "number",
545+
"minimum": 0,
546+
"maximum": 1000000000,
547+
"multipleOf": 0.001,
548+
},
549+
},
550+
}
551+
552+
builder = pjs.ObjectBuilder(schema)
553+
ns = builder.build_classes()
554+
ns.Base(sample=33.069)

0 commit comments

Comments
 (0)