Merge branch 'openapi/master' into openapi/merge

This commit is contained in:
Greg Myers
2020-03-20 15:38:40 +00:00
42 changed files with 1296 additions and 346 deletions

View File

@@ -19,7 +19,17 @@ RSpec.configure do |config|
title: 'API V1',
version: 'v1'
},
paths: {}
paths: {},
servers: [
{
url: 'https://{defaultHost}',
variables: {
defaultHost: {
default: 'www.example.com'
}
}
}
]
}
}

View File

@@ -1,3 +1,5 @@
# frozen_string_literal: true
module Rswag
module Specs

View File

@@ -35,11 +35,107 @@ module Rswag
end
end
## OA3
# # MUST HAVES
# # need to run ```npm install``` in rswag-ui dir to get assets to load
# # not sure if its an asset issue or what but this should load => http://localhost:3000/api-docs/index.html
# # TODO: fix examples in the main README
# def request_body(attributes)
# # can make this generic, and accept any incoming hash (like parameter method)
# attributes.compact!
# if metadata[:operation][:requestBody].blank?
# metadata[:operation][:requestBody] = attributes
# elsif metadata[:operation][:requestBody] && metadata[:operation][:requestBody][:content]
# # merge in
# content_hash = metadata[:operation][:requestBody][:content]
# incoming_content_hash = attributes[:content]
# content_hash.merge!(incoming_content_hash) if incoming_content_hash
# end
# end
# def request_body_json(schema:, required: true, description: nil, examples: nil)
# passed_examples = Array(examples)
# content_hash = { 'application/json' => { schema: schema, examples: examples }.compact! || {} }
# request_body(description: description, required: required, content: content_hash)
# if passed_examples.any?
# # the request_factory is going to have to resolve the different ways that the example can be given
# # it can contain a 'value' key which is a direct hash (easiest)
# # it can contain a 'external_value' key which makes an external call to load the json
# # it can contain a '$ref' key. Which points to #/components/examples/blog
# passed_examples.each do |passed_example|
# if passed_example.is_a?(Symbol)
# example_key_name = passed_example
# # TODO: write more tests around this adding to the parameter
# # if symbol try and use save_request_example
# param_attributes = { name: example_key_name, in: :body, required: required, param_value: example_key_name, schema: schema }
# parameter(param_attributes)
# elsif passed_example.is_a?(Hash) && passed_example[:externalValue]
# param_attributes = { name: passed_example, in: :body, required: required, param_value: passed_example[:externalValue], schema: schema }
# parameter(param_attributes)
# elsif passed_example.is_a?(Hash) && passed_example['$ref']
# param_attributes = { name: passed_example, in: :body, required: required, param_value: passed_example['$ref'], schema: schema }
# parameter(param_attributes)
# end
# end
# end
# end
# def request_body_text_plain(required: false, description: nil, examples: nil)
# content_hash = { 'test/plain' => { schema: {type: :string}, examples: examples }.compact! || {} }
# request_body(description: description, required: required, content: content_hash)
# end
# # TODO: add examples to this like we can for json, might be large lift as many assumptions are made on content-type
# def request_body_xml(schema:,required: false, description: nil, examples: nil)
# passed_examples = Array(examples)
# content_hash = { 'application/xml' => { schema: schema, examples: examples }.compact! || {} }
# request_body(description: description, required: required, content: content_hash)
# end
# def request_body_multipart(schema:, description: nil)
# content_hash = { 'multipart/form-data' => { schema: schema }}
# request_body(description: description, content: content_hash)
# schema.extend(Hashie::Extensions::DeepLocate)
# file_properties = schema.deep_locate ->(_k, v, _obj) { v == :binary }
# hash_locator = []
# file_properties.each do |match|
# hash_match = schema.deep_locate ->(_k, v, _obj) { v == match }
# hash_locator.concat(hash_match) unless hash_match.empty?
# end
# property_hashes = hash_locator.flat_map do |locator|
# locator.select { |_k,v| file_properties.include?(v) }
# end
# existing_keys = []
# property_hashes.each do |property_hash|
# property_hash.keys.each do |k|
# if existing_keys.include?(k)
# next
# else
# file_name = k
# existing_keys << k
# parameter name: file_name, in: :formData, type: :file, required: true
# end
# end
# end
# end
def parameter(attributes)
if attributes[:in] && attributes[:in].to_sym == :path
attributes[:required] = true
end
## IF OA3
# if attributes[:type] && attributes[:schema].nil?
# attributes[:schema] = {type: attributes[:type]}
# end
if metadata.has_key?(:operation)
metadata[:operation][:parameters] ||= []
metadata[:operation][:parameters] << attributes
@@ -57,9 +153,21 @@ module Rswag
def schema(value)
metadata[:response][:schema] = value
end
## OA3
# def schema(value, content_type: 'application/json')
# content_hash = {content_type => {schema: value}}
# metadata[:response][:content] = content_hash
# end
def header(name, attributes)
metadata[:response][:headers] ||= {}
## OA3
# if attributes[:type] && attributes[:schema].nil?
# attributes[:schema] = {type: attributes[:type]}
# attributes.delete(:type)
# end
metadata[:response][:headers][name] = attributes
end
@@ -71,6 +179,46 @@ module Rswag
metadata[:response][:examples] = example
end
## OA3
# # checks the examples in the parameters should be able to add $ref and externalValue examples.
# # This syntax would look something like this in the integration _spec.rb file
# #
# # request_body_json schema: { '$ref' => '#/components/schemas/blog' },
# # examples: [:blog, {name: :external_blog,
# # externalValue: 'http://api.sample.org/myjson_example'},
# # {name: :another_example,
# # '$ref' => '#/components/examples/flexible_blog_example'}]
# # The first value :blog, points to a let param of the same name, and is used to make the request in the
# # integration test (it is used to build the request payload)
# #
# # The second item in the array shows how to add an externalValue for the examples in the requestBody section
# # The third item shows how to add a $ref item that points to the components/examples section of the swagger spec.
# #
# # NOTE: that the externalValue will produce valid example syntax in the swagger output, but swagger-ui
# # will not show it yet
# def merge_other_examples!(example_metadata)
# # example.metadata[:operation][:requestBody][:content]['application/json'][:examples]
# content_node = example_metadata[:operation][:requestBody][:content]['application/json']
# return unless content_node
# external_example = example_metadata[:operation]&.dig(:parameters)&.detect { |p| p[:in] == :body && p[:name].is_a?(Hash) && p[:name][:externalValue] } || {}
# ref_example = example_metadata[:operation]&.dig(:parameters)&.detect { |p| p[:in] == :body && p[:name].is_a?(Hash) && p[:name]['$ref'] } || {}
# examples_node = content_node[:examples] ||= {}
# nodes_to_add = []
# nodes_to_add << external_example unless external_example.empty?
# nodes_to_add << ref_example unless ref_example.empty?
# nodes_to_add.each do |node|
# json_request_examples = examples_node ||= {}
# other_name = node[:name][:name]
# other_key = node[:name][:externalValue] ? :externalValue : '$ref'
# if other_name
# json_request_examples.merge!(other_name => {other_key => node[:param_value]})
# end
# end
# end
def run_test!(&block)
# NOTE: rspec 2.x support
if RSPEC_VERSION < 3
@@ -91,6 +239,30 @@ module Rswag
assert_response_matches_metadata(example.metadata, &block)
example.instance_exec(response, &block) if block_given?
end
## OA3
# after do |example|
# body_parameter = example.metadata[:operation]&.dig(:parameters)&.detect { |p| p[:in] == :body && p[:required] }
# if body_parameter && respond_to?(body_parameter[:name]) && example.metadata[:operation][:requestBody][:content]['application/json']
# # save response examples by default
# if example.metadata[:response][:examples].nil? || example.metadata[:response][:examples].empty?
# example.metadata[:response][:examples] = { 'application/json' => JSON.parse(response.body, symbolize_names: true) } unless response.body.to_s.empty?
# end
# # save request examples using the let(:param_name) { REQUEST_BODY_HASH } syntax in the test
# if response.code.to_s =~ /^2\d{2}$/
# example.metadata[:operation][:requestBody][:content]['application/json'] = { examples: {} } unless example.metadata[:operation][:requestBody][:content]['application/json'][:examples]
# json_request_examples = example.metadata[:operation][:requestBody][:content]['application/json'][:examples]
# json_request_examples[body_parameter[:name]] = { value: send(body_parameter[:name]) }
# example.metadata[:operation][:requestBody][:content]['application/json'][:examples] = json_request_examples
# end
# end
# self.class.merge_other_examples!(example.metadata) if example.metadata[:operation][:requestBody]
# end
end
end
end

