Skip to content

Commit

Permalink
Use BigDecimal for multiple_of check
Browse files Browse the repository at this point in the history
Floats aren't accurate enough here.

Fixes: #100

Also addresses overflow exposed by: json-schema-org/JSON-Schema-Test-Suite#438

```
FloatDomainError: Infinity
    /Users/dharsha/repos/json_schemer/lib/json_schemer/schema/base.rb:367:in `floor'
    /Users/dharsha/repos/json_schemer/lib/json_schemer/schema/base.rb:367:in `validate_numeric'
    /Users/dharsha/repos/json_schemer/lib/json_schemer/schema/base.rb:378:in `validate_number'
    /Users/dharsha/repos/json_schemer/lib/json_schemer/schema/base.rb:277:in `validate_type'
    /Users/dharsha/repos/json_schemer/lib/json_schemer/schema/base.rb:198:in `validate_instance'
```
  • Loading branch information
davishmcclurg committed Apr 1, 2022
1 parent 450ce77 commit ff7a4ba
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 2 deletions.
1 change: 1 addition & 0 deletions lib/json_schemer.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# frozen_string_literal: true
require 'base64'
require 'bigdecimal'
require 'ipaddr'
require 'json'
require 'net/http'
Expand Down
3 changes: 1 addition & 2 deletions lib/json_schemer/schema/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,7 @@ def validate_numeric(instance, &block)
validate_exclusive_minimum(instance, exclusive_minimum, minimum, &block) if exclusive_minimum

if multiple_of
quotient = data / multiple_of.to_f
yield error(instance, 'multipleOf') unless quotient.floor == quotient
yield error(instance, 'multipleOf') unless BigDecimal(data.to_s).modulo(multiple_of).zero?
end
end

Expand Down
6 changes: 6 additions & 0 deletions test/json_schemer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1050,4 +1050,10 @@ def test_it_validates_correctly_custom_keywords
assert schema.valid?(2)
refute schema.valid?(3)
end

def test_it_handles_multiple_of_floats
assert JSONSchemer.schema({ 'multipleOf' => 0.01 }).valid?(8.61)
refute JSONSchemer.schema({ 'multipleOf' => 0.01 }).valid?(8.666)
assert JSONSchemer.schema({ 'multipleOf' => 0.001 }).valid?(8.666)
end
end

0 comments on commit ff7a4ba

Please sign in to comment.