Gets v3 request example saving as well as response example saving

Adds rubocop to the gemset

adds guard to the gemset for testing
This commit is contained in:
Jay Danielian
2019-07-05 15:59:47 -04:00
parent 5d7fc44af4
commit 297cc447c8
24 changed files with 458 additions and 261 deletions

View File

@@ -1,8 +1,8 @@
# frozen_string_literal: true
module Rswag
module Specs
class Configuration
def initialize(rspec_config)
@rspec_config = rspec_config
end
@@ -12,6 +12,7 @@ module Rswag
if @rspec_config.swagger_root.nil?
raise ConfigurationError, 'No swagger_root provided. See swagger_helper.rb'
end
@rspec_config.swagger_root
end
end
@@ -21,6 +22,7 @@ module Rswag
if @rspec_config.swagger_docs.nil? || @rspec_config.swagger_docs.empty?
raise ConfigurationError, 'No swagger_docs defined. See swagger_helper.rb'
end
@rspec_config.swagger_docs
end
end
@@ -34,6 +36,7 @@ module Rswag
def get_swagger_doc(name)
return swagger_docs.values.first if name.nil?
raise ConfigurationError, "Unknown swagger_doc '#{name}'" unless swagger_docs[name]
swagger_docs[name]
end
end

View File

@@ -1,20 +1,21 @@
# frozen_string_literal: true
module Rswag
module Specs
module ExampleGroupHelpers
def path(template, metadata={}, &block)
def path(template, metadata = {}, &block)
metadata[:path_item] = { template: template }
describe(template, metadata, &block)
end
[ :get, :post, :patch, :put, :delete, :head ].each do |verb|
%i[get post patch put delete head].each do |verb|
define_method(verb) do |summary, &block|
api_metadata = { operation: { verb: verb, summary: summary } }
describe(verb, api_metadata, &block)
end
end
[ :operationId, :deprecated, :security ].each do |attr_name|
%i[operationId deprecated security].each do |attr_name|
define_method(attr_name) do |value|
metadata[:operation][attr_name] = value
end
@@ -23,32 +24,61 @@ module Rswag
# NOTE: 'description' requires special treatment because ExampleGroup already
# defines a method with that name. Provide an override that supports the existing
# functionality while also setting the appropriate metadata if applicable
def description(value=nil)
def description(value = nil)
return super() if value.nil?
metadata[:operation][:description] = value
end
# These are array properties - note the splat operator
[ :tags, :consumes, :produces, :schemes ].each do |attr_name|
%i[tags consumes produces schemes].each do |attr_name|
define_method(attr_name) do |*value|
metadata[:operation][attr_name] = value
end
end
#TODO: look at adding request_body method to handle diffs in Open API 2.0 to 3.0
# NICE TO HAVE
# TODO: update generator templates to include 3.0 syntax
# TODO: setup travis CI?
# MUST HAVES
# TODO: look at adding request_body method to handle diffs in Open API 2.0 to 3.0
# TODO: look at adding examples in content request_body
# https://swagger.io/docs/specification/describing-request-body/
# need to make sure we output requestBody in the swagger generator .json
# also need to make sure that it can handle content: , required: true/false, schema: ref
def request_body(attributes)
# can make this generic, and accept any incoming hash (like parameter method)
attributes.compact!
metadata[:operation][:requestBody] = attributes
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
if passed_examples.first.is_a?(Symbol)
example_key_name = passed_examples.first # can come up with better scheme here
# 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 }
parameter(param_attributes)
end
end
end
def parameter(attributes)
if attributes[:in] && attributes[:in].to_sym == :path
attributes[:required] = true
end
if metadata.has_key?(:operation)
if metadata.key?(:operation)
metadata[:operation][:parameters] ||= []
metadata[:operation][:parameters] << attributes
else
@@ -57,7 +87,7 @@ module Rswag
end
end
def response(code, description, metadata={}, &block)
def response(code, description, metadata = {}, &block)
metadata[:response] = { code: code, description: description }
context(description, metadata, &block)
end
@@ -76,6 +106,7 @@ module Rswag
# rspec-core ExampleGroup
def examples(example = nil)
return super() if example.nil?
metadata[:response][:examples] = example
end
@@ -99,6 +130,21 @@ module Rswag
assert_response_matches_metadata(example.metadata, &block)
example.instance_exec(response, &block) if block_given?
end
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
example.metadata[:response][:examples] = { 'application/json' => JSON.parse(response.body, symbolize_names: true) } unless response.body.to_s.empty?
# save request examples using the let(:param_name) { REQUEST_BODY_HASH } syntax in the test
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
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,9 +1,10 @@
# frozen_string_literal: true
require 'json-schema'
module Rswag
module Specs
class ExtendedSchema < JSON::Schema::Draft4
def initialize
super
@attributes['type'] = ExtendedTypeAttribute
@@ -13,9 +14,9 @@ module Rswag
end
class ExtendedTypeAttribute < JSON::Schema::TypeV4Attribute
def self.validate(current_schema, data, fragments, processor, validator, options={})
def self.validate(current_schema, data, fragments, processor, validator, options = {})
return if data.nil? && (current_schema.schema['nullable'] == true || current_schema.schema['x-nullable'] == true)
super
end
end

