voxpupuli / json-schema

Ruby JSON Schema Validator
MIT License
1.54k stars 243 forks source link

Does not fail for type number when the data is string #251

Closed bparanj closed 9 years ago

bparanj commented 9 years ago

According to this document: http://spacetelescope.github.io/understanding-json-schema/UnderstandingJSONSchema.pdf

type : 'number' should fail if the data is a string but it does not. Here is a spec to reproduce the problem:

require 'json-schema'

describe 'JSON Schema' do

  context 'illustrate how to use the number type for schema type number' do
    let(:schema) { {'type' => 'number'} }

    # This test will fail if the json-schema gem fixes the bug
    # Test is written to make the test pass to expose the bug.
    it 'Bug in json-schema gem. Numbers which are string should fail.' do
      data = '42'  

      result = JSON::Validator.validate(schema, data)

      expect(result).to be true      
    end
  end  

end
iainbeeston commented 9 years ago

No this is the expected result. When you pass "42" to JSON-Schema, it sees that it is a string and assumes that it's a JSON text which needs parsing. So it passes it to the JSON gem. That parses it as the number 42, which is valid in your schema.

To get the behaviour you expect you need to pass a JSON text containing the string "42" (eg data = '"42"'). Or you can tell json-schema that the string does not need parsing, by calling validate(schema, data, json: true) - this will try to validate the string "42"

bparanj commented 9 years ago

Thanks for the response. You can close it.