Skip to content

Commit

Permalink
Merge pull request #261 from azubieta/master
Browse files Browse the repository at this point in the history
Handle float operation errors when using divmod
  • Loading branch information
cwacek authored Sep 13, 2023
2 parents 47488cc + 06907b6 commit abf38dd
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
11 changes: 9 additions & 2 deletions python_jsonschema_objects/validators.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import decimal
import logging

import six
Expand Down Expand Up @@ -40,8 +41,14 @@ def __call__(self, name):

@registry.register()
def multipleOf(param, value, _):
quot, rem = divmod(value, param)
if rem != 0:
# This conversion to string is intentional because floats are imprecise.
# >>> decimal.Decimal(33.069)
# Decimal('33.0690000000000026147972675971686840057373046875')
# >>> decimal.Decimal('33.069')
# Decimal('33.069')
value = decimal.Decimal(str(value))
divisor = decimal.Decimal(str(param))
if value % divisor != 0:
raise ValidationError("{0} is not a multiple of {1}".format(value, param))


Expand Down
23 changes: 22 additions & 1 deletion test/test_pytest.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def test_schema_validation():
"$id": "test",
"type": "object",
"properties": {
"name": "string", # <-- this is invalid
"name": "string", # <-- this is invalid
"email": {"oneOf": [{"type": "string"}, {"type": "integer"}]},
},
"required": ["email"],
Expand Down Expand Up @@ -531,3 +531,24 @@ def test_justareference_example(markdown_examples):
)
ns = builder.build_classes()
ns.JustAReference("Hello")


def test_number_multiple_of_validation():
schema = {
"$schema": "http://json-schema.org/schema#",
"$id": "test",
"type": "object",
"title": "Base",
"properties": {
"sample": {
"type": "number",
"minimum": 0,
"maximum": 1000000000,
"multipleOf": 0.001,
},
},
}

builder = pjs.ObjectBuilder(schema)
ns = builder.build_classes()
ns.Base(sample=33.069)

0 comments on commit abf38dd

Please sign in to comment.