From 5df130922f3032b62fbaddac23832e7bdb7e4917 Mon Sep 17 00:00:00 2001 From: richie Date: Mon, 17 Oct 2016 14:47:11 -0700 Subject: [PATCH] Support x-nullable in respone_validator --- .../lib/rswag/specs/extended_schema.rb | 25 +++++++++++++++++++ .../lib/rswag/specs/response_validator.rb | 12 ++++++--- 2 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 rswag-specs/lib/rswag/specs/extended_schema.rb diff --git a/rswag-specs/lib/rswag/specs/extended_schema.rb b/rswag-specs/lib/rswag/specs/extended_schema.rb new file mode 100644 index 0000000..379868d --- /dev/null +++ b/rswag-specs/lib/rswag/specs/extended_schema.rb @@ -0,0 +1,25 @@ +require 'json-schema' + +module Rswag + module Specs + class ExtendedSchema < JSON::Schema::Validator + + def initialize + super + extend_schema_definition("http://json-schema.org/draft-04/schema#") + @attributes['type'] = ExtendedTypeAttribute + @uri = URI.parse('http://tempuri.org/rswag/specs/extended_schema') + end + end + + class ExtendedTypeAttribute < JSON::Schema::TypeV4Attribute + + def self.validate(current_schema, data, fragments, processor, validator, options={}) + return if data.nil? && current_schema.schema['x-nullable'] == true + super + end + end + + JSON::Validator.register_validator(ExtendedSchema.new) + end +end diff --git a/rswag-specs/lib/rswag/specs/response_validator.rb b/rswag-specs/lib/rswag/specs/response_validator.rb index febedbf..7a04c37 100644 --- a/rswag-specs/lib/rswag/specs/response_validator.rb +++ b/rswag-specs/lib/rswag/specs/response_validator.rb @@ -1,4 +1,6 @@ +require 'active_support/core_ext/hash/slice' require 'json-schema' +require 'rswag/specs/extended_schema' module Rswag module Specs @@ -23,10 +25,14 @@ module Rswag end def validate_body!(body) - schema = @api_metadata[:response][:schema] - return if schema.nil? + response_schema = @api_metadata[:response][:schema] + return if response_schema.nil? + begin - JSON::Validator.validate!(schema.merge(@global_metadata), body) + validation_schema = response_schema + .merge('$schema' => 'http://tempuri.org/rswag/specs/extended_schema') + .merge(@global_metadata.slice(:definitions)) + JSON::Validator.validate!(validation_schema, body) rescue JSON::Schema::ValidationError => ex raise UnexpectedResponse, "Expected response body to match schema: #{ex.message}" end