View File

@@ -1,10 +1,11 @@
# frozen_string_literal: true
require 'rswag/specs/request_factory'
require 'rswag/specs/response_validator'
module Rswag
module Specs
module ExampleHelpers
def submit_request(metadata)
request = RequestFactory.new.build_request(metadata, self)
@@ -19,10 +20,8 @@ module Rswag
send(
request[:verb],
request[:path],
{
params: request[:payload],
headers: request[:headers]
}
params: request[:payload],
headers: request[:headers]
)
end
end

View File

@@ -1,3 +1,5 @@
# frozen_string_literal: true
require 'json-schema'
module Rswag
@@ -15,6 +17,8 @@ module Rswag
class ExtendedTypeAttribute < JSON::Schema::TypeV4Attribute
def self.validate(current_schema, data, fragments, processor, validator, options={})
## OA3
# return if data.nil? && (current_schema.schema['nullable'] == true || current_schema.schema['x-nullable'] == true)
return if data.nil? && current_schema.schema['x-nullable'] == true
super
end

View File

@@ -1,3 +1,5 @@
# frozen_string_literal: true
module Rswag
module Specs
class Railtie < ::Rails::Railtie

View File

@@ -1,3 +1,5 @@
# frozen_string_literal: true
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/hash/conversions'
require 'json'
@@ -39,6 +41,10 @@ module Rswag
def derive_security_params(metadata, swagger_doc)
requirements = metadata[:operation][:security] || swagger_doc[:security] || []
scheme_names = requirements.flat_map { |r| r.keys }
## OA3
# scheme_names = requirements.flat_map(&:keys)
# components = swagger_doc[:components] || {}
# schemes = (components[:securitySchemes] || {}).slice(*scheme_names).values
schemes = (swagger_doc[:securityDefinitions] || {}).slice(*scheme_names).values
schemes.map do |scheme|
@@ -99,7 +105,7 @@ module Rswag
# Accept header
produces = metadata[:operation][:produces] || swagger_doc[:produces]
if produces
accept = example.respond_to?(:'Accept') ? example.send(:'Accept') : produces.first
accept = example.respond_to?(:Accept) ? example.send(:Accept) : produces.first
tuples << [ 'Accept', accept ]
end
@@ -145,13 +151,22 @@ module Rswag
tuples = parameters
.select { |p| p[:in] == :formData }
.map { |p| [ p[:name], example.send(p[:name]) ] }
Hash[ tuples ]
Hash[tuples]
end
def build_json_payload(parameters, example)
body_param = parameters.select { |p| p[:in] == :body }.first
body_param ? example.send(body_param[:name]).to_json : nil
end
## OA3
# def build_json_payload(parameters, example)
# body_param = parameters.select { |p| p[:in] == :body && p[:name].is_a?(Symbol) }.first
# return nil unless body_param
# source_body_param = example.send(body_param[:name]) if body_param[:name] && example.respond_to?(body_param[:name])
# source_body_param ||= body_param[:param_value]
# source_body_param ? source_body_param.to_json : nil
# end
end
end
end