View File

@@ -1,9 +1,10 @@
# frozen_string_literal: true
module Rswag
module Specs
class Railtie < ::Rails::Railtie
rake_tasks do
load File.expand_path('../../../tasks/rswag-specs_tasks.rake', __FILE__)
load File.expand_path('../../tasks/rswag-specs_tasks.rake', __dir__)
end
end
end

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'
@@ -5,7 +7,6 @@ require 'json'
module Rswag
module Specs
class RequestFactory
def initialize(config = ::Rswag::Specs.config)
@config = config
end
@@ -38,11 +39,11 @@ module Rswag
def derive_security_params(metadata, swagger_doc)
requirements = metadata[:operation][:security] || swagger_doc[:security] || []
scheme_names = requirements.flat_map { |r| r.keys }
scheme_names = requirements.flat_map(&:keys)
schemes = (swagger_doc[:components][:securitySchemes] || {}).slice(*scheme_names).values
schemes.map do |scheme|
param = (scheme[:type] == :apiKey) ? scheme.slice(:name, :in) : { name: 'Authorization', in: :header }
param = scheme[:type] == :apiKey ? scheme.slice(:name, :in) : { name: 'Authorization', in: :header }
param.merge(type: :string, required: requirements.one?)
end
end
@@ -51,10 +52,11 @@ module Rswag
key = ref.sub('#/parameters/', '').to_sym
definitions = swagger_doc[:parameters]
raise "Referenced parameter '#{ref}' must be defined" unless definitions && definitions[key]
definitions[key]
end
def add_verb(request, metadata)
def add_verb(request, metadata)
request[:verb] = metadata[:operation][:verb]
end
@@ -75,7 +77,7 @@ module Rswag
def build_query_string_part(param, value)
name = param[:name]
return "#{name}=#{value.to_s}" unless param[:type].to_sym == :array
return "#{name}=#{value}" unless param[:type].to_sym == :array
case param[:collectionFormat]
when :ssv
@@ -93,44 +95,44 @@ module Rswag
def add_headers(request, metadata, swagger_doc, parameters, example)
tuples = parameters
.select { |p| p[:in] == :header }
.map { |p| [ p[:name], example.send(p[:name]).to_s ] }
.select { |p| p[:in] == :header }
.map { |p| [p[:name], example.send(p[:name]).to_s] }
# Accept header
produces = metadata[:operation][:produces] || swagger_doc[:produces]
if produces
accept = example.respond_to?(:'Accept') ? example.send(:'Accept') : produces.first
tuples << [ 'Accept', accept ]
accept = example.respond_to?(:Accept) ? example.send(:Accept) : produces.first
tuples << ['Accept', accept]
end
# Content-Type header
consumes = metadata[:operation][:consumes] || swagger_doc[:consumes]
consumes = metadata[:operation][:consumes] || swagger_doc[:consumes]
if consumes
content_type = example.respond_to?(:'Content-Type') ? example.send(:'Content-Type') : consumes.first
tuples << [ 'Content-Type', content_type ]
tuples << ['Content-Type', content_type]
end
# Rails test infrastructure requires rackified headers
rackified_tuples = tuples.map do |pair|
[
case pair[0]
when 'Accept' then 'HTTP_ACCEPT'
when 'Content-Type' then 'CONTENT_TYPE'
when 'Authorization' then 'HTTP_AUTHORIZATION'
else pair[0]
when 'Accept' then 'HTTP_ACCEPT'
when 'Content-Type' then 'CONTENT_TYPE'
when 'Authorization' then 'HTTP_AUTHORIZATION'
else pair[0]
end,
pair[1]
]
end
request[:headers] = Hash[ rackified_tuples ]
request[:headers] = Hash[rackified_tuples]
end
def add_payload(request, parameters, example)
content_type = request[:headers]['CONTENT_TYPE']
return if content_type.nil?
if [ 'application/x-www-form-urlencoded', 'multipart/form-data' ].include?(content_type)
if ['application/x-www-form-urlencoded', 'multipart/form-data'].include?(content_type)
request[:payload] = build_form_payload(parameters, example)
else
request[:payload] = build_json_payload(parameters, example)
@@ -143,14 +145,21 @@ module Rswag
# Rails test infrastructure allows us to send the values directly as a hash
# PROS: simple to implement, CONS: serialization/deserialization is bypassed in test
tuples = parameters
.select { |p| p[:in] == :formData }
.map { |p| [ p[:name], example.send(p[:name]) ] }
Hash[ tuples ]
.select { |p| p[:in] == :formData }
.map { |p| [p[:name], example.send(p[:name])] }
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
return nil unless body_param
# p "example is #{example.send(body_param[:name]).to_json} ** AND body param is #{body_param}" if body_param
# body_param ? example.send(body_param[:name]).to_json : nil
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

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
@@ -41,12 +42,12 @@ module Rswag
response_schema = metadata[:response][:schema]
return if response_schema.nil?
components_schemas = {components: {schemas: swagger_doc[:components][:schemas]}}
components_schemas = { components: { schemas: swagger_doc[:components][:schemas] } }
validation_schema = response_schema
.merge('$schema' => 'http://tempuri.org/rswag/specs/extended_schema')
.merge(components_schemas)
.merge('$schema' => 'http://tempuri.org/rswag/specs/extended_schema')
.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

