voxpupuli / json-schema

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

Added new option :restrict_additional_properties. Datas can be a subs… #268

Closed tak2siva closed 8 years ago

tak2siva commented 8 years ago

…et of schema which is not possible with :strict

tak2siva commented 8 years ago

My application contracts are mostly a subset of the original. Looks like there is no way in json-schema to validate our needs. So added the option :restrict_additional_properties which will only check for additional properties.

schema = {
  "$schema" => "http://json-schema.org/draft-04/schema#",
  "properties" => {
    "a" => {"type" => "string"},
    "b" => {"type" => "string"}
  }
}

data = {"a" => "a"}
assert(JSON::Validator.validate(schema,data,:restrict_additional_properties => true)) ## Success

data = {"a" => "a", "d" => "d"}
assert(JSON::Validator.validate(schema,data,:restrict_additional_properties => true)) ## Fail
RST-J commented 8 years ago

If you simply want to make sure that there are no additional properties you should modify your schemas such that every object description has additionalProperties: false. As I understood your requirement, this should exactly do what you are looking for.

jlblcc commented 8 years ago

This option would be useful when developing schemas and for testing. Currently, I use an alternative validator to perform this type of testing. Strict mode doesn't help with testing partial examples, since all properties are treated as required.

tak2siva commented 8 years ago

@RST-J Nope. That didnt work.

data = {"a" => "a", "b" => "b", "c" => "c"}
assert(!JSON::Validator.validate(schema,data,:additionalProperties => false))  ## This test will fail 

data = {"a" => "a", "b" => "b", "c" => "c"}
assert(!JSON::Validator.validate(schema,data,:restrict_additional_properties => true))  ## This test will pass 
RST-J commented 8 years ago

No, I don't mean as an option to json-schema but as part of the schema you pass in:

schema = {
  "$schema" => "http://json-schema.org/draft-04/schema#",
  "properties" => {
    "a" => {"type" => "string"},
    "b" => {"type" => "string"}
  },
  "additionalProperties" => false
}
tak2siva commented 8 years ago

@RST-J Isn't that tedious and repetitive doing it for all endpoint's ? Especially when an established big projects starts using this gem. Why not a one time config for ?

iainbeeston commented 8 years ago

Sorry @tak2siva but weak ready have far too many custom options to maintain.

If you find it repetitive, why not add additionalProperties: false programmatically (you can provide the schema as a ruby hash, as well as a string)

tak2siva commented 8 years ago

No issues. Switched to an alternative long back.