View File

@@ -1,3 +1,5 @@
# frozen_string_literal: true
require 'active_support/core_ext/hash/slice'
require 'json-schema'
require 'json'
@@ -6,7 +8,6 @@ require 'rswag/specs/extended_schema'
module Rswag
module Specs
class ResponseValidator
def initialize(config = ::Rswag::Specs.config)
@config = config
end
@@ -25,8 +26,8 @@ module Rswag
expected = metadata[:response][:code].to_s
if response.code != expected
raise UnexpectedResponse,
"Expected response code '#{response.code}' to match '#{expected}'\n" \
"Response body: #{response.body}"
"Expected response code '#{response.code}' to match '#{expected}'\n" \
"Response body: #{response.body}"
end
end
@@ -40,13 +41,33 @@ module Rswag
def validate_body!(metadata, swagger_doc, body)
response_schema = metadata[:response][:schema]
return if response_schema.nil?
## OA3
# test_schemas = extract_schemas(metadata)
# return if test_schemas.nil? || test_schemas.empty?
# OA3
# components = swagger_doc[:components] || {}
# components_schemas = { components: { schemas: components[:schemas] } }
# validation_schema = test_schemas[:schema] # response_schema
validation_schema = response_schema
.merge('$schema' => 'http://tempuri.org/rswag/specs/extended_schema')
.merge(swagger_doc.slice(:definitions))
## OA3
# .merge(components_schemas)
errors = JSON::Validator.fully_validate(validation_schema, body)
raise UnexpectedResponse, "Expected response body to match schema: #{errors[0]}" if errors.any?
end
## OA3
# def extract_schemas(metadata)
# metadata[:operation] = {produces: []} if metadata[:operation].nil?
# produces = Array(metadata[:operation][:produces])
# producer_content = produces.first || 'application/json'
# response_content = metadata[:response][:content] || {producer_content => {}}
# response_content[producer_content]
# end
end
class UnexpectedResponse < StandardError; end