View File

@@ -1,10 +1,11 @@
# frozen_string_literal: true
require 'active_support/core_ext/hash/deep_merge'
require 'swagger_helper'
module Rswag
module Specs
class SwaggerFormatter
# NOTE: rspec 2.x support
if RSPEC_VERSION > 2
::RSpec::Core::Formatters.register self, :example_group_finished, :stop
@@ -19,22 +20,23 @@ module Rswag
def example_group_finished(notification)
# NOTE: rspec 2.x support
if RSPEC_VERSION > 2
metadata = notification.group.metadata
else
metadata = notification.metadata
end
metadata = if RSPEC_VERSION > 2
notification.group.metadata
else
notification.metadata
end
return unless metadata.key?(:response)
return unless metadata.has_key?(:response)
swagger_doc = @config.get_swagger_doc(metadata[:swagger_doc])
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|
file_path = File.join(@config.swagger_root, url_path)
dirname = File.dirname(file_path)
FileUtils.mkdir_p dirname unless File.exists?(dirname)
FileUtils.mkdir_p dirname unless File.exist?(dirname)
File.open(file_path, 'w') do |file|
file.write(JSON.pretty_generate(doc))
@@ -48,17 +50,31 @@ module Rswag
def metadata_to_swagger(metadata)
response_code = metadata[:response][:code]
response = metadata[:response].reject { |k,v| k == :code }
response = metadata[:response].reject { |k, _v| k == :code }
if response_code.to_s == '201'
# need to merge in to resppnse
if response[:examples]&.dig('application/json')
example = response[:examples].dig('application/json').dup
response.merge!(content: { 'application/json' => { example: example } })
response.delete(:examples)
end
end
verb = metadata[:operation][:verb]
operation = metadata[:operation]
.reject { |k,v| k == :verb }
.merge(responses: { response_code => response })
.reject { |k, _v| k == :verb }
.merge(responses: { response_code => response })
# can remove the 2.0 compliant body incoming parameters
if operation&.dig(:parameters)
operation[:parameters].reject! { |p| p[:in] == :body }
end
path_template = metadata[:path_item][:template]
path_item = metadata[:path_item]
.reject { |k,v| k == :template }
.merge(verb => operation)
.reject { |k, _v| k == :template }
.merge(verb => operation)
{ paths: { path_template => path_item } }
end