31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
# File 'lib/openapi_ruby/adapters/minitest.rb', line 31
def assert_api_response(method, expected_status, params: {}, headers: {}, body: nil, path_params: {}, &block)
context = find_context_for(method, path_params)
raise OpenapiRuby::Error, "No api_path defined for #{method.upcase} in #{self.class}" unless context
operation = context.operations[method.to_s]
raise OpenapiRuby::Error, "No #{method.upcase} operation defined" unless operation
response_ctx = operation.responses[expected_status.to_s]
raise OpenapiRuby::Error, "No response #{expected_status} defined for #{method.upcase}" unless response_ctx
base_path = resolve_base_path(context.schema_name)
path = "#{base_path}#{expand_path(context.path_template, params.merge(path_params))}"
security_params = resolve_security_params(operation, context.schema_name)
security_params.each do |param|
val = params[param[:name].to_sym] || params[param[:name]]
next if val.nil?
case param[:in].to_s
when "header" then [param[:name]] = val
when "query" then params[param[:name]] = val
when "cookie" then ["Cookie"] = "#{param[:name]}=#{val}"
end
end
["Accept"] ||= "application/json"
query_params = params.reject { |k, _| path_param_names(context).include?(k.to_s) }
if body
content_type = operation.request_body_definition&.dig("content")&.keys&.first || "application/json"
request_args = if content_type.include?("form-data") || content_type.include?("x-www-form-urlencoded")
{params: body, headers: }
else
{
params: body.is_a?(String) ? body : body.to_json,
headers: .merge("Content-Type" => content_type)
}
end
if query_params.any?
query_string = query_params.map { |k, v| "#{k}=#{CGI.escape(v.to_s)}" }.join("&")
path = "#{path}?#{query_string}"
end
else
request_args = {params: query_params, headers: }
end
send(method, path, **request_args)
assert_equal expected_status, response.status,
"Expected status #{expected_status}, got #{response.status}\nResponse body: #{response.body}"
if OpenapiRuby.configuration.validate_responses_in_tests && response_ctx.schema_definition
validator = Testing::ResponseValidator.new
body_data = parse_response_body
errors = validator.validate(
response_body: body_data,
status_code: response.status,
response_context: response_ctx
)
assert errors.empty?, "Response validation failed:\n#{errors.join("\n")}"
end
instance_eval(&block) if block
end
|