From 5883c6d90bf7c3e4d53c16c8132efa0575eeaa43 Mon Sep 17 00:00:00 2001 From: Yudai Takada Date: Tue, 10 Dec 2024 00:19:09 +0900 Subject: [PATCH] Enable Cop in some Layout departments (#435) * Enable Cop in some Layout departments Change to enable Cop to unify some Space, Indent and Line. * Auto-correct Layout/EmptyLines * Auto-correct Layout/IndentationWidth * Auto-correct Layout/LeadingCommentSpace * Auto-correct Layout/RedundantLineBreak * Auto-correct Layout/SpaceAfterColon * Auto-correct Layout/SpaceAfterComma * Auto-correct Layout/SpaceAroundEqualsInParameterDefault * Auto-correct Layout/SpaceAroundOperators * Auto-correct Layout/SpaceBeforeBlockBraces * Auto-correct Layout/SpaceInLambdaLiteral * Auto-correct Layout/SpaceInsideArrayLiteralBrackets * Auto-correct Layout/SpaceInsideBlockBraces * Auto-correct Layout/SpaceInsideHashLiteralBraces * Auto-correct Layout/TrailingEmptyLines * Auto-correct Layout/TrailingWhitespace --- .rubocop.yml | 120 ++++++++++++++++++ committee.gemspec | 4 +- lib/committee/bin/committee_stub.rb | 7 +- lib/committee/drivers.rb | 2 +- lib/committee/drivers/open_api_2/driver.rb | 27 +--- .../open_api_2/parameter_schema_builder.rb | 3 +- .../drivers/open_api_2/schema_builder.rb | 7 +- lib/committee/errors.rb | 4 +- lib/committee/middleware/base.rb | 4 +- .../middleware/request_validation.rb | 2 +- lib/committee/middleware/stub.rb | 2 +- lib/committee/request_unpacker.rb | 7 +- .../schema_validator/hyper_schema.rb | 114 ++++++++--------- .../hyper_schema/parameter_coercer.rb | 82 ++++++------ .../hyper_schema/request_validator.rb | 3 +- .../hyper_schema/response_validator.rb | 4 +- .../hyper_schema/string_params_coercer.rb | 120 +++++++++--------- lib/committee/schema_validator/open_api_3.rb | 8 +- .../open_api_3/request_validator.rb | 2 +- lib/committee/schema_validator/option.rb | 7 +- lib/committee/test/schema_coverage.rb | 8 +- lib/committee/utils.rb | 40 +++--- lib/committee/version.rb | 2 +- test/bin/committee_stub_test.rb | 6 +- test/committee_test.rb | 1 - test/drivers/hyper_schema/driver_test.rb | 1 - test/drivers/open_api_2/driver_test.rb | 4 +- .../open_api_2/header_schema_builder_test.rb | 10 +- test/drivers/open_api_2/link_test.rb | 1 - .../parameter_schema_builder_test.rb | 51 +------- test/drivers/open_api_3/driver_test.rb | 10 +- test/drivers_test.rb | 47 +++---- test/middleware/base_test.rb | 49 ++----- .../request_validation_open_api_3_test.rb | 71 ++++------- test/middleware/request_validation_test.rb | 72 +++-------- .../response_validation_open_api_3_test.rb | 42 +++--- test/middleware/response_validation_test.rb | 23 ++-- test/middleware/stub_test.rb | 17 +-- test/request_unpacker_test.rb | 85 +++---------- .../hyper_schema/parameter_coercer_test.rb | 6 +- .../hyper_schema/request_validator_test.rb | 24 +--- .../hyper_schema/response_generator_test.rb | 4 +- .../hyper_schema/response_validator_test.rb | 10 +- .../string_params_coercer_test.rb | 4 +- .../open_api_3/operation_wrapper_test.rb | 33 +++-- .../open_api_3/request_validator_test.rb | 27 ++-- .../open_api_3/response_validator_test.rb | 6 +- test/test/methods_new_version_test.rb | 4 +- test/test/methods_test.rb | 10 +- test/test/schema_coverage_test.rb | 21 +-- test/test_helper.rb | 17 +-- test/validation_error_test.rb | 6 +- 52 files changed, 529 insertions(+), 712 deletions(-) diff --git a/.rubocop.yml b/.rubocop.yml index 6535769f..e25d3509 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -11,9 +11,129 @@ AllCops: - 'examples/**/*' - 'vendor/**/*' +Layout/BlockEndNewline: + Enabled: true + +Layout/EmptyComment: + Enabled: true + +Layout/EmptyLines: + Enabled: true + +Layout/EndOfLine: + Enabled: true + Layout/ExtraSpacing: Enabled: true +Layout/IndentationStyle: + Enabled: true + +Layout/IndentationWidth: + Enabled: true + +Layout/InitialIndentation: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/LeadingEmptyLines: + Enabled: true + +Layout/LineContinuationLeadingSpace: + Enabled: true + +Layout/LineContinuationSpacing: + Enabled: true + +Layout/RedundantLineBreak: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAfterMethodName: + Enabled: true + +Layout/SpaceAfterNot: + Enabled: true + +Layout/SpaceAfterSemicolon: + Enabled: true + +Layout/SpaceAroundBlockParameters: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundMethodCallOperator: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeBlockBraces: + Enabled: true + +Layout/SpaceBeforeBrackets: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeComment: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Layout/SpaceBeforeSemicolon: + Enabled: true + +Layout/SpaceInLambdaLiteral: + Enabled: true + +Layout/SpaceInsideArrayLiteralBrackets: + Enabled: true + +Layout/SpaceInsideArrayPercentLiteral: + Enabled: true + +Layout/SpaceInsideBlockBraces: + Enabled: true + +SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +Layout/SpaceInsidePercentLiteralDelimiters: + Enabled: true + +Layout/SpaceInsideRangeLiteral: + Enabled: true + +Layout/SpaceInsideReferenceBrackets: + Enabled: true + +Layout/SpaceInsideStringInterpolation: + Enabled: true + +Layout/TrailingEmptyLines: + Enabled: true + +Layout/TrailingWhitespace: + Enabled: true + Performance: Exclude: - 'test/**/*' diff --git a/committee.gemspec b/committee.gemspec index 279a261e..905cc0a7 100644 --- a/committee.gemspec +++ b/committee.gemspec @@ -15,8 +15,8 @@ Gem::Specification.new do |s| s.homepage = "https://github.com/interagent/committee" s.license = "MIT" - s.executables << "committee-stub" - s.files = Dir["{bin,lib,test}/**/*.rb"] + s.executables << "committee-stub" + s.files = Dir["{bin,lib,test}/**/*.rb"] s.required_ruby_version = ">= 2.7.0" diff --git a/lib/committee/bin/committee_stub.rb b/lib/committee/bin/committee_stub.rb index 85674ef7..ed3fbfe1 100644 --- a/lib/committee/bin/committee_stub.rb +++ b/lib/committee/bin/committee_stub.rb @@ -30,12 +30,7 @@ def get_app(schema, options) # Gets an option parser for command line arguments. def get_options_parser - options = { - driver: nil, - help: false, - port: 9292, - tolerant: false, - } + options = { driver: nil, help: false, port: 9292, tolerant: false, } parser = OptionParser.new do |opts| opts.banner = "Usage: rackup [options] [JSON Schema file]" diff --git a/lib/committee/drivers.rb b/lib/committee/drivers.rb index 63223f24..c5dcecd9 100644 --- a/lib/committee/drivers.rb +++ b/lib/committee/drivers.rb @@ -65,7 +65,7 @@ def self.load_from_data(hash, schema_path = nil, parser_options: {}) 'from next version. Pass config `strict_reference_validation: true` (or false, if you must) ' + 'to quiet this warning.') opts[:strict_reference_validation] ||= false - + openapi = OpenAPIParser.parse_with_filepath(hash, schema_path, opts) return Committee::Drivers::OpenAPI3::Driver.new.parse(openapi) end diff --git a/lib/committee/drivers/open_api_2/driver.rb b/lib/committee/drivers/open_api_2/driver.rb index 9a29ae17..f053b5fa 100644 --- a/lib/committee/drivers/open_api_2/driver.rb +++ b/lib/committee/drivers/open_api_2/driver.rb @@ -81,13 +81,7 @@ def schema_class # These are fields that the OpenAPI 2 spec considers mandatory to be # included in the document's top level. - REQUIRED_FIELDS = [ - :consumes, - :definitions, - :paths, - :produces, - :swagger, - ].map(&:to_s).freeze + REQUIRED_FIELDS = [:consumes, :definitions, :paths, :produces, :swagger,].map(&:to_s).freeze def find_best_fit_response(link_data) if response_data = link_data["responses"]["200"] || response_data = link_data["responses"][200] @@ -97,8 +91,7 @@ def find_best_fit_response(link_data) else # Sort responses so that we can try to prefer any 3-digit status code. # If there are none, we'll just take anything from the list. - ordered_responses = link_data["responses"]. - select { |k, v| k.to_s =~ /[0-9]{3}/ } + ordered_responses = link_data["responses"].select { |k, v| k.to_s =~ /[0-9]{3}/ } if first = ordered_responses.first [first[0].to_i, first[1]] else @@ -117,9 +110,7 @@ def parse_definitions!(data) # that all references to it will still have correct paths (i.e. we can # still find a resource at '#/definitions/resource' instead of # '#/resource'). - schema = JsonSchema.parse!({ - "definitions" => data['definitions'], - }) + schema = JsonSchema.parse!({ "definitions" => data['definitions'], }) schema.expand_references! schema.uri = DEFINITIONS_PSEUDO_URI @@ -182,8 +173,7 @@ def parse_routes!(data, schema, store) # A link need not necessarily specify a target schema. if response_data["schema"] - target_schemas_data["properties"][href]["properties"][method] = - response_data["schema"] + target_schemas_data["properties"][href]["properties"][method] = response_data["schema"] end end @@ -199,10 +189,8 @@ def parse_routes!(data, schema, store) # #parse_definitions!, but what we're doing here is prefixing references # with a specialized internal URI so that they can reference definitions # from another document in the store. - schemas = - rewrite_references_and_parse(schemas_data, store) - target_schemas = - rewrite_references_and_parse(target_schemas_data, store) + schemas = rewrite_references_and_parse(schemas_data, store) + target_schemas = rewrite_references_and_parse(target_schemas_data, store) # As noted above, now that we've parsed our aggregate response schema, go # back through each link and them their response schema. @@ -218,8 +206,7 @@ def parse_routes!(data, schema, store) end # response - link.target_schema = - target_schemas.properties[link.href].properties[method] + link.target_schema = target_schemas.properties[link.href].properties[method] end end diff --git a/lib/committee/drivers/open_api_2/parameter_schema_builder.rb b/lib/committee/drivers/open_api_2/parameter_schema_builder.rb index 7acfd0b9..3231d05f 100644 --- a/lib/committee/drivers/open_api_2/parameter_schema_builder.rb +++ b/lib/committee/drivers/open_api_2/parameter_schema_builder.rb @@ -17,8 +17,7 @@ def call check_required_fields!(body_param) if link_data["parameters"].detect { |p| p["in"] == "form" } != nil - raise ArgumentError, "Committee: can't mix body parameter " \ - "with form parameters." + raise ArgumentError, "Committee: can't mix body parameter with form parameters." end schema_data = body_param["schema"] diff --git a/lib/committee/drivers/open_api_2/schema_builder.rb b/lib/committee/drivers/open_api_2/schema_builder.rb index 41dc8355..3bd32815 100644 --- a/lib/committee/drivers/open_api_2/schema_builder.rb +++ b/lib/committee/drivers/open_api_2/schema_builder.rb @@ -10,17 +10,14 @@ def initialize(link_data) private - LINK_REQUIRED_FIELDS = [ - :name - ].map(&:to_s).freeze + LINK_REQUIRED_FIELDS = [:name].map(&:to_s).freeze attr_accessor :link_data def check_required_fields!(param_data) LINK_REQUIRED_FIELDS.each do |field| if !param_data[field] - raise ArgumentError, - "Committee: no #{field} section in link data." + raise ArgumentError, "Committee: no #{field} section in link data." end end end diff --git a/lib/committee/errors.rb b/lib/committee/errors.rb index fe6f3064..a35227e7 100644 --- a/lib/committee/errors.rb +++ b/lib/committee/errors.rb @@ -10,7 +10,7 @@ class BadRequest < Error class InvalidRequest < Error attr_reader :original_error - def initialize(error_message=nil, original_error: nil) + def initialize(error_message = nil, original_error: nil) @original_error = original_error super(error_message) end @@ -19,7 +19,7 @@ def initialize(error_message=nil, original_error: nil) class InvalidResponse < Error attr_reader :original_error - def initialize(error_message=nil, original_error: nil) + def initialize(error_message = nil, original_error: nil) @original_error = original_error super(error_message) end diff --git a/lib/committee/middleware/base.rb b/lib/committee/middleware/base.rb index e187a490..146601af 100644 --- a/lib/committee/middleware/base.rb +++ b/lib/committee/middleware/base.rb @@ -3,7 +3,7 @@ module Committee module Middleware class Base - def initialize(app, options={}) + def initialize(app, options = {}) @app = app @error_class = options.fetch(:error_class, Committee::ValidationError) @@ -14,7 +14,7 @@ def initialize(app, options={}) @schema = self.class.get_schema(options) @router = @schema.build_router(options) - @accept_request_filter = options[:accept_request_filter] || -> (_) { true } + @accept_request_filter = options[:accept_request_filter] || ->(_) { true } end def call(env) diff --git a/lib/committee/middleware/request_validation.rb b/lib/committee/middleware/request_validation.rb index 48d7f952..8327d346 100644 --- a/lib/committee/middleware/request_validation.rb +++ b/lib/committee/middleware/request_validation.rb @@ -3,7 +3,7 @@ module Committee module Middleware class RequestValidation < Base - def initialize(app, options={}) + def initialize(app, options = {}) super @strict = options[:strict] diff --git a/lib/committee/middleware/stub.rb b/lib/committee/middleware/stub.rb index 4e0ddf4f..b019e70b 100644 --- a/lib/committee/middleware/stub.rb +++ b/lib/committee/middleware/stub.rb @@ -5,7 +5,7 @@ module Committee module Middleware class Stub < Base - def initialize(app, options={}) + def initialize(app, options = {}) super # A bug in Committee's cache implementation meant that it wasn't working diff --git a/lib/committee/request_unpacker.rb b/lib/committee/request_unpacker.rb index 5c9e6225..bbb4337b 100644 --- a/lib/committee/request_unpacker.rb +++ b/lib/committee/request_unpacker.rb @@ -20,7 +20,7 @@ def indifferent_params(object) end end - def initialize(options={}) + def initialize(options = {}) @allow_form_params = options[:allow_form_params] @allow_get_body = options[:allow_get_body] @allow_query_params = options[:allow_query_params] @@ -32,7 +32,7 @@ def unpack_request_params(request) # if Content-Type is empty or JSON, and there was a request body, try to # interpret it as JSON params = if !request.media_type || request.media_type =~ %r{application/(?:.*\+)?json} - parse_json(request) + parse_json(request) elsif @optimistic_json begin parse_json(request) @@ -87,8 +87,7 @@ def parse_json(request) # We want a hash specifically. '42', 42, and [42] will all be # decoded properly, but we can't use them here. if !hash.is_a?(Hash) - raise BadRequest, - "Invalid JSON input. Require object with parameters as keys." + raise BadRequest, "Invalid JSON input. Require object with parameters as keys." end self.class.indifferent_params(hash) end diff --git a/lib/committee/schema_validator/hyper_schema.rb b/lib/committee/schema_validator/hyper_schema.rb index 1419b01e..ac0ba4b9 100644 --- a/lib/committee/schema_validator/hyper_schema.rb +++ b/lib/committee/schema_validator/hyper_schema.rb @@ -42,71 +42,71 @@ def link_exist? private - def coerce_path_params - return {} unless link_exist? + def coerce_path_params + return {} unless link_exist? - Committee::SchemaValidator::HyperSchema::StringParamsCoercer.new(param_matches, link.schema, coerce_recursive: validator_option.coerce_recursive).call! - param_matches - end + Committee::SchemaValidator::HyperSchema::StringParamsCoercer.new(param_matches, link.schema, coerce_recursive: validator_option.coerce_recursive).call! + param_matches + end - def coerce_query_params(request) - return unless link_exist? - return if request.GET.nil? || link.schema.nil? + def coerce_query_params(request) + return unless link_exist? + return if request.GET.nil? || link.schema.nil? - Committee::SchemaValidator::HyperSchema::StringParamsCoercer.new(request.GET, link.schema, coerce_recursive: validator_option.coerce_recursive).call! - end + Committee::SchemaValidator::HyperSchema::StringParamsCoercer.new(request.GET, link.schema, coerce_recursive: validator_option.coerce_recursive).call! + end - def request_unpack(request) - unpacker = Committee::RequestUnpacker.new( - allow_form_params: validator_option.allow_form_params, - allow_get_body: validator_option.allow_get_body, - allow_query_params: validator_option.allow_query_params, - optimistic_json: validator_option.optimistic_json, - ) - - request.env[validator_option.headers_key] = unpacker.unpack_headers(request) - - # Attempts to coerce parameters that appear in a link's URL to Ruby - # types that can be validated with a schema. - param_matches_hash = validator_option.coerce_path_params ? coerce_path_params : {} - - # Attempts to coerce parameters that appear in a query string to Ruby - # types that can be validated with a schema. - coerce_query_params(request) if validator_option.coerce_query_params - - query_param = unpacker.unpack_query_params(request) - request_param, is_form_params = unpacker.unpack_request_params(request) - coerce_form_params(request_param) if validator_option.coerce_form_params && is_form_params - request.env[validator_option.request_body_hash_key] = request_param - - request.env[validator_option.params_key] = Committee::Utils.indifferent_hash - request.env[validator_option.params_key].merge!(Committee::Utils.deep_copy(query_param)) - request.env[validator_option.params_key].merge!(Committee::Utils.deep_copy(request_param)) - request.env[validator_option.params_key].merge!(Committee::Utils.deep_copy(param_matches_hash)) - end + def request_unpack(request) + unpacker = Committee::RequestUnpacker.new( + allow_form_params: validator_option.allow_form_params, + allow_get_body: validator_option.allow_get_body, + allow_query_params: validator_option.allow_query_params, + optimistic_json: validator_option.optimistic_json, + ) + + request.env[validator_option.headers_key] = unpacker.unpack_headers(request) + + # Attempts to coerce parameters that appear in a link's URL to Ruby + # types that can be validated with a schema. + param_matches_hash = validator_option.coerce_path_params ? coerce_path_params : {} + + # Attempts to coerce parameters that appear in a query string to Ruby + # types that can be validated with a schema. + coerce_query_params(request) if validator_option.coerce_query_params + + query_param = unpacker.unpack_query_params(request) + request_param, is_form_params = unpacker.unpack_request_params(request) + coerce_form_params(request_param) if validator_option.coerce_form_params && is_form_params + request.env[validator_option.request_body_hash_key] = request_param + + request.env[validator_option.params_key] = Committee::Utils.indifferent_hash + request.env[validator_option.params_key].merge!(Committee::Utils.deep_copy(query_param)) + request.env[validator_option.params_key].merge!(Committee::Utils.deep_copy(request_param)) + request.env[validator_option.params_key].merge!(Committee::Utils.deep_copy(param_matches_hash)) + end - def coerce_form_params(parameter) - return unless link_exist? - return unless link.schema - Committee::SchemaValidator::HyperSchema::StringParamsCoercer.new(parameter, link.schema).call! - end + def coerce_form_params(parameter) + return unless link_exist? + return unless link.schema + Committee::SchemaValidator::HyperSchema::StringParamsCoercer.new(parameter, link.schema).call! + end - def request_schema_validation(request) - return unless link_exist? - validator = Committee::SchemaValidator::HyperSchema::RequestValidator.new(link, check_content_type: validator_option.check_content_type, check_header: validator_option.check_header) - validator.call(request, request.env[validator_option.params_key], request.env[validator_option.headers_key]) - end + def request_schema_validation(request) + return unless link_exist? + validator = Committee::SchemaValidator::HyperSchema::RequestValidator.new(link, check_content_type: validator_option.check_content_type, check_header: validator_option.check_header) + validator.call(request, request.env[validator_option.params_key], request.env[validator_option.headers_key]) + end - def parameter_coerce!(request, link, coerce_key) - return unless link_exist? + def parameter_coerce!(request, link, coerce_key) + return unless link_exist? - Committee::SchemaValidator::HyperSchema::ParameterCoercer. - new(request.env[coerce_key], - link.schema, - coerce_date_times: validator_option.coerce_date_times, - coerce_recursive: validator_option.coerce_recursive). - call! - end + Committee::SchemaValidator::HyperSchema::ParameterCoercer. + new(request.env[coerce_key], + link.schema, + coerce_date_times: validator_option.coerce_date_times, + coerce_recursive: validator_option.coerce_recursive). + call! + end end end end diff --git a/lib/committee/schema_validator/hyper_schema/parameter_coercer.rb b/lib/committee/schema_validator/hyper_schema/parameter_coercer.rb index 0f552117..b3372dba 100644 --- a/lib/committee/schema_validator/hyper_schema/parameter_coercer.rb +++ b/lib/committee/schema_validator/hyper_schema/parameter_coercer.rb @@ -18,61 +18,61 @@ def call! private - def coerce_object!(hash, schema) - return false unless schema.respond_to?(:properties) + def coerce_object!(hash, schema) + return false unless schema.respond_to?(:properties) - is_coerced = false - schema.properties.each do |k, s| - original_val = hash[k] - unless original_val.nil? - new_value, is_changed = coerce_value!(original_val, s) - if is_changed - hash[k] = new_value - is_coerced = true - end + is_coerced = false + schema.properties.each do |k, s| + original_val = hash[k] + unless original_val.nil? + new_value, is_changed = coerce_value!(original_val, s) + if is_changed + hash[k] = new_value + is_coerced = true end end - - is_coerced end - def coerce_value!(original_val, s) - s.type.each do |to_type| - if @coerce_date_times && to_type == "string" && s.format == "date-time" - coerced_val = parse_date_time(original_val) - return coerced_val, true if coerced_val - end - - return original_val, true if @coerce_recursive && (to_type == "array") && coerce_array_data!(original_val, s) + is_coerced + end - return original_val, true if @coerce_recursive && (to_type == "object") && coerce_object!(original_val, s) + def coerce_value!(original_val, s) + s.type.each do |to_type| + if @coerce_date_times && to_type == "string" && s.format == "date-time" + coerced_val = parse_date_time(original_val) + return coerced_val, true if coerced_val end - return nil, false + + return original_val, true if @coerce_recursive && (to_type == "array") && coerce_array_data!(original_val, s) + + return original_val, true if @coerce_recursive && (to_type == "object") && coerce_object!(original_val, s) end + return nil, false + end - def coerce_array_data!(original_val, schema) - return false unless schema.respond_to?(:items) - return false unless original_val.is_a?(Array) + def coerce_array_data!(original_val, schema) + return false unless schema.respond_to?(:items) + return false unless original_val.is_a?(Array) - is_coerced = false - original_val.each_with_index do |d, index| - new_value, is_changed = coerce_value!(d, schema.items) - if is_changed - original_val[index] = new_value - is_coerced = true - end + is_coerced = false + original_val.each_with_index do |d, index| + new_value, is_changed = coerce_value!(d, schema.items) + if is_changed + original_val[index] = new_value + is_coerced = true end - - is_coerced end - def parse_date_time(original_val) - begin - DateTime.parse(original_val) - rescue ArgumentError => e - raise ::Committee::InvalidResponse unless e.message =~ /invalid date/ - end + is_coerced + end + + def parse_date_time(original_val) + begin + DateTime.parse(original_val) + rescue ArgumentError => e + raise ::Committee::InvalidResponse unless e.message =~ /invalid date/ end + end end end end diff --git a/lib/committee/schema_validator/hyper_schema/request_validator.rb b/lib/committee/schema_validator/hyper_schema/request_validator.rb index 1c86af51..1cd84143 100644 --- a/lib/committee/schema_validator/hyper_schema/request_validator.rb +++ b/lib/committee/schema_validator/hyper_schema/request_validator.rb @@ -35,8 +35,7 @@ def check_content_type!(request, data) content_type = ::Committee::SchemaValidator.request_media_type(request) if content_type && @link.enc_type && !empty_request?(request) unless Rack::Mime.match?(content_type, @link.enc_type) - raise Committee::InvalidRequest, - %{"Content-Type" request header must be set to "#{@link.enc_type}".} + raise Committee::InvalidRequest, %{"Content-Type" request header must be set to "#{@link.enc_type}".} end end end diff --git a/lib/committee/schema_validator/hyper_schema/response_validator.rb b/lib/committee/schema_validator/hyper_schema/response_validator.rb index d396219c..cc368a42 100644 --- a/lib/committee/schema_validator/hyper_schema/response_validator.rb +++ b/lib/committee/schema_validator/hyper_schema/response_validator.rb @@ -66,12 +66,10 @@ def response_media_type(response) end end - def check_content_type!(response) if @link.media_type unless Rack::Mime.match?(response_media_type(response), @link.media_type) - raise Committee::InvalidResponse, - %{"Content-Type" response header must be set to "#{@link.media_type}".} + raise Committee::InvalidResponse, %{"Content-Type" response header must be set to "#{@link.media_type}".} end end end diff --git a/lib/committee/schema_validator/hyper_schema/string_params_coercer.rb b/lib/committee/schema_validator/hyper_schema/string_params_coercer.rb index 23fb0fbf..d5fc8a75 100644 --- a/lib/committee/schema_validator/hyper_schema/string_params_coercer.rb +++ b/lib/committee/schema_validator/hyper_schema/string_params_coercer.rb @@ -27,78 +27,78 @@ def call! private - def coerce_object!(hash, schema) - return false unless schema.respond_to?(:properties) + def coerce_object!(hash, schema) + return false unless schema.respond_to?(:properties) - is_coerced = false - schema.properties.each do |k, s| - original_val = hash[k] - unless original_val.nil? - new_value, is_changed = coerce_value!(original_val, s) - if is_changed - hash[k] = new_value - is_coerced = true - end + is_coerced = false + schema.properties.each do |k, s| + original_val = hash[k] + unless original_val.nil? + new_value, is_changed = coerce_value!(original_val, s) + if is_changed + hash[k] = new_value + is_coerced = true end end - - is_coerced end - def coerce_value!(original_val, s) - unless original_val.nil? - s.type.each do |to_type| - case to_type - when "null" - return nil, true if original_val.empty? - when "integer" - begin - return Integer(original_val), true - rescue ArgumentError => e - raise e unless e.message =~ /invalid value for Integer/ - end - when "number" - begin - return Float(original_val), true - rescue ArgumentError => e - raise e unless e.message =~ /invalid value for Float/ - end - when "boolean" - if original_val == "true" || original_val == "1" - return true, true - end - if original_val == "false" || original_val == "0" - return false, true - end - when "array" - if @coerce_recursive && coerce_array_data!(original_val, s) - return original_val, true # change original value - end - when "object" - if @coerce_recursive && coerce_object!(original_val, s) - return original_val, true # change original value - end - end + is_coerced + end + + def coerce_value!(original_val, s) + unless original_val.nil? + s.type.each do |to_type| + case to_type + when "null" + return nil, true if original_val.empty? + when "integer" + begin + return Integer(original_val), true + rescue ArgumentError => e + raise e unless e.message =~ /invalid value for Integer/ + end + when "number" + begin + return Float(original_val), true + rescue ArgumentError => e + raise e unless e.message =~ /invalid value for Float/ + end + when "boolean" + if original_val == "true" || original_val == "1" + return true, true + end + if original_val == "false" || original_val == "0" + return false, true + end + when "array" + if @coerce_recursive && coerce_array_data!(original_val, s) + return original_val, true # change original value + end + when "object" + if @coerce_recursive && coerce_object!(original_val, s) + return original_val, true # change original value + end end end - return nil, false end + return nil, false + end - def coerce_array_data!(original_val, schema) - return false unless schema.respond_to?(:items) - return false unless original_val.is_a?(Array) + def coerce_array_data!(original_val, schema) + return false unless schema.respond_to?(:items) + return false unless original_val.is_a?(Array) - is_coerced = false - original_val.each_with_index do |d, index| - new_value, is_changed = coerce_value!(d, schema.items) - if is_changed - original_val[index] = new_value - is_coerced = true - end + is_coerced = false + original_val.each_with_index do |d, index| + new_value, is_changed = coerce_value!(d, schema.items) + if is_changed + original_val[index] = new_value + is_coerced = true end - - is_coerced end + + is_coerced + end end end end diff --git a/lib/committee/schema_validator/open_api_3.rb b/lib/committee/schema_validator/open_api_3.rb index 8ee6abd5..5309fcda 100644 --- a/lib/committee/schema_validator/open_api_3.rb +++ b/lib/committee/schema_validator/open_api_3.rb @@ -26,10 +26,10 @@ def response_validate(status, headers, response, test_method = false) full_body << chunk end - parse_to_json = !validator_option.parse_response_by_content_type || + parse_to_json = !validator_option.parse_response_by_content_type || headers.fetch('Content-Type', nil)&.start_with?('application/json') data = if parse_to_json - full_body.empty? ? {} : JSON.parse(full_body) + full_body.empty? ? {} : JSON.parse(full_body) else full_body end @@ -98,8 +98,8 @@ def request_unpack(request) def copy_coerced_data_to_params(request) order = if validator_option.parameter_overwrite_by_rails_rule - # (high priority) path_hash_key -> query_param -> request_body_hash - [validator_option.request_body_hash_key, validator_option.query_hash_key, validator_option.path_hash_key] + # (high priority) path_hash_key -> query_param -> request_body_hash + [validator_option.request_body_hash_key, validator_option.query_hash_key, validator_option.path_hash_key] else # (high priority) path_hash_key -> request_body_hash -> query_param [validator_option.query_hash_key, validator_option.request_body_hash_key, validator_option.path_hash_key] diff --git a/lib/committee/schema_validator/open_api_3/request_validator.rb b/lib/committee/schema_validator/open_api_3/request_validator.rb index 2f56819b..b8bf6c0a 100644 --- a/lib/committee/schema_validator/open_api_3/request_validator.rb +++ b/lib/committee/schema_validator/open_api_3/request_validator.rb @@ -27,7 +27,7 @@ def check_content_type(request, content_type) return true if @operation_object.optional_body? && empty_request?(request) message = if valid_content_types.size > 1 - types = valid_content_types.map {|x| %{"#{x}"} }.join(', ') + types = valid_content_types.map { |x| %{"#{x}"} }.join(', ') %{"Content-Type" request header must be set to any of the following: [#{types}].} else %{"Content-Type" request header must be set to "#{valid_content_types.first}".} diff --git a/lib/committee/schema_validator/option.rb b/lib/committee/schema_validator/option.rb index c00dabfa..c23d010c 100644 --- a/lib/committee/schema_validator/option.rb +++ b/lib/committee/schema_validator/option.rb @@ -21,12 +21,7 @@ class Option :parameter_overwrite_by_rails_rule # Non-boolean options: - attr_reader :headers_key, - :params_key, - :query_hash_key, - :request_body_hash_key, - :path_hash_key, - :prefix + attr_reader :headers_key, :params_key, :query_hash_key, :request_body_hash_key, :path_hash_key, :prefix def initialize(options, schema, schema_type) # Non-boolean options diff --git a/lib/committee/test/schema_coverage.rb b/lib/committee/test/schema_coverage.rb index a2dce88c..d146d39f 100644 --- a/lib/committee/test/schema_coverage.rb +++ b/lib/committee/test/schema_coverage.rb @@ -28,12 +28,7 @@ def flatten_report(report) path_coverage.each do |method, method_coverage| responses_coverage = method_coverage['responses'] responses_coverage.each do |response_status, is_covered| - responses << { - path: path_name, - method: method, - status: response_status, - is_covered: is_covered, - } + responses << { path: path_name, method: method, status: response_status, is_covered: is_covered, } end end end @@ -98,4 +93,3 @@ def report_flatten end end end - diff --git a/lib/committee/utils.rb b/lib/committee/utils.rb index 5d7481af..07520a08 100644 --- a/lib/committee/utils.rb +++ b/lib/committee/utils.rb @@ -1,28 +1,28 @@ # frozen_string_literal: true module Committee - module Utils - # Creates a Hash with indifferent access. - # - # (Copied from Sinatra) - def self.indifferent_hash - Hash.new { |hash,key| hash[key.to_s] if Symbol === key } - end - - def self.deep_copy(from) - if from.is_a?(Hash) - h = Committee::Utils.indifferent_hash - from.each_pair do |k, v| - h[k] = deep_copy(v) - end - return h - end + module Utils + # Creates a Hash with indifferent access. + # + # (Copied from Sinatra) + def self.indifferent_hash + Hash.new { |hash, key| hash[key.to_s] if Symbol === key } + end - if from.is_a?(Array) - return from.map{ |v| deep_copy(v) } - end + def self.deep_copy(from) + if from.is_a?(Hash) + h = Committee::Utils.indifferent_hash + from.each_pair do |k, v| + h[k] = deep_copy(v) + end + return h + end - return from + if from.is_a?(Array) + return from.map { |v| deep_copy(v) } end + + return from end + end end diff --git a/lib/committee/version.rb b/lib/committee/version.rb index aa8a53d9..ad67b04a 100644 --- a/lib/committee/version.rb +++ b/lib/committee/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Committee - VERSION = '5.5.0'.freeze + VERSION = '5.5.0'.freeze end diff --git a/test/bin/committee_stub_test.rb b/test/bin/committee_stub_test.rb index d234497b..c8df0a37 100644 --- a/test/bin/committee_stub_test.rb +++ b/test/bin/committee_stub_test.rb @@ -18,11 +18,7 @@ parser.parse!(["--help"]) assert_equal true, options[:help] - parser.parse!([ - "--driver", "open_api_2", - "--tolerant", "true", - "--port", "1234" - ]) + parser.parse!(["--driver", "open_api_2", "--tolerant", "true", "--port", "1234"]) assert_equal :open_api_2, options[:driver] assert_equal true, options[:tolerant] assert_equal "1234", options[:port] diff --git a/test/committee_test.rb b/test/committee_test.rb index 952c7faa..4927c28c 100644 --- a/test/committee_test.rb +++ b/test/committee_test.rb @@ -62,7 +62,6 @@ end end - it "doesn't warns on deprecated if cond is false" do old_stderr = $stderr old_verbose = $VERBOSE diff --git a/test/drivers/hyper_schema/driver_test.rb b/test/drivers/hyper_schema/driver_test.rb index 2ff658d9..0e49f577 100644 --- a/test/drivers/hyper_schema/driver_test.rb +++ b/test/drivers/hyper_schema/driver_test.rb @@ -46,4 +46,3 @@ assert_equal false, @driver.default_query_params end end - diff --git a/test/drivers/open_api_2/driver_test.rb b/test/drivers/open_api_2/driver_test.rb index 5520c10e..1f6b06d0 100644 --- a/test/drivers/open_api_2/driver_test.rb +++ b/test/drivers/open_api_2/driver_test.rb @@ -46,8 +46,7 @@ it "names capture groups into href regexes" do schema = @driver.parse(open_api_2_data) - assert_equal %r{^\/api\/pets\/(?[^\/]+)$}.inspect, - schema.routes["DELETE"][0][0].inspect + assert_equal %r{^\/api\/pets\/(?[^\/]+)$}.inspect, schema.routes["DELETE"][0][0].inspect end it "prefers a 200 response first" do @@ -153,4 +152,3 @@ def schema_data_with_responses(response_data) } end end - diff --git a/test/drivers/open_api_2/header_schema_builder_test.rb b/test/drivers/open_api_2/header_schema_builder_test.rb index 8fc41704..dffd195c 100644 --- a/test/drivers/open_api_2/header_schema_builder_test.rb +++ b/test/drivers/open_api_2/header_schema_builder_test.rb @@ -4,15 +4,7 @@ describe Committee::Drivers::OpenAPI2::HeaderSchemaBuilder do it "returns schema data for header" do - data = { - "parameters" => [ - { - "name" => "AUTH_TOKEN", - "type" => "string", - "in" => "header", - } - ] - } + data = { "parameters" => [{ "name" => "AUTH_TOKEN", "type" => "string", "in" => "header", }] } schema = call(data) assert_equal ["string"], schema.properties["AUTH_TOKEN"].type diff --git a/test/drivers/open_api_2/link_test.rb b/test/drivers/open_api_2/link_test.rb index 3b210a73..4b0496fa 100644 --- a/test/drivers/open_api_2/link_test.rb +++ b/test/drivers/open_api_2/link_test.rb @@ -49,4 +49,3 @@ assert_equal({ "title" => "target" }, @link.target_schema) end end - diff --git a/test/drivers/open_api_2/parameter_schema_builder_test.rb b/test/drivers/open_api_2/parameter_schema_builder_test.rb index acc3325b..eee3b230 100644 --- a/test/drivers/open_api_2/parameter_schema_builder_test.rb +++ b/test/drivers/open_api_2/parameter_schema_builder_test.rb @@ -7,14 +7,7 @@ end it "reflects a basic type into a schema" do - data = { - "parameters" => [ - { - "name" => "limit", - "type" => "integer", - } - ] - } + data = { "parameters" => [{ "name" => "limit", "type" => "integer", }] } schema, schema_data = call(data) assert_nil schema_data @@ -37,14 +30,7 @@ end it "reflects a required property into a schema" do - data = { - "parameters" => [ - { - "name" => "limit", - "required" => true, - } - ] - } + data = { "parameters" => [{ "name" => "limit", "required" => true, }] } schema, schema_data = call(data) assert_nil schema_data @@ -77,15 +63,7 @@ end it "reflects a enum property into a schema" do - data = { - "parameters" => [ - { - "name" => "type", - "type" => "string", - "enum" => ["hoge", "fuga"] - } - ] - } + data = { "parameters" => [{ "name" => "type", "type" => "string", "enum" => ["hoge", "fuga"] }] } schema, schema_data = call(data) assert_nil schema_data @@ -157,12 +135,7 @@ end it "requires that certain fields are present" do - data = { - "parameters" => [ - { - } - ] - } + data = { "parameters" => [{}] } e = assert_raises ArgumentError do call(data) end @@ -170,23 +143,11 @@ end it "requires that body parameters not be mixed with form parameters" do - data = { - "parameters" => [ - { - "name" => "payload", - "in" => "body", - }, - { - "name" => "limit", - "in" => "form", - }, - ] - } + data = { "parameters" => [{ "name" => "payload", "in" => "body", }, { "name" => "limit", "in" => "form", },] } e = assert_raises ArgumentError do call(data) end - assert_equal "Committee: can't mix body parameter with form parameters.", - e.message + assert_equal "Committee: can't mix body parameter with form parameters.", e.message end def call(data) diff --git a/test/drivers/open_api_3/driver_test.rb b/test/drivers/open_api_3/driver_test.rb index 6ce4a6cf..8fbc5f54 100644 --- a/test/drivers/open_api_3/driver_test.rb +++ b/test/drivers/open_api_3/driver_test.rb @@ -52,31 +52,31 @@ it "gets a nested template path" do obj = open_api_3_schema.operation_object("/path_template_test/abc/nested", "get") assert_equal "/path_template_test/{template_name}/nested", obj.original_path - assert_equal({"template_name"=>"abc"}, obj.path_params) + assert_equal({ "template_name" => "abc" }, obj.path_params) end it "gets a double nested template path" do obj = open_api_3_schema.operation_object("/path_template_test/test/nested/abc", "get") assert_equal "/path_template_test/{template_name}/nested/{nested_parameter}", obj.original_path - assert_equal({"template_name"=>"test", "nested_parameter" => "abc"}, obj.path_params) + assert_equal({ "template_name" => "test", "nested_parameter" => "abc" }, obj.path_params) end it "gets a twice nested template path" do obj = open_api_3_schema.operation_object("/path_template_test/test/abc", "get") assert_equal "/path_template_test/{template_name}/{nested_parameter}", obj.original_path - assert_equal({"template_name"=>"test", "nested_parameter" => "abc"}, obj.path_params) + assert_equal({ "template_name" => "test", "nested_parameter" => "abc" }, obj.path_params) end it "gets a twice nested concrete path" do obj = open_api_3_schema.operation_object("/path_template_test/test/abc/finish", "get") assert_equal "/path_template_test/{template_name}/{nested_parameter}/finish", obj.original_path - assert_equal({"template_name"=>"test", "nested_parameter" => "abc"}, obj.path_params) + assert_equal({ "template_name" => "test", "nested_parameter" => "abc" }, obj.path_params) end it "gets an ambiguous path" do obj = open_api_3_schema.operation_object("/ambiguous/no_template", "get") assert_equal "/{ambiguous}/no_template", obj.original_path - assert_equal({"ambiguous"=>"ambiguous"}, obj.path_params) + assert_equal({ "ambiguous" => "ambiguous" }, obj.path_params) end end end diff --git a/test/drivers_test.rb b/test/drivers_test.rb index b77c5cdd..02e20ab7 100644 --- a/test/drivers_test.rb +++ b/test/drivers_test.rb @@ -3,11 +3,7 @@ require "test_helper" describe Committee::Drivers do - DRIVERS = [ - :hyper_schema, - :open_api_2, - :open_api_3, - ].freeze + DRIVERS = [:hyper_schema, :open_api_2, :open_api_3,].freeze it "gets driver with .driver_from_name" do DRIVERS.each do |name| @@ -37,20 +33,20 @@ end it 'loads OpenAPI 3' do - s = Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options:{strict_reference_validation: true}) + s = Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options: { strict_reference_validation: true }) assert_kind_of Committee::Drivers::Schema, s assert_kind_of Committee::Drivers::OpenAPI3::Schema, s end it 'load OpenAPI 3 (patch version 3.0.1)' do - s = Committee::Drivers.load_from_file(open_api_3_0_1_schema_path, parser_options:{strict_reference_validation: true}) + s = Committee::Drivers.load_from_file(open_api_3_0_1_schema_path, parser_options: { strict_reference_validation: true }) assert_kind_of Committee::Drivers::Schema, s assert_kind_of Committee::Drivers::OpenAPI3::Schema, s end it 'fails to load OpenAPI 3.1+' do e = assert_raises(Committee::OpenAPI3Unsupported) do - Committee::Drivers.load_from_file(open_api_3_1_schema_path, parser_options:{strict_reference_validation: true}) + Committee::Drivers.load_from_file(open_api_3_1_schema_path, parser_options: { strict_reference_validation: true }) end assert_equal 'Committee does not support OpenAPI 3.1+ yet', e.message end @@ -64,13 +60,13 @@ # This test can be removed when the test above (raising on invalid reference) becomes default behavior? it 'allows loading OpenAPI 3 with invalid reference as existing behavior' do - s = Committee::Drivers.load_from_file(open_api_3_invalid_reference_path, parser_options:{strict_reference_validation: false}) + s = Committee::Drivers.load_from_file(open_api_3_invalid_reference_path, parser_options: { strict_reference_validation: false }) assert_kind_of Committee::Drivers::OpenAPI3::Schema, s end it 'errors on an unsupported file extension' do e = assert_raises(StandardError) do - Committee::Drivers.load_from_file('test.xml', parser_options:{strict_reference_validation: true}) + Committee::Drivers.load_from_file('test.xml', parser_options: { strict_reference_validation: true }) end assert_equal "Committee only supports the following file extensions: '.json', '.yaml', '.yml'", e.message end @@ -79,24 +75,24 @@ describe 'when loading the same file' do it 'returns the same object when the options are identical' do assert_equal( - Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options:{strict_reference_validation: true}).object_id, - Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options:{strict_reference_validation: true}).object_id, + Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options: { strict_reference_validation: true }).object_id, + Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options: { strict_reference_validation: true }).object_id, ) end it 'returns different objects if the options are different' do refute_equal( - Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options:{strict_reference_validation: true}).object_id, - Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options:{strict_reference_validation: false}).object_id, + Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options: { strict_reference_validation: true }).object_id, + Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options: { strict_reference_validation: false }).object_id, ) end it 'returns different objects if the file contents have changed' do - object_id = Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options:{strict_reference_validation: true}).object_id + object_id = Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options: { strict_reference_validation: true }).object_id original_file_contents = File.read(open_api_3_schema_path) File.write(open_api_3_schema_path, original_file_contents + "\n") refute_equal( - Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options:{strict_reference_validation: true}).object_id, + Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options: { strict_reference_validation: true }).object_id, object_id, ) File.write(open_api_3_schema_path, original_file_contents) @@ -107,13 +103,13 @@ describe 'load_from_json(schema_path)' do it 'loads OpenAPI2' do - s = Committee::Drivers.load_from_json(open_api_2_schema_path, parser_options:{strict_reference_validation: true}) + s = Committee::Drivers.load_from_json(open_api_2_schema_path, parser_options: { strict_reference_validation: true }) assert_kind_of Committee::Drivers::Schema, s assert_kind_of Committee::Drivers::OpenAPI2::Schema, s end it 'loads Hyper-Schema' do - s = Committee::Drivers.load_from_json(hyper_schema_schema_path, parser_options:{strict_reference_validation: true}) + s = Committee::Drivers.load_from_json(hyper_schema_schema_path, parser_options: { strict_reference_validation: true }) assert_kind_of Committee::Drivers::Schema, s assert_kind_of Committee::Drivers::HyperSchema::Schema, s end @@ -121,7 +117,7 @@ describe 'load_from_yaml(schema_path)' do it 'loads OpenAPI3' do - s = Committee::Drivers.load_from_yaml(open_api_3_schema_path, parser_options:{strict_reference_validation: true}) + s = Committee::Drivers.load_from_yaml(open_api_3_schema_path, parser_options: { strict_reference_validation: true }) assert_kind_of Committee::Drivers::Schema, s assert_kind_of Committee::Drivers::OpenAPI3::Schema, s end @@ -129,7 +125,7 @@ describe 'load_from_data(schema_path)' do it 'loads OpenAPI3' do - s = Committee::Drivers.load_from_data(open_api_3_data, parser_options:{strict_reference_validation: false}) + s = Committee::Drivers.load_from_data(open_api_3_data, parser_options: { strict_reference_validation: false }) assert_kind_of Committee::Drivers::Schema, s assert_kind_of Committee::Drivers::OpenAPI3::Schema, s end @@ -172,17 +168,13 @@ e = assert_raises do driver.send(name, *args) end - assert_equal "needs implementation", e.message, - "Incorrect error message while sending #{name}: #{e.message}" + assert_equal "needs implementation", e.message, "Incorrect error message while sending #{name}: #{e.message}" end end end describe Committee::Drivers::Schema do - SCHEMA_METHODS = { - driver: [], - build_router: [validator_option: nil, prefix: nil] - } + SCHEMA_METHODS = { driver: [], build_router: [validator_option: nil, prefix: nil] } it "has a set of abstract methods" do schema = Committee::Drivers::Schema.new @@ -190,8 +182,7 @@ e = assert_raises do schema.send(name, *args) end - assert_equal "needs implementation", e.message, - "Incorrect error message while sending #{name}: #{e.message}" + assert_equal "needs implementation", e.message, "Incorrect error message while sending #{name}: #{e.message}" end end end diff --git a/test/middleware/base_test.rb b/test/middleware/base_test.rb index 11d48d00..45b13915 100644 --- a/test/middleware/base_test.rb +++ b/test/middleware/base_test.rb @@ -10,12 +10,8 @@ def app end it "accepts just a schema object" do - @app = new_rack_app( - schema: hyper_schema - ) - params = { - "name" => "cloudnasium" - } + @app = new_rack_app(schema: hyper_schema) + params = { "name" => "cloudnasium" } header "Content-Type", "application/json" post "/apps", JSON.generate(params) assert_equal 200, last_response.status @@ -23,69 +19,50 @@ def app it "accepts just a OpenAPI3 schema object" do @app = new_rack_app(schema: open_api_3_schema) - params = { - "name" => "cloudnasium" - } + params = { "name" => "cloudnasium" } header "Content-Type", "application/json" post "/apps", JSON.generate(params) assert_equal 200, last_response.status end it "doesn't accept a schema string" do - @app = new_rack_app( - schema: JSON.dump(hyper_schema_data) - ) - params = { - "name" => "cloudnasium" - } + @app = new_rack_app(schema: JSON.dump(hyper_schema_data)) + params = { "name" => "cloudnasium" } header "Content-Type", "application/json" e = assert_raises(ArgumentError) do post "/apps", JSON.generate(params) end - assert_equal "Committee: schema expected to be an instance " + - "of Committee::Drivers::Schema.", e.message + assert_equal "Committee: schema expected to be an instance " + "of Committee::Drivers::Schema.", e.message end it "doesn't accept a schema hash" do - @app = new_rack_app( - schema: hyper_schema_data - ) - params = { - "name" => "cloudnasium" - } + @app = new_rack_app(schema: hyper_schema_data) + params = { "name" => "cloudnasium" } header "Content-Type", "application/json" e = assert_raises(ArgumentError) do post "/apps", JSON.generate(params) end - assert_equal "Committee: schema expected to be an instance " + - "of Committee::Drivers::Schema.", e.message + assert_equal "Committee: schema expected to be an instance " + "of Committee::Drivers::Schema.", e.message end it "doesn't accept a JsonSchema::Schema object" do - @app = new_rack_app( - schema: JsonSchema.parse!(hyper_schema_data) - ) - params = { - "name" => "cloudnasium" - } + @app = new_rack_app(schema: JsonSchema.parse!(hyper_schema_data)) + params = { "name" => "cloudnasium" } header "Content-Type", "application/json" e = assert_raises(ArgumentError) do post "/apps", JSON.generate(params) end - assert_equal "Committee: schema expected to be an instance " + - "of Committee::Drivers::Schema.", e.message + assert_equal "Committee: schema expected to be an instance " + "of Committee::Drivers::Schema.", e.message end it "doesn't accept other schema types" do - @app = new_rack_app( - schema: 7, - ) + @app = new_rack_app(schema: 7,) e = assert_raises(ArgumentError) do post "/apps" end diff --git a/test/middleware/request_validation_open_api_3_test.rb b/test/middleware/request_validation_open_api_3_test.rb index 1a941d1e..f434a7f7 100644 --- a/test/middleware/request_validation_open_api_3_test.rb +++ b/test/middleware/request_validation_open_api_3_test.rb @@ -11,9 +11,7 @@ def app it "OpenAPI3 pass through a valid request" do @app = new_rack_app(schema: open_api_3_schema) - params = { - "string_post_1" => "cloudnasium" - } + params = { "string_post_1" => "cloudnasium" } header "Content-Type", "application/json" post "/characters", JSON.generate(params) @@ -22,12 +20,12 @@ def app it "not parameter request" do check_parameter_string = lambda { |_| - [200, {integer: 1}, []] + [200, { integer: 1 }, []] } @app = new_rack_app_with_lambda(check_parameter_string, schema: open_api_3_schema) - put "/validate_no_parameter", {no_schema: 'no'} + put "/validate_no_parameter", { no_schema: 'no' } end it "passes given a datetime and with coerce_date_times enabled on GET endpoint" do @@ -150,9 +148,7 @@ def app it "passes given an invalid datetime string with coerce_date_times enabled" do @app = new_rack_app(schema: open_api_3_schema, coerce_date_times: true) - params = { - "datetime_string" => "invalid_datetime_format" - } + params = { "datetime_string" => "invalid_datetime_format" } get "/string_params_coercer", params assert_equal 400, last_response.status @@ -160,14 +156,7 @@ def app end it "passes a nested object with recursive option" do - params = { - "nested_array" => [ - { - "update_time" => "2016-04-01T16:00:00.000+09:00", - "per_page" => "1", - } - ], - } + params = { "nested_array" => [{ "update_time" => "2016-04-01T16:00:00.000+09:00", "per_page" => "1", }], } check_parameter = lambda { |env| hash = env["committee.query_hash"] @@ -248,9 +237,7 @@ def app [200, {}, []] } - @app = new_rack_app_with_lambda(check_parameter, - coerce_date_times: true, - schema: open_api_3_schema) + @app = new_rack_app_with_lambda(check_parameter, coerce_date_times: true, schema: open_api_3_schema) header "Content-Type", "application/json" post "/string_params_coercer", JSON.generate(params) @@ -260,9 +247,7 @@ def app it "OpenAPI3 detects an invalid request" do @app = new_rack_app(schema: open_api_3_schema, strict: true) header "Content-Type", "application/json" - params = { - "string_post_1" => 1 - } + params = { "string_post_1" => 1 } post "/characters", JSON.generate(params) assert_equal 400, last_response.status assert_match(/expected string, but received Integer:/i, last_response.body) @@ -278,9 +263,7 @@ def app it "take a prefix" do @app = new_rack_app(prefix: "/v1", schema: open_api_3_schema) - params = { - "string_post_1" => "cloudnasium" - } + params = { "string_post_1" => "cloudnasium" } header "Content-Type", "application/json" post "/v1/characters", JSON.generate(params) assert_equal 200, last_response.status @@ -288,9 +271,7 @@ def app it "take a prefix with invalid data" do @app = new_rack_app(prefix: "/v1", schema: open_api_3_schema) - params = { - "string_post_1" => 1 - } + params = { "string_post_1" => 1 } header "Content-Type", "application/json" post "/v1/characters", JSON.generate(params) assert_equal 400, last_response.status @@ -299,9 +280,7 @@ def app it "ignores paths outside the prefix" do @app = new_rack_app(prefix: "/v1", schema: open_api_3_schema) - params = { - "string_post_1" => 1 - } + params = { "string_post_1" => 1 } header "Content-Type", "application/json" post "/characters", JSON.generate(params) assert_equal 200, last_response.status @@ -309,9 +288,7 @@ def app it "don't check prefix with no option" do @app = new_rack_app(schema: open_api_3_schema) - params = { - "string_post_1" => 1 - } + params = { "string_post_1" => 1 } header "Content-Type", "application/json" post "/v1/characters", JSON.generate(params) assert_equal 200, last_response.status @@ -361,14 +338,14 @@ def app it "optionally coerces query params" do @app = new_rack_app(coerce_query_params: true, schema: open_api_3_schema) header "Content-Type", "application/json" - get "/string_params_coercer", {"integer_1" => "1"} + get "/string_params_coercer", { "integer_1" => "1" } assert_equal 200, last_response.status end it "still raises an error if query param coercion is not possible" do @app = new_rack_app(coerce_query_params: false, schema: open_api_3_schema) header "Content-Type", "application/json" - get "/string_params_coercer", {"integer_1" => "1"} + get "/string_params_coercer", { "integer_1" => "1" } assert_equal 400, last_response.status assert_match(/expected integer, but received String:/i, last_response.body) @@ -376,7 +353,7 @@ def app it "passes through a valid request for OpenAPI3" do check_parameter = lambda { |env| - assert_equal 3, env['committee.query_hash']['limit'] #5.0.x- + assert_equal 3, env['committee.query_hash']['limit'] # 5.0.x- [200, {}, []] } @@ -417,7 +394,7 @@ def app assert_equal env['committee.params']['integer'], 42 assert_equal env['committee.params'][:integer], 42 assert_equal env['committee.query_hash']['integer'], 42 - #assert_equal env['rack.request.query_hash'][:integer], 42 # this isn't hash indifferent hash because we use rack.request.query_hash + # assert_equal env['rack.request.query_hash'][:integer], 42 # this isn't hash indifferent hash because we use rack.request.query_hash [204, {}, []] end, schema: open_api_3_schema, parameter_overwrite_by_rails_rule: false) @@ -436,7 +413,7 @@ def app [204, {}, []] end, schema: open_api_3_schema, parameter_overwrite_by_rails_rule: false) - params = {integer: 21} + params = { integer: 21 } header "Content-Type", "application/json" post '/overwrite_same_parameter?integer=42', JSON.generate(params) @@ -452,11 +429,11 @@ def app assert_equal env['committee.request_body_hash']['integer'], 21 assert_equal env['committee.request_body_hash'][:integer], 21 assert_equal env['committee.query_hash']['integer'], 84 # we can't use query_parameter :( - #assert_equal env['rack.request.query_hash'][:integer], 21 # this isn't hash indifferent hash because we use rack.request.query_hash + # assert_equal env['rack.request.query_hash'][:integer], 21 # this isn't hash indifferent hash because we use rack.request.query_hash [204, {}, []] end, schema: open_api_3_schema, parameter_overwrite_by_rails_rule: false) - params = {integer: 21} + params = { integer: 21 } header "Content-Type", "application/json" post '/overwrite_same_parameter/84?integer=42', JSON.generate(params) @@ -475,7 +452,7 @@ def app [204, {}, []] end, schema: open_api_3_schema) - params = {integer: 21} + params = { integer: 21 } header "Content-Type", "application/json" post '/overwrite_same_parameter', JSON.generate(params) @@ -492,7 +469,7 @@ def app [204, {}, []] end, schema: open_api_3_schema) - params = {integer: 21} + params = { integer: 21 } header "Content-Type", "application/json" post '/overwrite_same_parameter?integer=42', JSON.generate(params) @@ -511,7 +488,7 @@ def app [204, {}, []] end, schema: open_api_3_schema) - params = {integer: 21} + params = { integer: 21 } header "Content-Type", "application/json" post '/overwrite_same_parameter/84?integer=42', JSON.generate(params) @@ -541,7 +518,7 @@ def app } assert_equal 'Committee OpenAPI3 not support trace method', e.message - end + end describe 'check header' do [ @@ -580,8 +557,8 @@ def app describe ':accept_request_filter' do [ { description: 'when not specified, includes everything', accept_request_filter: nil, expected: { status: 400 } }, - { description: 'when predicate matches, performs validation', accept_request_filter: -> (request) { request.path.start_with?('/v1/c') }, expected: { status: 400 } }, - { description: 'when predicate does not match, skips validation', accept_request_filter: -> (request) { request.path.start_with?('/v1/x') }, expected: { status: 200 } }, + { description: 'when predicate matches, performs validation', accept_request_filter: ->(request) { request.path.start_with?('/v1/c') }, expected: { status: 400 } }, + { description: 'when predicate does not match, skips validation', accept_request_filter: ->(request) { request.path.start_with?('/v1/x') }, expected: { status: 200 } }, ].each do |h| description = h[:description] accept_request_filter = h[:accept_request_filter] diff --git a/test/middleware/request_validation_test.rb b/test/middleware/request_validation_test.rb index bd95cd77..634d8afe 100644 --- a/test/middleware/request_validation_test.rb +++ b/test/middleware/request_validation_test.rb @@ -55,9 +55,7 @@ def app it "passes through a valid request" do @app = new_rack_app(schema: hyper_schema) - params = { - "name" => "cloudnasium" - } + params = { "name" => "cloudnasium" } header "Content-Type", "application/json" post "/apps", JSON.generate(params) assert_equal 200, last_response.status @@ -67,9 +65,7 @@ def app called_error = false pr = ->(_e) { called_error = true } @app = new_rack_app(schema: hyper_schema, error_handler: pr) - params = { - "name" => "cloudnasium" - } + params = { "name" => "cloudnasium" } header "Content-Type", "application/json" post "/apps", JSON.generate(params) assert !called_error @@ -79,9 +75,7 @@ def app called_error = false pr = ->(_e, _env) { called_error = true } @app = new_rack_app(schema: hyper_schema, error_handler: pr) - params = { - "name" => "cloudnasium" - } + params = { "name" => "cloudnasium" } header "Content-Type", "application/json" post "/apps", JSON.generate(params) assert !called_error @@ -89,10 +83,7 @@ def app it "passes given a datetime and with coerce_date_times enabled on GET endpoint" do key_name = "update_time" - params = { - key_name => "2016-04-01T16:00:00.000+09:00", - "query" => "cloudnasium" - } + params = { key_name => "2016-04-01T16:00:00.000+09:00", "query" => "cloudnasium" } check_parameter = lambda { |env| assert_equal DateTime, env['rack.request.query_hash'][key_name].class @@ -165,10 +156,7 @@ def app it "passes given a nested datetime and with coerce_recursive=true and coerce_date_times=true on POST endpoint" do key_name = "update_time" - params = { - key_name => "2016-04-01T16:00:00.000+09:00", - "array_property" => ARRAY_PROPERTY - } + params = { key_name => "2016-04-01T16:00:00.000+09:00", "array_property" => ARRAY_PROPERTY } check_parameter = lambda { |env| hash = env['committee.params'] @@ -191,10 +179,7 @@ def app it "passes given a nested datetime and with coerce_recursive=true and coerce_date_times=true on POST endpoint" do key_name = "update_time" - params = { - key_name => "2016-04-01T16:00:00.000+09:00", - "array_property" => ARRAY_PROPERTY - } + params = { key_name => "2016-04-01T16:00:00.000+09:00", "array_property" => ARRAY_PROPERTY } check_parameter = lambda { |env| hash = env['committee.params'] @@ -217,10 +202,7 @@ def app it "passes given a nested datetime and with coerce_recursive=false and coerce_date_times=true on POST endpoint" do key_name = "update_time" - params = { - key_name => "2016-04-01T16:00:00.000+09:00", - "array_property" => ARRAY_PROPERTY - } + params = { key_name => "2016-04-01T16:00:00.000+09:00", "array_property" => ARRAY_PROPERTY } check_parameter = lambda { |env| hash = env['committee.params'] @@ -243,10 +225,7 @@ def app it "passes given a nested datetime and with coerce_recursive=false and coerce_date_times=false on POST endpoint" do key_name = "update_time" - params = { - key_name => "2016-04-01T16:00:00.000+09:00", - "array_property" => ARRAY_PROPERTY - } + params = { key_name => "2016-04-01T16:00:00.000+09:00", "array_property" => ARRAY_PROPERTY } check_parameter = lambda { |env| hash = env['committee.params'] @@ -269,9 +248,7 @@ def app it "passes given an invalid datetime string with coerce_date_times enabled" do @app = new_rack_app(coerce_date_times: true, schema: hyper_schema) - params = { - "update_time" => "invalid_datetime_format" - } + params = { "update_time" => "invalid_datetime_format" } header "Content-Type", "application/json" post "/apps", JSON.generate(params) assert_equal 400, last_response.status @@ -288,9 +265,7 @@ def app it "detects an invalid request" do @app = new_rack_app(schema: hyper_schema) header "Content-Type", "application/json" - params = { - "name" => 1 - } + params = { "name" => 1 } post "/apps", JSON.generate(params) assert_equal 400, last_response.status assert_match(/invalid request/i, last_response.body) @@ -299,9 +274,7 @@ def app it "ignores errors when ignore_error: true" do @app = new_rack_app(schema: hyper_schema, ignore_error: true) header "Content-Type", "application/json" - params = { - "name" => 1 - } + params = { "name" => 1 } post "/apps", JSON.generate(params) assert_equal 200, last_response.status end @@ -311,9 +284,7 @@ def app pr = ->(e, _env) { called_err = e } @app = new_rack_app(schema: hyper_schema, error_handler: pr) header "Content-Type", "application/json" - params = { - "name" => 1 - } + params = { "name" => 1 } post "/apps", JSON.generate(params) assert_kind_of Committee::InvalidRequest, called_err end @@ -337,9 +308,7 @@ def app it "takes a prefix" do @app = new_rack_app(prefix: "/v1", schema: hyper_schema) - params = { - "name" => "cloudnasium" - } + params = { "name" => "cloudnasium" } header "Content-Type", "application/json" post "/v1/apps", JSON.generate(params) assert_equal 200, last_response.status @@ -374,9 +343,7 @@ def app it "optionally skip content_type check" do @app = new_rack_app(check_content_type: false, schema: hyper_schema) - params = { - "name" => "cloudnasium" - } + params = { "name" => "cloudnasium" } header "Content-Type", "text/html" post "/apps", JSON.generate(params) assert_equal 200, last_response.status @@ -385,14 +352,14 @@ def app it "optionally coerces query params" do @app = new_rack_app(coerce_query_params: true, schema: hyper_schema) header "Content-Type", "application/json" - get "/search/apps", {"per_page" => "10", "query" => "cloudnasium"} + get "/search/apps", { "per_page" => "10", "query" => "cloudnasium" } assert_equal 200, last_response.status end it "still raises an error if query param coercion is not possible" do @app = new_rack_app(coerce_query_params: true, schema: hyper_schema) header "Content-Type", "application/json" - get "/search/apps", {"per_page" => "foo", "query" => "cloudnasium"} + get "/search/apps", { "per_page" => "foo", "query" => "cloudnasium" } assert_equal 400, last_response.status assert_match(/invalid request/i, last_response.body) end @@ -470,7 +437,7 @@ def app coerce_recursive: true } - @app = new_rack_app({schema: hyper_schema}.merge(options)) + @app = new_rack_app({ schema: hyper_schema }.merge(options)) header "Content-Type", "application/x-www-form-urlencoded" post "/unknown" assert_equal 200, last_response.status @@ -479,8 +446,8 @@ def app describe ':accept_request_filter' do [ { description: 'when not specified, includes everything', accept_request_filter: nil, expected: { status: 400 } }, - { description: 'when predicate matches, performs validation', accept_request_filter: -> (request) { request.path.start_with?('/v1/a') }, expected: { status: 400 } }, - { description: 'when predicate does not match, skips validation', accept_request_filter: -> (request) { request.path.start_with?('/v1/x') }, expected: { status: 200 } }, + { description: 'when predicate matches, performs validation', accept_request_filter: ->(request) { request.path.start_with?('/v1/a') }, expected: { status: 400 } }, + { description: 'when predicate does not match, skips validation', accept_request_filter: ->(request) { request.path.start_with?('/v1/x') }, expected: { status: 200 } }, ].each do |h| description = h[:description] accept_request_filter = h[:accept_request_filter] @@ -503,7 +470,6 @@ def new_rack_app(options = {}) }, options) end - def new_rack_app_with_lambda(check_lambda, options = {}) Rack::Builder.new { use Committee::Middleware::RequestValidation, options diff --git a/test/middleware/response_validation_open_api_3_test.rb b/test/middleware/response_validation_open_api_3_test.rb index 1f18cca9..009b1d76 100644 --- a/test/middleware/response_validation_open_api_3_test.rb +++ b/test/middleware/response_validation_open_api_3_test.rb @@ -5,7 +5,7 @@ describe Committee::Middleware::ResponseValidation do include Rack::Test::Methods - CHARACTERS_RESPONSE = {"Otonokizaka" => ["Honoka.Kousaka"]} + CHARACTERS_RESPONSE = { "Otonokizaka" => ["Honoka.Kousaka"] } def app @app @@ -35,7 +35,7 @@ def app end it "passes through a invalid json with parse_response_by_content_type option" do - @app = new_response_rack("csv response", { "Content-Type" => "test/csv"}, schema: open_api_3_schema, parse_response_by_content_type: true) + @app = new_response_rack("csv response", { "Content-Type" => "test/csv" }, schema: open_api_3_schema, parse_response_by_content_type: true) get "/csv" @@ -59,13 +59,13 @@ def app end it "passes through a 204 (no content) response" do - @app = new_response_rack("", {}, {schema: open_api_3_schema}, {status: 204}) + @app = new_response_rack("", {}, { schema: open_api_3_schema }, { status: 204 }) post "/validate" assert_equal 204, last_response.status end it "passes through a 304 (not modified) response" do - @app = new_response_rack("", {}, {schema: open_api_3_schema}, {status: 304}) + @app = new_response_rack("", {}, { schema: open_api_3_schema }, { status: 304 }) post "/validate" assert_equal 304, last_response.status end @@ -93,10 +93,10 @@ def app end it "not parameter request" do - @app = new_response_rack({integer: '1'}.to_json, {}, schema: open_api_3_schema, raise: true) + @app = new_response_rack({ integer: '1' }.to_json, {}, schema: open_api_3_schema, raise: true) assert_raises(Committee::InvalidResponse) do - patch "/validate_no_parameter", {no_schema: 'no'} + patch "/validate_no_parameter", { no_schema: 'no' } end end @@ -178,7 +178,6 @@ def app raise: true, validate_success_only: false) - e = assert_raises(Committee::InvalidResponse) do get "/characters" end @@ -194,7 +193,6 @@ def app raise: true, validate_success_only: true) - get "/characters" assert_equal 400, last_response.status @@ -204,8 +202,8 @@ def app describe ':accept_request_filter' do [ { description: 'when not specified, includes everything', accept_request_filter: nil, expected: { status: 500 } }, - { description: 'when predicate matches, performs validation', accept_request_filter: -> (request) { request.path.start_with?('/v1/c') }, expected: { status: 500 } }, - { description: 'when predicate does not match, skips validation', accept_request_filter: -> (request) { request.path.start_with?('/v1/x') }, expected: { status: 200 } }, + { description: 'when predicate matches, performs validation', accept_request_filter: ->(request) { request.path.start_with?('/v1/c') }, expected: { status: 500 } }, + { description: 'when predicate does not match, skips validation', accept_request_filter: ->(request) { request.path.start_with?('/v1/x') }, expected: { status: 200 } }, ].each do |h| description = h[:description] accept_request_filter = h[:accept_request_filter] @@ -223,9 +221,9 @@ def app it 'does not suppress application error' do @app = Rack::Builder.new { - use Committee::Middleware::ResponseValidation, {schema: open_api_3_schema, raise: true} + use Committee::Middleware::ResponseValidation, { schema: open_api_3_schema, raise: true } run lambda { |_| - JSON.load('-') # invalid json + JSON.load('-') # invalid json } } @@ -234,14 +232,14 @@ def app end end - it "strict and invalid status" do - @app = new_response_rack(JSON.generate(CHARACTERS_RESPONSE), {}, {schema: open_api_3_schema, strict: true}, {status: 201}) + it "strict and invalid status" do + @app = new_response_rack(JSON.generate(CHARACTERS_RESPONSE), {}, { schema: open_api_3_schema, strict: true }, { status: 201 }) get "/characters" assert_equal 500, last_response.status end it "strict and invalid status with raise" do - @app = new_response_rack(JSON.generate(CHARACTERS_RESPONSE), {}, {schema: open_api_3_schema, strict: true, raise: true}, {status: 201}) + @app = new_response_rack(JSON.generate(CHARACTERS_RESPONSE), {}, { schema: open_api_3_schema, strict: true, raise: true }, { status: 201 }) assert_raises(Committee::InvalidResponse) do get "/characters" @@ -249,11 +247,7 @@ def app end it "strict and invalid content type" do - @app = new_response_rack("abc", - {}, - {schema: open_api_3_schema, strict: true}, - {content_type: 'application/text'} - ) + @app = new_response_rack("abc", {}, { schema: open_api_3_schema, strict: true }, { content_type: 'application/text' }) get "/characters" assert_equal 500, last_response.status end @@ -261,8 +255,8 @@ def app it "strict and invalid content type with raise" do @app = new_response_rack("abc", {}, - {schema: open_api_3_schema, strict: true, raise: true}, - {content_type: 'application/text'} + { schema: open_api_3_schema, strict: true, raise: true }, + { content_type: 'application/text' } ) assert_raises(Committee::InvalidResponse) do @@ -275,9 +269,7 @@ def app def new_response_rack(response, headers = {}, options = {}, rack_options = {}) status = rack_options[:status] || 200 content_type = rack_options[:content_type] || "application/json" - headers = { - "Content-Type" => content_type - }.merge(headers) + headers = { "Content-Type" => content_type }.merge(headers) Rack::Builder.new { use Committee::Middleware::ResponseValidation, options run lambda { |_| diff --git a/test/middleware/response_validation_test.rb b/test/middleware/response_validation_test.rb index c5d743df..f3865b04 100644 --- a/test/middleware/response_validation_test.rb +++ b/test/middleware/response_validation_test.rb @@ -106,8 +106,7 @@ def app end it "takes a prefix" do - @app = new_rack_app(JSON.generate([ValidApp]), {}, prefix: "/v1", - schema: hyper_schema) + @app = new_rack_app(JSON.generate([ValidApp]), {}, prefix: "/v1", schema: hyper_schema) get "/v1/apps" assert_equal 200, last_response.status end @@ -130,30 +129,26 @@ def app end it "passes through a valid response for OpenAPI" do - @app = new_rack_app(JSON.generate([ValidPet]), {}, - schema: open_api_2_schema) + @app = new_rack_app(JSON.generate([ValidPet]), {}, schema: open_api_2_schema) get "/api/pets" assert_equal 200, last_response.status end it "passes through a valid response for OpenAPI when data=nil, target_schema=empty, allow_blank_structures=true" do - @app = new_rack_app("null", {}, - allow_blank_structures: true, schema: open_api_2_schema) + @app = new_rack_app("null", {}, allow_blank_structures: true, schema: open_api_2_schema) get "/api/pets/cat" assert_equal 200, last_response.status end it "invalid responses for OpenAPI when data=nil, target_schema=empty, allow_blank_structures=false" do - @app = new_rack_app("null", {}, - allow_blank_structures: false, schema: open_api_2_schema) + @app = new_rack_app("null", {}, allow_blank_structures: false, schema: open_api_2_schema) get "/api/pets/cat" assert_equal 500, last_response.status assert_match(/Invalid response/i, last_response.body) end it "passes through a valid response for OpenAPI when data=nil, target_schema=present, allow_blank_structures=true" do - @app = new_rack_app("null", {}, - allow_blank_structures: true, schema: open_api_2_schema) + @app = new_rack_app("null", {}, allow_blank_structures: true, schema: open_api_2_schema) get "/api/pets/dog" assert_equal 500, last_response.status assert_match(/nil is not an array/i, last_response.body) @@ -169,8 +164,8 @@ def app describe ':accept_request_filter' do [ { description: 'when not specified, includes everything', accept_request_filter: nil, expected: { status: 500 } }, - { description: 'when predicate matches, performs validation', accept_request_filter: -> (request) { request.path.start_with?('/v1/a') }, expected: { status: 500 } }, - { description: 'when predicate does not match, skips validation', accept_request_filter: -> (request) { request.path.start_with?('/v1/x') }, expected: { status: 200 } }, + { description: 'when predicate matches, performs validation', accept_request_filter: ->(request) { request.path.start_with?('/v1/a') }, expected: { status: 500 } }, + { description: 'when predicate does not match, skips validation', accept_request_filter: ->(request) { request.path.start_with?('/v1/x') }, expected: { status: 200 } }, ].each do |h| description = h[:description] accept_request_filter = h[:accept_request_filter] @@ -188,9 +183,7 @@ def app private def new_rack_app(response, headers = {}, options = {}) - headers = { - "Content-Type" => "application/json" - }.merge(headers) + headers = { "Content-Type" => "application/json" }.merge(headers) Rack::Builder.new { use Committee::Middleware::ResponseValidation, options run lambda { |_| diff --git a/test/middleware/stub_test.rb b/test/middleware/stub_test.rb index 1360381d..119733be 100644 --- a/test/middleware/stub_test.rb +++ b/test/middleware/stub_test.rb @@ -27,16 +27,14 @@ def app @app = new_rack_app(call: true, schema: hyper_schema) get "/apps/heroku-api" assert_equal 200, last_response.status - assert_equal ValidApp, - JSON.parse(last_response.headers["Committee-Response"]) + assert_equal ValidApp, JSON.parse(last_response.headers["Committee-Response"]) end it "optionally returns the application's response" do @app = new_rack_app(call: true, schema: hyper_schema, suppress: true) get "/apps/heroku-api" assert_equal 429, last_response.status - assert_equal ValidApp, - JSON.parse(last_response.headers["Committee-Response"]) + assert_equal ValidApp, JSON.parse(last_response.headers["Committee-Response"]) assert_equal "", last_response.body end @@ -44,8 +42,7 @@ def app @app = new_rack_app(call: true, schema: hyper_schema, suppress: true) get "/apps/heroku-api" assert_equal 429, last_response.status - assert_equal "#/definitions/app/links/2/targetSchema", - last_response.headers["Committee-Response-Schema"] + assert_equal "#/definitions/app/links/2/targetSchema", last_response.headers["Committee-Response-Schema"] assert_equal "", last_response.body end @@ -122,15 +119,11 @@ def new_rack_app(options = {}) headers = {} if res = env["committee.response"] - headers.merge!({ - "Committee-Response" => JSON.generate(res) - }) + headers.merge!({ "Committee-Response" => JSON.generate(res) }) end if res = env["committee.response_schema"] - headers.merge!({ - "Committee-Response-Schema" => res.pointer, - }) + headers.merge!({ "Committee-Response-Schema" => res.pointer, }) end env["committee.suppress"] = suppress diff --git a/test/request_unpacker_test.rb b/test/request_unpacker_test.rb index e51d08a3..a70862d5 100644 --- a/test/request_unpacker_test.rb +++ b/test/request_unpacker_test.rb @@ -4,39 +4,28 @@ describe Committee::RequestUnpacker do it "unpacks JSON on Content-Type: application/json" do - env = { - "CONTENT_TYPE" => "application/json", - "rack.input" => StringIO.new('{"x":"y"}'), - } + env = { "CONTENT_TYPE" => "application/json", "rack.input" => StringIO.new('{"x":"y"}'), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new assert_equal([{ "x" => "y" }, false], unpacker.unpack_request_params(request)) end it "unpacks JSON on Content-Type: application/vnd.api+json" do - env = { - "CONTENT_TYPE" => "application/vnd.api+json", - "rack.input" => StringIO.new('{"x":"y"}'), - } + env = { "CONTENT_TYPE" => "application/vnd.api+json", "rack.input" => StringIO.new('{"x":"y"}'), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new assert_equal([{ "x" => "y" }, false], unpacker.unpack_request_params(request)) end it "unpacks JSON on no Content-Type" do - env = { - "rack.input" => StringIO.new('{"x":"y"}'), - } + env = { "rack.input" => StringIO.new('{"x":"y"}'), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new assert_equal([{ "x" => "y" }, false], unpacker.unpack_request_params(request)) end it "doesn't unpack JSON on application/x-ndjson" do - env = { - "CONTENT_TYPE" => "application/x-ndjson", - "rack.input" => StringIO.new('{"x":"y"}\n{"a":"b"}'), - } + env = { "CONTENT_TYPE" => "application/x-ndjson", "rack.input" => StringIO.new('{"x":"y"}\n{"a":"b"}'), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new assert_equal([{}, false], unpacker.unpack_request_params(request)) @@ -44,10 +33,7 @@ it "doesn't unpack JSON under other Content-Types" do %w[application/x-www-form-urlencoded multipart/form-data].each do |content_type| - env = { - "CONTENT_TYPE" => content_type, - "rack.input" => StringIO.new('{"x":"y"}'), - } + env = { "CONTENT_TYPE" => content_type, "rack.input" => StringIO.new('{"x":"y"}'), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new assert_equal([{}, false], unpacker.unpack_request_params(request)) @@ -56,10 +42,7 @@ it "unpacks JSON under other Content-Types with optimistic_json" do %w[application/x-www-form-urlencoded multipart/form-data].each do |content_type| - env = { - "CONTENT_TYPE" => content_type, - "rack.input" => StringIO.new('{"x":"y"}'), - } + env = { "CONTENT_TYPE" => content_type, "rack.input" => StringIO.new('{"x":"y"}'), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new(optimistic_json: true) assert_equal([{ "x" => "y" }, false], unpacker.unpack_request_params(request)) @@ -68,10 +51,7 @@ it "returns {} when unpacking non-JSON with optimistic_json" do %w[application/x-www-form-urlencoded multipart/form-data].each do |content_type| - env = { - "CONTENT_TYPE" => content_type, - "rack.input" => StringIO.new('x=y&foo=42'), - } + env = { "CONTENT_TYPE" => content_type, "rack.input" => StringIO.new('x=y&foo=42'), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new(optimistic_json: true) assert_equal([{}, false], unpacker.unpack_request_params(request)) @@ -79,10 +59,7 @@ end it "unpacks an empty hash on an empty request body" do - env = { - "CONTENT_TYPE" => "application/json", - "rack.input" => StringIO.new(""), - } + env = { "CONTENT_TYPE" => "application/json", "rack.input" => StringIO.new(""), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new assert_equal([{}, false], unpacker.unpack_request_params(request)) @@ -90,10 +67,7 @@ it "doesn't unpack form params" do %w[application/x-www-form-urlencoded multipart/form-data].each do |content_type| - env = { - "CONTENT_TYPE" => content_type, - "rack.input" => StringIO.new("x=y"), - } + env = { "CONTENT_TYPE" => content_type, "rack.input" => StringIO.new("x=y"), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new assert_equal([{}, false], unpacker.unpack_request_params(request)) @@ -102,10 +76,7 @@ it "unpacks form params with allow_form_params" do %w[application/x-www-form-urlencoded multipart/form-data].each do |content_type| - env = { - "CONTENT_TYPE" => content_type, - "rack.input" => StringIO.new("x=y"), - } + env = { "CONTENT_TYPE" => content_type, "rack.input" => StringIO.new("x=y"), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new(allow_form_params: true) assert_equal([{ "x" => "y" }, true], unpacker.unpack_request_params(request)) @@ -114,32 +85,22 @@ it "unpacks form & query params with allow_form_params and allow_query_params" do %w[application/x-www-form-urlencoded multipart/form-data].each do |content_type| - env = { - "CONTENT_TYPE" => content_type, - "rack.input" => StringIO.new("x=y"), - "QUERY_STRING" => "a=b" - } + env = { "CONTENT_TYPE" => content_type, "rack.input" => StringIO.new("x=y"), "QUERY_STRING" => "a=b" } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new(allow_form_params: true, allow_query_params: true) - assert_equal([ { "x" => "y"}, true], unpacker.unpack_request_params(request)) + assert_equal([{ "x" => "y" }, true], unpacker.unpack_request_params(request)) end end it "unpacks query params with allow_query_params" do - env = { - "rack.input" => StringIO.new(""), - "QUERY_STRING" => "a=b" - } + env = { "rack.input" => StringIO.new(""), "QUERY_STRING" => "a=b" } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new(allow_query_params: true) assert_equal({ "a" => "b" }, unpacker.unpack_query_params(request)) end it "errors if JSON is not an object" do - env = { - "CONTENT_TYPE" => "application/json", - "rack.input" => StringIO.new('[2]'), - } + env = { "CONTENT_TYPE" => "application/json", "rack.input" => StringIO.new('[2]'), } request = Rack::Request.new(env) assert_raises(Committee::BadRequest) do Committee::RequestUnpacker.new.unpack_request_params(request) @@ -147,10 +108,7 @@ end it "errors on an unknown Content-Type" do - env = { - "CONTENT_TYPE" => "application/whats-this", - "rack.input" => StringIO.new('{"x":"y"}'), - } + env = { "CONTENT_TYPE" => "application/whats-this", "rack.input" => StringIO.new('{"x":"y"}'), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new assert_equal([{}, false], unpacker.unpack_request_params(request)) @@ -158,19 +116,14 @@ # this is mostly here for line coverage it "unpacks JSON containing an array" do - env = { - "rack.input" => StringIO.new('{"x":[]}'), - } + env = { "rack.input" => StringIO.new('{"x":[]}'), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new assert_equal([{ "x" => [] }, false], unpacker.unpack_request_params(request)) end it "unpacks http header" do - env = { - "HTTP_FOO_BAR" => "some header value", - "rack.input" => StringIO.new(""), - } + env = { "HTTP_FOO_BAR" => "some header value", "rack.input" => StringIO.new(""), } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new({ allow_header_params: true }) assert_equal({ "FOO-BAR" => "some header value" }, unpacker.unpack_headers(request)) @@ -180,7 +133,7 @@ env = { "rack.input" => StringIO.new('{"x":1, "y":2}'), "REQUEST_METHOD" => "GET", - "QUERY_STRING"=>"data=value&x=aaa", + "QUERY_STRING" => "data=value&x=aaa", } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new({ allow_query_params: true, allow_get_body: true }) @@ -191,7 +144,7 @@ env = { "rack.input" => StringIO.new('{"x":1, "y":2}'), "REQUEST_METHOD" => "GET", - "QUERY_STRING"=>"data=value&x=aaa", + "QUERY_STRING" => "data=value&x=aaa", } request = Rack::Request.new(env) unpacker = Committee::RequestUnpacker.new({ allow_query_params: true, use_get_body: false }) diff --git a/test/schema_validator/hyper_schema/parameter_coercer_test.rb b/test/schema_validator/hyper_schema/parameter_coercer_test.rb index 763a0530..af388e2a 100644 --- a/test/schema_validator/hyper_schema/parameter_coercer_test.rb +++ b/test/schema_validator/hyper_schema/parameter_coercer_test.rb @@ -11,7 +11,7 @@ end it "pass datetime string" do - params = { "update_time" => "2016-04-01T16:00:00.000+09:00"} + params = { "update_time" => "2016-04-01T16:00:00.000+09:00" } call(params, coerce_date_times: true) assert_kind_of DateTime, params["update_time"] @@ -28,7 +28,7 @@ it "pass invalid datetime string, not convert" do invalid_datetime = "llmfllmf" - params = { "update_time" => invalid_datetime} + params = { "update_time" => invalid_datetime } call(params, coerce_date_times: true) assert_equal invalid_datetime, params["update_time"] @@ -104,7 +104,7 @@ class HashLikeObject < Hash; end - def call(params, options={}) + def call(params, options = {}) link = Committee::Drivers::HyperSchema::Link.new(@link) Committee::SchemaValidator::HyperSchema::ParameterCoercer.new(params, link.schema, options).call! end diff --git a/test/schema_validator/hyper_schema/request_validator_test.rb b/test/schema_validator/hyper_schema/request_validator_test.rb index dd0ee694..21a6ddf4 100644 --- a/test/schema_validator/hyper_schema/request_validator_test.rb +++ b/test/schema_validator/hyper_schema/request_validator_test.rb @@ -24,9 +24,7 @@ end it "passes through a valid request" do - data = { - "name" => "heroku-api", - } + data = { "name" => "heroku-api", } call(data) end @@ -36,9 +34,7 @@ "CONTENT_TYPE" => "application/json; charset=utf-8", "rack.input" => StringIO.new("{}"), }) - data = { - "name" => "heroku-api", - } + data = { "name" => "heroku-api", } call(data) end @@ -51,8 +47,7 @@ }) call({}) } - message = - %{"Content-Type" request header must be set to "application/json".} + message = %{"Content-Type" request header must be set to "application/json".} assert_equal message, e.message end @@ -87,9 +82,7 @@ end it "detects a parameter of the wrong pattern" do - data = { - "name" => "%@!" - } + data = { "name" => "%@!" } e = assert_raises(Committee::InvalidRequest) do call(data) end @@ -99,7 +92,7 @@ private - def call(data, headers={}, options={}) + def call(data, headers = {}, options = {}) # hyper-schema link should be dropped into driver wrapper before it's used link = Committee::Drivers::HyperSchema::Link.new(@link) Committee::SchemaValidator::HyperSchema::RequestValidator.new(link, options).call(@request, data, headers) @@ -117,11 +110,8 @@ def call(data, headers={}, options={}) }) end - it "passes through a valid request" do - headers = { - "AUTH-TOKEN" => "xxx" - } + headers = { "AUTH-TOKEN" => "xxx" } call({}, headers) end @@ -143,7 +133,7 @@ def call(data, headers={}, options={}) private - def call(data, headers={}, options={}) + def call(data, headers = {}, options = {}) # hyper-schema link should be dropped into driver wrapper before it's used Committee::SchemaValidator::HyperSchema::RequestValidator.new(@link, options).call(@request, data, headers) end diff --git a/test/schema_validator/hyper_schema/response_generator_test.rb b/test/schema_validator/hyper_schema/response_generator_test.rb index d8e5d84b..3de348c4 100644 --- a/test/schema_validator/hyper_schema/response_generator_test.rb +++ b/test/schema_validator/hyper_schema/response_generator_test.rb @@ -65,8 +65,8 @@ end expected = <<-eos.gsub(/\n +/, "").strip - At "get /apps/{(%23%2Fdefinitions%2Fapp%2Fdefinitions%2Fname)}" - "#/definitions/app/properties/maintenance": no "example" attribute and + At "get /apps/{(%23%2Fdefinitions%2Fapp%2Fdefinitions%2Fname)}"#{' '} + "#/definitions/app/properties/maintenance": no "example" attribute and#{' '} "null" is not allowed; don't know how to generate property. eos assert_equal expected, e.message diff --git a/test/schema_validator/hyper_schema/response_validator_test.rb b/test/schema_validator/hyper_schema/response_validator_test.rb index dee312b7..2c0e9d39 100644 --- a/test/schema_validator/hyper_schema/response_validator_test.rb +++ b/test/schema_validator/hyper_schema/response_validator_test.rb @@ -5,9 +5,7 @@ describe Committee::SchemaValidator::HyperSchema::ResponseValidator do before do @status = 200 - @headers = { - "Content-Type" => "application/json" - } + @headers = { "Content-Type" => "application/json" } @data = ValidApp.dup @schema = JsonSchema.parse!(hyper_schema_data) @schema.expand_references! @@ -78,16 +76,14 @@ it "detects a blank response Content-Type" do @headers = {} e = assert_raises(Committee::InvalidResponse) { call } - message = - %{"Content-Type" response header must be set to "#{@link.enc_type}".} + message = %{"Content-Type" response header must be set to "#{@link.enc_type}".} assert_equal message, e.message end it "detects an invalid response Content-Type" do @headers = { "Content-Type" => "text/html" } e = assert_raises(Committee::InvalidResponse) { call } - message = - %{"Content-Type" response header must be set to "#{@link.enc_type}".} + message = %{"Content-Type" response header must be set to "#{@link.enc_type}".} assert_equal message, e.message end diff --git a/test/schema_validator/hyper_schema/string_params_coercer_test.rb b/test/schema_validator/hyper_schema/string_params_coercer_test.rb index e122b56d..ad4313cb 100644 --- a/test/schema_validator/hyper_schema/string_params_coercer_test.rb +++ b/test/schema_validator/hyper_schema/string_params_coercer_test.rb @@ -121,7 +121,7 @@ private def check_convert(key, before_value, after_value) - data = {key => before_value} + data = { key => before_value } call(data) if !after_value.nil? @@ -131,7 +131,7 @@ def check_convert(key, before_value, after_value) end end - def call(data, options={}) + def call(data, options = {}) Committee::SchemaValidator::HyperSchema::StringParamsCoercer.new(data, @link.schema, options).call! end end diff --git a/test/schema_validator/open_api_3/operation_wrapper_test.rb b/test/schema_validator/open_api_3/operation_wrapper_test.rb index 0169b069..508a3b1a 100644 --- a/test/schema_validator/open_api_3/operation_wrapper_test.rb +++ b/test/schema_validator/open_api_3/operation_wrapper_test.rb @@ -52,7 +52,7 @@ def operation_object it 'invalid params' do e = assert_raises(Committee::InvalidRequest) { - operation_object.validate_request_params({}, {}, {"string" => 1}, HEADER, @validator_option) + operation_object.validate_request_params({}, {}, { "string" => 1 }, HEADER, @validator_option) } assert_match(/expected string, but received Integer: 1/i, e.message) @@ -61,10 +61,10 @@ def operation_object it 'support put method' do @method = "put" - operation_object.validate_request_params({}, {}, {"string" => "str"}, HEADER, @validator_option) + operation_object.validate_request_params({}, {}, { "string" => "str" }, HEADER, @validator_option) e = assert_raises(Committee::InvalidRequest) { - operation_object.validate_request_params({}, {}, {"string" => 1}, HEADER, @validator_option) + operation_object.validate_request_params({}, {}, { "string" => 1 }, HEADER, @validator_option) } assert_match(/expected string, but received Integer: 1/i, e.message) @@ -73,10 +73,10 @@ def operation_object it 'support patch method' do @method = "patch" - operation_object.validate_request_params({}, {}, {"integer" => 1}, HEADER, @validator_option) + operation_object.validate_request_params({}, {}, { "integer" => 1 }, HEADER, @validator_option) e = assert_raises(Committee::InvalidRequest) { - operation_object.validate_request_params({}, {}, {"integer" => "str"}, HEADER, @validator_option) + operation_object.validate_request_params({}, {}, { "integer" => "str" }, HEADER, @validator_option) } assert_match(/expected integer, but received String: "str"/i, e.message) @@ -84,7 +84,7 @@ def operation_object end it 'unknown param' do - operation_object.validate_request_params({}, {}, {"unknown" => 1}, HEADER, @validator_option) + operation_object.validate_request_params({}, {}, { "unknown" => 1 }, HEADER, @validator_option) end describe 'support get method' do @@ -95,7 +95,7 @@ def operation_object it 'correct' do operation_object.validate_request_params( {}, - {"query_string" => "query", "query_integer_list" => [1, 2]}, + { "query_string" => "query", "query_integer_list" => [1, 2] }, {}, HEADER, @validator_option @@ -103,7 +103,7 @@ def operation_object operation_object.validate_request_params( {}, - {"query_string" => "query", "query_integer_list" => [1, 2], "optional_integer" => 1}, + { "query_string" => "query", "query_integer_list" => [1, 2], "optional_integer" => 1 }, {}, HEADER, @validator_option @@ -114,7 +114,7 @@ def operation_object it 'not exist required' do e = assert_raises(Committee::InvalidRequest) { - operation_object.validate_request_params({}, {"query_integer_list" => [1, 2]}, {}, HEADER, @validator_option) + operation_object.validate_request_params({}, { "query_integer_list" => [1, 2] }, {}, HEADER, @validator_option) } assert_match(/missing required parameters: query_string/i, e.message) @@ -125,7 +125,7 @@ def operation_object e = assert_raises(Committee::InvalidRequest) { operation_object.validate_request_params( {}, - {"query_string" => 1, "query_integer_list" => [1, 2], "optional_integer" => 1}, + { "query_string" => 1, "query_integer_list" => [1, 2], "optional_integer" => 1 }, {}, HEADER, @validator_option @@ -144,14 +144,14 @@ def operation_object end it 'correct' do - operation_object.validate_request_params({}, {"limit" => "1"}, {}, HEADER, @validator_option) + operation_object.validate_request_params({}, { "limit" => "1" }, {}, HEADER, @validator_option) assert true end it 'invalid type' do e = assert_raises(Committee::InvalidRequest) { - operation_object.validate_request_params({}, {"limit" => "a"}, {}, HEADER, @validator_option) + operation_object.validate_request_params({}, { "limit" => "a" }, {}, HEADER, @validator_option) } assert_match(/expected integer, but received String: "a"/i, e.message) @@ -166,14 +166,14 @@ def operation_object end it 'correct' do - operation_object.validate_request_params({}, {"limit" => "1"}, {}, HEADER, @validator_option) + operation_object.validate_request_params({}, { "limit" => "1" }, {}, HEADER, @validator_option) assert true end it 'invalid type' do e = assert_raises(Committee::InvalidRequest) { - operation_object.validate_request_params({}, {"limit" => "a"}, {}, HEADER, @validator_option) + operation_object.validate_request_params({}, { "limit" => "a" }, {}, HEADER, @validator_option) } assert_match(/expected integer, but received String: "a"/i, e.message) @@ -183,17 +183,16 @@ def operation_object it 'support options method' do @method = "options" - operation_object.validate_request_params({}, {}, {"integer" => 1}, HEADER, @validator_option) + operation_object.validate_request_params({}, {}, { "integer" => 1 }, HEADER, @validator_option) e = assert_raises(Committee::InvalidRequest) { - operation_object.validate_request_params({}, {}, {"integer" => "str"}, HEADER, @validator_option) + operation_object.validate_request_params({}, {}, { "integer" => "str" }, HEADER, @validator_option) } assert_match(/expected integer, but received String: "str"/i, e.message) assert_kind_of(OpenAPIParser::OpenAPIError, e.original_error) end - describe '#content_types' do it 'returns supported content types' do @path = '/validate_content_types' diff --git a/test/schema_validator/open_api_3/request_validator_test.rb b/test/schema_validator/open_api_3/request_validator_test.rb index fc223a09..1cc7276a 100644 --- a/test/schema_validator/open_api_3/request_validator_test.rb +++ b/test/schema_validator/open_api_3/request_validator_test.rb @@ -20,16 +20,13 @@ def app it "optionally content_type check" do @app = new_rack_app(check_content_type: true, schema: open_api_3_schema) - params = { - "string_post_1" => "cloudnasium" - } + params = { "string_post_1" => "cloudnasium" } header "Content-Type", "text/html" post "/characters", JSON.generate(params) assert_equal 400, last_response.status body = JSON.parse(last_response.body) - message = - %{"Content-Type" request header must be set to "application/json".} + message = %{"Content-Type" request header must be set to "application/json".} assert_equal "bad_request", body['id'] assert_equal message, body['message'] @@ -37,9 +34,7 @@ def app it "validates content_type" do @app = new_rack_app(check_content_type: true, schema: open_api_3_schema) - params = { - "string_post_1" => "cloudnasium" - } + params = { "string_post_1" => "cloudnasium" } header "Content-Type", "text/html" post "/validate_content_types", JSON.generate(params) assert_equal 400, last_response.status @@ -53,9 +48,7 @@ def app it "optionally skip content_type check" do @app = new_rack_app(check_content_type: false, schema: open_api_3_schema) - params = { - "string_post_1" => "cloudnasium" - } + params = { "string_post_1" => "cloudnasium" } header "Content-Type", "text/html" post "/characters", JSON.generate(params) assert_equal 200, last_response.status @@ -63,9 +56,7 @@ def app it "if not exist requestBody definition, skip content_type check" do @app = new_rack_app(check_content_type: true, schema: open_api_3_schema) - params = { - "string_post_1" => "cloudnasium" - } + params = { "string_post_1" => "cloudnasium" } header "Content-Type", "application/json" patch "/validate_no_parameter", JSON.generate(params) assert_equal 200, last_response.status @@ -77,12 +68,10 @@ def app patch "/validate_empty_optional_body" assert_equal 200, last_response.status end - + it "does not mix up parameters and requestBody" do @app = new_rack_app(check_content_type: true, schema: open_api_3_schema) - params = { - "last_name" => "Skywalker" - } + params = { "last_name" => "Skywalker" } header "Content-Type", "application/json" post "/additional_properties?first_name=Luke", JSON.generate(params) assert_equal 200, last_response.status @@ -93,7 +82,7 @@ def app header "Content-Type", "application/x-www-form-urlencoded" patch "/validate_empty_optional_body", "{}" assert_equal 400, last_response.status - end + end it "validates content_type for option request" do @app = new_rack_app(check_content_type: true, schema: open_api_3_schema) diff --git a/test/schema_validator/open_api_3/response_validator_test.rb b/test/schema_validator/open_api_3/response_validator_test.rb index 0c10c3b9..5ee6bde0 100644 --- a/test/schema_validator/open_api_3/response_validator_test.rb +++ b/test/schema_validator/open_api_3/response_validator_test.rb @@ -5,10 +5,8 @@ describe Committee::SchemaValidator::OpenAPI3::ResponseValidator do before do @status = 200 - @headers = { - "Content-Type" => "application/json" - } - @data = {"string" => "Honoka.Kousaka"} + @headers = { "Content-Type" => "application/json" } + @data = { "string" => "Honoka.Kousaka" } @path = '/validate' @method = 'post' diff --git a/test/test/methods_new_version_test.rb b/test/test/methods_new_version_test.rb index 1f1ac49d..e49246cc 100644 --- a/test/test/methods_new_version_test.rb +++ b/test/test/methods_new_version_test.rb @@ -29,7 +29,7 @@ def response_data @committee_router = nil @committee_schema = nil - @committee_options = {schema: hyper_schema} + @committee_options = { schema: hyper_schema } end describe "#assert_schema_conform" do @@ -84,7 +84,7 @@ def response_data private - def new_rack_app(response, status=200, headers={ "Content-Type" => "application/json" }) + def new_rack_app(response, status = 200, headers = { "Content-Type" => "application/json" }) Rack::Builder.new { run lambda { |_| [status, headers, [response]] diff --git a/test/test/methods_test.rb b/test/test/methods_test.rb index e636943b..d5ff4f07 100644 --- a/test/test/methods_test.rb +++ b/test/test/methods_test.rb @@ -36,7 +36,7 @@ def response_data sc = JsonSchema.parse!(hyper_schema_data) sc.expand_references! s = Committee::Drivers::HyperSchema::Driver.new.parse(sc) - @committee_options.merge!({schema: s}) + @committee_options.merge!({ schema: s }) end describe "#assert_schema_conform" do @@ -111,7 +111,7 @@ def response_data describe "OpenAPI3" do before do - @committee_options.merge!({schema: open_api_3_schema}) + @committee_options.merge!({ schema: open_api_3_schema }) @correct_response = { string_1: :honoka } end @@ -153,7 +153,7 @@ def response_data it "not exist required" do @app = new_rack_app - get "/validate", {"query_string" => "query", "query_integer_list" => [1, 2]} + get "/validate", { "query_string" => "query", "query_integer_list" => [1, 2] } e = assert_raises(Committee::InvalidRequest) do assert_request_schema_confirm end @@ -208,7 +208,7 @@ def response_data end it "raises error when path does not match prefix" do - @committee_options.merge!({prefix: '/api'}) + @committee_options.merge!({ prefix: '/api' }) @app = new_rack_app(JSON.generate(@correct_response)) get "/characters" e = assert_raises(Committee::InvalidResponse) do @@ -350,7 +350,7 @@ def response_data private - def new_rack_app(response = nil, headers={ "Content-Type" => "application/json" }, status_code = 200) + def new_rack_app(response = nil, headers = { "Content-Type" => "application/json" }, status_code = 200) Rack::Builder.new { run lambda { |_| [status_code, headers, [response]] diff --git a/test/test/schema_coverage_test.rb b/test/test/schema_coverage_test.rb index db72ce32..69ca63be 100644 --- a/test/test/schema_coverage_test.rb +++ b/test/test/schema_coverage_test.rb @@ -21,9 +21,7 @@ def covered_responses end it 'can record and report coverage properly' do @schema_coverage.update_response_coverage!('/posts', 'get', '200') - assert_equal([ - '/posts get 200', - ], covered_responses) + assert_equal(['/posts get 200',], covered_responses) assert_equal([ '/threads/{id} get 200', '/posts get 404', @@ -34,10 +32,7 @@ def covered_responses ], uncovered_responses) @schema_coverage.update_response_coverage!('/likes', 'post', '200') - assert_equal([ - '/posts get 200', - '/likes post 200', - ], covered_responses) + assert_equal(['/posts get 200', '/likes post 200',], covered_responses) assert_equal([ '/threads/{id} get 200', '/posts get 404', @@ -47,11 +42,7 @@ def covered_responses ], uncovered_responses) @schema_coverage.update_response_coverage!('/likes', 'delete', '200') - assert_equal([ - '/posts get 200', - '/likes post 200', - '/likes delete 200', - ], covered_responses) + assert_equal(['/posts get 200', '/likes post 200', '/likes delete 200',], covered_responses) assert_equal([ '/threads/{id} get 200', '/posts get 404', @@ -66,11 +57,7 @@ def covered_responses '/likes post 200', '/likes delete 200', ], covered_responses) - assert_equal([ - '/threads/{id} get 200', - '/posts get 404', - '/posts post 200', - ], uncovered_responses) + assert_equal(['/threads/{id} get 200', '/posts get 404', '/posts post 200',], uncovered_responses) assert_equal({ '/threads/{id}' => { diff --git a/test/test_helper.rb b/test/test_helper.rb index 72470ef1..edfc7a15 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -36,17 +36,10 @@ end # For our hyper-schema example. -ValidApp = { - "maintenance" => false, - "name" => "example", -}.freeze +ValidApp = { "maintenance" => false, "name" => "example", }.freeze # For our OpenAPI example. -ValidPet = { - "id" => 123, - "name" => "example", - "tag" => "tag-123", -}.freeze +ValidPet = { "id" => 123, "name" => "example", "tag" => "tag-123", }.freeze def hyper_schema @hyper_schema ||= Committee::Drivers.load_from_json(hyper_schema_schema_path) @@ -61,11 +54,11 @@ def open_api_2_form_schema end def open_api_3_schema - @open_api_3_schema ||= Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options:{strict_reference_validation: true}) + @open_api_3_schema ||= Committee::Drivers.load_from_file(open_api_3_schema_path, parser_options: { strict_reference_validation: true }) end def open_api_3_coverage_schema - @open_api_3_coverage_schema ||= Committee::Drivers.load_from_file(open_api_3_coverage_schema_path, parser_options:{strict_reference_validation: true}) + @open_api_3_coverage_schema ||= Committee::Drivers.load_from_file(open_api_3_coverage_schema_path, parser_options: { strict_reference_validation: true }) end # Don't cache this because we'll often manipulate the created hash in tests. @@ -128,4 +121,4 @@ def open_api_3_1_schema_path def open_api_3_invalid_reference_path "./test/data/openapi3/invalid_reference.yaml" -end \ No newline at end of file +end diff --git a/test/validation_error_test.rb b/test/validation_error_test.rb index d727de4d..d7dceb3e 100644 --- a/test/validation_error_test.rb +++ b/test/validation_error_test.rb @@ -14,11 +14,7 @@ it "creates a Rack response object to render" do body = { id: :bad_request, message: "Error" } - response = [ - 400, - { "Content-Type" => "application/json" }, - [JSON.generate(body)] - ] + response = [400, { "Content-Type" => "application/json" }, [JSON.generate(body)]] assert_equal @error.render, response end