View File

@@ -1,3 +1,5 @@
# frozen_string_literal: true
require 'active_support/core_ext/hash/deep_merge'
require 'swagger_helper'
@@ -19,10 +21,10 @@ module Rswag
def example_group_finished(notification)
# NOTE: rspec 2.x support
if RSPEC_VERSION > 2
metadata = notification.group.metadata
metadata = if RSPEC_VERSION > 2
notification.group.metadata
else
metadata = notification.metadata
notification.metadata
end
# !metadata[:document] won't work, since nil means we should generate
@@ -34,8 +36,30 @@ module Rswag
swagger_doc.deep_merge!(metadata_to_swagger(metadata))
end
def stop(notification=nil)
def stop(_notification=nil)
@config.swagger_docs.each do |url_path, doc|
## OA3
# # remove 2.0 parameters
# doc[:paths]&.each_pair do |_k, v|
# v.each_pair do |_verb, value|
# is_hash = value.is_a?(Hash)
# if is_hash && value.dig(:parameters)
# schema_param = value&.dig(:parameters)&.find{|p| p[:in] == :body && p[:schema] }
# if value && schema_param && value&.dig(:requestBody, :content, 'application/json')
# value[:requestBody][:content]['application/json'].merge!(schema: schema_param[:schema])
# end
# value[:parameters].reject! { |p| p[:in] == :body || p[:in] == :formData }
# value[:parameters].each { |p| p.delete(:type) }
# value[:headers].each { |p| p.delete(:type)} if value[:headers]
# end
# value.delete(:consumes) if is_hash && value.dig(:consumes)
# value.delete(:produces) if is_hash && value.dig(:produces)
# end
# end
file_path = File.join(@config.swagger_root, url_path)
dirname = File.dirname(file_path)
FileUtils.mkdir_p dirname unless File.exists?(dirname)
@@ -61,12 +85,23 @@ module Rswag
def yaml_prepare(doc)
json_doc = JSON.pretty_generate(doc)
clean_doc = JSON.parse(json_doc)
JSON.parse(json_doc)
end
def metadata_to_swagger(metadata)
response_code = metadata[:response][:code]
response = metadata[:response].reject { |k,v| k == :code }
## OA3
# content_type = metadata[:response][:content].present? ? metadata[:response][:content].keys.first : 'application/json'
# # need to merge in to response
# if response[:examples]&.dig(content_type)
# example = response[:examples].dig(content_type).dup
# schema = response.dig(:content, content_type, :schema)
# new_hash = {example: example}
# new_hash[:schema] = schema if schema
# response.merge!(content: { content_type => new_hash })
# response.delete(:examples)
# end
verb = metadata[:operation][:verb]
operation = metadata[:operation]