diff --git a/.hound.yml b/.hound.yml new file mode 100644 index 00000000..5d0ff60b --- /dev/null +++ b/.hound.yml @@ -0,0 +1,2 @@ +ruby: + config_file: .rubocop.yml diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..be5d088c --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,253 @@ +AllCops: + Exclude: + - lib/json-schema/util/uuid.rb + UseCache: false +Style/ClassVars: + Description: Avoid the use of class variables. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-class-vars + Exclude: + - lib/json-schema/validator.rb +Style/CollectionMethods: + Description: Preferred collection methods. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#map-find-select-reduce-size + Enabled: true + PreferredMethods: + collect: map + collect!: map! + find: detect + find_all: select + reduce: inject +Style/DotPosition: + Description: Checks the position of the dot in multi-line method calls. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#consistent-multi-line-chains + Enabled: true + EnforcedStyle: trailing + SupportedStyles: + - leading + - trailing +Style/FileName: + Description: Use snake_case for source file names. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#snake-case-files + Enabled: false + Exclude: [] +Style/GuardClause: + Description: Check for conditionals that can be replaced with guard clauses + StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals + Enabled: false + MinBodyLength: 1 +Style/IfUnlessModifier: + Description: Favor modifier if/unless usage when you have a single-line body. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier + Enabled: false + MaxLineLength: 80 +Style/Lambda: + Description: Use the new lambda literal syntax for single-line blocks. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#lambda-multi-line + Enabled: false +Style/OptionHash: + Description: "Don't use option hashes when you can use keyword arguments." + Enabled: false +Style/PredicateName: + Description: Check the names of predicate methods. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#bool-methods-qmark + Enabled: true + NamePrefix: + - is_ + - has_ + - have_ + NamePrefixBlacklist: + - is_ + Exclude: + - spec/**/* +Style/Proc: + Description: Use proc instead of Proc.new. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#proc + Enabled: false +Style/RaiseArgs: + Description: Checks the arguments passed to raise/fail. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#exception-class-messages + Enabled: false + EnforcedStyle: exploded + SupportedStyles: + - compact + - exploded +Style/SignalException: + Description: Checks for proper usage of fail and raise. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#fail-method + Enabled: false + EnforcedStyle: semantic + SupportedStyles: + - only_raise + - only_fail + - semantic +Style/SingleLineBlockParams: + Description: Enforces the names of some block params. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#reduce-blocks + Enabled: false + Methods: + - reduce: + - a + - e + - inject: + - a + - e +Style/SingleLineMethods: + Description: Avoid single-line methods. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-single-line-methods + Enabled: false + AllowIfMethodIsEmpty: true +Style/SpecialGlobalVars: + Description: Avoid Perl-style global variables. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-cryptic-perlisms + Enabled: false +Style/StringLiterals: + Description: Checks if uses of quotes match the configured preference. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#consistent-string-literals + Enabled: true + EnforcedStyle: double_quotes + SupportedStyles: + - single_quotes + - double_quotes +Style/StringLiteralsInInterpolation: + Description: Checks if uses of quotes inside expressions in interpolated strings + match the configured preference. + Enabled: true + EnforcedStyle: single_quotes + SupportedStyles: + - single_quotes + - double_quotes +Metrics/AbcSize: + Description: A calculated magnitude based on number of assignments, branches, and + conditions. + Enabled: false + Max: 15 +Metrics/BlockNesting: + Description: Avoid excessive block nesting + StyleGuide: https://github.com/bbatsov/ruby-style-guide#three-is-the-number-thou-shalt-count + Enabled: false + Max: 3 +Metrics/ClassLength: + Description: Avoid classes longer than 100 lines of code. + Enabled: false + CountComments: false + Max: 100 +Metrics/LineLength: + Description: Limit lines to 80 characters. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#80-character-limits + Enabled: false +Metrics/ModuleLength: + Description: Avoid modules longer than 100 lines of code. + CountComments: false + Max: 100 + Enabled: false +Metrics/CyclomaticComplexity: + Description: A complexity metric that is strongly correlated to the number of test + cases needed to validate a method. + Enabled: false + Max: 6 +Metrics/MethodLength: + Description: Avoid methods longer than 10 lines of code. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#short-methods + Enabled: false + CountComments: false + Max: 10 +Metrics/ParameterLists: + Description: Avoid parameter lists longer than three or four parameters. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#too-many-params + Enabled: false + Max: 5 + CountKeywordArgs: true +Metrics/PerceivedComplexity: + Description: A complexity metric geared towards measuring complexity for a human + reader. + Enabled: false + Max: 7 +Lint/AssignmentInCondition: + Description: "Don't use assignment in conditions." + StyleGuide: https://github.com/bbatsov/ruby-style-guide#safe-assignment-in-condition + Enabled: false + AllowSafeAssignment: true +Style/InlineComment: + Description: Avoid inline comments. + Enabled: false +Style/AccessorMethodName: + Description: Check the naming of accessor methods for get_/set_. + Enabled: false +Style/Alias: + Description: Use alias_method instead of alias. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#alias-method + Enabled: false +Style/BlockDelimiters: + Description: Avoid using {...} for multi-line blocks (multiline chaining is always ugly). + Prefer {...} over do...end for single-line blocks. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#single-line-blocks + Enabled: true + EnforcedStyle: line_count_based + SupportedStyles: + - line_count_based + - semantic + - braces_for_chaining +Style/Documentation: + Description: Document classes and non-namespace modules. + Enabled: false +Style/EachWithObject: + Description: Prefer `each_with_object` over `inject` or `reduce`. + Enabled: false +Style/HashSyntax: + Description: "Prefer Ruby 1.9 hash syntax { a: 1, b: 2 } over 1.8 syntax { :a => 1, :b => 2 }." + EnforcedStyle: hash_rockets + Enabled: true + SupportedStyles: + - ruby19 + - ruby19_no_mixed_keys + - hash_rockets +Style/ModuleFunction: + Description: Checks for usage of `extend self` in modules. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#module-function + Enabled: false +Style/MultilineBlockChain: + Description: Avoid multi-line chains of blocks. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#single-line-blocks + Enabled: false +Style/OneLineConditional: + Description: Favor the ternary operator(?:) over if/then/else/end constructs. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#ternary-operator + Enabled: false +Style/Send: + Description: Prefer `Object#__send__` or `Object#public_send` to `send`, as `send` + may overlap with existing methods. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#prefer-public-send + Enabled: false +Style/SpaceInsideHashLiteralBraces: + Description: "Use spaces inside hash literal braces - or don't." + StyleGuide: https://github.com/bbatsov/ruby-style-guide#spaces-operators + EnforcedStyle: no_space + EnforcedStyleForEmptyBraces: no_space + SupportedStyles: + - space + - no_space +Style/VariableInterpolation: + Description: "Don't interpolate global, instance and class variables directly in strings." + StyleGuide: https://github.com/bbatsov/ruby-style-guide#curlies-interpolate + Enabled: false +Style/WhenThen: + Description: Use when x then ... for one-line cases. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#one-line-cases + Enabled: false +Style/WordArray: + Description: Use %w or %W for arrays of words. + StyleGuide: https://github.com/bbatsov/ruby-style-guide#percent-w + Enabled: false +Lint/EachWithObjectArgument: + Description: Check for immutable argument given to each_with_object. + Enabled: true +Lint/HandleExceptions: + Description: "Don't suppress exception." + StyleGuide: https://github.com/bbatsov/ruby-style-guide#dont-hide-exceptions + Enabled: false +Lint/LiteralInCondition: + Description: Checks of literals used in conditions. + Enabled: false +Lint/LiteralInInterpolation: + Description: Checks for literals used in interpolation. + Enabled: false diff --git a/Rakefile b/Rakefile index 76591dd9..0844f136 100644 --- a/Rakefile +++ b/Rakefile @@ -1,6 +1,6 @@ -require 'bundler' -require 'rake' -require 'rake/testtask' +require "bundler" +require "rake" +require "rake/testtask" Bundler::GemHelper.install_tasks @@ -16,7 +16,7 @@ Rake::TestTask.new do |t| t.libs << "." t.warning = true t.verbose = true - t.test_files = FileList.new('test/test*.rb') do |fl| + t.test_files = FileList.new("test/test*.rb") do |fl| fl.exclude(/test_helper\.rb$/) end end diff --git a/json-schema.gemspec b/json-schema.gemspec index 4c144529..1c4e7366 100644 --- a/json-schema.gemspec +++ b/json-schema.gemspec @@ -1,6 +1,6 @@ -require 'yaml' +require "yaml" -version_yaml = YAML.load(File.open('VERSION.yml').read) +version_yaml = YAML.load(File.open("VERSION.yml").read) version = "#{version_yaml['major']}.#{version_yaml['minor']}.#{version_yaml['patch']}" gem_name = "json-schema" @@ -11,17 +11,17 @@ Gem::Specification.new do |s| s.email = "hoxworth@gmail.com" s.homepage = "http://github.com/ruby-json-schema/json-schema/tree/master" s.summary = "Ruby JSON Schema Validator" - s.files = Dir[ "lib/**/*", "resources/*.json" ] + s.files = Dir["lib/**/*", "resources/*.json"] s.require_path = "lib" - s.extra_rdoc_files = ["README.textile","LICENSE.md"] + s.extra_rdoc_files = ["README.textile", "LICENSE.md"] s.required_ruby_version = ">= 1.8.7" s.license = "MIT" s.required_rubygems_version = ">= 1.8" s.add_development_dependency "rake" - s.add_development_dependency "minitest", '~> 5.0' + s.add_development_dependency "minitest", "~> 5.0" s.add_development_dependency "webmock" s.add_development_dependency "bundler" - s.add_runtime_dependency "addressable", '~> 2.3.8' + s.add_runtime_dependency "addressable", "~> 2.3.8" end diff --git a/lib/json-schema.rb b/lib/json-schema.rb index 630001d7..bad1eeae 100644 --- a/lib/json-schema.rb +++ b/lib/json-schema.rb @@ -1,19 +1,19 @@ -require 'rubygems' +require "rubygems" -if Gem::Specification::find_all_by_name('multi_json').any? - require 'multi_json' +if Gem::Specification.find_all_by_name("multi_json").any? + require "multi_json" # Force MultiJson to load an engine before we define the JSON constant here; otherwise, # it looks for things that are under the JSON namespace that aren't there (since we have defined it here) MultiJson.respond_to?(:adapter) ? MultiJson.adapter : MultiJson.engine end -require 'json-schema/util/array_set' -require 'json-schema/util/uri' -require 'json-schema/schema' -require 'json-schema/schema/reader' -require 'json-schema/validator' +require "json-schema/util/array_set" +require "json-schema/util/uri" +require "json-schema/schema" +require "json-schema/schema/reader" +require "json-schema/validator" -Dir[File.join(File.dirname(__FILE__), "json-schema/attributes/*.rb")].each {|file| require file } -Dir[File.join(File.dirname(__FILE__), "json-schema/attributes/formats/*.rb")].each {|file| require file } -Dir[File.join(File.dirname(__FILE__), "json-schema/validators/*.rb")].sort!.each {|file| require file } +Dir[File.join(File.dirname(__FILE__), "json-schema/attributes/*.rb")].each { |file| require file } +Dir[File.join(File.dirname(__FILE__), "json-schema/attributes/formats/*.rb")].each { |file| require file } +Dir[File.join(File.dirname(__FILE__), "json-schema/validators/*.rb")].sort!.each { |file| require file } diff --git a/lib/json-schema/attribute.rb b/lib/json-schema/attribute.rb index e75e5417..dca09451 100644 --- a/lib/json-schema/attribute.rb +++ b/lib/json-schema/attribute.rb @@ -1,9 +1,9 @@ -require 'json-schema/errors/validation_error' +require "json-schema/errors/validation_error" module JSON class Schema class Attribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(_current_schema, _data, _fragments, _processor, _validator, _options = {}) end def self.build_fragment(fragments) diff --git a/lib/json-schema/attributes/additionalitems.rb b/lib/json-schema/attributes/additionalitems.rb index a6c2ef9e..5df324c8 100644 --- a/lib/json-schema/attributes/additionalitems.rb +++ b/lib/json-schema/attributes/additionalitems.rb @@ -1,4 +1,4 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema @@ -7,18 +7,18 @@ def self.validate(current_schema, data, fragments, processor, validator, options return unless data.is_a?(Array) schema = current_schema.schema - return unless schema['items'].is_a?(Array) + return unless schema["items"].is_a?(Array) - case schema['additionalItems'] + case schema["additionalItems"] when false - if schema['items'].length != data.length + if schema["items"].length != data.length message = "The property '#{build_fragment(fragments)}' contains additional array elements outside of the schema when none are allowed" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) end when Hash - additional_items_schema = JSON::Schema.new(schema['additionalItems'], current_schema.uri, validator) + additional_items_schema = JSON::Schema.new(schema["additionalItems"], current_schema.uri, validator) data.each_with_index do |item, i| - next if i < schema['items'].length + next if i < schema["items"].length additional_items_schema.validate(item, fragments + [i.to_s], processor, options) end end diff --git a/lib/json-schema/attributes/additionalproperties.rb b/lib/json-schema/attributes/additionalproperties.rb index 331e681c..66278c15 100644 --- a/lib/json-schema/attributes/additionalproperties.rb +++ b/lib/json-schema/attributes/additionalproperties.rb @@ -1,16 +1,16 @@ -require 'json-schema/attribute' -require 'json-schema/attributes/extends' +require "json-schema/attribute" +require "json-schema/attributes/extends" module JSON class Schema class AdditionalPropertiesAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) schema = current_schema.schema - return unless data.is_a?(Hash) && (schema['type'].nil? || schema['type'] == 'object') + return unless data.is_a?(Hash) && (schema["type"].nil? || schema["type"] == "object") extra_properties = remove_valid_properties(data.keys, current_schema, validator) - addprop = schema['additionalProperties'] + addprop = schema["additionalProperties"] if addprop.is_a?(Hash) matching_properties = extra_properties # & addprop.keys matching_properties.each do |key| @@ -29,18 +29,18 @@ def self.validate(current_schema, data, fragments, processor, validator, options def self.remove_valid_properties(extra_properties, current_schema, validator) schema = current_schema.schema - if schema['properties'] - extra_properties = extra_properties - schema['properties'].keys + if schema["properties"] + extra_properties -= schema["properties"].keys end - if schema['patternProperties'] - schema['patternProperties'].each_key do |key| + if schema["patternProperties"] + schema["patternProperties"].each_key do |key| regexp = Regexp.new(key) extra_properties.reject! { |prop| regexp.match(prop) } end end - if extended_schemas = schema['extends'] + if extended_schemas = schema["extends"] extended_schemas = [extended_schemas] unless extended_schemas.is_a?(Array) extended_schemas.each do |schema_value| _, extended_schema = JSON::Schema::ExtendsAttribute.get_extended_uri_and_schema(schema_value, current_schema, validator) @@ -52,7 +52,6 @@ def self.remove_valid_properties(extra_properties, current_schema, validator) extra_properties end - end end end diff --git a/lib/json-schema/attributes/allof.rb b/lib/json-schema/attributes/allof.rb index 8f88d592..4aca17b9 100644 --- a/lib/json-schema/attributes/allof.rb +++ b/lib/json-schema/attributes/allof.rb @@ -1,4 +1,4 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema @@ -8,22 +8,22 @@ def self.validate(current_schema, data, fragments, processor, validator, options errors = Hash.new { |hsh, k| hsh[k] = [] } valid = true - current_schema.schema['allOf'].each_with_index do |element, schema_index| - schema = JSON::Schema.new(element,current_schema.uri,validator) + current_schema.schema["allOf"].each_with_index do |element, schema_index| + schema = JSON::Schema.new(element, current_schema.uri, validator) # We're going to add a little cruft here to try and maintain any validation errors that occur in the allOf # We'll handle this by keeping an error count before and after validation, extracting those errors and pushing them onto an error array pre_validation_error_count = validation_errors(processor).count begin - schema.validate(data,fragments,processor,options) + schema.validate(data, fragments, processor, options) rescue ValidationError valid = false end diff = validation_errors(processor).count - pre_validation_error_count while diff > 0 - diff = diff - 1 + diff -= 1 errors["allOf ##{schema_index}"].push(validation_errors(processor).pop) end end diff --git a/lib/json-schema/attributes/anyof.rb b/lib/json-schema/attributes/anyof.rb index 559bff3e..0f4e145c 100644 --- a/lib/json-schema/attributes/anyof.rb +++ b/lib/json-schema/attributes/anyof.rb @@ -1,4 +1,4 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema @@ -10,15 +10,15 @@ def self.validate(current_schema, data, fragments, processor, validator, options original_data = data.is_a?(Hash) ? data.clone : data - current_schema.schema['anyOf'].each_with_index do |element, schema_index| - schema = JSON::Schema.new(element,current_schema.uri,validator) + current_schema.schema["anyOf"].each_with_index do |element, schema_index| + schema = JSON::Schema.new(element, current_schema.uri, validator) # We're going to add a little cruft here to try and maintain any validation errors that occur in the anyOf # We'll handle this by keeping an error count before and after validation, extracting those errors and pushing them onto a union error pre_validation_error_count = validation_errors(processor).count begin - schema.validate(data,fragments,processor,options) + schema.validate(data, fragments, processor, options) valid = true rescue ValidationError # We don't care that these schemas don't validate - we only care that one validated @@ -27,7 +27,7 @@ def self.validate(current_schema, data, fragments, processor, validator, options diff = validation_errors(processor).count - pre_validation_error_count valid = false if diff > 0 while diff > 0 - diff = diff - 1 + diff -= 1 errors["anyOf ##{schema_index}"].push(validation_errors(processor).pop) end @@ -36,7 +36,7 @@ def self.validate(current_schema, data, fragments, processor, validator, options data = original_data end - if !valid + unless valid message = "The property '#{build_fragment(fragments)}' of type #{data.class} did not match one or more of the required schemas" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) validation_errors(processor).last.sub_errors = errors diff --git a/lib/json-schema/attributes/dependencies.rb b/lib/json-schema/attributes/dependencies.rb index e006921e..a76a117a 100644 --- a/lib/json-schema/attributes/dependencies.rb +++ b/lib/json-schema/attributes/dependencies.rb @@ -1,4 +1,4 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema @@ -6,8 +6,8 @@ class DependenciesAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) return unless data.is_a?(Hash) - current_schema.schema['dependencies'].each do |property, dependency_value| - next unless data.has_key?(property.to_s) + current_schema.schema["dependencies"].each do |property, dependency_value| + next unless data.key?(property.to_s) next unless accept_value?(dependency_value) case dependency_value diff --git a/lib/json-schema/attributes/disallow.rb b/lib/json-schema/attributes/disallow.rb index c76e3727..99d056db 100644 --- a/lib/json-schema/attributes/disallow.rb +++ b/lib/json-schema/attributes/disallow.rb @@ -1,10 +1,10 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class DisallowAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) - return unless type = validator.attributes['type'] + return unless type = validator.attributes["type"] type.validate(current_schema, data, fragments, processor, validator, options.merge(:disallow => true)) end end diff --git a/lib/json-schema/attributes/divisibleby.rb b/lib/json-schema/attributes/divisibleby.rb index d4655b54..d042906c 100644 --- a/lib/json-schema/attributes/divisibleby.rb +++ b/lib/json-schema/attributes/divisibleby.rb @@ -1,13 +1,13 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class DivisibleByAttribute < Attribute def self.keyword - 'divisibleBy' + "divisibleBy" end - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) return unless data.is_a?(Numeric) factor = current_schema.schema[keyword] diff --git a/lib/json-schema/attributes/enum.rb b/lib/json-schema/attributes/enum.rb index 90171f49..d8023d0f 100644 --- a/lib/json-schema/attributes/enum.rb +++ b/lib/json-schema/attributes/enum.rb @@ -1,20 +1,20 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class EnumAttribute < Attribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) - enum = current_schema.schema['enum'] + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) + enum = current_schema.schema["enum"] return if enum.include?(data) - values = enum.map { |val| + values = enum.map do |val| case val - when nil then 'null' - when Array then 'array' - when Hash then 'object' + when nil then "null" + when Array then "array" + when Hash then "object" else val.to_s end - }.join(', ') + end.join(", ") message = "The property '#{build_fragment(fragments)}' value #{data.inspect} did not match one of the following values: #{values}" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) diff --git a/lib/json-schema/attributes/extends.rb b/lib/json-schema/attributes/extends.rb index 38040f16..d3bccd7f 100644 --- a/lib/json-schema/attributes/extends.rb +++ b/lib/json-schema/attributes/extends.rb @@ -1,18 +1,18 @@ -require 'json-schema/attribute' -require 'json-schema/attributes/ref' +require "json-schema/attribute" +require "json-schema/attributes/ref" module JSON class Schema class ExtendsAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) - schemas = current_schema.schema['extends'] - schemas = [schemas] if !schemas.is_a?(Array) + schemas = current_schema.schema["extends"] + schemas = [schemas] unless schemas.is_a?(Array) schemas.each do |s| - uri,schema = get_extended_uri_and_schema(s, current_schema, validator) + uri, schema = get_extended_uri_and_schema(s, current_schema, validator) if schema schema.validate(data, fragments, processor, options) elsif uri - message = "The extended schema '#{uri.to_s}' cannot be found" + message = "The extended schema '#{uri}' cannot be found" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) else message = "The property '#{build_fragment(fragments)}' was not a valid schema" @@ -22,28 +22,30 @@ def self.validate(current_schema, data, fragments, processor, validator, options end def self.get_extended_uri_and_schema(s, current_schema, validator) - uri,schema = nil,nil + uri = nil + schema = nil - s = {'$ref' => s} if s.is_a?(String) + s = {"$ref" => s} if s.is_a?(String) if s.is_a?(Hash) uri = current_schema.uri - if s['$ref'] - ref_uri,ref_schema = JSON::Schema::RefAttribute.get_referenced_uri_and_schema(s, current_schema, validator) + if s["$ref"] + ref_uri, ref_schema = JSON::Schema::RefAttribute.get_referenced_uri_and_schema(s, current_schema, validator) if ref_schema if s.size == 1 # Check if anything else apart from $ref - uri,schema = ref_uri,ref_schema + uri = ref_uri + schema = ref_schema else s = s.dup - s.delete '$ref' + s.delete "$ref" s = ref_schema.schema.merge(s) end end end - schema ||= JSON::Schema.new(s,uri,validator) + schema ||= JSON::Schema.new(s, uri, validator) end - [uri,schema] + [uri, schema] end end end diff --git a/lib/json-schema/attributes/format.rb b/lib/json-schema/attributes/format.rb index 37f77052..9392a5a8 100644 --- a/lib/json-schema/attributes/format.rb +++ b/lib/json-schema/attributes/format.rb @@ -1,11 +1,11 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class FormatAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) - return unless data_valid_for_type?(data, current_schema.schema['type']) - format = current_schema.schema['format'].to_s + return unless data_valid_for_type?(data, current_schema.schema["type"]) + format = current_schema.schema["format"].to_s validator = validator.formats[format] validator.validate(current_schema, data, fragments, processor, validator, options) unless validator.nil? end diff --git a/lib/json-schema/attributes/formats/custom.rb b/lib/json-schema/attributes/formats/custom.rb index d1638419..8cb0651a 100644 --- a/lib/json-schema/attributes/formats/custom.rb +++ b/lib/json-schema/attributes/formats/custom.rb @@ -1,5 +1,5 @@ -require 'json-schema/attribute' -require 'json-schema/errors/custom_format_error' +require "json-schema/attribute" +require "json-schema/errors/custom_format_error" module JSON class Schema @@ -8,13 +8,11 @@ def initialize(validation_proc) @validation_proc = validation_proc end - def validate(current_schema, data, fragments, processor, validator, options = {}) - begin - @validation_proc.call data - rescue JSON::Schema::CustomFormatError => e - message = "The property '#{self.class.build_fragment(fragments)}' #{e.message}" - self.class.validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) - end + def validate(current_schema, data, fragments, processor, _validator, options = {}) + @validation_proc.call(data) + rescue JSON::Schema::CustomFormatError => e + message = "The property '#{self.class.build_fragment(fragments)}' #{e.message}" + self.class.validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) end end end diff --git a/lib/json-schema/attributes/formats/date.rb b/lib/json-schema/attributes/formats/date.rb index 24b21700..25b42562 100644 --- a/lib/json-schema/attributes/formats/date.rb +++ b/lib/json-schema/attributes/formats/date.rb @@ -1,17 +1,17 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class DateFormat < FormatAttribute REGEXP = /\A\d{4}-\d{2}-\d{2}\z/ - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) if data.is_a?(String) error_message = "The property '#{build_fragment(fragments)}' must be a date in the format of YYYY-MM-DD" if REGEXP.match(data) begin Date.parse(data) - rescue Exception + rescue validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) end else diff --git a/lib/json-schema/attributes/formats/date_time.rb b/lib/json-schema/attributes/formats/date_time.rb index b1baa15c..2eb17f0a 100644 --- a/lib/json-schema/attributes/formats/date_time.rb +++ b/lib/json-schema/attributes/formats/date_time.rb @@ -1,11 +1,11 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class DateTimeFormat < FormatAttribute REGEXP = /\A\d{4}-\d{2}-\d{2}T(\d{2}):(\d{2}):(\d{2})([\.,]\d+)?(Z|[+-](\d{2})(:?\d{2})?)?\z/ - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) # Timestamp in restricted ISO-8601 YYYY-MM-DDThh:mm:ssZ with optional decimal fraction of the second if data.is_a?(String) error_message = "The property '#{build_fragment(fragments)}' must be a date/time in the ISO-8601 format of YYYY-MM-DDThh:mm:ssZ or YYYY-MM-DDThh:mm:ss.ssZ" @@ -14,16 +14,16 @@ def self.validate(current_schema, data, fragments, processor, validator, options begin Date.parse(parts[0]) - rescue Exception + rescue validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) return end begin - validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) and return if m[1].to_i > 23 - validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) and return if m[2].to_i > 59 - validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) and return if m[3].to_i > 59 - rescue Exception + validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) && return if m[1].to_i > 23 + validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) && return if m[2].to_i > 59 + validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) && return if m[3].to_i > 59 + rescue validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) end else diff --git a/lib/json-schema/attributes/formats/date_time_v4.rb b/lib/json-schema/attributes/formats/date_time_v4.rb index 0a1903fc..782a11a7 100644 --- a/lib/json-schema/attributes/formats/date_time_v4.rb +++ b/lib/json-schema/attributes/formats/date_time_v4.rb @@ -1,9 +1,9 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class DateTimeV4Format < FormatAttribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) return unless data.is_a?(String) DateTime.rfc3339(data) rescue ArgumentError diff --git a/lib/json-schema/attributes/formats/ip.rb b/lib/json-schema/attributes/formats/ip.rb index 04b2e3ac..adfe038c 100644 --- a/lib/json-schema/attributes/formats/ip.rb +++ b/lib/json-schema/attributes/formats/ip.rb @@ -1,17 +1,17 @@ -require 'json-schema/attributes/format' -require 'ipaddr' -require 'socket' +require "json-schema/attributes/format" +require "ipaddr" +require "socket" module JSON class Schema class IPFormat < FormatAttribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) return unless data.is_a?(String) begin ip = IPAddr.new(data) rescue ArgumentError => e - raise e unless e.message == 'invalid address' + raise e unless e.message == "invalid address" end family = ip_version == 6 ? Socket::AF_INET6 : Socket::AF_INET diff --git a/lib/json-schema/attributes/formats/time.rb b/lib/json-schema/attributes/formats/time.rb index 158df193..3f038ff2 100644 --- a/lib/json-schema/attributes/formats/time.rb +++ b/lib/json-schema/attributes/formats/time.rb @@ -1,17 +1,17 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class TimeFormat < FormatAttribute REGEXP = /\A(\d{2}):(\d{2}):(\d{2})\z/ - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) if data.is_a?(String) error_message = "The property '#{build_fragment(fragments)}' must be a time in the format of hh:mm:ss" if (m = REGEXP.match(data)) - validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) and return if m[1].to_i > 23 - validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) and return if m[2].to_i > 59 - validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) and return if m[3].to_i > 59 + validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) && return if m[1].to_i > 23 + validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) && return if m[2].to_i > 59 + validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) && return if m[3].to_i > 59 else validation_error(processor, error_message, fragments, current_schema, self, options[:record_errors]) end diff --git a/lib/json-schema/attributes/formats/uri.rb b/lib/json-schema/attributes/formats/uri.rb index ff74ad7d..70d8590f 100644 --- a/lib/json-schema/attributes/formats/uri.rb +++ b/lib/json-schema/attributes/formats/uri.rb @@ -1,9 +1,9 @@ -require 'json-schema/attribute' -require 'addressable/uri' +require "json-schema/attribute" +require "addressable/uri" module JSON class Schema class UriFormat < FormatAttribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) return unless data.is_a?(String) error_message = "The property '#{build_fragment(fragments)}' must be a valid URI" begin diff --git a/lib/json-schema/attributes/items.rb b/lib/json-schema/attributes/items.rb index 7c3df6b6..4eec7d41 100644 --- a/lib/json-schema/attributes/items.rb +++ b/lib/json-schema/attributes/items.rb @@ -1,4 +1,4 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema @@ -6,7 +6,7 @@ class ItemsAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) return unless data.is_a?(Array) - items = current_schema.schema['items'] + items = current_schema.schema["items"] case items when Hash schema = JSON::Schema.new(items, current_schema.uri, validator) diff --git a/lib/json-schema/attributes/limit.rb b/lib/json-schema/attributes/limit.rb index 90de84f2..07b8553b 100644 --- a/lib/json-schema/attributes/limit.rb +++ b/lib/json-schema/attributes/limit.rb @@ -1,9 +1,9 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class LimitAttribute < Attribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) schema = current_schema.schema return unless data.is_a?(acceptable_type) && invalid?(schema, value(data)) @@ -17,7 +17,7 @@ def self.invalid?(schema, data) exclusive = exclusive?(schema) limit = limit(schema) - if limit_name.start_with?('max') + if limit_name.start_with?("max") exclusive ? data >= limit : data > limit else exclusive ? data <= limit : data < limit @@ -28,7 +28,7 @@ def self.limit(schema) schema[limit_name] end - def self.exclusive?(schema) + def self.exclusive?(_schema) false end @@ -40,7 +40,7 @@ def self.acceptable_type raise NotImplementedError end - def self.error_message(schema) + def self.error_message(_schema) raise NotImplementedError end @@ -55,7 +55,7 @@ def self.acceptable_type end def self.limit_name - 'minLength' + "minLength" end def self.error_message(schema) @@ -69,7 +69,7 @@ def self.value(data) class MaxLengthAttribute < MinLengthAttribute def self.limit_name - 'maxLength' + "maxLength" end def self.error_message(schema) @@ -87,7 +87,7 @@ def self.value(data) end def self.limit_name - 'minItems' + "minItems" end def self.error_message(schema) @@ -97,7 +97,7 @@ def self.error_message(schema) class MaxItemsAttribute < MinItemsAttribute def self.limit_name - 'maxItems' + "maxItems" end def self.error_message(schema) @@ -115,7 +115,7 @@ def self.value(data) end def self.limit_name - 'minProperties' + "minProperties" end def self.error_message(schema) @@ -125,7 +125,7 @@ def self.error_message(schema) class MaxPropertiesAttribute < MinPropertiesAttribute def self.limit_name - 'maxProperties' + "maxProperties" end def self.error_message(schema) @@ -139,40 +139,40 @@ def self.acceptable_type end def self.error_message(schema) - exclusivity = exclusive?(schema) ? 'exclusively' : 'inclusively' + exclusivity = exclusive?(schema) ? "exclusively" : "inclusively" format("did not have a %s value of %s, %s", limit_name, limit(schema), exclusivity) end end class MaximumAttribute < NumericLimitAttribute def self.limit_name - 'maximum' + "maximum" end def self.exclusive?(schema) - schema['exclusiveMaximum'] + schema["exclusiveMaximum"] end end class MaximumInclusiveAttribute < MaximumAttribute def self.exclusive?(schema) - schema['maximumCanEqual'] == false + schema["maximumCanEqual"] == false end end class MinimumAttribute < NumericLimitAttribute def self.limit_name - 'minimum' + "minimum" end def self.exclusive?(schema) - schema['exclusiveMinimum'] + schema["exclusiveMinimum"] end end class MinimumInclusiveAttribute < MinimumAttribute def self.exclusive?(schema) - schema['minimumCanEqual'] == false + schema["minimumCanEqual"] == false end end end diff --git a/lib/json-schema/attributes/maxdecimal.rb b/lib/json-schema/attributes/maxdecimal.rb index 00caa1f4..12516b4b 100644 --- a/lib/json-schema/attributes/maxdecimal.rb +++ b/lib/json-schema/attributes/maxdecimal.rb @@ -1,12 +1,12 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class MaxDecimalAttribute < Attribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) return unless data.is_a?(Numeric) - max_decimal_places = current_schema.schema['maxDecimal'] + max_decimal_places = current_schema.schema["maxDecimal"] s = data.to_s.split(".")[1] if s && s.length > max_decimal_places message = "The property '#{build_fragment(fragments)}' had more decimal places than the allowed #{max_decimal_places}" diff --git a/lib/json-schema/attributes/multipleof.rb b/lib/json-schema/attributes/multipleof.rb index 5d96c6c0..d36ece29 100644 --- a/lib/json-schema/attributes/multipleof.rb +++ b/lib/json-schema/attributes/multipleof.rb @@ -1,10 +1,10 @@ -require 'json-schema/attributes/divisibleby' +require "json-schema/attributes/divisibleby" module JSON class Schema class MultipleOfAttribute < DivisibleByAttribute def self.keyword - 'multipleOf' + "multipleOf" end end end diff --git a/lib/json-schema/attributes/not.rb b/lib/json-schema/attributes/not.rb index 52729ef3..03616f2d 100644 --- a/lib/json-schema/attributes/not.rb +++ b/lib/json-schema/attributes/not.rb @@ -1,15 +1,15 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class NotAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) - schema = JSON::Schema.new(current_schema.schema['not'],current_schema.uri,validator) + schema = JSON::Schema.new(current_schema.schema["not"], current_schema.uri, validator) failed = true errors_copy = processor.validation_errors.clone begin - schema.validate(data,fragments,processor,options) + schema.validate(data, fragments, processor, options) # If we're recording errors, we don't throw an exception. Instead, check the errors array length if options[:record_errors] && errors_copy.length != processor.validation_errors.length processor.validation_errors.replace(errors_copy) diff --git a/lib/json-schema/attributes/oneof.rb b/lib/json-schema/attributes/oneof.rb index d3549538..3dbe6fdc 100644 --- a/lib/json-schema/attributes/oneof.rb +++ b/lib/json-schema/attributes/oneof.rb @@ -1,4 +1,4 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema @@ -7,7 +7,7 @@ def self.validate(current_schema, data, fragments, processor, validator, options errors = Hash.new { |hsh, k| hsh[k] = [] } validation_error_count = 0 - one_of = current_schema.schema['oneOf'] + one_of = current_schema.schema["oneOf"] original_data = data.is_a?(Hash) ? data.clone : data success_data = nil @@ -15,10 +15,10 @@ def self.validate(current_schema, data, fragments, processor, validator, options valid = false one_of.each_with_index do |element, schema_index| - schema = JSON::Schema.new(element,current_schema.uri,validator) + schema = JSON::Schema.new(element, current_schema.uri, validator) pre_validation_error_count = validation_errors(processor).count begin - schema.validate(data,fragments,processor,options) + schema.validate(data, fragments, processor, options) success_data = data.is_a?(Hash) ? data.clone : data valid = true rescue ValidationError @@ -27,16 +27,14 @@ def self.validate(current_schema, data, fragments, processor, validator, options diff = validation_errors(processor).count - pre_validation_error_count valid = false if diff > 0 - validation_error_count += 1 if !valid + validation_error_count += 1 unless valid while diff > 0 - diff = diff - 1 + diff -= 1 errors["oneOf ##{schema_index}"].push(validation_errors(processor).pop) end data = original_data end - - if validation_error_count == one_of.length - 1 data = success_data return diff --git a/lib/json-schema/attributes/pattern.rb b/lib/json-schema/attributes/pattern.rb index f1ed5111..5fc4135f 100644 --- a/lib/json-schema/attributes/pattern.rb +++ b/lib/json-schema/attributes/pattern.rb @@ -1,12 +1,12 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class PatternAttribute < Attribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) return unless data.is_a?(String) - pattern = current_schema.schema['pattern'] + pattern = current_schema.schema["pattern"] regexp = Regexp.new(pattern) unless regexp.match(data) message = "The property '#{build_fragment(fragments)}' value #{data.inspect} did not match the regex '#{pattern}'" diff --git a/lib/json-schema/attributes/patternproperties.rb b/lib/json-schema/attributes/patternproperties.rb index 21e5b9c5..97de683b 100644 --- a/lib/json-schema/attributes/patternproperties.rb +++ b/lib/json-schema/attributes/patternproperties.rb @@ -1,4 +1,4 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema @@ -6,11 +6,11 @@ class PatternPropertiesAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) return unless data.is_a?(Hash) - current_schema.schema['patternProperties'].each do |property, property_schema| + current_schema.schema["patternProperties"].each do |property, property_schema| regexp = Regexp.new(property) # Check each key in the data hash to see if it matches the regex - data.each do |key, value| + data.each do |key, _value| next unless regexp.match(key) schema = JSON::Schema.new(property_schema, current_schema.uri, validator) schema.validate(data[key], fragments + [key], processor, options) diff --git a/lib/json-schema/attributes/properties.rb b/lib/json-schema/attributes/properties.rb index 13c0f252..0b75267a 100644 --- a/lib/json-schema/attributes/properties.rb +++ b/lib/json-schema/attributes/properties.rb @@ -1,47 +1,47 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class PropertiesAttribute < Attribute def self.required?(schema, options) - schema.fetch('required') { options[:strict] } + schema.fetch("required") { options[:strict] } end def self.validate(current_schema, data, fragments, processor, validator, options = {}) return unless data.is_a?(Hash) schema = current_schema.schema - schema['properties'].each do |property, property_schema| + schema["properties"].each do |property, property_schema| property = property.to_s if !data.key?(property) && - options[:insert_defaults] && - property_schema.has_key?('default') && - !property_schema['readonly'] - default = property_schema['default'] + options[:insert_defaults] && + property_schema.key?("default") && + !property_schema["readonly"] + default = property_schema["default"] data[property] = default.is_a?(Hash) ? default.clone : default end - if required?(property_schema, options) && !data.has_key?(property) + if required?(property_schema, options) && !data.key?(property) message = "The property '#{build_fragment(fragments)}' did not contain a required property of '#{property}'" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) end - if data.has_key?(property) + if data.key?(property) expected_schema = JSON::Schema.new(property_schema, current_schema.uri, validator) expected_schema.validate(data[property], fragments + [property], processor, options) end end # When strict is true, ensure no undefined properties exist in the data - return unless options[:strict] == true && !schema.key?('additionalProperties') + return unless options[:strict] == true && !schema.key?("additionalProperties") - diff = data.select do |k, v| + diff = data.select do |k, _v| k = k.to_s - if schema.has_key?('patternProperties') + if schema.key?("patternProperties") match = false - schema['patternProperties'].each do |property, property_schema| + schema["patternProperties"].each do |property, _property_schema| regexp = Regexp.new(property) if regexp.match(k) match = true @@ -49,14 +49,14 @@ def self.validate(current_schema, data, fragments, processor, validator, options end end - !schema['properties'].has_key?(k) && !match + !schema["properties"].key?(k) && !match else - !schema['properties'].has_key?(k) + !schema["properties"].key?(k) end end if diff.size > 0 - properties = diff.keys.join(', ') + properties = diff.keys.join(", ") message = "The property '#{build_fragment(fragments)}' contained undefined properties: '#{properties}'" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) end @@ -66,7 +66,7 @@ def self.validate(current_schema, data, fragments, processor, validator, options class PropertiesV4Attribute < PropertiesAttribute # draft4 relies on its own RequiredAttribute validation at a higher level, rather than # as an attribute of individual properties. - def self.required?(schema, options) + def self.required?(_schema, options) options[:strict] == true end end diff --git a/lib/json-schema/attributes/properties_optional.rb b/lib/json-schema/attributes/properties_optional.rb index 0468676c..9280d917 100644 --- a/lib/json-schema/attributes/properties_optional.rb +++ b/lib/json-schema/attributes/properties_optional.rb @@ -1,4 +1,4 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema @@ -7,15 +7,15 @@ def self.validate(current_schema, data, fragments, processor, validator, options return unless data.is_a?(Hash) schema = current_schema.schema - schema['properties'].each do |property, property_schema| + schema["properties"].each do |property, property_schema| property = property.to_s - if !property_schema['optional'] && !data.key?(property) + if !property_schema["optional"] && !data.key?(property) message = "The property '#{build_fragment(fragments)}' did not contain a required property of '#{property}'" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) end - if data.has_key?(property) + if data.key?(property) expected_schema = JSON::Schema.new(property_schema, current_schema.uri, validator) expected_schema.validate(data[property], fragments + [property], processor, options) end diff --git a/lib/json-schema/attributes/ref.rb b/lib/json-schema/attributes/ref.rb index a537cffe..856b6c44 100644 --- a/lib/json-schema/attributes/ref.rb +++ b/lib/json-schema/attributes/ref.rb @@ -1,16 +1,16 @@ -require 'json-schema/attribute' -require 'json-schema/errors/schema_error' +require "json-schema/attribute" +require "json-schema/errors/schema_error" module JSON class Schema class RefAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) - uri,schema = get_referenced_uri_and_schema(current_schema.schema, current_schema, validator) + uri, schema = get_referenced_uri_and_schema(current_schema.schema, current_schema, validator) if schema schema.validate(data, fragments, processor, options) elsif uri - message = "The referenced schema '#{uri.to_s}' cannot be found" + message = "The referenced schema '#{uri}' cannot be found" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) else message = "The property '#{build_fragment(fragments)}' was not a valid schema" @@ -19,21 +19,22 @@ def self.validate(current_schema, data, fragments, processor, validator, options end def self.get_referenced_uri_and_schema(s, current_schema, validator) - uri,schema = nil,nil + uri = nil + schema = nil - temp_uri = Addressable::URI.parse(s['$ref']) + temp_uri = Addressable::URI.parse(s["$ref"]) if temp_uri.relative? temp_uri = current_schema.uri.clone # Check for absolute path - path = s['$ref'].split("#")[0] - if path.nil? || path == '' + path = s["$ref"].split("#")[0] + if path.nil? || path == "" temp_uri.path = current_schema.uri.path - elsif path[0,1] == "/" + elsif path[0, 1] == "/" temp_uri.path = Pathname.new(path).cleanpath.to_s else temp_uri = current_schema.uri.join(path) end - temp_uri.fragment = s['$ref'].split("#")[1] + temp_uri.fragment = s["$ref"].split("#")[1] end temp_uri.fragment = "" if temp_uri.fragment.nil? @@ -46,28 +47,27 @@ def self.get_referenced_uri_and_schema(s, current_schema, validator) # Perform fragment resolution to retrieve the appropriate level for the schema target_schema = ref_schema.schema fragments = temp_uri.fragment.split("/") - fragment_path = '' + fragment_path = "" fragments.each do |fragment| - if fragment && fragment != '' - fragment = Addressable::URI.unescape(fragment.gsub('~0', '~').gsub('~1', '/')) - if target_schema.is_a?(Array) - target_schema = target_schema[fragment.to_i] - else - target_schema = target_schema[fragment] - end - fragment_path = fragment_path + "/#{fragment}" - if target_schema.nil? - raise SchemaError.new("The fragment '#{fragment_path}' does not exist on schema #{ref_schema.uri.to_s}") - end + next unless fragment && fragment != "" + fragment = Addressable::URI.unescape(fragment.gsub("~0", "~").gsub("~1", "/")) + if target_schema.is_a?(Array) + target_schema = target_schema[fragment.to_i] + else + target_schema = target_schema[fragment] + end + fragment_path += "/#{fragment}" + if target_schema.nil? + raise SchemaError.new("The fragment '#{fragment_path}' does not exist on schema #{ref_schema.uri}") end end # We have the schema finally, build it and validate! uri = temp_uri - schema = JSON::Schema.new(target_schema,temp_uri,validator) + schema = JSON::Schema.new(target_schema, temp_uri, validator) end - [uri,schema] + [uri, schema] end end end diff --git a/lib/json-schema/attributes/required.rb b/lib/json-schema/attributes/required.rb index b40b3f77..e5a2a215 100644 --- a/lib/json-schema/attributes/required.rb +++ b/lib/json-schema/attributes/required.rb @@ -1,23 +1,23 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class RequiredAttribute < Attribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) return unless data.is_a?(Hash) schema = current_schema.schema - defined_properties = schema['properties'] + defined_properties = schema["properties"] - schema['required'].each do |property, property_schema| - next if data.has_key?(property.to_s) + schema["required"].each do |property, _property_schema| + next if data.key?(property.to_s) prop_defaults = options[:insert_defaults] && defined_properties && defined_properties[property] && !defined_properties[property]["default"].nil? && !defined_properties[property]["readonly"] - if !prop_defaults + unless prop_defaults message = "The property '#{build_fragment(fragments)}' did not contain a required property of '#{property}'" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) end diff --git a/lib/json-schema/attributes/type.rb b/lib/json-schema/attributes/type.rb index 723ce938..a38e2610 100644 --- a/lib/json-schema/attributes/type.rb +++ b/lib/json-schema/attributes/type.rb @@ -1,4 +1,4 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema @@ -6,12 +6,12 @@ class TypeAttribute < Attribute def self.validate(current_schema, data, fragments, processor, validator, options = {}) union = true if options[:disallow] - types = current_schema.schema['disallow'] + types = current_schema.schema["disallow"] else - types = current_schema.schema['type'] + types = current_schema.schema["type"] end - if !types.is_a?(Array) + unless types.is_a?(Array) types = [types] union = false end @@ -25,14 +25,14 @@ def self.validate(current_schema, data, fragments, processor, validator, options valid = data_valid_for_type?(data, type) elsif type.is_a?(Hash) && union # Validate as a schema - schema = JSON::Schema.new(type,current_schema.uri,validator) + schema = JSON::Schema.new(type, current_schema.uri, validator) # We're going to add a little cruft here to try and maintain any validation errors that occur in this union type # We'll handle this by keeping an error count before and after validation, extracting those errors and pushing them onto a union error pre_validation_error_count = validation_errors(processor).count begin - schema.validate(data,fragments,processor,options.merge(:disallow => false)) + schema.validate(data, fragments, processor, options.merge(:disallow => false)) valid = true rescue ValidationError # We don't care that these schemas don't validate - we only care that one validated @@ -41,7 +41,7 @@ def self.validate(current_schema, data, fragments, processor, validator, options diff = validation_errors(processor).count - pre_validation_error_count valid = false if diff > 0 while diff > 0 - diff = diff - 1 + diff -= 1 union_errors["type ##{type_index}"].push(validation_errors(processor).pop) end end @@ -50,7 +50,7 @@ def self.validate(current_schema, data, fragments, processor, validator, options end if options[:disallow] - return if !valid + return unless valid message = "The property '#{build_fragment(fragments)}' matched one or more of the following types: #{list_types(types)}" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) elsif !valid @@ -66,16 +66,16 @@ def self.validate(current_schema, data, fragments, processor, validator, options end def self.list_types(types) - types.map { |type| type.is_a?(String) ? type : '(schema)' }.join(', ') + types.map { |type| type.is_a?(String) ? type : "(schema)" }.join(", ") end # Lookup Schema type of given class instance def self.type_of_data(data) - type, _ = TYPE_CLASS_MAPPINGS.map { |k,v| [k,v] }.sort_by { |(_, v)| + type, = TYPE_CLASS_MAPPINGS.map { |k, v| [k, v] }.sort_by do |(_, v)| -Array(v).map { |klass| klass.ancestors.size }.max - }.find { |(_, v)| - Array(v).any? { |klass| data.kind_of?(klass) } - } + end.detect do |(_, v)| + Array(v).any? { |klass| data.is_a?(klass) } + end type end end diff --git a/lib/json-schema/attributes/type_v4.rb b/lib/json-schema/attributes/type_v4.rb index 71545def..471103a7 100644 --- a/lib/json-schema/attributes/type_v4.rb +++ b/lib/json-schema/attributes/type_v4.rb @@ -1,24 +1,24 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class TypeV4Attribute < Attribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) union = true - types = current_schema.schema['type'] - if !types.is_a?(Array) + types = current_schema.schema["type"] + unless types.is_a?(Array) types = [types] union = false end return if types.any? { |type| data_valid_for_type?(data, type) } - types = types.map { |type| type.is_a?(String) ? type : '(schema)' }.join(', ') + types = types.map { |type| type.is_a?(String) ? type : "(schema)" }.join(", ") message = format( "The property '%s' of type %s did not match %s: %s", build_fragment(fragments), data.class, - union ? 'one or more of the following types' : 'the following type', + union ? "one or more of the following types" : "the following type", types ) diff --git a/lib/json-schema/attributes/uniqueitems.rb b/lib/json-schema/attributes/uniqueitems.rb index abf2b1e0..603b8643 100644 --- a/lib/json-schema/attributes/uniqueitems.rb +++ b/lib/json-schema/attributes/uniqueitems.rb @@ -1,9 +1,9 @@ -require 'json-schema/attribute' +require "json-schema/attribute" module JSON class Schema class UniqueItemsAttribute < Attribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) return unless data.is_a?(Array) if data.clone.uniq! diff --git a/lib/json-schema/errors/validation_error.rb b/lib/json-schema/errors/validation_error.rb index c8527dd4..1dc7b767 100644 --- a/lib/json-schema/errors/validation_error.rb +++ b/lib/json-schema/errors/validation_error.rb @@ -28,10 +28,10 @@ def to_string(subschema_level = 0) def to_hash base = {:schema => @schema.uri, :fragment => ::JSON::Schema::Attribute.build_fragment(fragments), :message => message_with_schema, :failed_attribute => @failed_attribute.to_s.split(":").last.split("Attribute").first} - if !@sub_errors.empty? + unless @sub_errors.empty? base[:errors] = @sub_errors.inject({}) do |hsh, (subschema, errors)| - subschema_sym = subschema.downcase.gsub(/\W+/, '_').to_sym - hsh[subschema_sym] = Array(errors).map{|e| e.to_hash} + subschema_sym = subschema.downcase.gsub(/\W+/, "_").to_sym + hsh[subschema_sym] = Array(errors).map(&:to_hash) hsh end end diff --git a/lib/json-schema/schema.rb b/lib/json-schema/schema.rb index cba7bac0..d346e712 100644 --- a/lib/json-schema/schema.rb +++ b/lib/json-schema/schema.rb @@ -1,27 +1,26 @@ -require 'pathname' +require "pathname" module JSON class Schema - attr_accessor :schema, :uri, :validator - def initialize(schema,uri,parent_validator=nil) + def initialize(schema, uri, parent_validator = nil) @schema = schema @uri = uri # If there is an ID on this schema, use it to generate the URI - if @schema['id'] && @schema['id'].kind_of?(String) - temp_uri = Addressable::URI.parse(@schema['id']) + if @schema["id"] && @schema["id"].is_a?(String) + temp_uri = Addressable::URI.parse(@schema["id"]) if temp_uri.relative? temp_uri = uri.join(temp_uri) end @uri = temp_uri end - @uri.fragment = '' + @uri.fragment = "" # If there is a $schema on this schema, use it to determine which validator to use - if @schema['$schema'] - @validator = JSON::Validator.validator_for(@schema['$schema']) + if @schema["$schema"] + @validator = JSON::Validator.validator_for(@schema["$schema"]) elsif parent_validator @validator = parent_validator else @@ -36,7 +35,7 @@ def validate(data, fragments, processor, options = {}) def self.stringify(schema) case schema when Hash then - Hash[schema.map { |key, value| [key.to_s, stringify(schema[key])] }] + Hash[schema.map { |key, _value| [key.to_s, stringify(schema[key])] }] when Array then schema.map do |schema_item| stringify(schema_item) @@ -50,8 +49,8 @@ def self.stringify(schema) # @return [JSON::Schema] a new schema matching an array whose items all match this schema. def to_array_schema - array_schema = { 'type' => 'array', 'items' => schema } - array_schema['$schema'] = schema['$schema'] unless schema['$schema'].nil? + array_schema = {"type" => "array", "items" => schema} + array_schema["$schema"] = schema["$schema"] unless schema["$schema"].nil? JSON::Schema.new(array_schema, uri, validator) end @@ -60,4 +59,3 @@ def to_s end end end - diff --git a/lib/json-schema/schema/reader.rb b/lib/json-schema/schema/reader.rb index 9b13c66b..4584fa17 100644 --- a/lib/json-schema/schema/reader.rb +++ b/lib/json-schema/schema/reader.rb @@ -1,6 +1,6 @@ -require 'open-uri' -require 'addressable/uri' -require 'pathname' +require "open-uri" +require "addressable/uri" +require "pathname" module JSON class Schema @@ -61,7 +61,7 @@ def initialize(options = {}) # @raise [JSON::ParserError] if the schema was not a valid JSON object def read(location) uri = Addressable::URI.parse(location.to_s) - body = if uri.scheme.nil? || uri.scheme == 'file' + body = if uri.scheme.nil? || uri.scheme == "file" uri = Addressable::URI.convert_path(uri.path) read_file(Pathname.new(uri.path).expand_path) else diff --git a/lib/json-schema/schema/validator.rb b/lib/json-schema/schema/validator.rb index 37592859..a267208a 100644 --- a/lib/json-schema/schema/validator.rb +++ b/lib/json-schema/schema/validator.rb @@ -4,13 +4,13 @@ class Validator attr_accessor :attributes, :formats, :uri, :names attr_reader :default_formats - def initialize() + def initialize @attributes = {} @formats = {} @default_formats = {} @uri = nil @names = [] - @metaschema_name = '' + @metaschema_name = "" end def extend_schema_definition(schema_uri) @@ -19,8 +19,8 @@ def extend_schema_definition(schema_uri) end def validate(current_schema, data, fragments, processor, options = {}) - current_schema.schema.each do |attr_name,attribute| - if @attributes.has_key?(attr_name.to_s) + current_schema.schema.each do |attr_name, _attribute| + if @attributes.key?(attr_name.to_s) @attributes[attr_name.to_s].validate(current_schema, data, fragments, processor, self, options) end end @@ -28,7 +28,7 @@ def validate(current_schema, data, fragments, processor, options = {}) end def metaschema - resources = File.expand_path('../../../../resources', __FILE__) + resources = File.expand_path("../../../../resources", __FILE__) File.join(resources, @metaschema_name) end end diff --git a/lib/json-schema/util/array_set.rb b/lib/json-schema/util/array_set.rb index 8a7ccf7a..b0ae4cf9 100644 --- a/lib/json-schema/util/array_set.rb +++ b/lib/json-schema/util/array_set.rb @@ -1,13 +1,13 @@ -require 'set' +require "set" # This is a hack that I don't want to ever use anywhere else or repeat EVER, but we need enums to be # an Array to pass schema validation. But we also want fast lookup! class ArraySet < Array def include?(obj) - if !defined? @values + unless defined? @values @values = Set.new - self.each { |x| @values << convert_to_float_if_fixnum(x) } + each { |x| @values << convert_to_float_if_fixnum(x) } end @values.include?(convert_to_float_if_fixnum(obj)) end diff --git a/lib/json-schema/util/uri.rb b/lib/json-schema/util/uri.rb index eca9e6ed..6bd25dff 100644 --- a/lib/json-schema/util/uri.rb +++ b/lib/json-schema/util/uri.rb @@ -6,7 +6,7 @@ def self.normalized_uri(uri) # Check for absolute path if uri.relative? data = uri.to_s - data = "#{Dir.pwd}/#{data}" if data[0,1] != '/' + data = "#{Dir.pwd}/#{data}" if data[0, 1] != "/" uri = Addressable::URI.convert_path(data) end uri diff --git a/lib/json-schema/validator.rb b/lib/json-schema/validator.rb index e22943ee..a28b90ff 100644 --- a/lib/json-schema/validator.rb +++ b/lib/json-schema/validator.rb @@ -1,20 +1,18 @@ -require 'addressable/uri' -require 'open-uri' -require 'pathname' -require 'bigdecimal' -require 'digest/sha1' -require 'date' -require 'thread' -require 'yaml' - -require 'json-schema/schema/reader' -require 'json-schema/errors/schema_error' -require 'json-schema/errors/json_parse_error' +require "addressable/uri" +require "open-uri" +require "pathname" +require "bigdecimal" +require "digest/sha1" +require "date" +require "thread" +require "yaml" + +require "json-schema/schema/reader" +require "json-schema/errors/schema_error" +require "json-schema/errors/json_parse_error" module JSON - class Validator - @@schemas = {} @@cache_schemas = false @@default_opts = { @@ -35,7 +33,7 @@ class Validator @@serializer = nil @@mutex = Mutex.new - def initialize(schema_data, data, opts={}) + def initialize(schema_data, data, opts = {}) @options = @@default_opts.clone.merge(opts) @errors = [] @@ -61,7 +59,7 @@ def initialize(schema_data, data, opts={}) end metaschema = base_validator ? base_validator.metaschema : validator.metaschema # Don't clear the cache during metaschema validation! - meta_validator = JSON::Validator.new(metaschema, @base_schema.schema, {:clear_cache => false}) + meta_validator = JSON::Validator.new(metaschema, @base_schema.schema, :clear_cache => false) meta_validator.validate rescue JSON::Schema::ValidationError, JSON::Schema::SchemaError raise $! @@ -84,21 +82,21 @@ def schema_from_fragment(base_schema, fragment) end fragments.each do |f| - if base_schema.is_a?(JSON::Schema) #test if fragment is a JSON:Schema instance - if !base_schema.schema.has_key?(f) + if base_schema.is_a?(JSON::Schema) # test if fragment is a JSON:Schema instance + unless base_schema.schema.key?(f) raise JSON::Schema::SchemaError.new("Invalid fragment resolution for :fragment option") end base_schema = base_schema.schema[f] elsif base_schema.is_a?(Hash) - if !base_schema.has_key?(f) + unless base_schema.key?(f) raise JSON::Schema::SchemaError.new("Invalid fragment resolution for :fragment option") end - base_schema = JSON::Schema.new(base_schema[f],schema_uri,@options[:version]) + base_schema = JSON::Schema.new(base_schema[f], schema_uri, @options[:version]) elsif base_schema.is_a?(Array) if base_schema[f.to_i].nil? raise JSON::Schema::SchemaError.new("Invalid fragment resolution for :fragment option") end - base_schema = JSON::Schema.new(base_schema[f.to_i],schema_uri,@options[:version]) + base_schema = JSON::Schema.new(base_schema[f.to_i], schema_uri, @options[:version]) else raise JSON::Schema::SchemaError.new("Invalid schema encountered when resolving :fragment option") end @@ -112,12 +110,12 @@ def schema_from_fragment(base_schema, fragment) end # Run a simple true/false validation of data against a schema - def validate() - @base_schema.validate(@data,[],self,@validation_options) + def validate + @base_schema.validate(@data, [], self, @validation_options) if @options[:errors_as_objects] - return @errors.map{|e| e.to_hash} + return @errors.map(&:to_hash) else - return @errors.map{|e| e.to_string} + return @errors.map(&:to_string) end ensure if @validation_options[:clear_cache] == true @@ -139,14 +137,14 @@ def load_ref_schema(parent_schema, ref) def absolutize_ref_uri(ref, parent_schema_uri) ref_uri = Addressable::URI.parse(ref) - ref_uri.fragment = '' + ref_uri.fragment = "" return ref_uri if ref_uri.absolute? # This is a self reference and thus the schema does not need to be re-loaded return parent_schema_uri if ref_uri.path.empty? uri = parent_schema_uri.clone - uri.fragment = '' + uri.fragment = "" Util::URI.normalized_uri(uri.join(ref_uri.path)) end @@ -163,39 +161,38 @@ def build_schemas(parent_schema) when String load_ref_schema(parent_schema, schema["extends"]) when Array - schema['extends'].each do |type| + schema["extends"].each do |type| handle_schema(parent_schema, type) end end # Check for schemas in union types ["type", "disallow"].each do |key| - if schema[key].is_a?(Array) - schema[key].each do |type| - if type.is_a?(Hash) - handle_schema(parent_schema, type) - end + next unless schema[key].is_a?(Array) + schema[key].each do |type| + if type.is_a?(Hash) + handle_schema(parent_schema, type) end end end # Schema properties whose values are objects, the values of which # are themselves schemas. - %w[definitions properties patternProperties].each do |key| + ["definitions", "properties", "patternProperties"].each do |key| next unless value = schema[key] - value.each do |k, inner_schema| + value.each do |_k, inner_schema| handle_schema(parent_schema, inner_schema) end end # Schema properties whose values are themselves schemas. - %w[additionalProperties additionalItems dependencies extends].each do |key| + ["additionalProperties", "additionalItems", "dependencies", "extends"].each do |key| next unless schema[key].is_a?(Hash) handle_schema(parent_schema, schema[key]) end # Schema properties whose values may be an array of schemas. - %w[allOf anyOf oneOf not].each do |key| + ["allOf", "anyOf", "oneOf", "not"].each do |key| next unless value = schema[key] Array(value).each do |inner_schema| handle_schema(parent_schema, inner_schema) @@ -216,7 +213,6 @@ def build_schemas(parent_schema) if schema["enum"].is_a?(Array) schema["enum"] = ArraySet.new(schema["enum"]) end - end # Either load a reference schema or create a new schema @@ -224,7 +220,7 @@ def handle_schema(parent_schema, obj) if obj.is_a?(Hash) schema_uri = parent_schema.uri.clone schema = JSON::Schema.new(obj, schema_uri, parent_schema.validator) - if obj['id'] + if obj["id"] Validator.add_schema(schema) end build_schemas(schema) @@ -239,58 +235,55 @@ def validation_errors @errors end - class << self - def validate(schema, data,opts={}) - begin - validator = JSON::Validator.new(schema, data, opts) - validator.validate - return true - rescue JSON::Schema::ValidationError, JSON::Schema::SchemaError - return false - end + def validate(schema, data, opts = {}) + validator = JSON::Validator.new(schema, data, opts) + validator.validate + return true + rescue JSON::Schema::ValidationError, JSON::Schema::SchemaError + return false end - def validate_json(schema, data, opts={}) + def validate_json(schema, data, opts = {}) validate(schema, data, opts.merge(:json => true)) end - def validate_uri(schema, data, opts={}) + def validate_uri(schema, data, opts = {}) validate(schema, data, opts.merge(:uri => true)) end - def validate!(schema, data,opts={}) + def validate!(schema, data, opts = {}) validator = JSON::Validator.new(schema, data, opts) validator.validate - return true + true end - alias_method 'validate2', 'validate!' + alias_method "validate2", "validate!" - def validate_json!(schema, data, opts={}) + def validate_json!(schema, data, opts = {}) validate!(schema, data, opts.merge(:json => true)) end - def validate_uri!(schema, data, opts={}) + def validate_uri!(schema, data, opts = {}) validate!(schema, data, opts.merge(:uri => true)) end - def fully_validate(schema, data, opts={}) + def fully_validate(schema, data, opts = {}) opts[:record_errors] = true validator = JSON::Validator.new(schema, data, opts) validator.validate end - def fully_validate_schema(schema, opts={}) + def fully_validate_schema(schema, opts = {}) data = schema schema = JSON::Validator.validator_for_name(opts[:version]).metaschema fully_validate(schema, data, opts) end - def fully_validate_json(schema, data, opts={}) + def fully_validate_json(schema, data, opts = {}) fully_validate(schema, data, opts.merge(:json => true)) end - def fully_validate_uri(schema, data, opts={}) + def fully_validate_uri(schema, data, opts = {}) fully_validate(schema, data, opts.merge(:uri => true)) end @@ -402,7 +395,7 @@ def json_backend def json_backend=(backend) if defined?(MultiJson) - backend = backend == 'json' ? 'json_gem' : backend + backend = backend == "json" ? "json_gem" : backend MultiJson.respond_to?(:use) ? MultiJson.use(backend) : MultiJson.engine = backend else backend = backend.to_s @@ -419,12 +412,12 @@ def parse(s) MultiJson.respond_to?(:adapter) ? MultiJson.load(s) : MultiJson.decode(s) else case @@json_backend.to_s - when 'json' + when "json" JSON.parse(s, :quirks_mode => true) - when 'yajl' + when "yajl" json = StringIO.new(s) parser = Yajl::Parser.new - parser.parse(json) or raise JSON::Schema::JsonParseError.new("The JSON could not be parsed by yajl") + parser.parse(json) || raise(JSON::Schema::JsonParseError.new("The JSON could not be parsed by yajl")) else raise JSON::Schema::JsonParseError.new("No supported JSON parsers found. The following parsers are suported:\n * yajl-ruby\n * json") end @@ -450,46 +443,45 @@ def merge_missing_values(source, destination) end end - if !defined?(MultiJson) - if Gem::Specification::find_all_by_name('json').any? - require 'json' - @@available_json_backends << 'json' - @@json_backend = 'json' + unless defined?(MultiJson) + if Gem::Specification.find_all_by_name("json").any? + require "json" + @@available_json_backends << "json" + @@json_backend = "json" else # Try force-loading json for rubies > 1.9.2 begin - require 'json' - @@available_json_backends << 'json' - @@json_backend = 'json' + require "json" + @@available_json_backends << "json" + @@json_backend = "json" rescue LoadError end end - - if Gem::Specification::find_all_by_name('yajl-ruby').any? - require 'yajl' - @@available_json_backends << 'yajl' - @@json_backend = 'yajl' + if Gem::Specification.find_all_by_name("yajl-ruby").any? + require "yajl" + @@available_json_backends << "yajl" + @@json_backend = "yajl" end - if @@json_backend == 'yajl' - @@serializer = lambda{|o| Yajl::Encoder.encode(o) } + if @@json_backend == "yajl" + @@serializer = lambda { |o| Yajl::Encoder.encode(o) } else - @@serializer = lambda{|o| YAML.dump(o) } + @@serializer = lambda { |o| YAML.dump(o) } end end private def validators_for_names(names) - names = names.map { |name| name.to_s } + names = names.map(&:to_s) [].tap do |memo| validators.each do |_, validator| if (validator.names & names).any? memo << validator end end - if names.include?('') + if names.include?("") memo << default_validator end end @@ -498,15 +490,15 @@ def validators_for_names(names) private - if Gem::Specification::find_all_by_name('uuidtools').any? - require 'uuidtools' - @@fake_uuid_generator = lambda{|s| UUIDTools::UUID.sha1_create(UUIDTools::UUID_URL_NAMESPACE, s).to_s } + if Gem::Specification.find_all_by_name("uuidtools").any? + require "uuidtools" + @@fake_uuid_generator = lambda { |s| UUIDTools::UUID.sha1_create(UUIDTools::UUID_URL_NAMESPACE, s).to_s } else - require 'json-schema/util/uuid' - @@fake_uuid_generator = lambda{|s| JSON::Util::UUID.create_v5(s,JSON::Util::UUID::Nil).to_s } + require "json-schema/util/uuid" + @@fake_uuid_generator = lambda { |s| JSON::Util::UUID.create_v5(s, JSON::Util::UUID::Nil).to_s } end - def serialize schema + def serialize(schema) if defined?(MultiJson) MultiJson.respond_to?(:dump) ? MultiJson.dump(schema) : MultiJson.encode(schema) else @@ -514,7 +506,7 @@ def serialize schema end end - def fake_uuid schema + def fake_uuid(schema) @@fake_uuid_generator.call(schema) end @@ -590,7 +582,7 @@ def initialize_data(data) def custom_open(uri) uri = Util::URI.normalized_uri(uri) if uri.is_a?(String) - if uri.absolute? && uri.scheme != 'file' + if uri.absolute? && uri.scheme != "file" open(uri.to_s).read else File.read(Addressable::URI.unescape(uri.path)) diff --git a/lib/json-schema/validators/draft1.rb b/lib/json-schema/validators/draft1.rb index 25910a77..3c9a101e 100644 --- a/lib/json-schema/validators/draft1.rb +++ b/lib/json-schema/validators/draft1.rb @@ -1,8 +1,7 @@ -require 'json-schema/schema/validator' +require "json-schema/schema/validator" module JSON class Schema - class Draft1 < Validator def initialize super @@ -25,21 +24,20 @@ def initialize "extends" => JSON::Schema::ExtendsAttribute } @default_formats = { - 'date-time' => DateTimeFormat, - 'date' => DateFormat, - 'time' => TimeFormat, - 'ip-address' => IP4Format, - 'ipv6' => IP6Format, - 'uri' => UriFormat + "date-time" => DateTimeFormat, + "date" => DateFormat, + "time" => TimeFormat, + "ip-address" => IP4Format, + "ipv6" => IP6Format, + "uri" => UriFormat } @formats = @default_formats.clone @uri = Addressable::URI.parse("http://json-schema.org/draft-01/schema#") @names = ["draft1"] @metaschema_name = "draft-01.json" end - - JSON::Validator.register_validator(self.new) + + JSON::Validator.register_validator(new) end - end end diff --git a/lib/json-schema/validators/draft2.rb b/lib/json-schema/validators/draft2.rb index 4f12ae7a..d86f7084 100644 --- a/lib/json-schema/validators/draft2.rb +++ b/lib/json-schema/validators/draft2.rb @@ -1,8 +1,7 @@ -require 'json-schema/schema/validator' +require "json-schema/schema/validator" module JSON class Schema - class Draft2 < Validator def initialize super @@ -26,21 +25,20 @@ def initialize "extends" => JSON::Schema::ExtendsAttribute } @default_formats = { - 'date-time' => DateTimeFormat, - 'date' => DateFormat, - 'time' => TimeFormat, - 'ip-address' => IP4Format, - 'ipv6' => IP6Format, - 'uri' => UriFormat + "date-time" => DateTimeFormat, + "date" => DateFormat, + "time" => TimeFormat, + "ip-address" => IP4Format, + "ipv6" => IP6Format, + "uri" => UriFormat } @formats = @default_formats.clone @uri = Addressable::URI.parse("http://json-schema.org/draft-02/schema#") @names = ["draft2"] @metaschema_name = "draft-02.json" end - - JSON::Validator.register_validator(self.new) + + JSON::Validator.register_validator(new) end - end end diff --git a/lib/json-schema/validators/draft3.rb b/lib/json-schema/validators/draft3.rb index 572cbabc..490112b1 100644 --- a/lib/json-schema/validators/draft3.rb +++ b/lib/json-schema/validators/draft3.rb @@ -1,8 +1,7 @@ -require 'json-schema/schema/validator' +require "json-schema/schema/validator" module JSON class Schema - class Draft3 < Validator def initialize super @@ -30,21 +29,20 @@ def initialize "$ref" => JSON::Schema::RefAttribute } @default_formats = { - 'date-time' => DateTimeFormat, - 'date' => DateFormat, - 'ip-address' => IP4Format, - 'ipv6' => IP6Format, - 'time' => TimeFormat, - 'uri' => UriFormat + "date-time" => DateTimeFormat, + "date" => DateFormat, + "ip-address" => IP4Format, + "ipv6" => IP6Format, + "time" => TimeFormat, + "uri" => UriFormat } @formats = @default_formats.clone @uri = Addressable::URI.parse("http://json-schema.org/draft-03/schema#") @names = ["draft3", "http://json-schema.org/draft-03/schema#"] @metaschema_name = "draft-03.json" end - - JSON::Validator.register_validator(self.new) + + JSON::Validator.register_validator(new) end - end end diff --git a/lib/json-schema/validators/draft4.rb b/lib/json-schema/validators/draft4.rb index dac27f2c..45e49702 100644 --- a/lib/json-schema/validators/draft4.rb +++ b/lib/json-schema/validators/draft4.rb @@ -1,8 +1,7 @@ -require 'json-schema/schema/validator' +require "json-schema/schema/validator" module JSON class Schema - class Draft4 < Validator def initialize super @@ -37,10 +36,10 @@ def initialize "$ref" => JSON::Schema::RefAttribute } @default_formats = { - 'date-time' => DateTimeV4Format, - 'ipv4' => IP4Format, - 'ipv6' => IP6Format, - 'uri' => UriFormat + "date-time" => DateTimeV4Format, + "ipv4" => IP4Format, + "ipv6" => IP6Format, + "uri" => UriFormat } @formats = @default_formats.clone @uri = Addressable::URI.parse("http://json-schema.org/draft-04/schema#") @@ -48,9 +47,8 @@ def initialize @metaschema_name = "draft-04.json" end - JSON::Validator.register_validator(self.new) - JSON::Validator.register_default_validator(self.new) + JSON::Validator.register_validator(new) + JSON::Validator.register_default_validator(new) end - end end diff --git a/lib/json-schema/validators/hyper-draft1.rb b/lib/json-schema/validators/hyper-draft1.rb index 2eabe9a4..29f8852d 100644 --- a/lib/json-schema/validators/hyper-draft1.rb +++ b/lib/json-schema/validators/hyper-draft1.rb @@ -1,13 +1,12 @@ module JSON class Schema - class HyperDraft1 < Draft1 def initialize super @uri = Addressable::URI.parse("http://json-schema.org/draft-01/hyper-schema#") end - JSON::Validator.register_validator(self.new) + JSON::Validator.register_validator(new) end end end diff --git a/lib/json-schema/validators/hyper-draft2.rb b/lib/json-schema/validators/hyper-draft2.rb index be02bc7d..8234f652 100644 --- a/lib/json-schema/validators/hyper-draft2.rb +++ b/lib/json-schema/validators/hyper-draft2.rb @@ -1,13 +1,12 @@ module JSON class Schema - class HyperDraft2 < Draft2 def initialize super @uri = Addressable::URI.parse("http://json-schema.org/draft-02/hyper-schema#") end - JSON::Validator.register_validator(self.new) + JSON::Validator.register_validator(new) end end end diff --git a/lib/json-schema/validators/hyper-draft4.rb b/lib/json-schema/validators/hyper-draft4.rb index d39b183f..28bc8482 100644 --- a/lib/json-schema/validators/hyper-draft4.rb +++ b/lib/json-schema/validators/hyper-draft4.rb @@ -1,13 +1,12 @@ module JSON class Schema - class HyperDraft4 < Draft4 def initialize super @uri = Addressable::URI.parse("http://json-schema.org/draft-04/hyper-schema#") end - JSON::Validator.register_validator(self.new) + JSON::Validator.register_validator(new) end end end diff --git a/test/support/array_validation.rb b/test/support/array_validation.rb index 3d6877f9..8d4dcce9 100644 --- a/test/support/array_validation.rb +++ b/test/support/array_validation.rb @@ -1,35 +1,35 @@ module ArrayValidation module ItemsTests def test_items_single_schema - schema = { 'items' => { 'type' => 'string' } } + schema = {"items" => {"type" => "string"}} assert_valid schema, [] - assert_valid schema, ['a'] - assert_valid schema, ['a', 'b'] + assert_valid schema, ["a"] + assert_valid schema, ["a", "b"] refute_valid schema, [1] - refute_valid schema, ['a', 1] + refute_valid schema, ["a", 1] # other types are disregarded - assert_valid schema, {'a' => 'foo'} + assert_valid schema, "a" => "foo" end def test_items_multiple_schemas schema = { - 'items' => [ - { 'type' => 'string' }, - { 'type' => 'integer' } + "items" => [ + {"type" => "string"}, + {"type" => "integer"} ] } - assert_valid schema, ['b', 1] - assert_valid schema, ['b', 1, nil] - refute_valid schema, [1, 'b'] + assert_valid schema, ["b", 1] + assert_valid schema, ["b", 1, nil] + refute_valid schema, [1, "b"] refute_valid schema, [] end def test_minitems - schema = { 'minItems' => 1 } + schema = {"minItems" => 1} assert_valid schema, [1] assert_valid schema, [1, 2] @@ -40,7 +40,7 @@ def test_minitems end def test_maxitems - schema = { 'maxItems' => 1 } + schema = {"maxItems" => 1} assert_valid schema, [] assert_valid schema, [1] @@ -54,36 +54,36 @@ def test_maxitems module AdditionalItemsTests def test_additional_items_false schema = { - 'items' => [ - { 'type' => 'integer' }, - { 'type' => 'string' } + "items" => [ + {"type" => "integer"}, + {"type" => "string"} ], - 'additionalItems' => false + "additionalItems" => false } - assert_valid schema, [1, 'string'] - refute_valid schema, [1, 'string', 2] - refute_valid schema, ['string', 1] + assert_valid schema, [1, "string"] + refute_valid schema, [1, "string", 2] + refute_valid schema, ["string", 1] end def test_additional_items_schema schema = { - 'items' => [ - { 'type' => 'integer' }, - { 'type' => 'string' } + "items" => [ + {"type" => "integer"}, + {"type" => "string"} ], - 'additionalItems' => { 'type' => 'integer' } + "additionalItems" => {"type" => "integer"} } - assert_valid schema, [1, 'string'] - assert_valid schema, [1, 'string', 2] - refute_valid schema, [1, 'string', 'string'] + assert_valid schema, [1, "string"] + assert_valid schema, [1, "string", 2] + refute_valid schema, [1, "string", "string"] end end module UniqueItemsTests def test_unique_items - schema = { 'uniqueItems' => true } + schema = {"uniqueItems" => true} assert_valid schema, [nil, 5] refute_valid schema, [nil, nil] @@ -94,15 +94,15 @@ def test_unique_items assert_valid schema, [4, 4.1] refute_valid schema, [4, 4] - assert_valid schema, ['a', 'ab'] - refute_valid schema, ['a', 'a'] + assert_valid schema, ["a", "ab"] + refute_valid schema, ["a", "a"] assert_valid schema, [[1], [2]] refute_valid schema, [[1], [1]] - assert_valid schema, [{'b' => 1}, {'c' => 2}] - assert_valid schema, [{'b' => 1}, {'c' => 1}] - refute_valid schema, [{'b' => 1}, {'b' => 1}] + assert_valid schema, [{"b" => 1}, {"c" => 2}] + assert_valid schema, [{"b" => 1}, {"c" => 1}] + refute_valid schema, [{"b" => 1}, {"b" => 1}] end end end diff --git a/test/support/enum_validation.rb b/test/support/enum_validation.rb index c83e5b90..7af5ef4f 100644 --- a/test/support/enum_validation.rb +++ b/test/support/enum_validation.rb @@ -1,9 +1,9 @@ module EnumValidation - module V1_V2 + module V1V2 def test_enum_optional schema = { "properties" => { - "a" => {"enum" => [1,'boo',[1,2,3],{"a" => "b"}], "optional" => true} + "a" => {"enum" => [1, "boo", [1, 2, 3], {"a" => "b"}], "optional" => true} } } @@ -12,11 +12,11 @@ def test_enum_optional end end - module V3_V4 + module V3V4 def test_enum_optional schema = { "properties" => { - "a" => {"enum" => [1,'boo',[1,2,3],{"a" => "b"}]} + "a" => {"enum" => [1, "boo", [1, 2, 3], {"a" => "b"}]} } } @@ -29,23 +29,23 @@ module General def test_enum_general schema = { "properties" => { - "a" => {"enum" => [1,'boo',[1,2,3],{"a" => "b"}]} + "a" => {"enum" => [1, "boo", [1, 2, 3], {"a" => "b"}]} } } - data = { "a" => 1 } + data = {"a" => 1} assert_valid schema, data - data["a"] = 'boo' + data["a"] = "boo" assert_valid schema, data - data["a"] = [1,2,3] + data["a"] = [1, 2, 3] assert_valid schema, data data["a"] = {"a" => "b"} assert_valid schema, data - data["a"] = 'taco' + data["a"] = "taco" refute_valid schema, data end @@ -59,7 +59,7 @@ def test_enum_number_integer_includes_float } } - data = { "a" => 0 } + data = {"a" => 0} assert_valid schema, data data["a"] = 0.0 @@ -82,13 +82,12 @@ def test_enum_number_float_includes_integer } } - data = { "a" => 0.0 } + data = {"a" => 0.0} assert_valid schema, data data["a"] = 0 assert_valid schema, data - data["a"] = 1.0 assert_valid schema, data @@ -106,13 +105,12 @@ def test_enum_integer_excludes_float } } - data = { "a" => 0 } + data = {"a" => 0} assert_valid schema, data data["a"] = 0.0 refute_valid schema, data - data["a"] = 1 assert_valid schema, data @@ -123,10 +121,10 @@ def test_enum_integer_excludes_float def test_enum_with_schema_validation schema = { "properties" => { - "a" => {"enum" => [1,'boo',[1,2,3],{"a" => "b"}]} + "a" => {"enum" => [1, "boo", [1, 2, 3], {"a" => "b"}]} } } - data = { "a" => 1 } + data = {"a" => 1} assert_valid(schema, data, :validate_schema => true) end end diff --git a/test/support/number_validation.rb b/test/support/number_validation.rb index c4d767e3..0ed3a83e 100644 --- a/test/support/number_validation.rb +++ b/test/support/number_validation.rb @@ -2,57 +2,57 @@ module NumberValidation module MinMaxTests def test_minimum schema = { - 'properties' => { - 'a' => { 'minimum' => 5 } + "properties" => { + "a" => {"minimum" => 5} } } - assert_valid schema, {'a' => 5} - assert_valid schema, {'a' => 6} + assert_valid schema, "a" => 5 + assert_valid schema, "a" => 6 - refute_valid schema, {'a' => 4} - refute_valid schema, {'a' => 4.99999} + refute_valid schema, "a" => 4 + refute_valid schema, "a" => 4.99999 # other types are disregarded - assert_valid schema, {'a' => 'str'} + assert_valid schema, "a" => "str" end def test_exclusive_minimum schema = { - 'properties' => { - 'a' => { 'minimum' => 5 }.merge(exclusive_minimum) + "properties" => { + "a" => {"minimum" => 5}.merge(exclusive_minimum) } } - assert_valid schema, {'a' => 6} - assert_valid schema, {'a' => 5.0001} - refute_valid schema, {'a' => 5} + assert_valid schema, "a" => 6 + assert_valid schema, "a" => 5.0001 + refute_valid schema, "a" => 5 end def test_maximum schema = { - 'properties' => { - 'a' => { 'maximum' => 5 } + "properties" => { + "a" => {"maximum" => 5} } } - assert_valid schema, {'a' => 4} - assert_valid schema, {'a' => 5} + assert_valid schema, "a" => 4 + assert_valid schema, "a" => 5 - refute_valid schema, {'a' => 6} - refute_valid schema, {'a' => 5.0001} + refute_valid schema, "a" => 6 + refute_valid schema, "a" => 5.0001 end def test_exclusive_maximum schema = { - 'properties' => { - 'a' => { 'maximum' => 5 }.merge(exclusive_maximum) + "properties" => { + "a" => {"maximum" => 5}.merge(exclusive_maximum) } } - assert_valid schema, {'a' => 4} - assert_valid schema, {'a' => 4.99999} - refute_valid schema, {'a' => 5} + assert_valid schema, "a" => 4 + assert_valid schema, "a" => 4.99999 + refute_valid schema, "a" => 5 end end @@ -60,34 +60,34 @@ def test_exclusive_maximum # Favor the newer name, but the behavior should be identical. module MultipleOfTests def multiple_of - 'multipleOf' + "multipleOf" end def test_multiple_of schema = { - 'properties' => { - 'a' => { multiple_of => 1.1 } + "properties" => { + "a" => {multiple_of => 1.1} } } - assert_valid schema, {'a' => 0} + assert_valid schema, "a" => 0 - assert_valid schema, {'a' => 2.2} - refute_valid schema, {'a' => 3.4} + assert_valid schema, "a" => 2.2 + refute_valid schema, "a" => 3.4 # other types are disregarded - assert_valid schema, {'a' => 'hi'} + assert_valid schema, "a" => "hi" end def test_multiple_of_zero schema = { - 'properties' => { - 'a' => { multiple_of => 0 } + "properties" => { + "a" => {multiple_of => 0} } } - refute_valid schema, {'a' => 5} - refute_valid schema, {'a' => 0} + refute_valid schema, "a" => 5 + refute_valid schema, "a" => 0 end end end diff --git a/test/support/object_validation.rb b/test/support/object_validation.rb index c5e15033..f2182188 100644 --- a/test/support/object_validation.rb +++ b/test/support/object_validation.rb @@ -2,67 +2,67 @@ module ObjectValidation module AdditionalPropertiesTests def test_additional_properties_false schema = { - 'properties' => { - 'a' => { 'type' => 'integer' } + "properties" => { + "a" => {"type" => "integer"} }, - 'additionalProperties' => false + "additionalProperties" => false } - assert_valid schema, {'a' => 1} - refute_valid schema, {'a' => 1, 'b' => 2} + assert_valid schema, "a" => 1 + refute_valid schema, "a" => 1, "b" => 2 end def test_additional_properties_schema schema = { - 'properties' => { - 'a' => { 'type' => 'integer' } + "properties" => { + "a" => {"type" => "integer"} }, - 'additionalProperties' => { 'type' => 'string' } + "additionalProperties" => {"type" => "string"} } - assert_valid schema, {'a' => 1} - assert_valid schema, {'a' => 1, 'b' => 'hi'} - refute_valid schema, {'a' => 1, 'b' => 2} + assert_valid schema, "a" => 1 + assert_valid schema, "a" => 1, "b" => "hi" + refute_valid schema, "a" => 1, "b" => 2 end end module PatternPropertiesTests def test_pattern_properties schema = { - 'patternProperties' => { - "\\d+ taco" => { 'type' => 'integer' } + "patternProperties" => { + "\\d+ taco" => {"type" => "integer"} } } - assert_valid schema, {'1 taco' => 1, '20 taco' => 20} - assert_valid schema, {'foo' => true, '1 taco' => 1} - refute_valid schema, {'1 taco' => 'yum'} + assert_valid schema, "1 taco" => 1, "20 taco" => 20 + assert_valid schema, "foo" => true, "1 taco" => 1 + refute_valid schema, "1 taco" => "yum" end def test_pattern_properties_additional_properties_false schema = { - 'patternProperties' => { - "\\d+ taco" => { 'type' => 'integer' } + "patternProperties" => { + "\\d+ taco" => {"type" => "integer"} }, - 'additionalProperties' => false + "additionalProperties" => false } - assert_valid schema, {'1 taco' => 1} - refute_valid schema, {'1 taco' => 'yum'} - refute_valid schema, {'1 taco' => 1, 'foo' => true} + assert_valid schema, "1 taco" => 1 + refute_valid schema, "1 taco" => "yum" + refute_valid schema, "1 taco" => 1, "foo" => true end def test_pattern_properties_additional_properties_schema schema = { - 'patternProperties' => { - "\\d+ taco" => { 'type' => 'integer' } + "patternProperties" => { + "\\d+ taco" => {"type" => "integer"} }, - 'additionalProperties' => { 'type' => 'string' } + "additionalProperties" => {"type" => "string"} } - assert_valid schema, {'1 taco' => 1} - assert_valid schema, {'1 taco' => 1, 'foo' => 'bar'} - refute_valid schema, {'1 taco' => 1, 'foo' => 2} + assert_valid schema, "1 taco" => 1 + assert_valid schema, "1 taco" => 1, "foo" => "bar" + refute_valid schema, "1 taco" => 1, "foo" => 2 end end end diff --git a/test/support/strict_validation.rb b/test/support/strict_validation.rb index 06d9fd65..f406fa8f 100644 --- a/test/support/strict_validation.rb +++ b/test/support/strict_validation.rb @@ -9,22 +9,22 @@ def test_strict_properties } data = {"a" => "a"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"b" => "b"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => "c"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) end def test_strict_error_message - schema = { :type => 'object', :properties => { :a => { :type => 'string' } } } - data = { :a => 'abc', :b => 'abc' } - errors = JSON::Validator.fully_validate(schema,data,:strict => true) + schema = {:type => "object", :properties => {:a => {:type => "string"}}} + data = {:a => "abc", :b => "abc"} + errors = JSON::Validator.fully_validate(schema, data, :strict => true) assert_match("The property '#/' contained undefined properties: 'b' in schema", errors[0]) end @@ -39,19 +39,19 @@ def test_strict_properties_additional_props } data = {"a" => "a"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"b" => "b"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => "c"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => 3} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) end def test_strict_properties_pattern_props @@ -65,25 +65,24 @@ def test_strict_properties_pattern_props } data = {"a" => "a"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"b" => "b"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => "c"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => 3} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "23 taco" => 3} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "23 taco" => "cheese"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) end - end diff --git a/test/support/string_validation.rb b/test/support/string_validation.rb index b8d911cb..8385126e 100644 --- a/test/support/string_validation.rb +++ b/test/support/string_validation.rb @@ -2,114 +2,114 @@ module StringValidation module ValueTests def test_minlength schema = { - 'properties' => { - 'a' => { 'minLength' => 1 } + "properties" => { + "a" => {"minLength" => 1} } } - assert_valid schema, {'a' => 't'} - refute_valid schema, {'a' => ''} + assert_valid schema, "a" => "t" + refute_valid schema, "a" => "" # other types are disregarded - assert_valid schema, {'a' => 5} + assert_valid schema, "a" => 5 end def test_maxlength schema = { - 'properties' => { - 'a' => { 'maxLength' => 2 } + "properties" => { + "a" => {"maxLength" => 2} } } - assert_valid schema, {'a' => 'tt'} - assert_valid schema, {'a' => ''} - refute_valid schema, {'a' => 'ttt'} + assert_valid schema, "a" => "tt" + assert_valid schema, "a" => "" + refute_valid schema, "a" => "ttt" # other types are disregarded - assert_valid schema, {'a' => 5} + assert_valid schema, "a" => 5 end def test_pattern schema = { - 'properties' => { - 'a' => { 'pattern' => "\\d+ taco" } + "properties" => { + "a" => {"pattern" => "\\d+ taco"} } } - assert_valid schema, {'a' => '156 taco bell'} - refute_valid schema, {'a' => 'x taco'} + assert_valid schema, "a" => "156 taco bell" + refute_valid schema, "a" => "x taco" # other types are disregarded - assert_valid schema, {'a' => 5} + assert_valid schema, "a" => 5 end end module FormatTests # Draft1..3 use the format name `ip-address`; draft4 changed it to `ipv4`. def ipv4_format - 'ip-address' + "ip-address" end def test_format_unknown schema = { - 'properties' => { - 'a' => { 'format' => 'unknown' } + "properties" => { + "a" => {"format" => "unknown"} } } - assert_valid schema, {'a' => 'absolutely anything!'} - assert_valid schema, {'a' => ''} + assert_valid schema, "a" => "absolutely anything!" + assert_valid schema, "a" => "" end def test_format_union schema = { - 'properties' => { - 'a' => { - 'type' => ['string', 'null'], - 'format' => 'date-time' + "properties" => { + "a" => { + "type" => ["string", "null"], + "format" => "date-time" } } } - assert_valid schema, {'a' => nil} - refute_valid schema, {'a' => 'wrong'} + assert_valid schema, "a" => nil + refute_valid schema, "a" => "wrong" end def test_format_ipv4 schema = { - 'properties' => { - 'a' => { 'format' => ipv4_format } + "properties" => { + "a" => {"format" => ipv4_format} } } - assert_valid schema, {"a" => "1.1.1.1"} - refute_valid schema, {"a" => "1.1.1"} - refute_valid schema, {"a" => "1.1.1.300"} - refute_valid schema, {"a" => "1.1.1"} - refute_valid schema, {"a" => "1.1.1.1b"} + assert_valid schema, "a" => "1.1.1.1" + refute_valid schema, "a" => "1.1.1" + refute_valid schema, "a" => "1.1.1.300" + refute_valid schema, "a" => "1.1.1" + refute_valid schema, "a" => "1.1.1.1b" # other types are disregarded - assert_valid schema, {'a' => 5} + assert_valid schema, "a" => 5 end def test_format_ipv6 schema = { - 'properties' => { - 'a' => { 'format' => 'ipv6' } + "properties" => { + "a" => {"format" => "ipv6"} } } - assert_valid schema, {"a" => "1111:2222:8888:9999:aaaa:cccc:eeee:ffff"} - assert_valid schema, {"a" => "1111:0:8888:0:0:0:eeee:ffff"} - assert_valid schema, {"a" => "1111:2222:8888::eeee:ffff"} - assert_valid schema, {"a" => "::1"} - - refute_valid schema, {"a" => "1111:2222:8888:99999:aaaa:cccc:eeee:ffff"} - refute_valid schema, {"a" => "1111:2222:8888:9999:aaaa:cccc:eeee:gggg"} - refute_valid schema, {"a" => "1111:2222::9999::cccc:eeee:ffff"} - refute_valid schema, {"a" => "1111:2222:8888:9999:aaaa:cccc:eeee:ffff:bbbb"} - refute_valid schema, {"a" => "42"} - refute_valid schema, {"a" => "b"} + assert_valid schema, "a" => "1111:2222:8888:9999:aaaa:cccc:eeee:ffff" + assert_valid schema, "a" => "1111:0:8888:0:0:0:eeee:ffff" + assert_valid schema, "a" => "1111:2222:8888::eeee:ffff" + assert_valid schema, "a" => "::1" + + refute_valid schema, "a" => "1111:2222:8888:99999:aaaa:cccc:eeee:ffff" + refute_valid schema, "a" => "1111:2222:8888:9999:aaaa:cccc:eeee:gggg" + refute_valid schema, "a" => "1111:2222::9999::cccc:eeee:ffff" + refute_valid schema, "a" => "1111:2222:8888:9999:aaaa:cccc:eeee:ffff:bbbb" + refute_valid schema, "a" => "42" + refute_valid schema, "a" => "b" end end @@ -118,37 +118,37 @@ def test_format_ipv6 module DateAndTimeFormatTests def test_format_time schema = { - 'properties' => { - 'a' => { 'format' => 'time' } + "properties" => { + "a" => {"format" => "time"} } } - assert_valid schema, {"a" => "12:00:00"} - refute_valid schema, {"a" => "12:00"} - refute_valid schema, {"a" => "12:00:60"} - refute_valid schema, {"a" => "12:60:00"} - refute_valid schema, {"a" => "24:00:00"} - refute_valid schema, {"a" => "0:00:00"} - refute_valid schema, {"a" => "-12:00:00"} - refute_valid schema, {"a" => "12:00:00b"} - assert_valid schema, {"a" => "12:00:00"} - refute_valid schema, {"a" => "12:00:00\nabc"} + assert_valid schema, "a" => "12:00:00" + refute_valid schema, "a" => "12:00" + refute_valid schema, "a" => "12:00:60" + refute_valid schema, "a" => "12:60:00" + refute_valid schema, "a" => "24:00:00" + refute_valid schema, "a" => "0:00:00" + refute_valid schema, "a" => "-12:00:00" + refute_valid schema, "a" => "12:00:00b" + assert_valid schema, "a" => "12:00:00" + refute_valid schema, "a" => "12:00:00\nabc" end def test_format_date schema = { - 'properties' => { - 'a' => { 'format' => 'date' } + "properties" => { + "a" => {"format" => "date"} } } - assert_valid schema, {"a" => "2010-01-01"} - refute_valid schema, {"a" => "2010-01-32"} - refute_valid schema, {"a" => "n2010-01-01"} - refute_valid schema, {"a" => "2010-1-01"} - refute_valid schema, {"a" => "2010-01-1"} - refute_valid schema, {"a" => "2010-01-01n"} - refute_valid schema, {"a" => "2010-01-01\nabc"} + assert_valid schema, "a" => "2010-01-01" + refute_valid schema, "a" => "2010-01-32" + refute_valid schema, "a" => "n2010-01-01" + refute_valid schema, "a" => "2010-1-01" + refute_valid schema, "a" => "2010-01-1" + refute_valid schema, "a" => "2010-01-01n" + refute_valid schema, "a" => "2010-01-01\nabc" end end end diff --git a/test/support/type_validation.rb b/test/support/type_validation.rb index 20965b7d..7a53966d 100644 --- a/test/support/type_validation.rb +++ b/test/support/type_validation.rb @@ -3,13 +3,13 @@ module TypeValidation # see draft4#/definitions/simpleTypes module SimpleTypeTests TYPES = { - 'integer' => 5, - 'number' => 5.0, - 'string' => 'str', - 'boolean' => true, - 'object' => {}, - 'array' => [], - 'null' => nil + "integer" => 5, + "number" => 5.0, + "string" => "str", + "boolean" => true, + "object" => {}, + "array" => [], + "null" => nil } TYPES.each do |name, value| @@ -17,39 +17,39 @@ module SimpleTypeTests define_method(:"test_#{name}_type_property") do schema = { - 'properties' => { 'a' => { 'type' => name } } + "properties" => {"a" => {"type" => name}} } - assert_valid schema, {'a' => value} + assert_valid schema, "a" => value other_values.each do |other_value| - refute_valid schema, {'a' => other_value} + refute_valid schema, "a" => other_value end end define_method(:"test_#{name}_type_value") do - schema = { 'type' => name } + schema = {"type" => name} assert_valid schema, value other_values.each do |other_value| - schema = { 'type' => name } + schema = {"type" => name} refute_valid schema, other_value end end end def test_type_union - schema = { 'type' => ['integer', 'string'] } + schema = {"type" => ["integer", "string"]} assert_valid schema, 5 - assert_valid schema, 'str' + assert_valid schema, "str" refute_valid schema, nil - refute_valid schema, [5, 'str'] + refute_valid schema, [5, "str"] end end # The draft1..3 schemas support an additional type, `any`. module AnyTypeTests def test_any_type - schema = { 'type' => 'any' } + schema = {"type" => "any"} SimpleTypeTests::TYPES.values.each do |value| assert_valid schema, value @@ -61,21 +61,21 @@ def test_any_type module SchemaUnionTypeTests def test_union_type_with_schemas schema = { - 'properties' => { - 'a' => { - 'type' => [ - {'type' => 'string'}, - {'type' => 'object', 'properties' => { 'b' => { 'type' => 'integer' }}} + "properties" => { + "a" => { + "type" => [ + {"type" => "string"}, + {"type" => "object", "properties" => {"b" => {"type" => "integer"}}} ] } } } - assert_valid schema, {'a' => 'test'} - refute_valid schema, {'a' => 5} + assert_valid schema, "a" => "test" + refute_valid schema, "a" => 5 - assert_valid schema, {'a' => {'b' => 5}} - refute_valid schema, {'a' => {'b' => 'taco'}} + assert_valid schema, "a" => {"b" => 5} + refute_valid schema, "a" => {"b" => "taco"} end end end diff --git a/test/test_all_of_ref_schema.rb b/test/test_all_of_ref_schema.rb index 8ab6bf0d..a8fab3d3 100644 --- a/test/test_all_of_ref_schema.rb +++ b/test/test_all_of_ref_schema.rb @@ -1,12 +1,12 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class AllOfRefSchemaTest < Minitest::Test def schema - schema_fixture_path('all_of_ref_schema.json') + schema_fixture_path("all_of_ref_schema.json") end def data - data_fixture_path('all_of_ref_data.json') + data_fixture_path("all_of_ref_data.json") end def test_all_of_ref_schema_fails @@ -20,8 +20,8 @@ def test_all_of_ref_schema_succeeds def test_all_of_ref_subschema_errors errors = JSON::Validator.fully_validate(schema, data, :errors_as_objects => true) nested_errors = errors[0][:errors] - assert_equal([:allof_0], nested_errors.keys, 'should have nested errors for each allOf subschema') - assert_match(/the property '#\/name' of type String did not match the following type: integer/i, nested_errors[:allof_0][0][:message]) + assert_equal([:allof_0], nested_errors.keys, "should have nested errors for each allOf subschema") + assert_match(%r{the property '#/name' of type String did not match the following type: integer}i, nested_errors[:allof_0][0][:message]) end def test_all_of_ref_message diff --git a/test/test_any_of_ref_schema.rb b/test/test_any_of_ref_schema.rb index 475222de..9bbd0944 100644 --- a/test/test_any_of_ref_schema.rb +++ b/test/test_any_of_ref_schema.rb @@ -1,22 +1,22 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class AnyOfRefSchemaTest < Minitest::Test def schema - schema_fixture_path('any_of_ref_schema.json') + schema_fixture_path("any_of_ref_schema.json") end def test_any_of_ref_schema - assert_valid schema, data_fixture_path('any_of_ref_data.json') + assert_valid schema, data_fixture_path("any_of_ref_data.json") end def test_any_of_ref_subschema_errors data = %({"names": ["jack"]}) errors = JSON::Validator.fully_validate(schema, data, :errors_as_objects => true) nested_errors = errors[0][:errors] - assert_equal([:anyof_0, :anyof_1, :anyof_2], nested_errors.keys, 'should have nested errors for each anyOf subschema') - assert_match(/the property '#\/names\/0' value "jack" did not match the regex 'john'/i, nested_errors[:anyof_0][0][:message]) - assert_match(/the property '#\/names\/0' value "jack" did not match the regex 'jane'/i, nested_errors[:anyof_1][0][:message]) - assert_match(/the property '#\/names\/0' value "jack" did not match the regex 'jimmy'/i, nested_errors[:anyof_2][0][:message]) + assert_equal([:anyof_0, :anyof_1, :anyof_2], nested_errors.keys, "should have nested errors for each anyOf subschema") + assert_match(%r{the property '#/names/0' value "jack" did not match the regex 'john'}i, nested_errors[:anyof_0][0][:message]) + assert_match(%r{the property '#/names/0' value "jack" did not match the regex 'jane'}i, nested_errors[:anyof_1][0][:message]) + assert_match(%r{the property '#/names/0' value "jack" did not match the regex 'jimmy'}i, nested_errors[:anyof_2][0][:message]) end def test_any_of_ref_message diff --git a/test/test_bad_schema_ref.rb b/test/test_bad_schema_ref.rb index ef4d9761..568593e7 100644 --- a/test/test_bad_schema_ref.rb +++ b/test/test_bad_schema_ref.rb @@ -1,6 +1,5 @@ -require File.expand_path('../test_helper', __FILE__) -require 'socket' - +require File.expand_path("../test_helper", __FILE__) +require "socket" class BadSchemaRefTest < Minitest::Test def setup @@ -15,12 +14,12 @@ def test_bad_uri_ref schema = { "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "array", - "items" => { "$ref" => "../google.json"} + "items" => {"$ref" => "../google.json"} } - data = [1,2,3] + data = [1, 2, 3] assert_raises(Errno::ENOENT) do - JSON::Validator.validate(schema,data) + JSON::Validator.validate(schema, data) end end @@ -28,12 +27,12 @@ def test_bad_host_ref schema = { "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "array", - "items" => { "$ref" => "http://ppcheesecheseunicornnuuuurrrrr.example.invalid/json.schema"} + "items" => {"$ref" => "http://ppcheesecheseunicornnuuuurrrrr.example.invalid/json.schema"} } - data = [1,2,3] + data = [1, 2, 3] assert_raises(SocketError, OpenURI::HTTPError) do - JSON::Validator.validate(schema,data) + JSON::Validator.validate(schema, data) end end end diff --git a/test/test_common_test_suite.rb b/test/test_common_test_suite.rb index 3c9d3aff..69f31296 100644 --- a/test/test_common_test_suite.rb +++ b/test/test_common_test_suite.rb @@ -1,15 +1,15 @@ -require File.expand_path('../test_helper', __FILE__) -require 'json' +require File.expand_path("../test_helper", __FILE__) +require "json" class CommonTestSuiteTest < Minitest::Test - TEST_DIR = File.expand_path('../test-suite/tests', __FILE__) + TEST_DIR = File.expand_path("../test-suite/tests", __FILE__) # These are test files which we know fail spectacularly, either because we # don't support that functionality or because they require external # dependencies. To allow finer-grained control over which tests to run, # you can replace `:all` with an array containing the names of individual # tests to skip. - IGNORED_TESTS = Hash.new { |h,k| h[k] = [] }.merge({ + IGNORED_TESTS = Hash.new { |h, k| h[k] = [] }.merge( "draft3/optional/jsregex.json" => :all, "draft3/optional/format.json" => [ "validation of regular expressions", @@ -23,11 +23,11 @@ class CommonTestSuiteTest < Minitest::Test "validation of e-mail addresses", "validation of host names" ] - }) + ) def setup Dir["#{TEST_DIR}/../remotes/**/*.json"].each do |path| - schema = path.sub(%r{^.*/remotes/}, '') + schema = path.sub(%r{^.*/remotes/}, "") stub_request(:get, "http://localhost:1234/#{schema}"). to_return(:body => File.read(path), :status => 200) end @@ -37,7 +37,7 @@ def setup version = File.basename(suite).to_sym Dir["#{suite}/**/*.json"].each do |tfile| test_list = JSON.parse(File.read(tfile)) - rel_file = tfile[TEST_DIR.length+1..-1] + rel_file = tfile[TEST_DIR.length + 1..-1] test_list.each do |test| schema = test["schema"] @@ -45,18 +45,18 @@ def setup test["tests"].each do |t| next if IGNORED_TESTS[rel_file] == :all - next if IGNORED_TESTS[rel_file].any? { |ignored| + next if IGNORED_TESTS[rel_file].any? do |ignored| base_description == ignored || "#{base_description}/#{t['description']}" == ignored - } + end err_id = "#{rel_file}: #{base_description}/#{t['description']}" define_method("test_#{err_id}") do errors = JSON::Validator.fully_validate(schema, - t["data"], - :parse_data => false, - :validate_schema => true, - :version => version - ) + t["data"], + :parse_data => false, + :validate_schema => true, + :version => version + ) assert_equal t["valid"], errors.empty?, "Common test suite case failed: #{err_id}" end end diff --git a/test/test_custom_format.rb b/test/test_custom_format.rb index 794383e5..5a70418a 100644 --- a/test/test_custom_format.rb +++ b/test/test_custom_format.rb @@ -1,17 +1,17 @@ # encoding: utf-8 -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class JSONSchemaCustomFormatTest < Minitest::Test def setup - @all_versions = ['draft1', 'draft2', 'draft3', 'draft4', nil] + @all_versions = ["draft1", "draft2", "draft3", "draft4", nil] @format_proc = lambda { |value| raise JSON::Schema::CustomFormatError.new("must be 42") unless value == "42" } @schema_4 = { "$schema" => "http://json-schema.org/draft-04/schema#", "properties" => { "a" => { "type" => "string", - "format" => "custom", - }, + "format" => "custom" + } } } @schema_3 = @schema_4.clone @@ -27,32 +27,32 @@ def setup "draft2" => @schema_2, "draft3" => @schema_3, "draft4" => @schema_4, - nil => @default, + nil => @default } JSON::Validator.restore_default_formats end def test_single_registration @all_versions.each do |version| - assert(JSON::Validator.validator_for_name(version).formats['custom'].nil?, "Format 'custom' for #{version || 'default'} should be nil") + assert(JSON::Validator.validator_for_name(version).formats["custom"].nil?, "Format 'custom' for #{version || 'default'} should be nil") JSON::Validator.register_format_validator("custom", @format_proc, [version]) - assert(JSON::Validator.validator_for_name(version).formats['custom'].is_a?(JSON::Schema::CustomFormat), "Format 'custom' should be registered for #{version || 'default'}") + assert(JSON::Validator.validator_for_name(version).formats["custom"].is_a?(JSON::Schema::CustomFormat), "Format 'custom' should be registered for #{version || 'default'}") (@all_versions - [version]).each do |other_version| - assert(JSON::Validator.validator_for_name(other_version).formats['custom'].nil?, "Format 'custom' should still be nil for #{other_version || 'default'}") + assert(JSON::Validator.validator_for_name(other_version).formats["custom"].nil?, "Format 'custom' should still be nil for #{other_version || 'default'}") end JSON::Validator.deregister_format_validator("custom", [version]) - assert(JSON::Validator.validator_for_name(version).formats['custom'].nil?, "Format 'custom' should be deregistered for #{version || 'default'}") + assert(JSON::Validator.validator_for_name(version).formats["custom"].nil?, "Format 'custom' should be deregistered for #{version || 'default'}") end end def test_register_for_all_by_default JSON::Validator.register_format_validator("custom", @format_proc) @all_versions.each do |version| - assert(JSON::Validator.validator_for_name(version).formats['custom'].is_a?(JSON::Schema::CustomFormat), "Format 'custom' should be registered for #{version || 'default'}") + assert(JSON::Validator.validator_for_name(version).formats["custom"].is_a?(JSON::Schema::CustomFormat), "Format 'custom' should be registered for #{version || 'default'}") end JSON::Validator.restore_default_formats @all_versions.each do |version| - assert(JSON::Validator.validator_for_name(version).formats['custom'].nil?, "Format 'custom' should still be nil for #{version || 'default'}") + assert(JSON::Validator.validator_for_name(version).formats["custom"].nil?, "Format 'custom' should still be nil for #{version || 'default'}") end end @@ -60,9 +60,9 @@ def test_multi_registration unregistered_version = @all_versions.delete("draft1") JSON::Validator.register_format_validator("custom", @format_proc, @all_versions) @all_versions.each do |version| - assert(JSON::Validator.validator_for_name(version).formats['custom'].is_a?(JSON::Schema::CustomFormat), "Format 'custom' should be registered for #{version || 'default'}") + assert(JSON::Validator.validator_for_name(version).formats["custom"].is_a?(JSON::Schema::CustomFormat), "Format 'custom' should be registered for #{version || 'default'}") end - assert(JSON::Validator.validator_for_name(unregistered_version).formats['custom'].nil?, "Format 'custom' should still be nil for #{unregistered_version}") + assert(JSON::Validator.validator_for_name(unregistered_version).formats["custom"].nil?, "Format 'custom' should still be nil for #{unregistered_version}") end def test_format_validation @@ -83,11 +83,11 @@ def test_format_validation assert(!JSON::Validator.validate(schema, data), "#{prefix} fails with 'custom' format validator and wrong data") errors = JSON::Validator.fully_validate(schema, data) - assert(errors.count == 1 && errors.first.match(/The property '#\/a' must be 42 in schema/), "#{prefix} records fromat error") + assert(errors.count == 1 && errors.first.match(%r{The property '#/a' must be 42 in schema}), "#{prefix} records format error") data["a"] = 23 errors = JSON::Validator.fully_validate(schema, data) - assert(errors.count == 1 && errors.first.match(/The property '#\/a' of type (?:integer|Fixnum) did not match the following type: string/), "#{prefix} records no fromat error on type mismatch") + assert(errors.count == 1 && errors.first.match(%r{The property '#/a' of type (?:integer|Fixnum) did not match the following type: string}), "#{prefix} records no format error on type mismatch") end end @@ -115,5 +115,3 @@ def test_override_default_format end end end - - diff --git a/test/test_definition.rb b/test/test_definition.rb index 42541204..be75b1c8 100644 --- a/test/test_definition.rb +++ b/test/test_definition.rb @@ -1,15 +1,13 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class RelativeDefinitionTest < Minitest::Test - def test_definition_schema - assert_valid schema_fixture_path('definition_schema.json'), {"a" => 5} + assert_valid schema_fixture_path("definition_schema.json"), "a" => 5 end def test_relative_definition - schema = schema_fixture_path('relative_definition_schema.json') - assert_valid schema, {"a" => 5} - refute_valid schema, {"a" => "foo"} + schema = schema_fixture_path("relative_definition_schema.json") + assert_valid schema, "a" => 5 + refute_valid schema, "a" => "foo" end - end diff --git a/test/test_extended_schema.rb b/test/test_extended_schema.rb index b7023860..fe720ef0 100644 --- a/test/test_extended_schema.rb +++ b/test/test_extended_schema.rb @@ -1,10 +1,10 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class BitwiseAndAttribute < JSON::Schema::Attribute - def self.validate(current_schema, data, fragments, processor, validator, options = {}) + def self.validate(current_schema, data, fragments, processor, _validator, options = {}) return unless data.is_a?(Integer) - if data & current_schema.schema['bitwise-and'].to_i == 0 + if data & current_schema.schema["bitwise-and"].to_i == 0 message = "The property '#{build_fragment(fragments)}' did not evaluate to true when bitwise-AND'd with #{current_schema.schema['bitwise-and']}" validation_error(processor, message, fragments, current_schema, self, options[:record_errors]) end @@ -19,7 +19,7 @@ def initialize @uri = Addressable::URI.parse("http://test.com/test.json") end - JSON::Validator.register_validator(self.new) + JSON::Validator.register_validator(new) end class TestExtendedSchema < Minitest::Test @@ -36,9 +36,9 @@ def test_extended_schema_validation } } - assert_valid schema, {"a" => 1, "b" => "taco"} - refute_valid schema, {"a" => 0, "b" => "taco"} - refute_valid schema, {"a" => 1, "b" => 5} + assert_valid schema, "a" => 1, "b" => "taco" + refute_valid schema, "a" => 0, "b" => "taco" + refute_valid schema, "a" => 1, "b" => 5 end def test_unextended_schema @@ -55,8 +55,8 @@ def test_unextended_schema } } - assert_valid schema, {"a" => 0, "b" => "taco"} - assert_valid schema, {"a" => 1, "b" => "taco"} - refute_valid schema, {"a" => 1, "b" => 5} + assert_valid schema, "a" => 0, "b" => "taco" + assert_valid schema, "a" => 1, "b" => "taco" + refute_valid schema, "a" => 1, "b" => 5 end end diff --git a/test/test_extends_and_additionalProperties.rb b/test/test_extends_and_additionalProperties.rb index 9f6b40db..c8888add 100644 --- a/test/test_extends_and_additionalProperties.rb +++ b/test/test_extends_and_additionalProperties.rb @@ -1,7 +1,6 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class ExtendsNestedTest < Minitest::Test - def assert_validity(valid, schema_name, data, msg) msg = "Schema should be #{valid ? :valid : :invalid}.\n(#{schema_name}) #{msg}" schema = schema_fixture_path("#{schema_name}.schema.json") @@ -14,13 +13,13 @@ def assert_validity(valid, schema_name, data, msg) end end - %w[ + %w( extends_and_additionalProperties-1-filename extends_and_additionalProperties-1-ref extends_and_additionalProperties-2-filename extends_and_additionalProperties-2-ref - ].each do |schema_name| - test_prefix = 'test_' + schema_name.gsub('-','_') + ).each do |schema_name| + test_prefix = "test_" + schema_name.tr("-", "_") class_eval <<-EOB def #{test_prefix}_valid_outer @@ -40,13 +39,12 @@ def #{test_prefix}_invalid_inner end EOB - if schema_name['extends_and_additionalProperties-1'] - class_eval <<-EOB - def #{test_prefix}_invalid_outer - assert_validity false, '#{schema_name}', {"whaaaaat"=>true}, "Outer defn allowing anything when it shouldn't" - end - EOB - end + next unless schema_name["extends_and_additionalProperties-1"] + class_eval <<-EOB + def #{test_prefix}_invalid_outer + assert_validity false, '#{schema_name}', {"whaaaaat"=>true}, "Outer defn allowing anything when it shouldn't" + end + EOB end end diff --git a/test/test_files_v3.rb b/test/test_files_v3.rb index d85d970c..6e59a0a3 100644 --- a/test/test_files_v3.rb +++ b/test/test_files_v3.rb @@ -1,43 +1,41 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class JSONSchemaTest < Minitest::Test - # # These tests are ONLY run if there is an appropriate JSON backend parser available # def test_schema_from_file - assert_valid schema_fixture_path('good_schema_1.json'), { "a" => 5 } - refute_valid schema_fixture_path('good_schema_1.json'), { "a" => "bad" } + assert_valid schema_fixture_path("good_schema_1.json"), "a" => 5 + refute_valid schema_fixture_path("good_schema_1.json"), "a" => "bad" end def test_data_from_file - schema = {"$schema" => "http://json-schema.org/draft-03/schema#","type" => "object", "properties" => {"a" => {"type" => "integer"}}} - assert_valid schema, data_fixture_path('good_data_1.json'), :uri => true - refute_valid schema, data_fixture_path('bad_data_1.json'), :uri => true + schema = {"$schema" => "http://json-schema.org/draft-03/schema#", "type" => "object", "properties" => {"a" => {"type" => "integer"}}} + assert_valid schema, data_fixture_path("good_data_1.json"), :uri => true + refute_valid schema, data_fixture_path("bad_data_1.json"), :uri => true end def test_data_from_json - if JSON::Validator.json_backend != nil - schema = {"$schema" => "http://json-schema.org/draft-03/schema#","type" => "object", "properties" => {"a" => {"type" => "integer"}}} - assert_valid schema, %Q({"a": 5}), :json => true - refute_valid schema, %Q({"a": "poop"}), :json => true + unless JSON::Validator.json_backend.nil? + schema = {"$schema" => "http://json-schema.org/draft-03/schema#", "type" => "object", "properties" => {"a" => {"type" => "integer"}}} + assert_valid schema, %({"a": 5}), :json => true + refute_valid schema, %({"a": "poop"}), :json => true end end def test_both_from_file - assert_valid schema_fixture_path('good_schema_1.json'), data_fixture_path('good_data_1.json'), :uri => true - refute_valid schema_fixture_path('good_schema_1.json'), data_fixture_path('bad_data_1.json'), :uri => true + assert_valid schema_fixture_path("good_schema_1.json"), data_fixture_path("good_data_1.json"), :uri => true + refute_valid schema_fixture_path("good_schema_1.json"), data_fixture_path("bad_data_1.json"), :uri => true end def test_file_ref - assert_valid schema_fixture_path('good_schema_2.json'), { "b" => { "a" => 5 } } - refute_valid schema_fixture_path('good_schema_1.json'), { "b" => { "a" => "boo" } } + assert_valid schema_fixture_path("good_schema_2.json"), "b" => {"a" => 5} + refute_valid schema_fixture_path("good_schema_1.json"), "b" => {"a" => "boo"} end def test_file_extends - assert_valid schema_fixture_path('good_schema_extends1.json'), { "a" => 5 } - assert_valid schema_fixture_path('good_schema_extends2.json'), { "a" => 5, "b" => { "a" => 5 } } + assert_valid schema_fixture_path("good_schema_extends1.json"), "a" => 5 + assert_valid schema_fixture_path("good_schema_extends2.json"), "a" => 5, "b" => {"a" => 5} end - end diff --git a/test/test_fragment_resolution.rb b/test/test_fragment_resolution.rb index 95985c40..46005973 100644 --- a/test/test_fragment_resolution.rb +++ b/test/test_fragment_resolution.rb @@ -1,4 +1,4 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class FragmentResolution < Minitest::Test def test_fragment_resolution @@ -9,7 +9,7 @@ def test_fragment_resolution "a" => { "type" => "object", "properties" => { - "b" => {"type" => "integer" } + "b" => {"type" => "integer"} } } } @@ -20,11 +20,11 @@ def test_fragment_resolution assert_valid schema, data, :fragment => "#/properties/a" assert_raises JSON::Schema::SchemaError do - JSON::Validator.validate!(schema,data,:fragment => "/properties/a") + JSON::Validator.validate!(schema, data, :fragment => "/properties/a") end assert_raises JSON::Schema::SchemaError do - JSON::Validator.validate!(schema,data,:fragment => "#/properties/b") + JSON::Validator.validate!(schema, data, :fragment => "#/properties/b") end end end diff --git a/test/test_fragment_validation_with_ref.rb b/test/test_fragment_validation_with_ref.rb index 459c541c..c441cf1b 100644 --- a/test/test_fragment_validation_with_ref.rb +++ b/test/test_fragment_validation_with_ref.rb @@ -1,4 +1,4 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class FragmentValidationWithRef < Minitest::Test def whole_schema diff --git a/test/test_full_validation.rb b/test/test_full_validation.rb index 4fe470a5..013844d1 100644 --- a/test/test_full_validation.rb +++ b/test/test_full_validation.rb @@ -1,7 +1,6 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class JSONFullValidation < Minitest::Test - def test_full_validation data = {"b" => {"a" => 5}} schema = { @@ -13,8 +12,8 @@ def test_full_validation } } } - - errors = JSON::Validator.fully_validate(schema,data) + + errors = JSON::Validator.fully_validate(schema, data) assert(errors.empty?) data = {"c" => 5} @@ -31,10 +30,10 @@ def test_full_validation } } - errors = JSON::Validator.fully_validate(schema,data) + errors = JSON::Validator.fully_validate(schema, data) assert(errors.length == 2) end - + def test_full_validation_with_union_types data = {"b" => 5} schema = { @@ -42,32 +41,32 @@ def test_full_validation_with_union_types "type" => "object", "properties" => { "b" => { - "type" => ["null","integer"] + "type" => ["null", "integer"] } } } - - errors = JSON::Validator.fully_validate(schema,data) + + errors = JSON::Validator.fully_validate(schema, data) assert(errors.empty?) - + schema = { "$schema" => "http://json-schema.org/draft-03/schema#", "type" => "object", "properties" => { "b" => { - "type" => ["integer","null"] + "type" => ["integer", "null"] } } } - - errors = JSON::Validator.fully_validate(schema,data) + + errors = JSON::Validator.fully_validate(schema, data) assert(errors.empty?) - + data = {"b" => "a string"} - - errors = JSON::Validator.fully_validate(schema,data) + + errors = JSON::Validator.fully_validate(schema, data) assert(errors.length == 1) - + schema = { "$schema" => "http://json-schema.org/draft-03/schema#", "type" => "object", @@ -90,24 +89,23 @@ def test_full_validation_with_union_types } } } - + data = {"b" => {"c" => "taco"}} - - errors = JSON::Validator.fully_validate(schema,data) + + errors = JSON::Validator.fully_validate(schema, data) assert(errors.empty?) - + data = {"b" => {"d" => 6}} - - errors = JSON::Validator.fully_validate(schema,data) + + errors = JSON::Validator.fully_validate(schema, data) assert(errors.empty?) - + data = {"b" => {"c" => 6, "d" => "OH GOD"}} - - errors = JSON::Validator.fully_validate(schema,data) + + errors = JSON::Validator.fully_validate(schema, data) assert(errors.length == 1) end - - + def test_full_validation_with_object_errors data = {"b" => {"a" => 5}} schema = { @@ -119,8 +117,8 @@ def test_full_validation_with_object_errors } } } - - errors = JSON::Validator.fully_validate(schema,data,:errors_as_objects => true) + + errors = JSON::Validator.fully_validate(schema, data, :errors_as_objects => true) assert(errors.empty?) data = {"c" => 5} @@ -137,14 +135,14 @@ def test_full_validation_with_object_errors } } - errors = JSON::Validator.fully_validate(schema,data,:errors_as_objects => true) + errors = JSON::Validator.fully_validate(schema, data, :errors_as_objects => true) assert(errors.length == 2) assert(errors[0][:failed_attribute] == "Properties") assert(errors[0][:fragment] == "#/") assert(errors[1][:failed_attribute] == "Type") assert(errors[1][:fragment] == "#/c") end - + def test_full_validation_with_nested_required_properties schema = { "$schema" => "http://json-schema.org/draft-03/schema#", @@ -154,25 +152,25 @@ def test_full_validation_with_nested_required_properties "required" => true, "type" => "object", "properties" => { - "a" => {"type"=>"integer","required"=>true}, - "b" => {"type"=>"integer","required"=>true}, - "c" => {"type"=>"integer","required"=>false}, - "d" => {"type"=>"integer","required"=>false}, - "e" => {"type"=>"integer","required"=>false}, + "a" => {"type" => "integer", "required" => true}, + "b" => {"type" => "integer", "required" => true}, + "c" => {"type" => "integer", "required" => false}, + "d" => {"type" => "integer", "required" => false}, + "e" => {"type" => "integer", "required" => false} } } } } - data = {"x" => {"a"=>5, "d"=>5, "e"=>"what?"}} - - errors = JSON::Validator.fully_validate(schema,data,:errors_as_objects => true) + data = {"x" => {"a" => 5, "d" => 5, "e" => "what?"}} + + errors = JSON::Validator.fully_validate(schema, data, :errors_as_objects => true) assert_equal 2, errors.length assert_equal '#/x', errors[0][:fragment] - assert_equal 'Properties', errors[0][:failed_attribute] + assert_equal "Properties", errors[0][:failed_attribute] assert_equal '#/x/e', errors[1][:fragment] - assert_equal 'Type', errors[1][:failed_attribute] + assert_equal "Type", errors[1][:failed_attribute] end - + def test_full_validation_with_nested_required_propertiesin_array schema = { "$schema" => "http://json-schema.org/draft-03/schema#", @@ -184,25 +182,25 @@ def test_full_validation_with_nested_required_propertiesin_array "items" => { "type" => "object", "properties" => { - "a" => {"type"=>"integer","required"=>true}, - "b" => {"type"=>"integer","required"=>true}, - "c" => {"type"=>"integer","required"=>false}, - "d" => {"type"=>"integer","required"=>false}, - "e" => {"type"=>"integer","required"=>false}, + "a" => {"type" => "integer", "required" => true}, + "b" => {"type" => "integer", "required" => true}, + "c" => {"type" => "integer", "required" => false}, + "d" => {"type" => "integer", "required" => false}, + "e" => {"type" => "integer", "required" => false} } } } } } - missing_b= {"a"=>5} - e_is_wrong_type= {"a"=>5,"b"=>5,"e"=>"what?"} + missing_b = {"a" => 5} + e_is_wrong_type = {"a" => 5, "b" => 5, "e" => "what?"} data = {"x" => [missing_b, e_is_wrong_type]} - - errors = JSON::Validator.fully_validate(schema,data,:errors_as_objects => true) + + errors = JSON::Validator.fully_validate(schema, data, :errors_as_objects => true) assert_equal 2, errors.length assert_equal '#/x/0', errors[0][:fragment] - assert_equal 'Properties', errors[0][:failed_attribute] + assert_equal "Properties", errors[0][:failed_attribute] assert_equal '#/x/1/e', errors[1][:fragment] - assert_equal 'Type', errors[1][:failed_attribute] + assert_equal "Type", errors[1][:failed_attribute] end end diff --git a/test/test_helper.rb b/test/test_helper.rb index e8d6aef1..ce3cbf12 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -1,47 +1,49 @@ -require 'minitest/autorun' -require 'webmock/minitest' +require "minitest/autorun" +require "webmock/minitest" -$:.unshift(File.expand_path('../../lib', __FILE__)) -require 'json-schema' +$LOAD_PATH.unshift(File.expand_path("../../lib", __FILE__)) +require "json-schema" -Dir[File.join(File.expand_path('../support', __FILE__), '*.rb')].each do |support_file| +Dir[File.join(File.expand_path("../support", __FILE__), "*.rb")].each do |support_file| require support_file end -class Minitest::Test - def schema_fixture_path(filename) - File.join(File.dirname(__FILE__), 'schemas', filename) - end - - def data_fixture_path(filename) - File.join(File.dirname(__FILE__), 'data', filename) - end +module Minitest + class Test + def schema_fixture_path(filename) + File.join(File.dirname(__FILE__), "schemas", filename) + end - def assert_valid(schema, data, options = {}) - if !options.key?(:version) && respond_to?(:schema_version) - options = options.merge(:version => schema_version) + def data_fixture_path(filename) + File.join(File.dirname(__FILE__), "data", filename) end - errors = JSON::Validator.fully_validate(schema, data, options) - assert_equal([], errors, "#{data.inspect} should be valid for schema:\n#{schema.inspect}") - end + def assert_valid(schema, data, options = {}) + if !options.key?(:version) && respond_to?(:schema_version) + options = options.merge(:version => schema_version) + end - def refute_valid(schema, data, options = {}) - if !options.key?(:version) && respond_to?(:schema_version) - options = options.merge(:version => schema_version) + errors = JSON::Validator.fully_validate(schema, data, options) + assert_equal([], errors, "#{data.inspect} should be valid for schema:\n#{schema.inspect}") end - errors = JSON::Validator.fully_validate(schema, data, options) - refute_equal([], errors, "#{data.inspect} should be invalid for schema:\n#{schema.inspect}") - end + def refute_valid(schema, data, options = {}) + if !options.key?(:version) && respond_to?(:schema_version) + options = options.merge(:version => schema_version) + end + + errors = JSON::Validator.fully_validate(schema, data, options) + refute_equal([], errors, "#{data.inspect} should be invalid for schema:\n#{schema.inspect}") + end - def parser_error - if defined?(::Yajl) - Yajl::ParseError - elsif defined?(::MultiJson) - MultiJson::ParseError - else - JSON::ParserError + def parser_error + if defined?(::Yajl) + Yajl::ParseError + elsif defined?(::MultiJson) + MultiJson::ParseError + else + JSON::ParserError + end end end end diff --git a/test/test_initialize_data.rb b/test/test_initialize_data.rb index bf61c65f..6f23a443 100644 --- a/test/test_initialize_data.rb +++ b/test/test_initialize_data.rb @@ -1,10 +1,9 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class InitializeDataTest < Minitest::Test - def test_parse_character_string - schema = {'type' => 'string'} - data = 'hello world' + schema = {"type" => "string"} + data = "hello world" assert(JSON::Validator.validate(schema, data)) @@ -18,8 +17,8 @@ def test_parse_character_string end def test_parse_integer_string - schema = {'type' => 'integer'} - data = '42' + schema = {"type" => "integer"} + data = "42" assert(JSON::Validator.validate(schema, data)) @@ -31,7 +30,7 @@ def test_parse_integer_string end def test_parse_hash_string - schema = { 'type' => 'object', 'properties' => { 'a' => { 'type' => 'string' } } } + schema = {"type" => "object", "properties" => {"a" => {"type" => "string"}}} data = '{"a": "b"}' assert(JSON::Validator.validate(schema, data)) @@ -44,7 +43,7 @@ def test_parse_hash_string end def test_parse_json_string - schema = {'type' => 'string'} + schema = {"type" => "string"} data = '"hello world"' assert(JSON::Validator.validate(schema, data)) @@ -57,8 +56,8 @@ def test_parse_json_string end def test_parse_valid_uri_string - schema = {'type' => 'string'} - data = 'http://foo.bar/' + schema = {"type" => "string"} + data = "http://foo.bar/" stub_request(:get, "foo.bar").to_return(:body => '"hello world"', :status => 200) @@ -74,8 +73,8 @@ def test_parse_valid_uri_string end def test_parse_invalid_uri_string - schema = {'type' => 'string'} - data = 'http://foo.bar/' + schema = {"type" => "string"} + data = "http://foo.bar/" stub_request(:get, "foo.bar").to_timeout @@ -91,7 +90,7 @@ def test_parse_invalid_uri_string end def test_parse_integer - schema = {'type' => 'integer'} + schema = {"type" => "integer"} data = 42 assert(JSON::Validator.validate(schema, data)) @@ -104,8 +103,8 @@ def test_parse_integer end def test_parse_hash - schema = { 'type' => 'object', 'properties' => { 'a' => { 'type' => 'string' } } } - data = { 'a' => 'b' } + schema = {"type" => "object", "properties" => {"a" => {"type" => "string"}}} + data = {"a" => "b"} assert(JSON::Validator.validate(schema, data)) diff --git a/test/test_jsonschema_draft1.rb b/test/test_jsonschema_draft1.rb index 06c8298e..e1e44afa 100644 --- a/test/test_jsonschema_draft1.rb +++ b/test/test_jsonschema_draft1.rb @@ -1,4 +1,4 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class JSONSchemaDraft1Test < Minitest::Test def schema_version @@ -6,17 +6,17 @@ def schema_version end def exclusive_minimum - { 'minimumCanEqual' => false } + {"minimumCanEqual" => false} end def exclusive_maximum - { 'maximumCanEqual' => false } + {"maximumCanEqual" => false} end include ArrayValidation::ItemsTests include EnumValidation::General - include EnumValidation::V1_V2 + include EnumValidation::V1V2 include NumberValidation::MinMaxTests @@ -42,7 +42,7 @@ def test_optional data = {} refute_valid schema, data - data['a'] = "Hello" + data["a"] = "Hello" assert_valid schema, data schema = { @@ -73,21 +73,18 @@ def test_max_decimal data["a"] = 3.455 refute_valid schema, data - schema["properties"]["a"]["maxDecimal"] = 0 data["a"] = 4.0 refute_valid schema, data - data["a"] = 'boo' + data["a"] = "boo" assert_valid schema, data data["a"] = 5 assert_valid schema, data end - - def test_disallow # Set up the default datatype schema = { @@ -100,16 +97,14 @@ def test_disallow "a" => nil } - - data["a"] = 'string' + data["a"] = "string" assert_valid schema, data data["a"] = 5 refute_valid schema, data - - schema["properties"]["a"]["disallow"] = ["integer","string"] - data["a"] = 'string' + schema["properties"]["a"]["disallow"] = ["integer", "string"] + data["a"] = "string" refute_valid schema, data data["a"] = 5 @@ -117,25 +112,22 @@ def test_disallow data["a"] = false assert_valid schema, data - end def test_format_datetime schema = { "type" => "object", - "properties" => { "a" => {"type" => "string", "format" => "date-time"}} + "properties" => {"a" => {"type" => "string", "format" => "date-time"}} } - assert_valid schema, {"a" => "2010-01-01T12:00:00Z"} - refute_valid schema, {"a" => "2010-01-32T12:00:00Z"} - refute_valid schema, {"a" => "2010-13-01T12:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T24:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:60:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:60Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00z"} - refute_valid schema, {"a" => "2010-01-0112:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00Z\nabc"} + assert_valid schema, "a" => "2010-01-01T12:00:00Z" + refute_valid schema, "a" => "2010-01-32T12:00:00Z" + refute_valid schema, "a" => "2010-13-01T12:00:00Z" + refute_valid schema, "a" => "2010-01-01T24:00:00Z" + refute_valid schema, "a" => "2010-01-01T12:60:00Z" + refute_valid schema, "a" => "2010-01-01T12:00:60Z" + refute_valid schema, "a" => "2010-01-01T12:00:00z" + refute_valid schema, "a" => "2010-01-0112:00:00Z" + refute_valid schema, "a" => "2010-01-01T12:00:00Z\nabc" end - end - diff --git a/test/test_jsonschema_draft2.rb b/test/test_jsonschema_draft2.rb index 6b4c25c2..80bd54e6 100644 --- a/test/test_jsonschema_draft2.rb +++ b/test/test_jsonschema_draft2.rb @@ -1,4 +1,4 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class JSONSchemaDraft2Test < Minitest::Test def schema_version @@ -6,22 +6,22 @@ def schema_version end def exclusive_minimum - { 'minimumCanEqual' => false } + {"minimumCanEqual" => false} end def exclusive_maximum - { 'maximumCanEqual' => false } + {"maximumCanEqual" => false} end def multiple_of - 'divisibleBy' + "divisibleBy" end include ArrayValidation::ItemsTests include ArrayValidation::UniqueItemsTests include EnumValidation::General - include EnumValidation::V1_V2 + include EnumValidation::V1V2 include NumberValidation::MinMaxTests include NumberValidation::MultipleOfTests @@ -48,7 +48,7 @@ def test_optional data = {} refute_valid schema, data - data['a'] = "Hello" + data["a"] = "Hello" assert_valid schema, data schema = { @@ -73,16 +73,14 @@ def test_disallow "a" => nil } - - data["a"] = 'string' + data["a"] = "string" assert_valid schema, data data["a"] = 5 refute_valid schema, data - - schema["properties"]["a"]["disallow"] = ["integer","string"] - data["a"] = 'string' + schema["properties"]["a"]["disallow"] = ["integer", "string"] + data["a"] = "string" refute_valid schema, data data["a"] = 5 @@ -95,19 +93,17 @@ def test_disallow def test_format_datetime schema = { "type" => "object", - "properties" => { "a" => {"type" => "string", "format" => "date-time"}} + "properties" => {"a" => {"type" => "string", "format" => "date-time"}} } - assert_valid schema, {"a" => "2010-01-01T12:00:00Z"} - refute_valid schema, {"a" => "2010-01-32T12:00:00Z"} - refute_valid schema, {"a" => "2010-13-01T12:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T24:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:60:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:60Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00z"} - refute_valid schema, {"a" => "2010-01-0112:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00Z\nabc"} + assert_valid schema, "a" => "2010-01-01T12:00:00Z" + refute_valid schema, "a" => "2010-01-32T12:00:00Z" + refute_valid schema, "a" => "2010-13-01T12:00:00Z" + refute_valid schema, "a" => "2010-01-01T24:00:00Z" + refute_valid schema, "a" => "2010-01-01T12:60:00Z" + refute_valid schema, "a" => "2010-01-01T12:00:60Z" + refute_valid schema, "a" => "2010-01-01T12:00:00z" + refute_valid schema, "a" => "2010-01-0112:00:00Z" + refute_valid schema, "a" => "2010-01-01T12:00:00Z\nabc" end - end - diff --git a/test/test_jsonschema_draft3.rb b/test/test_jsonschema_draft3.rb index 1c9cae7b..33ef5a08 100644 --- a/test/test_jsonschema_draft3.rb +++ b/test/test_jsonschema_draft3.rb @@ -1,5 +1,5 @@ # encoding: utf-8 -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class JSONSchemaDraft3Test < Minitest::Test def schema_version @@ -7,15 +7,15 @@ def schema_version end def exclusive_minimum - { 'exclusiveMinimum' => true } + {"exclusiveMinimum" => true} end def exclusive_maximum - { 'exclusiveMaximum' => true } + {"exclusiveMaximum" => true} end def multiple_of - 'divisibleBy' + "divisibleBy" end include ArrayValidation::ItemsTests @@ -23,7 +23,7 @@ def multiple_of include ArrayValidation::UniqueItemsTests include EnumValidation::General - include EnumValidation::V3_V4 + include EnumValidation::V3V4 include NumberValidation::MinMaxTests include NumberValidation::MultipleOfTests @@ -55,13 +55,13 @@ def test_types # Test an array of unioned-type objects that prevent additionalProperties schema["properties"]["a"] = { - 'type' => 'array', - 'items' => { - 'type' => [ - { 'type' => 'object', 'properties' => { "b" => { "type" => "integer" } } }, - { 'type' => 'object', 'properties' => { "c" => { "type" => "string" } } } + "type" => "array", + "items" => { + "type" => [ + {"type" => "object", "properties" => {"b" => {"type" => "integer"}}}, + {"type" => "object", "properties" => {"c" => {"type" => "string"}}} ], - 'additionalProperties' => false + "additionalProperties" => false } } @@ -85,7 +85,7 @@ def test_required data = {} refute_valid schema, data - data['a'] = "Hello" + data["a"] = "Hello" assert_valid schema, data schema = { @@ -109,13 +109,13 @@ def test_strict_properties_required_props } data = {"a" => "a"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"b" => "b"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) end def test_strict_properties_additional_props @@ -129,19 +129,19 @@ def test_strict_properties_additional_props } data = {"a" => "a"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"b" => "b"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => "c"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => 3} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) end def test_strict_properties_pattern_props @@ -155,25 +155,25 @@ def test_strict_properties_pattern_props } data = {"a" => "a"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"b" => "b"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => "c"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => 3} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "23 taco" => 3} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "23 taco" => "cheese"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) end def test_disallow @@ -189,16 +189,14 @@ def test_disallow "a" => nil } - - data["a"] = 'string' + data["a"] = "string" assert_valid schema, data data["a"] = 5 refute_valid schema, data - - schema["properties"]["a"]["disallow"] = ["integer","string"] - data["a"] = 'string' + schema["properties"]["a"]["disallow"] = ["integer", "string"] + data["a"] = "string" refute_valid schema, data data["a"] = 5 @@ -206,23 +204,20 @@ def test_disallow data["a"] = false assert_valid schema, data - end - - def test_extends schema = { "$schema" => "http://json-schema.org/draft-03/schema#", "properties" => { - "a" => { "type" => "integer"} + "a" => {"type" => "integer"} } } schema2 = { "$schema" => "http://json-schema.org/draft-03/schema#", "properties" => { - "a" => { "maximum" => 5 } + "a" => {"maximum" => 5} } } @@ -231,7 +226,7 @@ def test_extends } assert_valid schema, data - assert(!JSON::Validator.validate(schema2,data)) + assert(!JSON::Validator.validate(schema2, data)) schema["extends"] = schema2 @@ -242,69 +237,68 @@ def test_list_option schema = { "$schema" => "http://json-schema.org/draft-03/schema#", "type" => "object", - "properties" => { "a" => {"type" => "integer", "required" => true} } + "properties" => {"a" => {"type" => "integer", "required" => true}} } - data = [{"a" => 1},{"a" => 2},{"a" => 3}] - assert(JSON::Validator.validate(schema,data,:list => true)) + data = [{"a" => 1}, {"a" => 2}, {"a" => 3}] + assert(JSON::Validator.validate(schema, data, :list => true)) refute_valid schema, data data = {"a" => 1} - assert(!JSON::Validator.validate(schema,data,:list => true)) + assert(!JSON::Validator.validate(schema, data, :list => true)) - data = [{"a" => 1},{"b" => 2},{"a" => 3}] - assert(!JSON::Validator.validate(schema,data,:list => true)) + data = [{"a" => 1}, {"b" => 2}, {"a" => 3}] + assert(!JSON::Validator.validate(schema, data, :list => true)) end - def test_self_reference schema = { "$schema" => "http://json-schema.org/draft-03/schema#", "type" => "object", - "properties" => { "a" => {"type" => "integer"}, "b" => {"$ref" => "#"}} + "properties" => {"a" => {"type" => "integer"}, "b" => {"$ref" => "#"}} } - assert_valid schema, {"a" => 5, "b" => {"b" => {"a" => 1}}} - refute_valid schema, {"a" => 5, "b" => {"b" => {"a" => 'taco'}}} + assert_valid schema, "a" => 5, "b" => {"b" => {"a" => 1}} + refute_valid schema, "a" => 5, "b" => {"b" => {"a" => "taco"}} end def test_format_datetime schema = { "$schema" => "http://json-schema.org/draft-03/schema#", "type" => "object", - "properties" => { "a" => {"type" => "string", "format" => "date-time"}} + "properties" => {"a" => {"type" => "string", "format" => "date-time"}} } - assert_valid schema, {"a" => "2010-01-01T12:00:00Z"} - assert_valid schema, {"a" => "2010-01-01T12:00:00.1Z"} - assert_valid schema, {"a" => "2010-01-01T12:00:00,1Z"} - refute_valid schema, {"a" => "2010-01-32T12:00:00Z"} - refute_valid schema, {"a" => "2010-13-01T12:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T24:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:60:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:60Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00z"} - refute_valid schema, {"a" => "2010-01-0112:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00.1Z\nabc"} + assert_valid schema, "a" => "2010-01-01T12:00:00Z" + assert_valid schema, "a" => "2010-01-01T12:00:00.1Z" + assert_valid schema, "a" => "2010-01-01T12:00:00,1Z" + refute_valid schema, "a" => "2010-01-32T12:00:00Z" + refute_valid schema, "a" => "2010-13-01T12:00:00Z" + refute_valid schema, "a" => "2010-01-01T24:00:00Z" + refute_valid schema, "a" => "2010-01-01T12:60:00Z" + refute_valid schema, "a" => "2010-01-01T12:00:60Z" + refute_valid schema, "a" => "2010-01-01T12:00:00z" + refute_valid schema, "a" => "2010-01-0112:00:00Z" + refute_valid schema, "a" => "2010-01-01T12:00:00.1Z\nabc" # test with a specific timezone - assert_valid schema, {"a" => "2010-01-01T12:00:00+01"} - assert_valid schema, {"a" => "2010-01-01T12:00:00+01:00"} - assert_valid schema, {"a" => "2010-01-01T12:00:00+01:30"} - assert_valid schema, {"a" => "2010-01-01T12:00:00+0234"} - refute_valid schema, {"a" => "2010-01-01T12:00:00+01:"} - refute_valid schema, {"a" => "2010-01-01T12:00:00+0"} + assert_valid schema, "a" => "2010-01-01T12:00:00+01" + assert_valid schema, "a" => "2010-01-01T12:00:00+01:00" + assert_valid schema, "a" => "2010-01-01T12:00:00+01:30" + assert_valid schema, "a" => "2010-01-01T12:00:00+0234" + refute_valid schema, "a" => "2010-01-01T12:00:00+01:" + refute_valid schema, "a" => "2010-01-01T12:00:00+0" # do not allow mixing Z and specific timezone - refute_valid schema, {"a" => "2010-01-01T12:00:00Z+01"} - refute_valid schema, {"a" => "2010-01-01T12:00:00+01Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00+01:30Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00+0Z"} + refute_valid schema, "a" => "2010-01-01T12:00:00Z+01" + refute_valid schema, "a" => "2010-01-01T12:00:00+01Z" + refute_valid schema, "a" => "2010-01-01T12:00:00+01:30Z" + refute_valid schema, "a" => "2010-01-01T12:00:00+0Z" # test without any timezone - assert_valid schema, {"a" => "2010-01-01T12:00:00"} - assert_valid schema, {"a" => "2010-01-01T12:00:00.12345"} - assert_valid schema, {"a" => "2010-01-01T12:00:00,12345"} - assert_valid schema, {"a" => "2010-01-01T12:00:00.12345"} + assert_valid schema, "a" => "2010-01-01T12:00:00" + assert_valid schema, "a" => "2010-01-01T12:00:00.12345" + assert_valid schema, "a" => "2010-01-01T12:00:00,12345" + assert_valid schema, "a" => "2010-01-01T12:00:00.12345" end def test_format_uri @@ -313,18 +307,16 @@ def test_format_uri data3 = {"a" => "http://ja.wikipedia.org/wiki/メインページ"} schema = { - "$schema" => "http://json-schema.org/draft-03/schema#", - "type" => "object", - "properties" => { "a" => {"type" => "string", "format" => "uri"}} + "$schema" => "http://json-schema.org/draft-03/schema#", + "type" => "object", + "properties" => {"a" => {"type" => "string", "format" => "uri"}} } - assert(JSON::Validator.validate(schema,data1)) - assert(!JSON::Validator.validate(schema,data2)) - assert(JSON::Validator.validate(schema,data3)) + assert(JSON::Validator.validate(schema, data1)) + assert(!JSON::Validator.validate(schema, data2)) + assert(JSON::Validator.validate(schema, data3)) end - - def test_schema schema = { "$schema" => "http://json-schema.org/THIS-IS-NOT-A-SCHEMA", @@ -368,7 +360,7 @@ def test_dependency "c" => {"type" => "integer"} }, "dependencies" => { - "a" => ["b","c"] + "a" => ["b", "c"] } } @@ -391,7 +383,7 @@ def test_default data = {:b => 2} assert_valid schema, data assert_nil(data["a"]) - assert(JSON::Validator.validate(schema,data, :insert_defaults => true)) + assert(JSON::Validator.validate(schema, data, :insert_defaults => true)) assert_equal(42, data["a"]) assert_equal(2, data[:b]) @@ -407,7 +399,7 @@ def test_default data = {:b => 2} refute_valid schema, data assert_nil(data["a"]) - assert(JSON::Validator.validate(schema,data, :insert_defaults => true)) + assert(JSON::Validator.validate(schema, data, :insert_defaults => true)) assert_equal(42, data["a"]) assert_equal(2, data[:b]) @@ -423,7 +415,7 @@ def test_default data = {:b => 2} refute_valid schema, data assert_nil(data["a"]) - assert(!JSON::Validator.validate(schema,data, :insert_defaults => true)) + assert(!JSON::Validator.validate(schema, data, :insert_defaults => true)) assert_nil(data["a"]) assert_equal(2, data[:b]) @@ -439,12 +431,8 @@ def test_default data = {:b => 2} assert_valid schema, data assert_nil(data["a"]) - assert(!JSON::Validator.validate(schema,data, :insert_defaults => true)) - assert_equal("42",data["a"]) + assert(!JSON::Validator.validate(schema, data, :insert_defaults => true)) + assert_equal("42", data["a"]) assert_equal(2, data[:b]) - end - - end - diff --git a/test/test_jsonschema_draft4.rb b/test/test_jsonschema_draft4.rb index 8ddb7e10..a2ea000c 100644 --- a/test/test_jsonschema_draft4.rb +++ b/test/test_jsonschema_draft4.rb @@ -1,5 +1,5 @@ # encoding: utf-8 -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class JSONSchemaDraft4Test < Minitest::Test def schema_version @@ -7,15 +7,15 @@ def schema_version end def exclusive_minimum - { 'exclusiveMinimum' => true } + {"exclusiveMinimum" => true} end def exclusive_maximum - { 'exclusiveMaximum' => true } + {"exclusiveMaximum" => true} end def ipv4_format - 'ipv4' + "ipv4" end include ArrayValidation::ItemsTests @@ -23,7 +23,7 @@ def ipv4_format include ArrayValidation::UniqueItemsTests include EnumValidation::General - include EnumValidation::V3_V4 + include EnumValidation::V3V4 include NumberValidation::MinMaxTests include NumberValidation::MultipleOfTests @@ -50,7 +50,7 @@ def test_required data = {} refute_valid schema, data - data['a'] = "Hello" + data["a"] = "Hello" assert_valid schema, data schema = { @@ -65,23 +65,23 @@ def test_required end def test_min_properties - schema = { 'minProperties' => 2 } + schema = {"minProperties" => 2} - assert_valid schema, {'a' => 1, 'b' => 2} - assert_valid schema, {'a' => 1, 'b' => 2, 'c' => 3} + assert_valid schema, "a" => 1, "b" => 2 + assert_valid schema, "a" => 1, "b" => 2, "c" => 3 - refute_valid schema, {'a' => 1} + refute_valid schema, "a" => 1 refute_valid schema, {} end def test_max_properties - schema = { 'maxProperties' => 2 } + schema = {"maxProperties" => 2} - assert_valid schema, {'a' => 1, 'b' => 2} - assert_valid schema, {'a' => 1} + assert_valid schema, "a" => 1, "b" => 2 + assert_valid schema, "a" => 1 assert_valid schema, {} - refute_valid schema, {'a' => 1, 'b' => 2, 'c' => 3} + refute_valid schema, "a" => 1, "b" => 2, "c" => 3 end def test_strict_properties @@ -94,16 +94,16 @@ def test_strict_properties } data = {"a" => "a"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"b" => "b"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => "c"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) end def test_strict_properties_additional_props @@ -117,19 +117,19 @@ def test_strict_properties_additional_props } data = {"a" => "a"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"b" => "b"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => "c"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => 3} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) end def test_strict_properties_pattern_props @@ -143,25 +143,25 @@ def test_strict_properties_pattern_props } data = {"a" => "a"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"b" => "b"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b"} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => "c"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "c" => 3} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "23 taco" => 3} - assert(JSON::Validator.validate(schema,data,:strict => true)) + assert(JSON::Validator.validate(schema, data, :strict => true)) data = {"a" => "a", "b" => "b", "23 taco" => "cheese"} - assert(!JSON::Validator.validate(schema,data,:strict => true)) + assert(!JSON::Validator.validate(schema, data, :strict => true)) end def test_list_option @@ -169,18 +169,18 @@ def test_list_option "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "object", "required" => ["a"], - "properties" => { "a" => {"type" => "integer"} } + "properties" => {"a" => {"type" => "integer"}} } - data = [{"a" => 1},{"a" => 2},{"a" => 3}] - assert(JSON::Validator.validate(schema,data,:list => true)) + data = [{"a" => 1}, {"a" => 2}, {"a" => 3}] + assert(JSON::Validator.validate(schema, data, :list => true)) refute_valid schema, data data = {"a" => 1} - assert(!JSON::Validator.validate(schema,data,:list => true)) + assert(!JSON::Validator.validate(schema, data, :list => true)) - data = [{"a" => 1},{"b" => 2},{"a" => 3}] - assert(!JSON::Validator.validate(schema,data,:list => true)) + data = [{"a" => 1}, {"b" => 2}, {"a" => 3}] + assert(!JSON::Validator.validate(schema, data, :list => true)) end def test_default_with_strict_and_anyof @@ -239,7 +239,7 @@ def test_default_with_anyof data = {} assert(JSON::Validator.validate(schema, data, :insert_defaults => true, :strict => true)) - assert(data['foo'] == 'view') + assert(data["foo"] == "view") end def test_default_with_strict_and_oneof @@ -270,39 +270,39 @@ def test_default_with_strict_and_oneof } assert(JSON::Validator.validate(schema, data, :insert_defaults => true, :strict => true)) - assert(!data.key?('foo')) + assert(!data.key?("foo")) end def test_self_reference schema = { "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "object", - "properties" => { "a" => {"type" => "integer"}, "b" => {"$ref" => "#"}} + "properties" => {"a" => {"type" => "integer"}, "b" => {"$ref" => "#"}} } - assert_valid schema, {"a" => 5, "b" => {"b" => {"a" => 1}}} - refute_valid schema, {"a" => 5, "b" => {"b" => {"a" => 'taco'}}} + assert_valid schema, "a" => 5, "b" => {"b" => {"a" => 1}} + refute_valid schema, "a" => 5, "b" => {"b" => {"a" => "taco"}} end def test_format_datetime schema = { "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "object", - "properties" => { "a" => {"type" => "string", "format" => "date-time"}} - } - - assert_valid schema, {"a" => "2010-01-01T12:00:00Z"} - assert_valid schema, {"a" => "2010-01-01T12:00:00.1Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00,1Z"} - refute_valid schema, {"a" => "2010-01-01T12:00:00+0000"} - assert_valid schema, {"a" => "2010-01-01T12:00:00+00:00"} - refute_valid schema, {"a" => "2010-01-32T12:00:00Z"} - refute_valid schema, {"a" => "2010-13-01T12:00:00Z"} - assert_valid schema, {"a" => "2010-01-01T24:00:00Z"} - refute_valid schema, {"a" => "2010-01-01T12:60:00Z"} - assert_valid schema, {"a" => "2010-01-01T12:00:60Z"} - assert_valid schema, {"a" => "2010-01-01T12:00:00z"} - refute_valid schema, {"a" => "2010-01-0112:00:00Z"} + "properties" => {"a" => {"type" => "string", "format" => "date-time"}} + } + + assert_valid schema, "a" => "2010-01-01T12:00:00Z" + assert_valid schema, "a" => "2010-01-01T12:00:00.1Z" + refute_valid schema, "a" => "2010-01-01T12:00:00,1Z" + refute_valid schema, "a" => "2010-01-01T12:00:00+0000" + assert_valid schema, "a" => "2010-01-01T12:00:00+00:00" + refute_valid schema, "a" => "2010-01-32T12:00:00Z" + refute_valid schema, "a" => "2010-13-01T12:00:00Z" + assert_valid schema, "a" => "2010-01-01T24:00:00Z" + refute_valid schema, "a" => "2010-01-01T12:60:00Z" + assert_valid schema, "a" => "2010-01-01T12:00:60Z" + assert_valid schema, "a" => "2010-01-01T12:00:00z" + refute_valid schema, "a" => "2010-01-0112:00:00Z" end def test_format_uri @@ -313,12 +313,12 @@ def test_format_uri schema = { "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "object", - "properties" => { "a" => {"type" => "string", "format" => "uri"}} + "properties" => {"a" => {"type" => "string", "format" => "uri"}} } - assert(JSON::Validator.validate(schema,data1)) - assert(!JSON::Validator.validate(schema,data2)) - assert(JSON::Validator.validate(schema,data3)) + assert(JSON::Validator.validate(schema, data1)) + assert(!JSON::Validator.validate(schema, data2)) + assert(JSON::Validator.validate(schema, data3)) end def test_schema @@ -328,7 +328,7 @@ def test_schema } data = {"a" => "taco"} - assert(!JSON::Validator.validate(schema,data)) + assert(!JSON::Validator.validate(schema, data)) schema = { "$schema" => "http://json-schema.org/draft-04/schema#", @@ -364,7 +364,7 @@ def test_dependency "c" => {"type" => "integer"} }, "dependencies" => { - "a" => ["b","c"] + "a" => ["b", "c"] } } @@ -376,28 +376,28 @@ def test_dependency def test_schema_dependency schema = { - "type"=> "object", - "properties"=> { - "name"=> { "type"=> "string" }, - "credit_card"=> { "type"=> "number" } + "type" => "object", + "properties" => { + "name" => {"type" => "string"}, + "credit_card" => {"type" => "number"} }, - "required"=> ["name"], - "dependencies"=> { - "credit_card"=> { - "properties"=> { - "billing_address"=> { "type"=> "string" } + "required" => ["name"], + "dependencies" => { + "credit_card" => { + "properties" => { + "billing_address" => {"type" => "string"} }, - "required"=> ["billing_address"] + "required" => ["billing_address"] } } } data = { "name" => "John Doe", - "credit_card" => 5555555555555555 + "credit_card" => 5_555_555_555_555_555 } - assert(!JSON::Validator.validate(schema,data), 'test schema dependency with invalid data') - data['billing_address'] = "Somewhere over the rainbow" - assert(JSON::Validator.validate(schema,data), 'test schema dependency with valid data') + assert(!JSON::Validator.validate(schema, data), "test schema dependency with invalid data") + data["billing_address"] = "Somewhere over the rainbow" + assert(JSON::Validator.validate(schema, data), "test schema dependency with valid data") end def test_default @@ -413,7 +413,7 @@ def test_default data = {:b => 2} assert_valid schema, data assert_nil(data["a"]) - assert(JSON::Validator.validate(schema,data, :insert_defaults => true)) + assert(JSON::Validator.validate(schema, data, :insert_defaults => true)) assert_equal(42, data["a"]) assert_equal(2, data[:b]) @@ -430,7 +430,7 @@ def test_default data = {:b => 2} refute_valid schema, data assert_nil(data["a"]) - assert(JSON::Validator.validate(schema,data, :insert_defaults => true)) + assert(JSON::Validator.validate(schema, data, :insert_defaults => true)) assert_equal(42, data["a"]) assert_equal(2, data[:b]) @@ -447,7 +447,7 @@ def test_default data = {:b => 2} refute_valid schema, data assert_nil(data["a"]) - assert(!JSON::Validator.validate(schema,data, :insert_defaults => true)) + assert(!JSON::Validator.validate(schema, data, :insert_defaults => true)) assert_nil(data["a"]) assert_equal(2, data[:b]) @@ -463,10 +463,9 @@ def test_default data = {:b => 2} assert_valid schema, data assert_nil(data["a"]) - assert(!JSON::Validator.validate(schema,data, :insert_defaults => true)) - assert_equal("42",data["a"]) + assert(!JSON::Validator.validate(schema, data, :insert_defaults => true)) + assert_equal("42", data["a"]) assert_equal(2, data[:b]) - end def test_boolean_false_default @@ -515,7 +514,6 @@ def test_all_of refute_valid schema, data end - def test_any_of schema = { "$schema" => "http://json-schema.org/draft-04/schema#", @@ -546,7 +544,6 @@ def test_any_of refute_valid schema, data end - def test_one_of schema = { "$schema" => "http://json-schema.org/draft-04/schema#", @@ -578,13 +575,12 @@ def test_one_of refute_valid schema, data end - def test_not # Start with a simple not schema = { "$schema" => "http://json-schema.org/draft-04/schema#", "properties" => { - "a" => {"not" => { "type" => ["string", "boolean"]}} + "a" => {"not" => {"type" => ["string", "boolean"]}} } } @@ -602,16 +598,16 @@ def test_not "$schema" => "http://json-schema.org/draft-04/schema#", "properties" => { "a" => {"not" => {"anyOf" => [ - { - "type" => ["string","boolean"] - }, - { - "type" => "object", - "properties" => { - "b" => {"type" => "boolean"} - } + { + "type" => ["string", "boolean"] + }, + { + "type" => "object", + "properties" => { + "b" => {"type" => "boolean"} } - ]} + } + ]} } } } @@ -637,16 +633,16 @@ def test_not_fully_validate schema = { "$schema" => "http://json-schema.org/draft-04/schema#", "properties" => { - "a" => {"not" => { "type" => ["string", "boolean"]}} + "a" => {"not" => {"type" => ["string", "boolean"]}} } } data = {"a" => 1} - errors = JSON::Validator.fully_validate(schema,data) + errors = JSON::Validator.fully_validate(schema, data) assert_equal(0, errors.length) data = {"a" => "taco"} - errors = JSON::Validator.fully_validate(schema,data) + errors = JSON::Validator.fully_validate(schema, data) assert_equal(1, errors.length) end @@ -654,7 +650,7 @@ def test_definitions schema = { "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "array", - "items" => { "$ref" => "#/definitions/positiveInteger"}, + "items" => {"$ref" => "#/definitions/positiveInteger"}, "definitions" => { "positiveInteger" => { "type" => "integer", @@ -664,12 +660,10 @@ def test_definitions } } - data = [1,2,3] + data = [1, 2, 3] assert_valid schema, data - data = [-1,2,3] + data = [-1, 2, 3] refute_valid schema, data end end - - diff --git a/test/test_list_option.rb b/test/test_list_option.rb index 2360cf53..967def00 100644 --- a/test/test_list_option.rb +++ b/test/test_list_option.rb @@ -1,14 +1,14 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class ListOptionTest < Minitest::Test def test_list_option_reusing_schemas schema_hash = { "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "object", - "properties" => { "a" => { "type" => "integer" } } + "properties" => {"a" => {"type" => "integer"}} } - uri = Addressable::URI.parse('http://example.com/item') + uri = Addressable::URI.parse("http://example.com/item") schema = JSON::Schema.new(schema_hash, uri) JSON::Validator.add_schema(schema) diff --git a/test/test_load_ref_schema.rb b/test/test_load_ref_schema.rb index f37942dc..dc336676 100644 --- a/test/test_load_ref_schema.rb +++ b/test/test_load_ref_schema.rb @@ -1,18 +1,18 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class LoadRefSchemaTests < Minitest::Test def load_other_schema JSON::Validator.add_schema(JSON::Schema.new( - { - '$schema' => 'http://json-schema.org/draft-04/schema#', - 'type' => 'object', - 'properties' => { - "title" => { - "type" => "string" - } - } - }, - Addressable::URI.parse("http://example.com/schema#") + { + "$schema" => 'http://json-schema.org/draft-04/schema#', + "type" => "object", + "properties" => { + "title" => { + "type" => "string" + } + } + }, + Addressable::URI.parse("http://example.com/schema#") )) end @@ -23,7 +23,7 @@ def test_cached_schema } data = {} load_other_schema - validator = JSON::Validator.new(schema, data) + JSON::Validator.new(schema, data) assert JSON::Validator.schema_loaded?(schema_url) end @@ -34,7 +34,7 @@ def test_cached_schema_with_fragment } data = {} load_other_schema - validator = JSON::Validator.new(schema, data) + JSON::Validator.new(schema, data) assert JSON::Validator.schema_loaded?(schema_url) end end diff --git a/test/test_merge_missing_values.rb b/test/test_merge_missing_values.rb index a375a89e..a387133f 100644 --- a/test/test_merge_missing_values.rb +++ b/test/test_merge_missing_values.rb @@ -1,11 +1,11 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class MergeMissingValuesTest < Minitest::Test def test_merge_missing_values_for_string - original = 'foo' - updated = 'foo' + original = "foo" + updated = "foo" JSON::Validator.merge_missing_values(updated, original) - assert_equal('foo', original) + assert_equal("foo", original) end def test_merge_missing_values_for_empty_array @@ -23,23 +23,23 @@ def test_merge_missing_values_for_empty_hash end def test_merge_missing_values_for_new_values - original = {:hello => 'world'} - updated = {'hello' => 'world', 'foo' => 'bar'} + original = {:hello => "world"} + updated = {"hello" => "world", "foo" => "bar"} JSON::Validator.merge_missing_values(updated, original) - assert_equal({:hello => 'world', 'foo' => 'bar'}, original) + assert_equal({:hello => "world", "foo" => "bar"}, original) end def test_merge_missing_values_for_nested_array - original = [:hello, 'world', 1, 2, 3, {:foo => :bar, 'baz' => 'qux'}] - updated = ['hello', 'world', 1, 2, 3, {'foo' => 'bar', 'baz' => 'qux', 'this_is' => 'new'}] + original = [:hello, "world", 1, 2, 3, {:foo => :bar, "baz" => "qux"}] + updated = ["hello", "world", 1, 2, 3, {"foo" => "bar", "baz" => "qux", "this_is" => "new"}] JSON::Validator.merge_missing_values(updated, original) - assert_equal([:hello, 'world', 1, 2, 3, {:foo => :bar, 'baz' => 'qux', 'this_is' => 'new'}], original) + assert_equal([:hello, "world", 1, 2, 3, {:foo => :bar, "baz" => "qux", "this_is" => "new"}], original) end def test_merge_missing_values_for_nested_hash - original = {:hello => 'world', :foo => ['bar', :baz, {:uno => {:due => 3}}]} - updated = {'hello' => 'world', 'foo' => ['bar', 'baz', {'uno' => {'due' => 3, 'this_is' => 'new'}}], 'ack' => 'sed'} + original = {:hello => "world", :foo => ["bar", :baz, {:uno => {:due => 3}}]} + updated = {"hello" => "world", "foo" => ["bar", "baz", {"uno" => {"due" => 3, "this_is" => "new"}}], "ack" => "sed"} JSON::Validator.merge_missing_values(updated, original) - assert_equal({:hello => 'world', :foo => ['bar', :baz, {:uno => {:due => 3, 'this_is' => 'new'}}], 'ack' => 'sed'}, original) + assert_equal({:hello => "world", :foo => ["bar", :baz, {:uno => {:due => 3, "this_is" => "new"}}], "ack" => "sed"}, original) end end diff --git a/test/test_minitems.rb b/test/test_minitems.rb index d17d2242..e422c336 100644 --- a/test/test_minitems.rb +++ b/test/test_minitems.rb @@ -1,11 +1,11 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class MinItemsTest < Minitest::Test def test_minitems_nils schema = { "type" => "array", "minItems" => 1, - "items" => { "type" => "object" } + "items" => {"type" => "object"} } errors = JSON::Validator.fully_validate(schema, [nil]) diff --git a/test/test_one_of.rb b/test/test_one_of.rb index f26e924f..c311011e 100644 --- a/test/test_one_of.rb +++ b/test/test_one_of.rb @@ -1,9 +1,9 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class OneOfTest < Minitest::Test def test_one_of_links_schema - schema = schema_fixture_path('one_of_ref_links_schema.json') - data = data_fixture_path('one_of_ref_links_data.json') + schema = schema_fixture_path("one_of_ref_links_schema.json") + data = data_fixture_path("one_of_ref_links_data.json") assert_valid schema, data end @@ -12,21 +12,21 @@ def test_one_of_with_string_patterns "$schema" => "http://json-schema.org/draft-04/schema#", "oneOf" => [ { - "properties" => {"a" => {"type" => "string", "pattern" => "foo"}}, + "properties" => {"a" => {"type" => "string", "pattern" => "foo"}} }, { - "properties" => {"a" => {"type" => "string", "pattern" => "bar"}}, + "properties" => {"a" => {"type" => "string", "pattern" => "bar"}} }, { - "properties" => {"a" => {"type" => "string", "pattern" => "baz"}}, + "properties" => {"a" => {"type" => "string", "pattern" => "baz"}} } ] } - assert_valid schema, { "a" => "foo" } - refute_valid schema, { "a" => "foobar" } - assert_valid schema, { "a" => "baz" } - refute_valid schema, { "a" => 5 } + assert_valid schema, "a" => "foo" + refute_valid schema, "a" => "foobar" + assert_valid schema, "a" => "baz" + refute_valid schema, "a" => 5 end def test_one_of_sub_errors @@ -34,22 +34,22 @@ def test_one_of_sub_errors "$schema" => "http://json-schema.org/draft-04/schema#", "oneOf" => [ { - "properties" => {"a" => {"type" => "string", "pattern" => "foo"}}, + "properties" => {"a" => {"type" => "string", "pattern" => "foo"}} }, { - "properties" => {"a" => {"type" => "string", "pattern" => "bar"}}, + "properties" => {"a" => {"type" => "string", "pattern" => "bar"}} }, { - "properties" => {"a" => {"type" => "number", "minimum" => 10}}, + "properties" => {"a" => {"type" => "number", "minimum" => 10}} } ] } - errors = JSON::Validator.fully_validate(schema, { "a" => 5 }, :errors_as_objects => true) + errors = JSON::Validator.fully_validate(schema, {"a" => 5}, :errors_as_objects => true) nested_errors = errors[0][:errors] - assert_equal([:oneof_0,:oneof_1,:oneof_2], nested_errors.keys, 'should have nested errors for each allOf subschema') - assert_match(/the property '#\/a' of type Fixnum did not match the following type: string/i, nested_errors[:oneof_0][0][:message]) - assert_match(/the property '#\/a' did not have a minimum value of 10, inclusively/i, nested_errors[:oneof_2][0][:message]) + assert_equal([:oneof_0, :oneof_1, :oneof_2], nested_errors.keys, "should have nested errors for each allOf subschema") + assert_match(%r{the property '#/a' of type Fixnum did not match the following type: string}i, nested_errors[:oneof_0][0][:message]) + assert_match(%r{the property '#/a' did not have a minimum value of 10, inclusively}i, nested_errors[:oneof_2][0][:message]) end def test_one_of_sub_errors_message @@ -57,18 +57,18 @@ def test_one_of_sub_errors_message "$schema" => "http://json-schema.org/draft-04/schema#", "oneOf" => [ { - "properties" => {"a" => {"type" => "string", "pattern" => "foo"}}, + "properties" => {"a" => {"type" => "string", "pattern" => "foo"}} }, { - "properties" => {"a" => {"type" => "string", "pattern" => "bar"}}, + "properties" => {"a" => {"type" => "string", "pattern" => "bar"}} }, { - "properties" => {"a" => {"type" => "number", "minimum" => 10}}, + "properties" => {"a" => {"type" => "number", "minimum" => 10}} } ] } - errors = JSON::Validator.fully_validate(schema, { "a" => 5 }) + errors = JSON::Validator.fully_validate(schema, "a" => 5) expected_message = """The property '#/' of type Hash did not match any of the required schemas. The schema specific errors were: - oneOf #0: @@ -79,7 +79,5 @@ def test_one_of_sub_errors_message - The property '#/a' did not have a minimum value of 10, inclusively""" assert_equal(expected_message, errors[0]) - end - end diff --git a/test/test_ruby_schema.rb b/test/test_ruby_schema.rb index 7693b336..e62f491d 100644 --- a/test/test_ruby_schema.rb +++ b/test/test_ruby_schema.rb @@ -1,9 +1,9 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class RubySchemaTest < Minitest::Test def test_string_keys schema = { - "type" => 'object', + "type" => "object", "required" => ["a"], "properties" => { "a" => {"type" => "integer", "default" => 42}, @@ -11,12 +11,12 @@ def test_string_keys } } - assert_valid schema, { "a" => 5 } + assert_valid schema, "a" => 5 end def test_symbol_keys schema = { - :type => 'object', + :type => "object", :required => ["a"], :properties => { :a => {:type => "integer", :default => 42}, @@ -24,12 +24,12 @@ def test_symbol_keys } } - assert_valid schema, { :a => 5 } + assert_valid schema, :a => 5 end def test_symbol_keys_in_hash_within_array schema = { - :type => 'object', + :type => "object", :properties => { :a => { :type => "array", diff --git a/test/test_schema_loader.rb b/test/test_schema_loader.rb index b267e071..7c7ad989 100644 --- a/test/test_schema_loader.rb +++ b/test/test_schema_loader.rb @@ -1,8 +1,8 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class TestSchemaReader < Minitest::Test - ADDRESS_SCHEMA_URI = 'http://json-schema.org/address' - ADDRESS_SCHEMA_PATH = File.expand_path('../schemas/address_microformat.json', __FILE__) + ADDRESS_SCHEMA_URI = "http://json-schema.org/address" + ADDRESS_SCHEMA_PATH = File.expand_path("../schemas/address_microformat.json", __FILE__) def stub_address_request(body = File.read(ADDRESS_SCHEMA_PATH)) stub_request(:get, ADDRESS_SCHEMA_URI). @@ -27,21 +27,21 @@ def test_accept_all_files def test_refuse_all_uris reader = JSON::Schema::Reader.new(:accept_uri => false) - refute reader.accept_uri?(Addressable::URI.parse('http://foo.com')) + refute reader.accept_uri?(Addressable::URI.parse("http://foo.com")) end def test_refuse_all_files reader = JSON::Schema::Reader.new(:accept_file => false) - refute reader.accept_file?(Pathname.new('/foo/bar/baz')) + refute reader.accept_file?(Pathname.new("/foo/bar/baz")) end def test_accept_uri_proc reader = JSON::Schema::Reader.new( - :accept_uri => proc { |uri| uri.host == 'json-schema.org' } + :accept_uri => proc { |uri| uri.host == "json-schema.org" } ) - assert reader.accept_uri?(Addressable::URI.parse('http://json-schema.org/address')) - refute reader.accept_uri?(Addressable::URI.parse('http://sub.json-schema.org/address')) + assert reader.accept_uri?(Addressable::URI.parse("http://json-schema.org/address")) + refute reader.accept_uri?(Addressable::URI.parse("http://sub.json-schema.org/address")) end def test_accept_file_proc @@ -51,19 +51,19 @@ def test_accept_file_proc :accept_file => proc { |path| path.to_s.start_with?(test_root.to_s) } ) - assert reader.accept_file?(test_root.join('anything.json')) - refute reader.accept_file?(test_root.join('..', 'anything.json')) + assert reader.accept_file?(test_root.join("anything.json")) + refute reader.accept_file?(test_root.join("..", "anything.json")) end def test_file_scheme reader = JSON::Schema::Reader.new(:accept_uri => true, :accept_file => false) assert_raises(JSON::Schema::ReadRefused) do - reader.read('file://' + ADDRESS_SCHEMA_PATH) + reader.read("file://" + ADDRESS_SCHEMA_PATH) end end def test_parse_error - stub_address_request('this is totally not valid JSON!') + stub_address_request("this is totally not valid JSON!") reader = JSON::Schema::Reader.new diff --git a/test/test_schema_type_attribute.rb b/test/test_schema_type_attribute.rb index 5b446e94..fabea8a5 100644 --- a/test/test_schema_type_attribute.rb +++ b/test/test_schema_type_attribute.rb @@ -1,15 +1,15 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class TestSchemaTypeAttribute < Minitest::Test def test_type_of_data - assert_equal(type_of_data(String.new), 'string') - assert_equal(type_of_data(Numeric.new), 'number') - assert_equal(type_of_data(1), 'integer') - assert_equal(type_of_data(true), 'boolean') - assert_equal(type_of_data(false), 'boolean') - assert_equal(type_of_data(Hash.new), 'object') - assert_equal(type_of_data(nil), 'null') - assert_equal(type_of_data(Object.new), 'any') + assert_equal(type_of_data(""), "string") + assert_equal(type_of_data(Numeric.new), "number") + assert_equal(type_of_data(1), "integer") + assert_equal(type_of_data(true), "boolean") + assert_equal(type_of_data(false), "boolean") + assert_equal(type_of_data({}), "object") + assert_equal(type_of_data(nil), "null") + assert_equal(type_of_data(Object.new), "any") end private diff --git a/test/test_schema_validation.rb b/test/test_schema_validation.rb index 940715e4..7fe2a1d2 100644 --- a/test/test_schema_validation.rb +++ b/test/test_schema_validation.rb @@ -1,5 +1,5 @@ -require File.expand_path('../test_helper', __FILE__) -require 'tmpdir' +require File.expand_path("../test_helper", __FILE__) +require "tmpdir" class JSONSchemaValidation < Minitest::Test def valid_schema_v3 @@ -124,8 +124,8 @@ def symbolized_schema def test_draft03_validation data = {"b" => {"a" => 5}} - assert(JSON::Validator.validate(valid_schema_v3,data,:validate_schema => true, :version => :draft3)) - assert(!JSON::Validator.validate(invalid_schema_v3,data,:validate_schema => true, :version => :draft3)) + assert(JSON::Validator.validate(valid_schema_v3, data, :validate_schema => true, :version => :draft3)) + assert(!JSON::Validator.validate(invalid_schema_v3, data, :validate_schema => true, :version => :draft3)) end def test_validate_just_schema_draft03 @@ -137,11 +137,10 @@ def test_validate_just_schema_draft03 assert_match(/the property .*required.*did not match/i, errors.first) end - def test_draft04_validation data = {"b" => {"a" => 5}} - assert(JSON::Validator.validate(valid_schema_v4,data,:validate_schema => true, :version => :draft4)) - assert(!JSON::Validator.validate(invalid_schema_v4,data,:validate_schema => true, :version => :draft4)) + assert(JSON::Validator.validate(valid_schema_v4, data, :validate_schema => true, :version => :draft4)) + assert(!JSON::Validator.validate(invalid_schema_v4, data, :validate_schema => true, :version => :draft4)) end def test_validate_just_schema_draft04 @@ -155,16 +154,16 @@ def test_validate_just_schema_draft04 def test_validate_schema_3_without_version_option data = {"b" => {"a" => 5}} - assert(JSON::Validator.validate(valid_schema_v3,data,:validate_schema => true)) - assert(!JSON::Validator.validate(invalid_schema_v3,data,:validate_schema => true)) + assert(JSON::Validator.validate(valid_schema_v3, data, :validate_schema => true)) + assert(!JSON::Validator.validate(invalid_schema_v3, data, :validate_schema => true)) end def test_schema_validation_from_different_directory Dir.mktmpdir do |tmpdir| Dir.chdir(tmpdir) do data = {"b" => {"a" => 5}} - assert(JSON::Validator.validate(valid_schema_v4,data,:validate_schema => true, :version => :draft4)) - assert(!JSON::Validator.validate(invalid_schema_v4,data,:validate_schema => true, :version => :draft4)) + assert(JSON::Validator.validate(valid_schema_v4, data, :validate_schema => true, :version => :draft4)) + assert(!JSON::Validator.validate(invalid_schema_v4, data, :validate_schema => true, :version => :draft4)) end end end @@ -172,7 +171,7 @@ def test_schema_validation_from_different_directory def test_validate_schema_with_symbol_keys data = { "created_at" => "2014-01-25T00:58:33-08:00", - "id" => 8517194300913402149003, + "id" => 8_517_194_300_913_402_149_003, "name" => "chelsey", "real_name" => "Mekhi Hegmann", "website" => nil, diff --git a/test/test_stringify.rb b/test/test_stringify.rb index 99994373..523b6bb4 100644 --- a/test/test_stringify.rb +++ b/test/test_stringify.rb @@ -1,28 +1,28 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class StringifyTest < Minitest::Test def test_stringify_on_hash hash = { - :a => 'foo', - 'b' => :bar + :a => "foo", + "b" => :bar } - assert_equal({'a' => 'foo', 'b' => 'bar'}, JSON::Schema.stringify(hash), 'symbol keys should be converted to strings') + assert_equal({"a" => "foo", "b" => "bar"}, JSON::Schema.stringify(hash), "symbol keys should be converted to strings") end def test_stringify_on_array array = [ :a, - 'b' + "b" ] - assert_equal(['a', 'b'], JSON::Schema.stringify(array), 'symbols in an array should be converted to strings') + assert_equal(["a", "b"], JSON::Schema.stringify(array), "symbols in an array should be converted to strings") end def test_stringify_on_hash_of_arrays hash = { :a => [:foo], - 'b' => :bar + "b" => :bar } - assert_equal({'a' => ['foo'], 'b' => 'bar'}, JSON::Schema.stringify(hash), 'symbols in a nested array should be converted to strings') + assert_equal({"a" => ["foo"], "b" => "bar"}, JSON::Schema.stringify(hash), "symbols in a nested array should be converted to strings") end def test_stringify_on_array_of_hashes @@ -32,7 +32,7 @@ def test_stringify_on_array_of_hashes :b => :bar } ] - assert_equal(['a', {'b' => 'bar'}], JSON::Schema.stringify(array), 'symbols keys in a nested hash should be converted to strings') + assert_equal(["a", {"b" => "bar"}], JSON::Schema.stringify(array), "symbols keys in a nested hash should be converted to strings") end def test_stringify_on_hash_of_hashes @@ -43,6 +43,6 @@ def test_stringify_on_hash_of_hashes } } } - assert_equal({'a' => {'b' => {'foo' => 'bar'} } }, JSON::Schema.stringify(hash), 'symbols in a nested hash of hashes should be converted to strings') + assert_equal({"a" => {"b" => {"foo" => "bar"}}}, JSON::Schema.stringify(hash), "symbols in a nested hash of hashes should be converted to strings") end end diff --git a/test/test_uri_related.rb b/test/test_uri_related.rb index 70069ba5..1e577598 100644 --- a/test/test_uri_related.rb +++ b/test/test_uri_related.rb @@ -1,11 +1,11 @@ # coding: utf-8 -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class UriRelatedTest < Minitest::Test def test_asian_characters schema = { - "$schema"=> "http://json-schema.org/draft-04/schema#", - "id"=> "http://俺:鍵@例え.テスト/p?条件#ここ#", + "$schema" => "http://json-schema.org/draft-04/schema#", + "id" => "http://俺:鍵@例え.テスト/p?条件#ここ#", "type" => "object", "required" => ["a"], "properties" => { @@ -15,7 +15,7 @@ def test_asian_characters } } } - data = { "a" => 5 } + data = {"a" => 5} assert_valid schema, data end @@ -24,12 +24,12 @@ def test_schema_ref_with_empty_fragment "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "object", "required" => ["names"], - "properties"=> { - "names"=> { - "type"=> "array", - "items"=> { - "anyOf"=> [ - { "$ref" => "test/schemas/ref john with spaces schema.json#" }, + "properties" => { + "names" => { + "type" => "array", + "items" => { + "anyOf" => [ + {"$ref" => "test/schemas/ref john with spaces schema.json#"} ] } } @@ -44,12 +44,12 @@ def test_schema_ref_from_file_with_spaces "$schema" => "http://json-schema.org/draft-04/schema#", "type" => "object", "required" => ["names"], - "properties"=> { - "names"=> { - "type"=> "array", - "items"=> { - "anyOf"=> [ - { "$ref" => "test/schemas/ref john with spaces schema.json" } + "properties" => { + "names" => { + "type" => "array", + "items" => { + "anyOf" => [ + {"$ref" => "test/schemas/ref john with spaces schema.json"} ] } } diff --git a/test/test_validator.rb b/test/test_validator.rb index eb65de61..9bbe9bb4 100644 --- a/test/test_validator.rb +++ b/test/test_validator.rb @@ -1,13 +1,12 @@ -require File.expand_path('../test_helper', __FILE__) +require File.expand_path("../test_helper", __FILE__) class TestValidator < Minitest::Test - class MockReader def read(location) schema = { - '$schema' => 'http://json-schema.org/draft-04/schema#', - 'type' => 'string', - 'minLength' => 2 + "$schema" => 'http://json-schema.org/draft-04/schema#', + "type" => "string", + "minLength" => 2 } JSON::Schema.new(schema, Addressable::URI.parse(location.to_s)) @@ -24,30 +23,29 @@ def teardown def test_default_schema_reader reader = JSON::Validator.schema_reader - assert reader.accept_uri?(Addressable::URI.parse('http://example.com')) - assert reader.accept_file?(Pathname.new('/etc/passwd')) + assert reader.accept_uri?(Addressable::URI.parse("http://example.com")) + assert reader.accept_file?(Pathname.new("/etc/passwd")) end def test_set_default_schema_reader JSON::Validator.schema_reader = MockReader.new - schema = { '$ref' => 'http://any.url/at/all' } - assert_valid schema, 'abc' - refute_valid schema, 'a' + schema = {"$ref" => "http://any.url/at/all"} + assert_valid schema, "abc" + refute_valid schema, "a" end def test_validate_with_reader reader = MockReader.new - schema = { '$ref' => 'http://any.url/at/all' } - assert_valid schema, 'abc', :schema_reader => reader - refute_valid schema, 'a', :schema_reader => reader + schema = {"$ref" => "http://any.url/at/all"} + assert_valid schema, "abc", :schema_reader => reader + refute_valid schema, "a", :schema_reader => reader end def test_validate_list_with_reader reader = MockReader.new - schema = { '$ref' => 'http://what.ever/schema' } - assert_valid schema, ['abc', 'def'], :schema_reader => reader, :list => true - refute_valid schema, ['abc', 'a'], :schema_reader => reader, :list => true + schema = {"$ref" => "http://what.ever/schema"} + assert_valid schema, ["abc", "def"], :schema_reader => reader, :list => true + refute_valid schema, ["abc", "a"], :schema_reader => reader, :list => true end - end