repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
CoralineAda/seer | https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/lib/seer/pie_chart.rb | lib/seer/pie_chart.rb | module Seer
# =USAGE
#
# In your controller:
#
# @data = Widgets.all # Must be an array of objects that respond to the specidied data method
# # (In this example, 'quantity'
#
# In your view:
#
# <div id="chart"></div>
#
# <%= Seer::visualize(
# @data,
# :as => :pie_chart,
# :series => {:series_label => 'name', :data_method => 'quantity'},
# :chart_options => {
# :height => 300,
# :width => 300,
# :axis_font_size => 11,
# :title => "Widget Quantities",
# :point_size => 5,
# :is_3_d => true
# }
# )
# -%>
#
# For details on the chart options, see the Google API docs at
# http://code.google.com/apis/visualization/documentation/gallery/piechart.html
#
class PieChart
include Seer::Chart
# Chart options accessors
attr_accessor :background_color, :border_color, :enable_tooltip, :focus_border_color, :height, :is_3_d, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :pie_join_angle, :pie_minimal_angle, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :tooltip_width, :width
# Graph data
attr_accessor :data, :data_method, :data_table, :label_method
def initialize(args={}) #:nodoc:
# Standard options
args.each{ |method,arg| self.send("#{method}=",arg) if self.respond_to?(method) }
# Chart options
args[:chart_options].each{ |method, arg| self.send("#{method}=",arg) if self.respond_to?(method) }
# Handle defaults
@colors ||= args[:chart_options][:colors] || DEFAULT_COLORS
@legend ||= args[:chart_options][:legend] || DEFAULT_LEGEND_LOCATION
@height ||= args[:chart_options][:height] || DEFAULT_HEIGHT
@width ||= args[:chart_options][:width] || DEFAULT_WIDTH
@is_3_d ||= args[:chart_options][:is_3_d]
@data_table = []
end
def data_table #:nodoc:
data.each_with_index do |datum, column|
@data_table << [
" data.setValue(#{column}, 0,'#{datum.send(label_method)}');\r",
" data.setValue(#{column}, 1, #{datum.send(data_method)});\r"
]
end
@data_table
end
def is_3_d #:nodoc:
@is_3_d.blank? ? false : @is_3_d
end
def nonstring_options #:nodoc:
[:colors, :enable_tooltip, :height, :is_3_d, :legend_font_size, :pie_join_angle, :pie_minimal_angle, :title_font_size, :tooltip_font_size, :tooltip_width, :width]
end
def string_options #:nodoc:
[:background_color, :border_color, :focus_border_color, :legend, :legend_background_color, :legend_text_color, :title, :title_color]
end
def to_js #:nodoc:
%{
<script type="text/javascript">
google.load('visualization', '1', {'packages':['piechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
#{data_columns}
#{data_table.join("\r")}
var options = {};
#{options}
var container = document.getElementById('#{self.chart_element}');
var chart = new google.visualization.PieChart(container);
chart.draw(data, options);
}
</script>
}
end
def self.render(data, args) #:nodoc:
graph = Seer::PieChart.new(
:data => data,
:label_method => args[:series][:series_label],
:data_method => args[:series][:data_method],
:chart_options => args[:chart_options],
:chart_element => args[:in_element] || 'chart'
)
graph.to_js
end
end
end
| ruby | MIT | 2419e7a03a0cbf0c320b6cdfdcc902f6cf178709 | 2026-01-04T17:47:08.820980Z | false |
CoralineAda/seer | https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/lib/seer/area_chart.rb | lib/seer/area_chart.rb | module Seer
# =USAGE
#
# In your controller:
#
# @data = Widgets.all # Must be an array, and must respond
# # to the data method specified below (in this example, 'quantity')
#
# @series = @data.map{|w| w.widget_stats} # An array of arrays
#
# In your view:
#
# <div id="chart"></div>
#
# <%= Seer::visualize(
# @data,
# :as => :area_chart,
# :in_element => 'chart',
# :series => {
# :series_label => 'name',
# :data_label => 'date',
# :data_method => 'quantity',
# :data_series => @series
# },
# :chart_options => {
# :height => 300,
# :width => 300,
# :axis_font_size => 11,
# :colors => ['#7e7587','#990000','#009900'],
# :title => "Widget Quantities",
# :point_size => 5
# }
# )
# -%>
#
# For details on the chart options, see the Google API docs at
# http://code.google.com/apis/visualization/documentation/gallery/areachart.html
#
class AreaChart
include Seer::Chart
# Graph options
attr_accessor :axis_color, :axis_background_color, :axis_font_size, :background_color, :border_color, :data_table, :enable_tooltip, :focus_border_color, :height, :is_stacked, :legend, :legend_background_color, :legend_font_size, :legend_text_color, :line_size, :log_scale, :max, :min, :point_size, :reverse_axis, :show_categories, :title, :title_x, :title_y, :title_color, :title_font_size, :tooltip_font_size, :tooltip_height, :number, :tooltip_width, :width
# Graph data
attr_accessor :series_label, :data_label, :data, :data_method, :data_series
def initialize(args={}) #:nodoc:
# Standard options
args.each{ |method,arg| self.send("#{method}=",arg) if self.respond_to?(method) }
# Chart options
args[:chart_options].each{ |method, arg| self.send("#{method}=",arg) if self.respond_to?(method) }
# Handle defaults
@colors ||= args[:chart_options][:colors] || DEFAULT_COLORS
@legend ||= args[:chart_options][:legend] || DEFAULT_LEGEND_LOCATION
@height ||= args[:chart_options][:height] || DEFAULT_HEIGHT
@width ||= args[:chart_options][:width] || DEFAULT_WIDTH
@data_table = []
end
def data_columns #:nodoc:
_data_columns = " data.addRows(#{data_rows.size});\r"
_data_columns << " data.addColumn('string', 'Date');\r"
data.each do |datum|
_data_columns << " data.addColumn('number', '#{datum.send(series_label)}');\r"
end
_data_columns
end
def data_table #:nodoc:
_rows = data_rows
_rows.each_with_index do |r,i|
@data_table << " data.setCell(#{i}, 0,'#{r}');\r"
end
data_series.each_with_index do |column,i|
column.each_with_index do |c,j|
@data_table << " data.setCell(#{j},#{i+1},#{c.send(data_method)});\r"
end
end
@data_table
end
def data_rows
data_series.inject([]) do |rows, element|
rows |= element.map { |e| e.send(data_label) }
end
end
def nonstring_options #:nodoc:
[ :axis_font_size, :colors, :enable_tooltip, :height, :is_stacked, :legend_font_size, :line_size, :log_scale, :max, :min, :point_size, :reverse_axis, :show_categories, :title_font_size, :tooltip_font_size, :tooltip_height, :tooltip_width, :width]
end
def string_options #:nodoc:
[ :axis_color, :axis_background_color, :background_color, :border_color, :focus_border_color, :legend, :legend_background_color, :legend_text_color, :title, :title_x, :title_y, :title_color ]
end
def to_js #:nodoc:
%{
<script type="text/javascript">
google.load('visualization', '1', {'packages':['areachart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
#{data_columns}
#{data_table.join("\r")}
var options = {};
#{options}
var container = document.getElementById('#{self.chart_element}');
var chart = new google.visualization.AreaChart(container);
chart.draw(data, options);
}
</script>
}
end
def self.render(data, args) #:nodoc:
graph = Seer::AreaChart.new(
:data => data,
:series_label => args[:series][:series_label],
:data_series => args[:series][:data_series],
:data_label => args[:series][:data_label],
:data_method => args[:series][:data_method],
:chart_options => args[:chart_options],
:chart_element => args[:in_element] || 'chart'
)
graph.to_js
end
end
end
| ruby | MIT | 2419e7a03a0cbf0c320b6cdfdcc902f6cf178709 | 2026-01-04T17:47:08.820980Z | false |
CoralineAda/seer | https://github.com/CoralineAda/seer/blob/2419e7a03a0cbf0c320b6cdfdcc902f6cf178709/lib/seer/geomap.rb | lib/seer/geomap.rb | module Seer
# Geomap creates a map of a country, continent, or region, with colors and values assigned to
# specific regions. Values are displayed as a color scale, and you can specify optional hovertext
# for regions.
#
# =USAGE=
#
# In your view:
#
# <div id="my_geomap_container" class="chart"></div>
#
# <%= Seer::visualize(
# @locations,
# :as => :geomap,
# :in_element => 'my_geomap_container',
# :series => {
# :series_label => 'name',
# :data_label => '# widgets',
# :data_method => 'widget_count'
# },
# :chart_options => {
# :data_mode => 'regions',
# :region => 'US',
# }
# )
# -%>
#
# ==@locations==
#
# A collection of objects (ActiveRecord or otherwise) that must respond to the
# following methods:
#
# latitude # => returns the latitude in decimal format
# longitude # => returns the longitude in decimal format
# geocoded? # => result of latitude && longitude
#
# For details on the chart options, see the Google API docs at
# http://code.google.com/apis/visualization/documentation/gallery/geomap.html
#
class Geomap
include Seer::Chart
COUNTRY_CODES = ['world', 'AX', 'AF', 'AL', 'DZ', 'AS', 'AD', 'AO', 'AI', 'AQ', 'AG', 'AR', 'AM', 'AW', 'AU', 'AT', 'AZ', 'BS', 'BH', 'BD', 'BB', 'BY', 'BE', 'BZ', 'BJ', 'BM', 'BT', 'BO', 'BA', 'BW', 'BV', 'BR', 'IO', 'BN', 'BG', 'BF', 'BI', 'KH', 'CM', 'CA', 'CV', 'KY', 'CF', 'TD', 'CL', 'CN', 'CX', 'CC', 'CO', 'KM', 'CD', 'CG', 'CK', 'CR', 'CI', 'HR', 'CU', 'CY', 'CZ', 'DK', 'DJ', 'DM', 'DO', 'EC', 'EG', 'SV', 'GQ', 'ER', 'EE', 'ET', 'FK', 'FO', 'FJ', 'FI', 'FR', 'GF', 'PF', 'TF', 'GA', 'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GL', 'GD', 'GP', 'GU', 'GT', 'GN', 'GW', 'GY', 'HT', 'HM', 'HN', 'HK', 'HU', 'IS', 'IN', 'ID', 'IR', 'IQ', 'IE', 'IL', 'IT', 'JM', 'JP', 'JO', 'KZ', 'KE', 'KI', 'KP', 'KR', 'KW', 'KG', 'LA', 'LV', 'LB', 'LS', 'LR', 'LY', 'LI', 'LT', 'LU', 'MO', 'MK', 'MG', 'MW', 'MY', 'MV', 'ML', 'MT', 'MH', 'MQ', 'MR', 'MU', 'YT', 'MX', 'FM', 'MD', 'MC', 'MN', 'MS', 'MA', 'MZ', 'MM', 'NA', 'NR', 'NP', 'NL', 'AN', 'NC', 'NZ', 'NI', 'NE', 'NG', 'NU', 'NF', 'MP', 'NO', 'OM', 'PK', 'PW', 'PS', 'PA', 'PG', 'PY', 'PE', 'PH', 'PN', 'PL', 'PT', 'PR', 'QA', 'RE', 'RO', 'RU', 'RW', 'SH', 'KN', 'LC', 'PM', 'VC', 'WS', 'SM', 'ST', 'SA', 'SN', 'CS', 'SC', 'SL', 'SG', 'SK', 'SI', 'SB', 'SO', 'ZA', 'GS', 'ES', 'LK', 'SD', 'SR', 'SJ', 'SZ', 'SE', 'CH', 'SY', 'TW', 'TJ', 'TZ', 'TH', 'TL', 'TG', 'TK', 'TO', 'TT', 'TN', 'TR', 'TM', 'TC', 'TV', 'UG', 'UA', 'AE', 'GB', 'US', 'us_metro', 'UM', 'UY', 'UZ', 'VU', 'VA', 'VE', 'VN', 'VG', 'VI', 'WF', 'EH', 'YE', 'ZM', 'ZW', '005', '013', '021', '002', '017', '015', '018', '030', '034', '035', '143', '145', '151', '154', '155', '039']
# Chart options accessors
attr_accessor :data_mode, :enable_tooltip, :height, :legend_background_color, :legend_font_size, :legend_text_color, :legend, :region, :show_legend, :show_zoom_out, :title_color, :title_font_size, :title_x, :title_y, :title, :tooltip_font_size, :tooltip_height, :tooltip_width, :width, :zoom_out_label
# Graph data
attr_accessor :data, :data_label, :data_method, :data_table, :label_method
def initialize(args={}) #:nodoc:
# Standard options
args.each{ |method,arg| self.send("#{method}=",arg) if self.respond_to?(method) }
# Chart options
args[:chart_options].each{ |method, arg| self.send("#{method}=",arg) if self.respond_to?(method) }
# Handle defaults
@colors ||= args[:chart_options][:colors] || DEFAULT_COLORS
@legend ||= args[:chart_options][:legend] || DEFAULT_LEGEND_LOCATION
@height ||= args[:chart_options][:height] || DEFAULT_HEIGHT
@width ||= args[:chart_options][:width] || DEFAULT_WIDTH
end
def data_columns #:nodoc:
_data_columns = "data.addRows(#{data_table.size});"
if self.data_mode == 'markers'
_data_columns << %{
data.addColumn('number', 'LATITUDE');
data.addColumn('number', 'LONGITUDE');
data.addColumn('number', '#{data_method}');
data.addColumn('string', '#{label_method}');
}
else
_data_columns << " data.addColumn('string', '#{label_method}');"
_data_columns << " data.addColumn('number', '#{data_method}');"
_data_columns
end
_data_columns
end
def data_mode=(mode) #:nodoc:
raise ArgumentError, "Invalid data mode option: #{mode}. Must be one of 'regions' or 'markers'." unless ['regions', 'markers'].include?(mode)
@data_mode = mode
end
def data_table #:nodoc:
@data_table = []
data.select{ |d| d.geocoded? }.each_with_index do |datum, column|
if data_mode == "markers"
@data_table << [
" data.setValue(#{column}, 0, #{datum.latitude});\r",
" data.setValue(#{column}, 1, #{datum.longitude});\r",
" data.setValue(#{column}, 2, #{datum.send(data_method)});\r",
" data.setValue(#{column}, 3, '#{datum.send(label_method)}');\r"
]
else # Regions
@data_table << [
" data.setValue(#{column}, 0, '#{datum.name}');\r",
" data.setValue(#{column}, 1, #{datum.send(data_method)});\r"
]
end
end
@data_table
end
# Because Google is not consistent in their @#!$ API...
def formatted_colors
"[#{@colors.map{|color| "'#{color.gsub(/\#/,'0x')}'"} * ','}]"
end
def nonstring_options #:nodoc:
[:colors, :enable_tooltip, :height, :legend_font_size, :title_font_size, :tooltip_font_size, :tooltip_width, :width]
end
def string_options #:nodoc:
[:data_mode, :legend, :legend_background_color, :legend_text_color, :title, :title_x, :title_y, :title_color, :region]
end
def to_js
%{
<script type="text/javascript">
google.load('visualization', '1', {'packages':['geomap']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
#{data_columns}
#{data_table.join("\r")}
var options = {};
#{options}
var container = document.getElementById('#{self.chart_element}');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
}
</script>
}
end
def region=(desired_region)
raise ArgumentError, "Invalid region: #{desired_region}" unless COUNTRY_CODES.include?(desired_region)
@region = desired_region
end
# ====================================== Class Methods =========================================
def self.render(data, args)
map = Seer::Geomap.new(
:region => args[:chart_options][:region],
:data_mode => args[:chart_options][:data_mode],
:data => data,
:label_method => args[:series][:series_label],
:data_method => args[:series][:data_method],
:chart_options => args[:chart_options],
:chart_element => args[:in_element] || 'chart'
)
map.to_js
end
end
end
| ruby | MIT | 2419e7a03a0cbf0c320b6cdfdcc902f6cf178709 | 2026-01-04T17:47:08.820980Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser_spec.rb | spec/openapi_parser_spec.rb | require_relative './spec_helper'
require 'uri'
require 'json'
require 'yaml'
require 'pathname'
RSpec.describe OpenAPIParser do
it 'has a version number' do
expect(OpenAPIParser::VERSION).not_to be nil
end
describe 'parse' do
it do
parsed = OpenAPIParser.parse(petstore_schema)
root = OpenAPIParser.parse(petstore_schema, {})
expect(parsed.openapi).to eq root.openapi
end
end
describe 'parse_with_filepath' do
it 'loads correct schema' do
parsed = OpenAPIParser.parse_with_filepath(petstore_schema, petstore_schema_path, {})
root = OpenAPIParser.parse(petstore_schema, {})
expect(parsed.openapi).to eq root.openapi
end
it 'sets @uri' do
parsed = OpenAPIParser.parse_with_filepath(petstore_schema, petstore_schema_path, {})
schema_path = (Pathname.getwd + petstore_schema_path).to_s
expect(parsed.instance_variable_get(:@uri).scheme).to eq "file"
expect(parsed.instance_variable_get(:@uri).path).to eq schema_path
end
it 'does not set @uri when passed filepath is nil' do
parsed = OpenAPIParser.parse_with_filepath(petstore_schema, nil, {})
expect(parsed.instance_variable_get(:@uri)).to be nil
end
end
describe 'load' do
let(:loaded) { OpenAPIParser.load(petstore_schema_path, {}) }
it 'loads correct schema' do
root = OpenAPIParser.parse(petstore_schema, {})
expect(loaded.openapi).to eq root.openapi
end
it 'sets @uri' do
schema_path = (Pathname.getwd + petstore_schema_path).to_s
expect(loaded.instance_variable_get(:@uri).scheme).to eq "file"
expect(loaded.instance_variable_get(:@uri).path).to eq schema_path
end
end
describe 'load_uri' do
context 'with yaml extension' do
let(:schema_registry) { {} }
let(:uri) { URI.join("file:///", (Pathname.getwd + petstore_schema_path).to_s) }
let!(:loaded) { OpenAPIParser.load_uri(uri, config: OpenAPIParser::Config.new({}), schema_registry: schema_registry) }
it 'loads correct schema' do
root = OpenAPIParser.parse(petstore_schema, {})
expect(loaded.openapi).to eq root.openapi
end
it 'sets @uri' do
expect(loaded.instance_variable_get(:@uri)).to eq uri
end
it 'registers schema in schema_registry' do
expect(schema_registry).to eq({ uri => loaded })
end
end
context 'with json extension' do
let(:schema_registry) { {} }
let(:uri) { URI.join("file:///", (Pathname.getwd + json_petstore_schema_path).to_s) }
let!(:loaded) { OpenAPIParser.load_uri(uri, config: OpenAPIParser::Config.new({}), schema_registry: schema_registry) }
it 'loads correct schema' do
root = OpenAPIParser.parse(JSON.parse(IO.read(json_petstore_schema_path)), {})
expect(loaded.openapi).to eq root.openapi
end
it 'sets @uri' do
expect(loaded.instance_variable_get(:@uri)).to eq uri
end
it 'registers schema in schema_registry' do
expect(schema_registry).to eq({ uri => loaded })
end
end
context 'with yaml content and unsupported extension' do
let(:schema_registry) { {} }
let(:uri) { URI.join("file:///", (Pathname.getwd + yaml_with_unsupported_extension_petstore_schema_path).to_s) }
let!(:loaded) { OpenAPIParser.load_uri(uri, config: OpenAPIParser::Config.new({}), schema_registry: schema_registry) }
it 'loads correct schema' do
root = OpenAPIParser.parse(YAML.load_file(yaml_with_unsupported_extension_petstore_schema_path), {})
expect(loaded.openapi).to eq root.openapi
end
it 'sets @uri' do
expect(loaded.instance_variable_get(:@uri)).to eq uri
end
it 'registers schema in schema_registry' do
expect(schema_registry).to eq({ uri => loaded })
end
end
context 'with json content and unsupported extension' do
let(:schema_registry) { {} }
let(:uri) { URI.join("file:///", (Pathname.getwd + json_with_unsupported_extension_petstore_schema_path).to_s) }
let!(:loaded) { OpenAPIParser.load_uri(uri, config: OpenAPIParser::Config.new({}), schema_registry: schema_registry) }
it 'loads correct schema' do
root = OpenAPIParser.parse(JSON.parse(IO.read(json_with_unsupported_extension_petstore_schema_path)), {})
expect(loaded.openapi).to eq root.openapi
end
it 'sets @uri' do
expect(loaded.instance_variable_get(:@uri)).to eq uri
end
it 'registers schema in schema_registry' do
expect(schema_registry).to eq({ uri => loaded })
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/spec_helper.rb | spec/spec_helper.rb | require 'bundler'
if Gem::Version.create(RUBY_VERSION) < Gem::Version.create("3.2.0")
require 'pry'
end
require 'rspec-parameterized'
require 'simplecov'
require 'psych'
SimpleCov.start do
add_filter 'spec'
end
SimpleCov.minimum_coverage 99
require 'openapi_parser'
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = '.rspec_status'
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
def load_yaml_file(path)
Psych.safe_load(open(path).read, permitted_classes: [Date, Time])
end
def normal_schema
load_yaml_file('./spec/data/normal.yml')
end
def broken_reference_schema
load_yaml_file('./spec/data/reference-broken.yaml')
end
def petstore_schema
load_yaml_file(petstore_schema_path)
end
def petstore_schema_path
'./spec/data/petstore-expanded.yaml'
end
def petstore_with_discriminator_schema
load_yaml_file('./spec/data/petstore-with-discriminator.yaml')
end
def petstore_with_mapped_polymorphism_schema
load_yaml_file('./spec/data/petstore-with-mapped-polymorphism.yaml')
end
def petstore_with_polymorphism_schema
load_yaml_file('./spec/data/petstore-with-polymorphism.yaml')
end
def json_petstore_schema_path
'./spec/data/petstore.json'
end
def json_with_unsupported_extension_petstore_schema_path
'./spec/data/petstore.json.unsupported_extension'
end
def yaml_with_unsupported_extension_petstore_schema_path
'./spec/data/petstore.yaml.unsupported_extension'
end
def path_item_ref_schema_path
'./spec/data/path-item-ref.yaml'
end
def path_item_ref_schema
load_yaml_file(path_item_ref_schema_path)
end
def build_validate_test_schema(new_properties)
b = load_yaml_file('./spec/data/validate_test.yaml')
obj = b['paths']['/validate_test']['post']['requestBody']['content']['application/json']['schema']['properties']
obj.merge!(change_string_key(new_properties))
b
end
def change_string_key(hash)
new_data = hash.map do |k, v|
if v.kind_of?(Hash)
[k.to_s, change_string_key(v)]
elsif v.kind_of?(Array)
[k.to_s, v.map { |child| change_string_key(child) }]
else
[k.to_s, v]
end
end
new_data.to_h
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/path_item_ref_spec.rb | spec/openapi_parser/path_item_ref_spec.rb | require_relative '../spec_helper'
RSpec.describe 'path item $ref' do
let(:root) { OpenAPIParser.parse_with_filepath(
path_item_ref_schema, path_item_ref_schema_path, {})
}
let(:request_operation) { root.request_operation(:post, '/ref-sample') }
it 'understands path item $ref' do
ret = request_operation.validate_request_body('application/json', { 'test' => 'test' })
expect(ret).to eq({ 'test' => "test" })
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schema_validator_spec.rb | spec/openapi_parser/schema_validator_spec.rb | require_relative '../spec_helper'
RSpec.describe OpenAPIParser::SchemaValidator do
let(:root) { OpenAPIParser.parse(normal_schema, config) }
let(:config) { {} }
describe 'validate_request_body' do
subject { request_operation.validate_request_body('application/json', params) }
let(:content_type) { 'application/json' }
let(:http_method) { :post }
let(:request_path) { '/validate' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
it 'correct' do
params = [
['string', 'str'],
['integer', 1],
['boolean', true],
['boolean', false],
['number', 0.1],
].to_h
ret = request_operation.validate_request_body(content_type, params)
expect(ret).to eq({ 'boolean' => false, 'integer' => 1, 'number' => 0.1, 'string' => 'str' })
end
it 'number allow integer' do
params = { 'number' => 1 }
ret = request_operation.validate_request_body(content_type, params)
expect(ret).to eq({ 'number' => 1 })
end
it 'correct object data' do
params = {
'object_1' =>
{
'string_1' => nil,
'integer_1' => nil,
'boolean_1' => nil,
'number_1' => nil,
},
}
ret = request_operation.validate_request_body(content_type, params)
expect(ret).to eq({ 'object_1' => { 'boolean_1' => nil, 'integer_1' => nil, 'number_1' => nil, 'string_1' => nil } })
end
it 'invalid params' do
invalids = [
['string', 1],
['string', true],
['string', false],
['integer', '1'],
['integer', 0.1],
['integer', true],
['integer', false],
['boolean', 1],
['boolean', 'true'],
['boolean', 'false'],
['boolean', '0.1'],
['number', '0.1'],
['number', true],
['number', false],
['array', false],
['array', 1],
['array', true],
['array', '1'],
]
invalids.each do |key, value|
params = { key.to_s => value }
expect { request_operation.validate_request_body(content_type, params) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::ValidateError)
expect(e.message).to end_with("expected #{key}, but received #{value.class}: #{value.inspect}")
end
end
end
it 'required params' do
object = {
'string_2' => 'str',
'integer_2' => 1,
'boolean_2' => true,
'number_2' => 0.1,
}
object.keys.each do |key|
deleted_object = object.reject { |k, _v| k == key }
params = { 'object_2' => deleted_object }
expect { request_operation.validate_request_body(content_type, params) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with("missing required parameters: #{key}")
end
end
params = { 'object_2' => {} }
expect { request_operation.validate_request_body(content_type, params) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with("missing required parameters: #{object.keys.join(", ")}")
end
end
context 'nested required params' do
subject { request_operation.validate_request_body(content_type, { 'required_object' => required_object }) }
let(:required_object_base) do
JSON.parse(
{
need_object: {
string: 'abc',
},
no_need_object: {
integer: 1,
},
}.to_json,
)
end
let(:required_object) { required_object_base }
context 'normal' do
it { expect(subject).to eq({ 'required_object' => { 'need_object' => { 'string' => 'abc' }, 'no_need_object' => { 'integer' => 1 } } }) }
end
context 'no need object delete' do
let(:required_object) do
required_object_base.delete 'no_need_object'
required_object_base
end
it { expect(subject).to eq({ 'required_object' => { 'need_object' => { 'string' => 'abc' } } }) }
end
context 'delete required params' do
let(:required_object) do
required_object_base['need_object'].delete 'string'
required_object_base
end
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with('missing required parameters: string')
end
end
end
context 'required object not exist' do
let(:required_object) do
required_object_base.delete 'need_object'
required_object_base
end
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with('missing required parameters: need_object')
end
end
end
end
describe 'array' do
subject { request_operation.validate_request_body(content_type, { 'array' => array_data }) }
context 'correct' do
let(:array_data) { [1] }
it { expect(subject).to eq({ 'array' => [1] }) }
end
context 'other value include' do
let(:array_data) { [1, 1.1] }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::ValidateError)
expect(e.message).to end_with("expected integer, but received Float: 1.1")
end
end
end
context 'empty' do
let(:array_data) { [] }
it { expect(subject).to eq({ 'array' => [] }) }
end
context 'nil' do
let(:array_data) { [nil] }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotNullError)
expect(e.message.include?("does not allow null values")).to eq true
end
end
end
context 'anyOf' do
it do
expect(request_operation.validate_request_body(content_type, { 'any_of' => ['test', true] })).
to eq({ 'any_of' => ['test', true] })
end
it 'invalid' do
expect { request_operation.validate_request_body(content_type, { 'any_of' => [1] }) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotAnyOf)).to eq true
expect(e.message.start_with?("1 isn't any of")).to eq true
end
end
end
context 'anyOf with nullable' do
subject { request_operation.validate_request_body(content_type, { 'any_of_with_nullable' => params }) }
context 'integer' do
let(:params) { 1 }
it { expect(subject).to eq({ 'any_of_with_nullable' => 1 }) }
end
context 'null' do
let(:params) { nil }
it { expect(subject).to eq({ 'any_of_with_nullable' => nil }) }
end
context 'invalid' do
let(:params) { 'foo' }
it { expect { subject }.to raise_error(OpenAPIParser::NotAnyOf) }
end
end
context 'unspecified_type' do
it do
expect(request_operation.validate_request_body(content_type, { 'unspecified_type' => "foo" })).
to eq({ 'unspecified_type' => "foo" })
end
it do
expect(request_operation.validate_request_body(content_type, { 'unspecified_type' => [1, 2] })).
to eq({ 'unspecified_type' => [1, 2] })
end
end
end
describe 'object' do
subject { request_operation.validate_request_body(content_type, { 'object_1' => object_data }) }
context 'correct' do
let(:object_data) { {} }
it { expect(subject).to eq({ 'object_1' => {} }) }
end
context 'not object' do
let(:object_data) { [] }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::ValidateError)
expect(e.message).to end_with("expected object, but received Array: []")
end
end
end
end
describe 'enum' do
context 'enum string' do
it 'include enum' do
['a', 'b'].each do |str|
expect(request_operation.validate_request_body(content_type, { 'enum_string' => str })).
to eq({ 'enum_string' => str })
end
end
it 'not include enum' do
expect { request_operation.validate_request_body(content_type, { 'enum_string' => 'x' }) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotEnumInclude)).to eq true
expect(e.message.start_with?("\"x\" isn't part of the enum")).to eq true
end
end
it 'not include enum (empty string)' do
expect { request_operation.validate_request_body(content_type, { 'enum_string' => '' }) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotEnumInclude)).to eq true
expect(e.message.start_with?("\"\" isn't part of the enum")).to eq true
end
end
end
context 'enum integer' do
it 'include enum' do
[1, 2].each do |str|
expect(request_operation.validate_request_body(content_type, { 'enum_integer' => str })).
to eq({ 'enum_integer' => str })
end
end
it 'not include enum' do
expect { request_operation.validate_request_body(content_type, { 'enum_integer' => 3 }) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotEnumInclude)).to eq true
expect(e.message.start_with?("3 isn't part of the enum")).to eq true
end
end
end
context 'enum number' do
it 'include enum' do
[1.0, 2.1].each do |str|
expect(request_operation.validate_request_body(content_type, { 'enum_number' => str })).
to eq({ 'enum_number' => str })
end
end
it 'not include enum' do
expect { request_operation.validate_request_body(content_type, { 'enum_number' => 1.1 }) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotEnumInclude)).to eq true
expect(e.message.start_with?("1.1 isn't part of the enum")).to eq true
end
end
end
context 'enum boolean' do
it 'include enum' do
expect(request_operation.validate_request_body(content_type, { 'enum_boolean' => true })).
to eq({ 'enum_boolean' => true })
end
it 'not include enum' do
expect { request_operation.validate_request_body(content_type, { 'enum_boolean' => false }) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotEnumInclude)).to eq true
expect(e.message.start_with?("false isn't part of the enum")).to eq true
end
end
end
end
describe 'all_of' do
subject { request_operation.validate_request_body(content_type, { 'all_of_data' => params }) }
let(:correct_params) do
{
'id' => 1,
'name' => 'name_dana',
'tag' => 'tag_data',
}
end
let(:params) { correct_params }
it { expect(subject).not_to eq nil }
context 'option value deleted' do
let(:params) do
d = correct_params
d.delete('tag')
d
end
it { expect(subject).not_to eq nil }
end
context 'not any_of schema in first' do
let(:params) do
d = correct_params
d.delete('name')
d
end
it { expect { subject }.to raise_error(::OpenAPIParser::NotExistRequiredKey) }
end
context 'not any_of schema in second' do
context 'not exist required key' do
let(:params) do
d = correct_params
d.delete('id')
d
end
it { expect { subject }.to raise_error(::OpenAPIParser::NotExistRequiredKey) }
end
context 'type error' do
let(:params) do
correct_params['id'] = 'abc'
correct_params
end
it { expect { subject }.to raise_error(::OpenAPIParser::ValidateError) }
end
end
end
describe 'allOf with nullable' do
context 'with nullable' do
subject { request_operation.validate_request_body(content_type, { 'all_of_with_nullable' => params }) }
context 'integer' do
let(:params) { 1 }
it { expect(subject).to eq({ 'all_of_with_nullable' => 1 }) }
end
context 'null' do
let(:params) { nil }
it { expect(subject).to eq({ 'all_of_with_nullable' => nil }) }
end
context 'invalid' do
let(:params) { 'foo' }
it { expect { subject }.to raise_error(::OpenAPIParser::ValidateError) }
end
end
end
describe 'one_of' do
context 'normal' do
subject { request_operation.validate_request_body(content_type, { 'one_of_data' => params }) }
let(:correct_params) do
{
'name' => 'name',
'integer_1' => 42,
}
end
let(:params) { correct_params }
it { expect(subject).not_to eq nil }
context 'no schema matched' do
let(:params) do
{
'integer_1' => 42,
}
end
it do
expect { subject }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotOneOf)).to eq true
expect(e.message.include?("isn't one of")).to eq true
end
end
end
context 'multiple schema matched' do
let(:params) do
{
'name' => 'name',
'integer_1' => 42,
'string_1' => 'string_1',
}
end
it do
expect { subject }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotOneOf)).to eq true
expect(e.message.include?("isn't one of")).to eq true
end
end
end
end
context 'with discriminator' do
subject { request_operation.validate_request_body(content_type, { 'one_of_with_discriminator' => params }) }
let(:correct_params) do
{
'objType' => 'obj1',
'name' => 'name',
'integer_1' => 42,
}
end
let(:params) { correct_params }
it { expect(subject).not_to eq nil }
end
context 'with nullable' do
subject { request_operation.validate_request_body(content_type, { 'one_of_with_nullable' => params }) }
context 'integer' do
let(:params) { 1 }
it { expect(subject).to eq({ 'one_of_with_nullable' => 1 }) }
end
context 'null' do
let(:params) { nil }
it { expect(subject).to eq({ 'one_of_with_nullable' => nil }) }
end
context 'invalid' do
let(:params) { 'foo' }
it { expect { subject }.to raise_error(OpenAPIParser::NotOneOf) }
end
end
end
it 'unknown param' do
expect { request_operation.validate_request_body(content_type, { 'unknown' => 1 }) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistPropertyDefinition)
expect(e.message).to end_with("does not define properties: unknown")
end
end
end
describe 'coerce' do
subject { request_operation.validate_request_parameter(params, {}) }
let(:config) { { coerce_value: true } }
let(:content_type) { 'application/json' }
let(:http_method) { :get }
let(:request_path) { '/string_params_coercer' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { { key.to_s => value&.to_s } }
let(:nested_array) do
[
{
'update_time' => '2016-04-01T16:00:00.000+09:00',
'per_page' => '1',
'nested_coercer_object' => {
'update_time' => '2016-04-01T16:00:00.000+09:00',
'threshold' => '1.5',
},
'nested_no_coercer_object' => {
'per_page' => '1',
'threshold' => '1.5',
},
'nested_coercer_array' => [
{
'update_time' => '2016-04-01T16:00:00.000+09:00',
'threshold' => '1.5',
},
],
'nested_no_coercer_array' => [
{
'per_page' => '1',
'threshold' => '1.5',
},
],
},
{
'update_time' => '2016-04-01T16:00:00.000+09:00',
'per_page' => '1',
'threshold' => '1.5',
},
{
'threshold' => '1.5',
'per_page' => '1',
},
]
end
context 'request_body' do
subject { request_operation.validate_request_body(content_type, params) }
let(:http_method) { :post }
let(:params) { { 'nested_array' => nested_array } }
let(:config) { { coerce_value: true, datetime_coerce_class: DateTime } }
context 'correct' do
it do
subject
nested_array = params['nested_array']
first_data = nested_array[0]
expect(first_data['update_time'].class).to eq DateTime
expect(first_data['per_page'].class).to eq Integer
end
end
context 'datetime' do
let(:params) { { 'datetime' => datetime_str, 'string' => 'str' } }
let(:request_path) { '/validate' }
let(:datetime_str) { '2016-04-01T16:00:00+09:00' }
it do
subject
expect(params['datetime'].class).to eq DateTime
expect(params['string'].class).to eq String
end
end
context 'overwrite initialize option' do
subject { request_operation.validate_request_body(content_type, params, options) }
let(:options) { OpenAPIParser::SchemaValidator::Options.new(coerce_value: false) }
it do
expect { subject }.to raise_error(OpenAPIParser::ValidateError)
end
end
context 'anyOf' do
where(:before_value, :result_value) do
[
[true, true],
['true', true],
['3.5', 3.5],
[3.5, 3.5],
[10, 10],
['10', 10],
%w[pineapple pineapple]
]
end
with_them do
let(:params) { { 'any_of' => before_value } }
it do
expect(subject).to eq({ 'any_of' => result_value })
expect(params['any_of']).to eq result_value
end
end
end
end
context 'string' do
context "doesn't coerce params not in the schema" do
let(:params) { { 'owner' => 'admin' } }
it do
expect(subject).to eq({ 'owner' => 'admin' })
expect(params['owner']).to eq 'admin'
end
end
context 'skips values for string param' do
let(:params) { { key.to_s => value.to_s } }
let(:key) { 'string_1' }
let(:value) { 'foo' }
it do
expect(subject).to eq({ key.to_s => value.to_s })
expect(params[key]).to eq value
end
end
end
context 'boolean' do
let(:key) { 'boolean_1' }
context 'coerces valid values for boolean param' do
where(:before_value, :result_value) do
[
['true', true],
['false', false],
['1', true],
['0', false],
]
end
with_them do
let(:value) { before_value }
it do
expect(subject).to eq({ key.to_s => result_value })
expect(params[key]).to eq result_value
end
end
end
context 'skips invalid values for boolean param' do
let(:value) { 'foo' }
it do
expect { subject }.to raise_error(OpenAPIParser::ValidateError)
end
end
end
context 'integer' do
let(:key) { 'integer_1' }
context 'coerces valid values for integer param' do
let(:value) { '3' }
let(:params) { { key.to_s => value.to_s } }
it do
expect(subject).to eq({ key.to_s => 3 })
expect(params[key]).to eq 3
end
context 'overwrite initialize option' do
subject { request_operation.validate_request_parameter(params, {}, options) }
let(:options) { OpenAPIParser::SchemaValidator::Options.new(coerce_value: false) }
it do
expect { subject }.to raise_error(OpenAPIParser::ValidateError)
end
end
end
context 'skips invalid values for integer param' do
using RSpec::Parameterized::TableSyntax
where(:before_value) { ['3.5', 'false', ''] }
with_them do
let(:value) { before_value }
it do
expect { subject }.to raise_error(OpenAPIParser::ValidateError)
end
end
end
end
context 'number' do
let(:key) { 'number_1' }
context 'null value is valid' do
let(:value) { nil }
it do
expect(subject).to eq({ key.to_s => nil })
expect(params[key]).to eq(nil)
end
end
context 'coerces valid values for number param' do
where(:before_value, :result_value) do
[
['3', 3.0],
['3.5', 3.5],
]
end
with_them do
let(:value) { before_value }
it do
expect(subject).to eq({ key.to_s => result_value })
expect(params[key]).to eq result_value
end
end
end
context 'invalid values' do
let(:value) { 'false' }
it do
expect { subject }.to raise_error(OpenAPIParser::ValidateError)
end
end
end
describe 'array' do
context 'normal array' do
let(:params) do
{
'normal_array' => [
'1',
],
}
end
it do
expect(subject['normal_array'][0]).to eq 1
expect(params['normal_array'][0]).to eq 1
end
end
context 'nested_array' do
let(:params) do
{ 'nested_array' => nested_array }
end
let(:coerce_date_times) { false }
it do
subject
nested_array = params['nested_array']
first_data = nested_array[0]
expect(first_data['update_time'].class).to eq String
expect(first_data['per_page'].class).to eq Integer
second_data = nested_array[1]
expect(second_data['update_time'].class).to eq String
expect(first_data['per_page'].class).to eq Integer
expect(second_data['threshold'].class).to eq Float
third_data = nested_array[2]
expect(first_data['per_page'].class).to eq Integer
expect(third_data['threshold'].class).to eq Float
expect(first_data['nested_coercer_object']['update_time'].class).to eq String
expect(first_data['nested_coercer_object']['threshold'].class).to eq Float
expect(first_data['nested_no_coercer_object']['per_page'].class).to eq String
expect(first_data['nested_no_coercer_object']['threshold'].class).to eq String
expect(first_data['nested_coercer_array'].first['update_time'].class).to eq String
expect(first_data['nested_coercer_array'].first['threshold'].class).to eq Float
expect(first_data['nested_no_coercer_array'].first['per_page'].class).to eq String
expect(first_data['nested_no_coercer_array'].first['threshold'].class).to eq String
end
end
end
context 'datetime_coercer' do
let(:config) { { coerce_value: true, datetime_coerce_class: DateTime } }
context 'correct datetime' do
let(:params) { { 'datetime_string' => '2016-04-01T16:00:00.000+09:00' } }
it do
expect(subject['datetime_string'].class).to eq DateTime
expect(params['datetime_string'].class).to eq DateTime
end
end
context 'correct Time' do
let(:params) { { 'datetime_string' => '2016-04-01T16:00:00.000+09:00' } }
let(:config) { { coerce_value: true, datetime_coerce_class: Time } }
it do
expect(subject['datetime_string'].class).to eq Time
expect(params['datetime_string'].class).to eq Time
end
end
context 'invalid datetime raise validation error' do
let(:params) { { 'datetime_string' => 'honoka' } }
it { expect { subject }.to raise_error(OpenAPIParser::InvalidDateTimeFormat) }
end
context "don't change object type" do
class HashLikeObject < Hash; end
let(:params) do
h = HashLikeObject.new
h['datetime_string'] = '2016-04-01T16:00:00.000+09:00'
h
end
it do
expect(subject['datetime_string'].class).to eq DateTime
expect(subject.class).to eq HashLikeObject
end
end
context 'nested array' do
let(:params) { { 'nested_array' => nested_array } }
it do
subject
nested_array = params['nested_array']
first_data = nested_array[0]
expect(first_data['update_time'].class).to eq DateTime
second_data = nested_array[1]
expect(second_data['update_time'].class).to eq DateTime
expect(first_data['nested_coercer_object']['update_time'].class).to eq DateTime
expect(first_data['nested_coercer_array'][0]['update_time'].class).to eq DateTime
end
end
end
context 'anyOf' do
let(:key) { 'any_of' }
context 'coerces valid values for any_of param' do
where(:before_value, :result_value) do
[
['true', true],
['3.5', 3.5],
['10', 10]
]
end
with_them do
let(:value) { before_value }
it do
expect(subject).to eq({ key.to_s => result_value })
expect(params[key]).to eq result_value
end
end
end
context 'invalid values' do
let(:value) { 'pineapple' }
it do
expect { subject }.to raise_error(OpenAPIParser::NotAnyOf)
end
end
end
end
describe 'coerce path parameter' do
subject { request_operation.validate_path_params }
let(:content_type) { 'application/json' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:http_method) { :get }
let(:config) { { coerce_value: true } }
context 'correct in operation object' do
let(:request_path) { '/coerce_path_params/1' }
it do
expect(request_operation.path_params).to eq({ 'integer' => '1' })
subject
expect(request_operation.path_params).to eq({ 'integer' => 1 })
end
end
context 'correct in path item object' do
let(:request_path) { '/coerce_path_params_in_path_item/1' }
it do
expect(request_operation.path_params).to eq({ 'integer' => '1' })
subject
expect(request_operation.path_params).to eq({ 'integer' => 1 })
end
end
end
describe 'coerce query parameter' do
subject { request_operation.validate_request_parameter(params, headers) }
let(:root) { OpenAPIParser.parse(normal_schema, config) }
let(:content_type) { 'application/json' }
let(:http_method) { :get }
let(:request_path) { '/coerce_query_prams_in_operation_and_path_item' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
let(:headers) { {} }
let(:config) { { coerce_value: true } }
context 'correct in all params' do
let(:params) { {'operation_integer' => '1', 'path_item_integer' => '2'} }
let(:correct) { {'operation_integer' => 1, 'path_item_integer' => 2} }
it { expect(subject).to eq(correct) }
end
context 'invalid operation integer only' do
let(:params) { {'operation_integer' => '1'} }
it { expect{subject}.to raise_error(OpenAPIParser::NotExistRequiredKey) }
end
context 'invalid path_item integer only' do
let(:params) { {'path_item_integer' => '2'} }
it { expect{subject}.to raise_error(OpenAPIParser::NotExistRequiredKey) }
end
end
describe 'validate header in parameter' do
subject do
request_operation.validate_request_parameter(params, headers)
end
let(:root) { OpenAPIParser.parse(petstore_schema, config) }
let(:content_type) { 'application/json' }
let(:http_method) { :get }
let(:request_path) { '/animals/1' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
let(:headers) { {} }
context 'invalid header' do
context 'path item require' do
let(:headers) { { 'header_2' => 'h' } }
it { expect { subject }.to raise_error(OpenAPIParser::NotExistRequiredKey) }
end
context 'operation require' do
let(:headers) { { 'token' => 1 } }
it { expect { subject }.to raise_error(OpenAPIParser::NotExistRequiredKey) }
end
end
context 'valid header' do
let(:headers) { { 'TOKEN' => 1, 'header_2' => 'h' } }
it { expect(subject).not_to eq nil }
context 'with validate_header = false' do
let(:config) { { validate_header: false } }
context 'path item require' do
let(:headers) { { 'header_2' => 'h' } }
it { expect(subject).not_to eq nil }
end
context 'operation require' do
let(:headers) { { 'token' => 1 } }
it { expect(subject).not_to eq nil }
end
end
end
end
describe 'validatable' do
class ValidatableTest
include OpenAPIParser::SchemaValidator::Validatable
end
describe 'validate_schema' do
subject { ValidatableTest.new.validate_schema(nil, nil) }
it { expect { subject }.to raise_error(StandardError).with_message('implement') }
end
describe 'validate_integer(value, schema)' do
subject { ValidatableTest.new.validate_integer(nil, nil) }
it { expect { subject }.to raise_error(StandardError).with_message('implement') }
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/path_item_finder_spec.rb | spec/openapi_parser/path_item_finder_spec.rb | require_relative '../spec_helper'
RSpec.describe OpenAPIParser::PathItemFinder do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'parse_path_parameters' do
subject { OpenAPIParser::PathItemFinder.new(root.paths) }
it 'matches a single parameter with no additional characters' do
result = subject.parse_path_parameters('{id}', '123')
expect(result).to eq({'id' => '123'})
end
it 'matches a single parameter with extension' do
result = subject.parse_path_parameters('{id}.json', '123.json')
expect(result).to eq({'id' => '123'})
end
it 'matches a single parameter with additional characters' do
result = subject.parse_path_parameters('stuff_{id}_hoge', 'stuff_123_hoge')
expect(result).to eq({'id' => '123'})
end
it 'matches multiple parameters with additional characters' do
result = subject.parse_path_parameters('{stuff_with_underscores-and-hyphens}_{id}_hoge', '4_123_hoge')
expect(result).to eq({'stuff_with_underscores-and-hyphens' => '4', 'id' => '123'})
end
# Open API spec does not specifically define what characters are acceptable as a parameter name,
# so allow everything in between {}.
it 'matches when parameter contains regex characters' do
result = subject.parse_path_parameters('{id?}.json', '123.json')
expect(result).to eq({'id?' => '123'})
result = subject.parse_path_parameters('{id.}.json', '123.json')
expect(result).to eq({'id.' => '123'})
result = subject.parse_path_parameters('{{id}}.json', '{123}.json')
expect(result).to eq({'id' => '123'})
end
it 'fails to match' do
result = subject.parse_path_parameters('stuff_{id}_', '123')
expect(result).to be_nil
result = subject.parse_path_parameters('{p1}-{p2}.json', 'foo.json')
expect(result).to be_nil
result = subject.parse_path_parameters('{p1}.json', 'foo.txt')
expect(result).to be_nil
result = subject.parse_path_parameters('{{id}}.json', '123.json')
expect(result).to be_nil
end
it 'fails to match when a Regex escape character is used in the path' do
result = subject.parse_path_parameters('{id}.json', '123-json')
expect(result).to be_nil
end
it 'fails to match no input' do
result = subject.parse_path_parameters('', '')
expect(result).to be_nil
end
it 'matches when the last character of the variable is the same as the next character' do
result = subject.parse_path_parameters('{p1}schedule', 'adminsschedule')
expect(result).to eq({'p1' => 'admins'})
result = subject.parse_path_parameters('{p1}schedule', 'usersschedule')
expect(result).to eq({'p1' => 'users'})
end
end
describe 'find' do
subject { OpenAPIParser::PathItemFinder.new(root.paths) }
it do
expect(subject.class).to eq OpenAPIParser::PathItemFinder
result = subject.operation_object(:get, '/pets')
expect(result.class).to eq OpenAPIParser::PathItemFinder::Result
expect(result.original_path).to eq('/pets')
expect(result.operation_object.object_reference).to eq root.find_object('#/paths/~1pets/get').object_reference
expect(result.path_params.empty?).to eq true
result = subject.operation_object(:get, '/pets/1')
expect(result.original_path).to eq('/pets/{id}')
expect(result.operation_object.object_reference).to eq root.find_object('#/paths/~1pets~1{id}/get').object_reference
expect(result.path_params['id']).to eq '1'
result = subject.operation_object(:post, '/pets/lessie/adopt/123')
expect(result.original_path).to eq('/pets/{nickname}/adopt/{param_2}')
expect(result.operation_object.object_reference)
.to eq root.find_object('#/paths/~1pets~1{nickname}~1adopt~1{param_2}/post').object_reference
expect(result.path_params['nickname']).to eq 'lessie'
expect(result.path_params['param_2']).to eq '123'
end
it 'matches path items that end in a file extension' do
result = subject.operation_object(:get, '/animals/123/456.json')
expect(result.original_path).to eq('/animals/{groupId}/{id}.json')
expect(result.operation_object.object_reference).to eq root.find_object('#/paths/~1animals~1{groupId}~1{id}.json/get').object_reference
expect(result.path_params['groupId']).to eq '123'
expect(result.path_params['id']).to eq '456'
end
it 'ignores invalid HTTP methods' do
expect(subject.operation_object(:exit, '/pets')).to eq(nil)
expect(subject.operation_object(:blah, '/pets')).to eq(nil)
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/parameter_validator_spec.rb | spec/openapi_parser/parameter_validator_spec.rb | require_relative '../spec_helper'
RSpec.describe OpenAPIParser::ParameterValidator do
let(:root) { OpenAPIParser.parse(normal_schema, config) }
let(:config) { {} }
describe 'validate' do
subject { request_operation.validate_request_parameter(params, {}) }
let(:content_type) { 'application/json' }
let(:http_method) { :get }
let(:request_path) { '/validate' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
context 'correct' do
context 'no optional' do
let(:params) { { 'query_string' => 'query', 'query_integer_list' => [1, 2], 'queryString' => 'Query' } }
it { expect(subject).to eq({ 'query_string' => 'query', 'query_integer_list' => [1, 2], 'queryString' => 'Query' }) }
end
context 'with optional' do
let(:params) { { 'query_string' => 'query', 'query_integer_list' => [1, 2], 'queryString' => 'Query', 'optional_integer' => 1 } }
it { expect(subject).to eq({ 'optional_integer' => 1, 'query_integer_list' => [1, 2], 'queryString' => 'Query', 'query_string' => 'query' }) }
end
end
context 'invalid' do
context 'not exist required' do
context 'not exist data' do
let(:params) { { 'query_integer_list' => [1, 2], 'queryString' => 'Query' } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with('missing required parameters: query_string')
end
end
end
context 'not exist array' do
let(:params) { { 'query_string' => 'query', 'queryString' => 'Query' } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with('missing required parameters: query_integer_list')
end
end
end
end
context 'non null check' do
context 'optional' do
let(:params) { { 'query_string' => 'query', 'query_integer_list' => [1, 2], 'queryString' => 'Query', 'optional_integer' => nil } }
it { expect { subject }.to raise_error(OpenAPIParser::NotNullError) }
end
context 'optional' do
let(:params) { { 'query_string' => 'query', 'query_integer_list' => nil, 'queryString' => 'Query' } }
it { expect { subject }.to raise_error(OpenAPIParser::NotNullError) }
end
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/request_operation_spec.rb | spec/openapi_parser/request_operation_spec.rb | require_relative '../spec_helper'
RSpec.describe OpenAPIParser::RequestOperation do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
let(:config) { OpenAPIParser::Config.new({}) }
let(:path_item_finder) { OpenAPIParser::PathItemFinder.new(root.paths) }
describe 'find' do
it 'no path items' do
ro = OpenAPIParser::RequestOperation.create(:get, '/pets', path_item_finder, config.request_validator_options)
expect(ro.operation_object.object_reference).to eq '#/paths/~1pets/get'
expect(ro.http_method).to eq('get')
expect(ro.path_item.object_id).to eq root.paths.path['/pets'].object_id
end
it 'path items' do
ro = OpenAPIParser::RequestOperation.create(:get, '/pets/1', path_item_finder, config.request_validator_options)
expect(ro.operation_object.object_reference).to eq '#/paths/~1pets~1{id}/get'
expect(ro.path_item.object_id).to eq root.paths.path['/pets/{id}'].object_id
end
it 'no path' do
ro = OpenAPIParser::RequestOperation.create(:get, 'no', path_item_finder, config.request_validator_options)
expect(ro).to eq nil
end
it 'no method' do
ro = OpenAPIParser::RequestOperation.create(:head, '/pets/1', path_item_finder, config.request_validator_options)
expect(ro).to eq nil
end
end
describe 'OpenAPI#request_operation' do
it 'no path items' do
ro = root.request_operation(:get, '/pets')
expect(ro.operation_object.object_reference).to eq '#/paths/~1pets/get'
ro = OpenAPIParser::RequestOperation.create(:head, '/pets/1', path_item_finder, config.request_validator_options)
expect(ro).to eq nil
end
end
describe 'validate_response_body' do
subject { request_operation.validate_response_body(response_body) }
let(:root) { OpenAPIParser.parse(normal_schema, init_config) }
let(:init_config) { {} }
let(:response_body) do
OpenAPIParser::RequestOperation::ValidatableResponseBody.new(status_code, data, headers)
end
let(:headers) { { 'Content-Type' => content_type } }
let(:status_code) { 200 }
let(:http_method) { :post }
let(:content_type) { 'application/json' }
let(:request_operation) { root.request_operation(http_method, '/validate') }
context 'correct' do
let(:data) { { 'string' => 'Honoka.Kousaka' } }
it { expect(subject).to eq({ 'string' => 'Honoka.Kousaka' }) }
end
context 'no content type' do
let(:content_type) { nil }
let(:data) { { 'string' => 1 } }
it { expect(subject).to eq true }
end
context 'with header' do
let(:root) { OpenAPIParser.parse(petstore_schema, init_config) }
let(:http_method) { :get }
let(:request_operation) { root.request_operation(http_method, '/pets') }
let(:headers_base) { { 'Content-Type' => content_type } }
let(:data) { [] }
context 'valid header type' do
let(:headers) { headers_base.merge('x-next': 'next', 'x-limit' => 1) }
it { expect(subject).to eq [] }
end
context 'invalid header type' do
let(:headers) { headers_base.merge('x-next': 'next', 'x-limit' => '1') }
it { expect { subject }.to raise_error(OpenAPIParser::ValidateError) }
end
context 'invalid non-nullbale header value' do
let(:headers) { headers_base.merge('non-nullable-x-limit' => nil) }
it { expect { subject }.to raise_error(OpenAPIParser::NotNullError) }
end
context 'no check option' do
let(:headers) { headers_base.merge('x-next': 'next', 'x-limit' => '1') }
let(:init_config) { { validate_header: false } }
it { expect(subject).to eq [] }
end
end
context 'invalid schema' do
let(:data) { { 'string' => 1 } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::ValidateError)
expect(e.message).to end_with("expected string, but received Integer: 1")
end
end
end
context 'no status code use default' do
let(:status_code) { 419 }
let(:data) { { 'integer' => '1' } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::ValidateError)
expect(e.message).to end_with("expected integer, but received String: \"1\"")
end
end
end
context 'with option' do
context 'strict option' do
let(:http_method) { :put }
context 'method parameter' do
subject { request_operation.validate_response_body(response_body, response_validate_options) }
let(:response_body) do
OpenAPIParser::RequestOperation::ValidatableResponseBody.new(status_code, data, headers)
end
let(:headers) { { 'Content-Type' => content_type } }
let(:response_validate_options) { OpenAPIParser::SchemaValidator::ResponseValidateOptions.new(strict: true) }
let(:data) { {} }
context 'not exist status code' do
let(:status_code) { 201 }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistStatusCodeDefinition)
expect(e.message).to end_with("status code definition does not exist")
end
end
end
context 'not exist content type' do
let(:content_type) { 'application/xml' }
let(:data) { '<something></something>' }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistContentTypeDefinition)
expect(e.message).to end_with("response definition does not exist")
end
end
end
context 'with nil content type when the response body is blank' do
let(:status_code) { 204 }
let(:content_type) { nil }
let(:data) { '' }
let(:http_method) { :get }
it do
expect { subject }.to_not raise_error
expect(subject).to eq true
end
end
end
context 'default parameter' do
subject { request_operation.validate_response_body(response_body) }
let(:data) { {} }
let(:init_config) { { strict_response_validation: true } }
let(:response_body) do
OpenAPIParser::RequestOperation::ValidatableResponseBody.new(status_code, data, headers)
end
let(:headers) { { 'Content-Type' => content_type } }
context 'not exist status code' do
let(:status_code) { 201 }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistStatusCodeDefinition)
expect(e.message).to end_with("status code definition does not exist")
end
end
end
context 'not exist content type' do
let(:content_type) { 'application/xml' }
let(:data) { '<something></something>' }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistContentTypeDefinition)
expect(e.message).to end_with("response definition does not exist")
end
end
end
end
end
end
end
end
RSpec.describe OpenAPIParser::RequestOperation::ValidatableResponseBody do
describe '#content_type' do
context 'when key is lowercase' do
let(:headers) { {"content-type" => "application/json"} }
it 'finds the key' do
expect(
OpenAPIParser::RequestOperation::ValidatableResponseBody.new(nil, nil, headers).content_type
).to eq "application/json"
end
end
context 'when key is mixed case' do
let(:headers) { {"Content-Type" => "application/json"} }
it 'finds the key' do
expect(
OpenAPIParser::RequestOperation::ValidatableResponseBody.new(nil, nil, headers).content_type
).to eq "application/json"
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/concerns/findable_spec.rb | spec/openapi_parser/concerns/findable_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Findable do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'openapi object' do
subject { root }
it do
expect(subject.find_object('#/paths/~1pets/get').object_reference).to eq root.paths.path['/pets'].get.object_reference
expect(subject.find_object('#/components/requestBodies/test_body').object_reference).to eq root.components.request_bodies['test_body'].object_reference
expect(subject.instance_variable_get(:@find_object_cache).size).to eq 2
end
end
describe 'schema object' do
subject { root.paths }
it do
expect(subject.find_object('#/paths/~1pets/get').object_reference).to eq root.paths.path['/pets'].get.object_reference
end
end
describe 'remote reference' do
describe 'local file reference' do
let(:root) { OpenAPIParser.load('spec/data/remote-file-ref.yaml') }
let(:request_operation) { root.request_operation(:post, '/local_file_reference') }
it 'validates request body using schema defined in another openapi yaml file' do
request_operation.validate_request_body('application/json', { 'name' => 'name' })
end
end
describe 'http reference' do
let(:root) { OpenAPIParser.load('spec/data/remote-http-ref.yaml') }
let(:request_operation) { root.request_operation(:post, '/http_reference') }
it 'validates request body using schema defined in openapi yaml file accessed via http' do
request_operation.validate_request_body('application/json', { 'name' => 'name' })
end
end
describe 'cyclic remote reference' do
let(:root) { OpenAPIParser.load('spec/data/cyclic-remote-ref1.yaml') }
let(:request_operation) { root.request_operation(:post, '/cyclic_reference') }
it 'validates request body using schema defined in another openapi yaml file' do
request_operation.validate_request_body('application/json', { 'content' => 1 })
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/concerns/media_type_selectable_spec.rb | spec/openapi_parser/concerns/media_type_selectable_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::MediaTypeSelectable do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe '#select_media_type(content_type, content)' do
subject { media_type_selectable.select_media_type(content_type) }
context '*/* exist' do
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
let(:responses) { operation.responses }
let(:media_type_selectable) { responses.response['200'] }
context 'application/json' do
let(:content_type) { 'application/json' }
it { expect(subject.object_reference.include?('application~1json')).to eq true }
end
context 'application/unknown' do
let(:content_type) { 'application/unknown' }
it { expect(subject.object_reference.include?('application~1unknown')).to eq true }
end
context 'application/abc' do
let(:content_type) { 'application/abc' }
it { expect(subject.object_reference.include?('application~1*')).to eq true }
end
context 'not mach' do
let(:content_type) { 'xyz/abc' }
it { expect(subject.object_reference.include?('*~1*')).to eq true }
end
end
context '*/* not exist' do
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.post }
let(:request_body) { operation.request_body }
let(:media_type_selectable) { request_body }
let(:content_type) { 'application/unknown' }
it 'return nil' do
expect(subject).to eq nil
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/concerns/expandable_spec.rb | spec/openapi_parser/concerns/expandable_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Expandable do
let(:root) { OpenAPIParser.parse(normal_schema, {}) }
describe 'expand_reference' do
subject { root }
it do
subject
expect(subject.find_object('#/paths/~1reference/get/parameters/0').class).to eq OpenAPIParser::Schemas::Parameter
expect(subject.find_object('#/paths/~1reference/get/responses/default').class).to eq OpenAPIParser::Schemas::Response
expect(subject.find_object('#/paths/~1reference/post/responses/default').class).to eq OpenAPIParser::Schemas::Response
path = '#/paths/~1string_params_coercer/post/requestBody/content/application~1json/schema/properties/nested_array'
expect(subject.find_object(path).class).to eq OpenAPIParser::Schemas::Schema
end
context 'undefined spec references' do
let(:invalid_reference) { '#/paths/~1ref-sample~1broken_reference/get/requestBody' }
let(:not_configured) { {} }
let(:raise_on_invalid_reference) { { strict_reference_validation: true } }
let(:misconfiguration) {
{
expand_reference: false,
strict_reference_validation: true
}
}
it 'raises when configured to do so' do
raise_message = "'#/components/requestBodies/foobar' was referenced but could not be found"
expect { OpenAPIParser.parse(broken_reference_schema, raise_on_invalid_reference) }.to(
raise_error(OpenAPIParser::MissingReferenceError) { |error| expect(error.message).to eq(raise_message) }
)
end
it 'does not raise when not configured, returns nil reference' do
subject = OpenAPIParser.parse(broken_reference_schema, not_configured)
expect(subject.find_object(invalid_reference)).to be_nil
end
it 'does not raise when configured, but expand_reference is false' do
subject = OpenAPIParser.parse(broken_reference_schema, misconfiguration)
expect(subject.find_object(invalid_reference)).to be_nil
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/concerns/schema_loader/base_spec.rb | spec/openapi_parser/concerns/schema_loader/base_spec.rb | require_relative '../../../spec_helper'
RSpec.describe OpenAPIParser::SchemaLoader::Base do
describe '#load_data' do
subject { OpenAPIParser::SchemaLoader::Base.new(nil, {}).load_data(nil, nil) }
it { expect { subject }.to raise_error(StandardError).with_message('need implement') }
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/operation_spec.rb | spec/openapi_parser/schemas/operation_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Operation do
let(:root) { OpenAPIParser.parse(petstore_schema, { expand_reference: false }) }
describe '#init' do
subject { path_item.get }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
it do
expect(subject).not_to be nil
expect(subject.object_reference).to eq '#/paths/~1pets/get'
expect(subject.root.object_id).to be root.object_id
end
end
describe 'attributes' do
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
expect(operation.description.start_with?('Returns all pets')).to eq true
expect(operation.tags).to eq ['tag_1', 'tag_2']
expect(operation.summary).to eq 'sum'
expect(operation.operation_id).to eq 'findPets'
expect(operation.deprecated).to eq true
expect(operation.responses.class).to eq OpenAPIParser::Schemas::Responses
expect(operation._openapi_all_child_objects.size).to eq 5 # parameters * 5 + responses
end
end
describe 'parameters' do
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
expect(operation.parameters.size).to eq 4
expect(operation.parameters[0].kind_of?(OpenAPIParser::Schemas::Parameter)).to eq true
expect(operation.parameters[2].kind_of?(OpenAPIParser::Schemas::Reference)).to eq true
end
end
describe 'findable' do
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
expect(operation.find_object('#/paths/~1pets/get').object_reference).to eq operation.object_reference
expect(operation.find_object('#/paths/~1pets/get/1')).to eq nil
expect(operation.find_object('#/paths/~1pets/get/responses').object_reference).to eq operation.responses.object_reference
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/response_spec.rb | spec/openapi_parser/schemas/response_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Response do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'correct init' do
subject { responses.default }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
let(:responses) { operation.responses }
it do
expect(subject.class).to eq OpenAPIParser::Schemas::Response
expect(subject.object_reference).to eq '#/paths/~1pets/get/responses/default'
expect(subject.root.object_id).to be root.object_id
expect(subject.description).to eq 'unexpected error'
expect(subject.content.class).to eq Hash
expect(subject.content['application/json'].class).to eq OpenAPIParser::Schemas::MediaType
expect(subject.content['application/json'].object_reference).to eq '#/paths/~1pets/get/responses/default/content/application~1json'
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/media_type_spec.rb | spec/openapi_parser/schemas/media_type_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::MediaType do
let(:root) { OpenAPIParser.parse(petstore_schema, { expand_reference: false }) }
describe 'correct init' do
subject { request_body.content['application/json'] }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.post }
let(:request_body) { operation.request_body }
it do
expect(subject.class).to eq OpenAPIParser::Schemas::MediaType
expect(subject.object_reference).to eq '#/paths/~1pets/post/requestBody/content/application~1json'
expect(subject.root.object_id).to be root.object_id
expect(subject.schema.class).to eq OpenAPIParser::Schemas::Reference
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/header_spec.rb | spec/openapi_parser/schemas/header_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Header do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'correct init' do
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
let(:response) { operation.responses.response['200'] }
it do
h = response.headers['x-next']
expect(h).not_to be nil
expect(h.object_reference).to eq '#/paths/~1pets/get/responses/200/headers/x-next'
expect(h.root.object_id).to be root.object_id
expect(h.schema.class).to be OpenAPIParser::Schemas::Schema
end
it 'headers reference' do
h = response.headers['x-limit']
expect(h).not_to be nil
expect(h.class).to be OpenAPIParser::Schemas::Header
expect(h.object_reference).to eq '#/components/headers/X-Rate-Limit-Limit'
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/path_item_spec.rb | spec/openapi_parser/schemas/path_item_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::PathItem do
let(:root) { OpenAPIParser.parse(normal_schema, {}) }
describe '#init' do
subject { path_item }
let(:paths) { root.paths }
let(:path_item) { paths.path['/characters'] }
it do
expect(subject).not_to be nil
expect(subject.object_reference).to eq '#/paths/~1characters'
expect(subject.summary).to eq 'summary_text'
expect(subject.description).to eq 'desc'
expect(subject.root.object_id).to be root.object_id
end
end
describe '#parameters' do
subject { path_item }
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
let(:paths) { root.paths }
let(:path_item) { paths.path['/animals/{id}'] }
it do
expect(subject.parameters.size).to eq 2
expect(subject.parameters.first.name).to eq 'id'
end
end
describe '#get' do
subject { path_item.get }
let(:paths) { root.paths }
let(:path_item) { paths.path['/characters'] }
it do
expect(subject).not_to eq nil
expect(subject.kind_of?(OpenAPIParser::Schemas::Operation)).to eq true
expect(subject.object_reference).to eq '#/paths/~1characters/get'
end
end
describe '#post' do
subject { path_item.post }
let(:paths) { root.paths }
let(:path_item) { paths.path['/characters'] }
it do
expect(subject).not_to eq nil
expect(subject.kind_of?(OpenAPIParser::Schemas::Operation)).to eq true
end
end
describe '#head' do
subject { path_item.head }
let(:paths) { root.paths }
let(:path_item) { paths.path['/characters'] }
it do
expect(subject).to eq nil # head is null
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/reference_spec.rb | spec/openapi_parser/schemas/reference_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Reference do
let(:root) { OpenAPIParser.parse(petstore_schema, { expand_reference: false }) }
describe 'correct init' do
subject { operation.parameters[2] }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
expect(subject).not_to be nil
expect(subject.class).to eq OpenAPIParser::Schemas::Reference
expect(subject.object_reference).to eq '#/paths/~1pets/get/parameters/2'
expect(subject.ref).to eq '#/components/parameters/test'
expect(subject.root.object_id).to be root.object_id
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/paths_spec.rb | spec/openapi_parser/schemas/paths_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Paths do
let(:root) { OpenAPIParser.parse(normal_schema, {}) }
describe 'correct init' do
subject { root.paths }
it do
expect(subject).not_to be nil
expect(subject.object_reference).to eq '#/paths'
expect(subject.root.object_id).to be root.object_id
end
end
describe 'invalid schema' do
subject { root.paths }
let(:invalid_schema) do
data = normal_schema
data.delete 'paths'
data
end
let(:root) { OpenAPIParser.parse(invalid_schema, {}) }
it { expect(subject).to eq nil }
end
describe '#path' do
subject { paths.path[path_name] }
let(:paths) { root.paths }
let(:path_name) { '/characters' }
it do
expect(subject).not_to eq nil
expect(subject.kind_of?(OpenAPIParser::Schemas::PathItem)).to eq true
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/schema_spec.rb | spec/openapi_parser/schemas/schema_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Schema do
let(:root) { OpenAPIParser.parse(petstore_schema, { expand_reference: false }) }
describe 'correct init' do
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
parameters = operation.parameters
s = parameters.first.schema
# @type OpenAPIParser::Schemas::Schema s
expect(s).not_to be nil
expect(s.kind_of?(OpenAPIParser::Schemas::Schema)).to eq true
expect(s.root.object_id).to be root.object_id
expect(s.object_reference).to eq '#/paths/~1pets/get/parameters/0/schema'
expect(s.type).to eq 'array'
expect(s.items.class).to eq OpenAPIParser::Schemas::Schema
expect(s.additional_properties.class).to eq OpenAPIParser::Schemas::Schema
s = parameters[1].schema
expect(s.format).to eq 'int32'
expect(s.default).to eq 1
s = parameters[3].schema
expect(s.all_of.size).to eq 2
expect(s.all_of[0].class).to eq OpenAPIParser::Schemas::Reference
expect(s.all_of[1].class).to eq OpenAPIParser::Schemas::Schema
expect(s.properties.class).to eq Hash
expect(s.properties['pop'].class).to eq OpenAPIParser::Schemas::Schema
expect(s.properties['pop'].type).to eq 'string'
expect(s.properties['pop'].read_only).to eq true
expect(s.properties['pop'].example).to eq 'test'
expect(s.properties['pop'].deprecated).to eq true
expect(s.properties['int'].write_only).to eq true
expect(s.additional_properties).to eq true
expect(s.description).to eq 'desc'
expect(s.nullable).to eq true
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/request_body_spec.rb | spec/openapi_parser/schemas/request_body_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::RequestBody do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'correct init' do
subject { operation.request_body }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.post }
it do
expect(subject).not_to be nil
expect(subject.object_reference).to eq '#/paths/~1pets/post/requestBody'
expect(subject.description).to eq 'Pet to add to the store'
expect(subject.required).to eq true
expect(subject.content.class).to eq Hash
expect(subject.root.object_id).to be root.object_id
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/polymorphism_spec.rb | spec/openapi_parser/schemas/polymorphism_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::RequestBody do
let(:content_type) { 'application/json' }
let(:http_method) { :post }
let(:request_path) { '/pet' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
context 'whith discriminator with mapping' do
let(:root) { OpenAPIParser.parse(petstore_with_mapped_polymorphism_schema, {}) }
context 'with valid body' do
let(:body) do
{
"petType" => "Cat",
"name" => "Mr. Cat",
"huntingSkill" => "lazy"
}
end
it 'picks correct object based on mapping and succeeds' do
request_operation.validate_request_body(content_type, body)
end
end
context 'with body missing required value' do
let(:body) do
{
"petType" => "tinyLion",
"name" => "Mr. Cat"
}
end
it 'picks correct object based on mapping and fails' do
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with("missing required parameters: huntingSkill")
end
end
end
context 'with body containing unresolvable discriminator mapping' do
let(:body) do
{
"petType" => "coolCow",
"name" => "Ms. Cow"
}
end
it "throws error" do
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotExistDiscriminatorMappedSchema)).to eq true
expect(e.message).to match("^discriminator mapped schema #/components/schemas/coolCow does not exist.*?$")
end
end
end
context 'with body missing discriminator propertyName' do
let(:body) do
{
"name" => "Mr. Cat",
"huntingSkill" => "lazy"
}
end
it "throws error if discriminator propertyName is not present on object" do
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotExistDiscriminatorPropertyName)).to eq true
expect(e.message).to match("^discriminator propertyName petType does not exist in value.*?$")
end
end
end
end
describe 'discriminator without mapping' do
let(:root) { OpenAPIParser.parse(petstore_with_polymorphism_schema, {}) }
context 'with valid body' do
let(:body) do
{
"petType" => "Cat",
"name" => "Mr. Cat",
"huntingSkill" => "lazy"
}
end
it 'picks correct object based on mapping and succeeds' do
request_operation.validate_request_body(content_type, body)
end
end
context 'with body missing required value' do
let(:body) do
{
"petType" => "Cat",
"name" => "Mr. Cat"
}
end
it 'picks correct object based on mapping and fails' do
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with("missing required parameters: huntingSkill")
end
end
end
context 'with body containing unresolvable discriminator mapping' do
let(:body) do
{
"petType" => "Cow",
"name" => "Ms. Cow"
}
end
it "throws error" do
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotExistDiscriminatorMappedSchema)).to eq true
expect(e.message).to match("^discriminator mapped schema #/components/schemas/Cow does not exist.*?$")
end
end
end
context 'with body missing discriminator propertyName' do
let(:body) do
{
"name" => "Mr. Cat",
"huntingSkill" => "lazy"
}
end
it "throws error if discriminator propertyName is not present on object" do
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotExistDiscriminatorPropertyName)).to eq true
expect(e.message).to match("^discriminator propertyName petType does not exist in value.*?$")
end
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/responses_spec.rb | spec/openapi_parser/schemas/responses_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Responses do
describe 'correct init' do
subject { operation.responses }
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
expect(subject.class).to eq OpenAPIParser::Schemas::Responses
expect(subject.root.object_id).to be root.object_id
expect(subject.object_reference).to eq '#/paths/~1pets/get/responses'
expect(subject.default.class).to eq OpenAPIParser::Schemas::Response
expect(subject.response['200'].class).to eq OpenAPIParser::Schemas::Response
expect(subject.response['200'].object_reference).to eq '#/paths/~1pets/get/responses/200'
end
end
describe '#validate_response_body(status_code, content_type, params)' do
subject { responses.validate(response_body, response_validate_options) }
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
let(:responses) { operation.responses }
let(:content_type) { 'application/json' }
let(:response_validate_options) { OpenAPIParser::SchemaValidator::ResponseValidateOptions.new }
let(:response_body) do
OpenAPIParser::RequestOperation::ValidatableResponseBody.new(status_code, params, headers)
end
let(:headers) { { 'Content-Type' => content_type } }
context '200' do
let(:params) { [{ 'id' => 1, 'name' => 'name' }] }
let(:status_code) { 200 }
it { expect(subject).to eq([{ 'id' => 1, 'name' => 'name' }]) }
end
context '4XX' do
let(:status_code) { 400 }
context 'correct' do
let(:params) { { 'message' => 'error' } }
it { expect(subject).to eq({ 'message' => 'error' }) }
end
context 'invalid (200 response)' do
let(:params) { [{ 'id' => 1, 'name' => 'name' }] }
it { expect { subject }.to raise_error(OpenAPIParser::ValidateError) }
end
end
context '404 (prefer use 4xx)' do
let(:status_code) { 404 }
context 'correct' do
let(:params) { { 'id' => 1 } }
it { expect(subject).to eq({ 'id' => 1 }) }
end
context 'invalid (4xx response)' do
let(:params) { { 'message' => 'error' } }
it { expect { subject }.to raise_error(OpenAPIParser::NotExistRequiredKey) }
end
end
context 'invalid status code use default' do
context 'bigger' do
let(:status_code) { 1400 }
let(:params) { { 'message' => 'error' } }
it { expect { subject }.to raise_error(OpenAPIParser::NotExistRequiredKey) }
end
context 'smaller' do
let(:status_code) { 40 }
let(:params) { { 'message' => 'error' } }
it { expect { subject }.to raise_error(OpenAPIParser::NotExistRequiredKey) }
end
end
end
describe 'response_validate_options' do
subject { responses.validate(response_body, response_validate_options) }
let(:root) { OpenAPIParser.parse(normal_schema, {}) }
let(:paths) { root.paths }
let(:path_item) { paths.path['/date_time'] }
let(:operation) { path_item.get }
let(:responses) { operation.responses }
let(:content_type) { 'application/json' }
let(:validator_options) { {} }
let(:response_validate_options) { OpenAPIParser::SchemaValidator::ResponseValidateOptions.new(**validator_options) }
let(:response_body) do
OpenAPIParser::RequestOperation::ValidatableResponseBody.new(status_code, params, headers)
end
let(:headers) { { 'Content-Type' => content_type } }
context 'allow_empty_date_and_datetime' do
context 'true' do
let(:validator_options) { { allow_empty_date_and_datetime: true } }
context 'date' do
context '200' do
let(:params) { { 'date' => '' } }
let(:status_code) { 200 }
it { expect(subject).to eq({ 'date' => '' }) }
end
context '400' do
let(:params) { { 'date' => '' } }
let(:status_code) { 400 }
it { expect(subject).to eq(nil) }
end
end
context 'date-time' do
context '200' do
let(:params) { { 'date-time' => '' } }
let(:status_code) { 200 }
it { expect(subject).to eq({ 'date-time' => '' }) }
end
context '400' do
let(:params) { { 'date-time' => '' } }
let(:status_code) { 400 }
it { expect(subject).to eq(nil) }
end
end
end
context 'false' do
let(:validator_options) { { allow_empty_date_and_datetime: false } }
context 'date' do
context '200' do
let(:params) { { 'date' => '' } }
let(:status_code) { 200 }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"\" is not conformant with date format")
end
end
end
context '400' do
let(:params) { { 'date' => '' } }
let(:status_code) { 400 }
it { expect(subject).to eq(nil) }
end
end
context 'date-time' do
context '200' do
let(:params) { { 'date-time' => '' } }
let(:status_code) { 200 }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateTimeFormat)
expect(e.message).to end_with("Value: \"\" is not conformant with date-time format")
end
end
end
context '400' do
let(:params) { { 'date-time' => '' } }
let(:status_code) { 400 }
it { expect(subject).to eq(nil) }
end
end
end
end
end
describe 'resolve reference init' do
subject { operation.responses }
let(:schema) { YAML.load_file('./spec/data/reference_in_responses.yaml') }
let(:root) { OpenAPIParser.parse(schema, {}) }
let(:paths) { root.paths }
let(:path_item) { paths.path['/info'] }
let(:operation) { path_item.get }
let(:response_object) { subject.response['200'] }
it do
expect(response_object.class).to eq OpenAPIParser::Schemas::Response
expect(response_object.description).to eq 'reference response'
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/discriminator_spec.rb | spec/openapi_parser/schemas/discriminator_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::RequestBody do
let(:root) { OpenAPIParser.parse(petstore_with_discriminator_schema, {}) }
describe 'discriminator' do
let(:content_type) { 'application/json' }
let(:http_method) { :post }
let(:request_path) { '/save_the_pets' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
it 'picks correct object based on mapping and succeeds' do
body = {
"baskets" => [
{
"name" => "cats",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"milk_stock" => 10
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
it 'picks correct object based on implicit mapping and succeeds' do
body = {
"baskets" => [
{
"name" => "CatBasket",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"milk_stock" => 10
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
it 'picks correct object based on mapping and fails' do
body = {
"baskets" => [
{
"name" => "cats",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"nut_stock" => 10 # passing squirrel attribute here, but discriminator still picks cats and fails
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistPropertyDefinition)
expect(e.message).to end_with("does not define properties: nut_stock")
end
end
it 'picks correct object based on implicit mapping and fails' do
body = {
"baskets" => [
{
"name" => "CatBasket",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"nut_stock" => 10 # passing squirrel attribute here, but discriminator still picks cats and fails
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistPropertyDefinition)
expect(e.message).to end_with("does not define properties: nut_stock")
end
end
it "throws error when discriminator mapping is not found" do
body = {
"baskets" => [
{
"name" => "dogs",
"content" => [
{
"name" => "Mr. Dog",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Dog bruiser",
"nut_stock" => 10
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotExistDiscriminatorMappedSchema)).to eq true
expect(e.message).to match("^discriminator mapped schema #/components/schemas/dogs does not exist.*?$")
end
end
it "throws error if discriminator propertyName is not present on object" do
body = {
"baskets" => [
{
"content" => [
{
"name" => "Mr. Dog",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Dog bruiser",
"milk_stock" => 10
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotExistDiscriminatorPropertyName)).to eq true
expect(e.message).to match("^discriminator propertyName name does not exist in value.*?$")
end
end
end
describe 'discriminator without mapping' do
let(:content_type) { 'application/json' }
let(:http_method) { :post }
let(:request_path) { '/save_the_pets_without_mapping' }
let(:request_operation) { root.request_operation(http_method, request_path) }
it 'picks correct object based on implicit mapping and succeeds' do
body = {
"baskets" => [
{
"name" => "CatBasket",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"milk_stock" => 10
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
it 'picks correct object based on implicit mapping and fails' do
body = {
"baskets" => [
{
"name" => "CatBasket",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"nut_stock" => 10 # passing squirrel attribute here, but discriminator still picks cats and fails
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistPropertyDefinition)
expect(e.message).to end_with("does not define properties: nut_stock")
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/components_spec.rb | spec/openapi_parser/schemas/components_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Components do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'correct init' do
subject { root.find_object('#/components') }
it do
expect(subject.root.object_id).to be root.object_id
expect(subject.class).to eq OpenAPIParser::Schemas::Components
expect(subject.object_reference).to eq '#/components'
expect(subject.parameters['test'].class).to eq OpenAPIParser::Schemas::Parameter
expect(subject.parameters['test_ref'].class).to eq OpenAPIParser::Schemas::Parameter
expect(subject.schemas['Pet'].class).to eq OpenAPIParser::Schemas::Schema
expect(subject.responses['normal'].class).to eq OpenAPIParser::Schemas::Response
expect(subject.request_bodies['test_body'].class).to eq OpenAPIParser::Schemas::RequestBody
expect(subject.request_bodies['test_body'].object_reference).to eq '#/components/requestBodies/test_body'
expect(subject.headers['X-Rate-Limit-Limit'].class).to eq OpenAPIParser::Schemas::Header
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/open_api_spec.rb | spec/openapi_parser/schemas/open_api_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::OpenAPI do
subject { OpenAPIParser.parse(petstore_schema, {}) }
describe 'init' do
it 'correct init' do
expect(subject).not_to be nil
expect(subject.root.object_id).to eq subject.object_id
end
end
describe '#openapi' do
it { expect(subject.openapi).to eq '3.0.0' }
end
describe '#paths' do
it { expect(subject.paths).not_to eq nil }
end
describe '#components' do
it { expect(subject.components).not_to eq nil }
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/base_spec.rb | spec/openapi_parser/schemas/base_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Base do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'inspect' do
subject { root.inspect }
it { expect(subject).to eq '#' }
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schemas/parameter_spec.rb | spec/openapi_parser/schemas/parameter_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::Parameter do
let(:root) { OpenAPIParser.parse(petstore_schema, {}) }
describe 'correct init' do
subject { operation.parameters.first }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
expect(subject).not_to be nil
expect(subject.object_reference).to eq '#/paths/~1pets/get/parameters/0'
expect(subject.root.object_id).to be root.object_id
end
end
describe 'attributes' do
subject { operation.parameters.first }
let(:paths) { root.paths }
let(:path_item) { paths.path['/pets'] }
let(:operation) { path_item.get }
it do
results = {
name: 'tags',
in: 'query',
description: 'tags to filter by',
required: false,
style: 'form',
}
results.each { |k, v| expect(subject.send(k)).to eq v }
expect(subject.allow_empty_value).to eq true
end
end
describe 'header support' do
subject { path_item.parameters.last }
let(:paths) { root.paths }
let(:path_item) { paths.path['/animals/{id}'] }
it do
results = {
name: 'token',
in: 'header',
description: 'token to be passed as a header',
required: true,
style: 'simple',
}
results.each { |k, v| expect(subject.send(k)).to eq v }
expect(subject.schema.type).to eq 'integer'
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schema_validator/array_validator_spec.rb | spec/openapi_parser/schema_validator/array_validator_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::SchemaValidator::ArrayValidator do
let(:replace_schema) { {} }
let(:root) { OpenAPIParser.parse(build_validate_test_schema(replace_schema), config) }
let(:config) { {} }
let(:target_schema) do
root.paths.path['/validate_test'].operation(:post).request_body.content['application/json'].schema
end
let(:options) { ::OpenAPIParser::SchemaValidator::Options.new }
describe 'validate array' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:params) { {} }
let(:replace_schema) do
{
ids: {
type: 'array',
items: { 'type': 'integer' },
maxItems: 2,
minItems: 1,
uniqueItems: true
},
}
end
context 'correct' do
let(:params) { { 'ids' => [1] } }
it { expect(subject).to eq({ 'ids' => [1] }) }
end
context 'invalid' do
context 'max items breached' do
let(:invalid_array) { [1,2,3,4] }
let(:params) { { 'ids' => invalid_array } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::MoreThanMaxItems)
expect(e.message).to end_with("#{invalid_array} contains more than max items")
end
end
end
context 'min items breached' do
let(:invalid_array) { [] }
let(:params) { { 'ids' => invalid_array } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::LessThanMinItems)
expect(e.message).to end_with("#{invalid_array} contains fewer than min items")
end
end
end
context 'unique items breached' do
let(:invalid_array) { [1, 1] }
let(:params) { { 'ids' => invalid_array } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotUniqueItems)
expect(e.message).to end_with("#{invalid_array} contains duplicate items")
end
end
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schema_validator/integer_validator_spec.rb | spec/openapi_parser/schema_validator/integer_validator_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::SchemaValidator::IntegerValidator do
let(:replace_schema) { {} }
let(:root) { OpenAPIParser.parse(build_validate_test_schema(replace_schema), config) }
let(:config) { {} }
let(:target_schema) do
root.paths.path['/validate_test'].operation(:post).request_body.content['application/json'].schema
end
let(:options) { ::OpenAPIParser::SchemaValidator::Options.new }
describe 'validate integer maximum value' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:params) { {} }
let(:replace_schema) do
{
my_integer: {
type: 'integer',
maximum: 10,
},
}
end
context 'correct' do
let(:params) { { 'my_integer' => 10 } }
it { expect(subject).to eq({ 'my_integer' => 10 }) }
end
context 'invalid' do
context 'more than maximum' do
let(:more_than_maximum) { 11 }
let(:params) { { 'my_integer' => more_than_maximum } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::MoreThanMaximum)
expect(e.message).to end_with("#{more_than_maximum} is more than maximum value")
end
end
end
end
end
describe 'validate integer minimum value' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:params) { {} }
let(:replace_schema) do
{
my_integer: {
type: 'integer',
minimum: 10,
},
}
end
context 'correct' do
let(:params) { { 'my_integer' => 10 } }
it { expect(subject).to eq({ 'my_integer' => 10 }) }
end
context 'invalid' do
context 'less than minimum' do
let(:less_than_minimum) { 9 }
let(:params) { { 'my_integer' => less_than_minimum } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::LessThanMinimum)
expect(e.message).to end_with("#{less_than_minimum} is less than minimum value")
end
end
end
end
end
describe 'validate integer exclusiveMaximum value' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:params) { {} }
let(:replace_schema) do
{
my_integer: {
type: 'integer',
maximum: 10,
exclusiveMaximum: true,
},
}
end
context 'correct' do
let(:params) { { 'my_integer' => 9 } }
it { expect(subject).to eq({ 'my_integer' => 9 }) }
end
context 'invalid' do
context 'more than or equal to exclusive maximum' do
let(:more_than_equal_exclusive_maximum) { 10 }
let(:params) { { 'my_integer' => more_than_equal_exclusive_maximum } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::MoreThanExclusiveMaximum)
expect(e.message).to end_with("#{more_than_equal_exclusive_maximum} cannot be more than or equal to exclusive maximum value")
end
end
end
end
end
describe 'validate integer exclusiveMinimum value' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:params) { {} }
let(:replace_schema) do
{
my_integer: {
type: 'integer',
minimum: 10,
exclusiveMinimum: true,
},
}
end
context 'correct' do
let(:params) { { 'my_integer' => 11 } }
it { expect(subject).to eq({ 'my_integer' => 11 }) }
end
context 'invalid' do
context 'less than or equal to exclusive minimum' do
let(:less_than_equal_exclusive_minimum) { 10 }
let(:params) { { 'my_integer' => less_than_equal_exclusive_minimum } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::LessThanExclusiveMinimum)
expect(e.message).to end_with("#{less_than_equal_exclusive_minimum} cannot be less than or equal to exclusive minimum value")
end
end
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schema_validator/base_spec.rb | spec/openapi_parser/schema_validator/base_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::SchemaValidator::Base do
describe '#coerce_and_validate(_value, _schema)' do
subject { OpenAPIParser::SchemaValidator::Base.new(nil, nil).coerce_and_validate(nil, nil) }
it { expect { subject }.to raise_error(StandardError).with_message('need implement') }
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schema_validator/all_of_validator_spec.rb | spec/openapi_parser/schema_validator/all_of_validator_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::Schemas::RequestBody do
let(:root) { OpenAPIParser.parse(petstore_with_discriminator_schema, {}) }
describe 'allOf nested objects' do
let(:content_type) { 'application/json' }
let(:http_method) { :post }
let(:request_path) { '/save_the_pets' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
context "without additionalProperties defined" do
it 'passes when sending all properties' do
body = {
"baskets" => [
{
"name" => "dragon",
"mass" => 10,
"fire_range" => 20
}
]
}
request_operation.validate_request_body(content_type, body)
end
it 'fails when sending unknown properties' do
body = {
"baskets" => [
{
"name" => "dragon",
"mass" => 10,
"fire_range" => 20,
"speed" => 20
}
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistPropertyDefinition)
expect(e.message).to end_with("does not define properties: speed")
end
end
it 'fails when missing required property' do
body = {
"baskets" => [
{
"name" => "dragon",
"mass" => 10,
}
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with("missing required parameters: fire_range")
end
end
end
context "with additionalProperties defined" do
it 'passes when sending all properties' do
body = {
"baskets" => [
{
"name" => "hydra",
"mass" => 10,
"head_count" => 20
}
]
}
request_operation.validate_request_body(content_type, body)
end
it 'succeeds when sending unknown properties of correct type based on additionalProperties' do
body = {
"baskets" => [
{
"name" => "hydra",
"mass" => 10,
"head_count" => 20,
"speed" => "20"
}
]
}
request_operation.validate_request_body(content_type, body)
end
it 'allows sending unknown properties of incorrect type based on additionalProperties when nested' do
body = {
"baskets" => [
{
"name" => "hydra",
"mass" => 10,
"head_count" => 20,
"speed" => 20
}
]
}
# TODO for now we don't validate on additionalProperites, but this should fail on speed have to be string
request_operation.validate_request_body(content_type, body)
end
it 'fails when missing required property' do
body = {
"baskets" => [
{
"name" => "hydra",
"mass" => 10,
}
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistRequiredKey)
expect(e.message).to end_with("missing required parameters: head_count")
end
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schema_validator/string_validator_spec.rb | spec/openapi_parser/schema_validator/string_validator_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::SchemaValidator::StringValidator do
let(:replace_schema) { {} }
let(:root) { OpenAPIParser.parse(build_validate_test_schema(replace_schema), config) }
let(:config) { {} }
let(:target_schema) do
root.paths.path['/validate_test'].operation(:post).request_body.content['application/json'].schema
end
let(:options) { ::OpenAPIParser::SchemaValidator::Options.new }
describe 'validate string pattern' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:params) { {} }
let(:replace_schema) do
{
number_str: {
type: 'string',
pattern: '[0-9]+:[0-9]+',
},
}
end
context 'correct' do
let(:params) { { 'number_str' => '11:22' } }
it { expect(subject).to eq({ 'number_str' => '11:22' }) }
end
context 'invalid' do
let(:invalid_str) { '11922' }
let(:params) { { 'number_str' => invalid_str } }
context 'error pattern' do
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidPattern)
expect(e.message).to end_with("pattern [0-9]+:[0-9]+ does not match value: #{invalid_str.inspect}")
end
end
end
context 'error pattern with example' do
let(:replace_schema) do
{
number_str: {
type: 'string',
pattern: '[0-9]+:[0-9]+',
example: '11:22'
},
}
end
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidPattern)
expect(e.message).to end_with("pattern [0-9]+:[0-9]+ does not match value: #{invalid_str.inspect}, example: 11:22")
end
end
end
end
end
describe 'validate string length' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
describe 'validate max length' do
let(:params) { {} }
let(:replace_schema) do
{
str: {
type: 'string',
maxLength: 5,
},
}
end
context 'valid' do
let(:value) { 'A' * 5 }
let(:params) { { 'str' => value } }
it { is_expected.to eq({ 'str' => value }) }
end
context 'invalid' do
context 'more than max' do
let(:value) { 'A' * 6 }
let(:params) { { 'str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::MoreThanMaxLength)
expect(e.message).to end_with("#{value.inspect} is longer than max length")
end
end
end
end
end
describe 'validate min length' do
let(:params) { {} }
let(:replace_schema) do
{
str: {
type: 'string',
minLength: 5,
},
}
end
context 'valid' do
let(:value) { 'A' * 5 }
let(:params) { { 'str' => value } }
it { is_expected.to eq({ 'str' => value }) }
end
context 'invalid' do
context 'less than min' do
let(:value) { 'A' * 4 }
let(:params) { { 'str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::LessThanMinLength)
expect(e.message).to end_with("#{value.inspect} is shorter than min length")
end
end
end
end
end
end
describe 'validate email format' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:params) { {} }
let(:replace_schema) do
{
email_str: {
type: 'string',
format: 'email',
},
}
end
context 'correct' do
let(:params) { { 'email_str' => 'hello@example.com' } }
it { expect(subject).to eq({ 'email_str' => 'hello@example.com' }) }
end
context 'invalid' do
context 'error pattern' do
let(:value) { 'not_email' }
let(:params) { { 'email_str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidEmailFormat)
expect(e.message).to end_with("email address format does not match value: \"not_email\"")
end
end
end
end
end
describe 'validate uuid format' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:params) { {} }
let(:replace_schema) do
{
uuid_str: {
type: 'string',
format: 'uuid',
},
}
end
context 'correct' do
context 'lowercase' do
let(:params) { { 'uuid_str' => 'fd33fb1e-b1f6-401e-994d-8a2545e1aef7' } }
it { expect(subject).to eq({ 'uuid_str' => 'fd33fb1e-b1f6-401e-994d-8a2545e1aef7' }) }
end
context 'uppercase' do
let(:params) { { 'uuid_str' => 'FD33FB1E-B1F6-401E-994D-8A2545E1AEF7' } }
it { expect(subject).to eq({ 'uuid_str' => 'FD33FB1E-B1F6-401E-994D-8A2545E1AEF7' }) }
end
end
context 'invalid' do
%w[
not_uuid
zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz
204730d-fd3f5-364b-9aeb-d1372aba0d35
204730df_d3f5_364b_9aeb_d1372aba0d35
204730df-d3f5-364b-9aeb-d1372aba0d35-deadbeef
deadbeef-204730df-d3f5-364b-9aeb-d1372aba0d35
].each do |invalid_uuid|
context 'error pattern' do
let(:params) { { 'uuid_str' => invalid_uuid } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidUUIDFormat)
expect(e.message).to end_with("Value: \"#{invalid_uuid}\" is not conformant with UUID format")
end
end
end
end
end
end
describe 'validate date format' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:params) { {} }
let(:replace_schema) do
{
date_str: {
type: 'string',
format: 'date',
},
}
end
context 'correct' do
let(:options) { ::OpenAPIParser::SchemaValidator::Options.new(coerce_value: true, date_coerce_class: date_coerce_class) }
let(:params) { { 'date_str' => '2021-02-12' } }
context 'when date_coerce_class is nil' do
let(:date_coerce_class) { nil }
it 'return String' do
expect(subject).to eq({ 'date_str' => '2021-02-12' })
end
end
context 'when date_coerce_class is Date' do
let(:date_coerce_class) { Date }
it 'return Date' do
expect(subject).to eq({ 'date_str' => Date.iso8601('2021-02-12') })
end
end
end
context 'invalid' do
context 'arbitrary string' do
let(:value) { 'not_date' }
let(:params) { { 'date_str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"#{value}\" is not conformant with date format")
end
end
end
context 'incomplete date string (2 digit year)' do
let(:value) { '12-12-12' }
let(:params) { { 'date_str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"#{value}\" is not conformant with date format")
end
end
end
context 'invalid date string format (/ separator)' do
let(:value) { '12/12/12' }
let(:params) { { 'date_str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"#{value}\" is not conformant with date format")
end
end
end
context 'date with YY-MM-DD' do
let(:value) { '21-02-12' }
let(:params) { { 'date_str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"21-02-12\" is not conformant with date format")
end
end
end
context 'date with YYYYMMDD' do
let(:value) { '20210212' }
let(:params) { { 'date_str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"20210212\" is not conformant with date format")
end
end
end
context 'date with YYMMDD' do
let(:value) { '210212' }
let(:params) { { 'date_str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"210212\" is not conformant with date format")
end
end
end
context 'datetime' do
let(:value) { '2021-02-12T12:59:00.000+09:00' }
let(:params) { { 'date_str' => value } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"2021-02-12T12:59:00.000+09:00\" is not conformant with date format")
end
end
end
end
context 'when allow_empty_date_and_datetime is true' do
let(:options) { ::OpenAPIParser::SchemaValidator::Options.new(allow_empty_date_and_datetime: true) }
context 'empty string' do
let(:params) { { 'date_str' => '' } }
it { expect(subject).to eq({ 'date_str' => '' }) }
end
end
context 'when allow_empty_date_and_datetime is false' do
let(:options) { ::OpenAPIParser::SchemaValidator::Options.new(allow_empty_date_and_datetime: false) }
context 'empty string' do
let(:params) { { 'date_str' => '' } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateFormat)
expect(e.message).to end_with("Value: \"\" is not conformant with date format")
end
end
end
end
end
describe 'validate date-time format' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:replace_schema) do
{
datetime_str: {
type: 'string',
format: 'date-time',
},
}
end
context 'correct' do
let(:options) { ::OpenAPIParser::SchemaValidator::Options.new(coerce_value: true, datetime_coerce_class: datetime_coerce_class) }
let(:params) { { 'datetime_str' => '2022-01-01T12:59:00.000+09:00' } }
context 'when datetime_coerce_class is nil' do
let(:datetime_coerce_class) { nil }
it 'return String' do
expect(subject).to eq({ 'datetime_str' => '2022-01-01T12:59:00.000+09:00' })
end
end
context 'when datetime_coerce_class is Time' do
let(:datetime_coerce_class) { Time }
it 'return Time' do
expect(subject).to eq({ 'datetime_str' => DateTime.rfc3339('2022-01-01T12:59:00.000+09:00').to_time })
end
end
context 'when datetime_coerce_class is DateTime' do
let(:datetime_coerce_class) { DateTime }
it 'return DateTime' do
expect(subject).to eq({ 'datetime_str' => DateTime.rfc3339('2022-01-01T12:59:00.000+09:00') })
end
end
end
context 'invalid' do
context 'arbitrary string' do
let(:params) { { 'datetime_str' => 'not_date' } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateTimeFormat)
expect(e.message).to end_with("Value: \"not_date\" is not conformant with date-time format")
end
end
end
context 'datetime without timezone' do
let(:params) { { 'datetime_str' => '2022-01-01T12:59:00.000' } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateTimeFormat)
expect(e.message).to end_with("Value: \"2022-01-01T12:59:00.000\" is not conformant with date-time format")
end
end
end
end
context 'when allow_empty_date_and_datetime is true' do
let(:options) { ::OpenAPIParser::SchemaValidator::Options.new(allow_empty_date_and_datetime: true) }
context 'empty string' do
let(:params) { { 'datetime_str' => '' } }
it { expect(subject).to eq({ 'datetime_str' => '' }) }
end
end
context 'when allow_empty_date_and_datetime is false' do
let(:options) { ::OpenAPIParser::SchemaValidator::Options.new(allow_empty_date_and_datetime: false) }
context 'empty string' do
let(:params) { { 'datetime_str' => '' } }
it do
expect { subject }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::InvalidDateTimeFormat)
expect(e.message).to end_with("Value: \"\" is not conformant with date-time format")
end
end
end
end
end
describe 'validate binary format' do
subject { OpenAPIParser::SchemaValidator.validate(params, target_schema, options) }
let(:replace_schema) do
{
binary: {
type: 'string',
format: 'binary',
},
}
end
context 'correct' do
context 'arbitrary object except string' do
let(:params) { { 'binary' => ['b', 'i', 'n', 'a', 'r', 'y'] } }
it { expect(subject).to eq({ 'binary' => ['b', 'i', 'n', 'a', 'r', 'y'] }) }
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/spec/openapi_parser/schema_validator/object_validator_spec.rb | spec/openapi_parser/schema_validator/object_validator_spec.rb | require_relative '../../spec_helper'
RSpec.describe OpenAPIParser::SchemaValidator::ObjectValidator do
before do
@validator = OpenAPIParser::SchemaValidator::ObjectValidator.new(nil, nil)
@root = OpenAPIParser.parse(
'openapi' => '3.0.0',
'components' => {
'schemas' => {
'object_with_required_but_no_properties' => {
'type' => 'object',
'required' => ['id'],
},
},
},
)
end
it 'shows error when required key is absent' do
schema = @root.components.schemas['object_with_required_but_no_properties']
_value, e = *@validator.coerce_and_validate({}, schema)
expect(e&.message).to match('.* missing required parameters: id')
end
end
RSpec.describe OpenAPIParser::Schemas::RequestBody do
describe 'object properties' do
context 'discriminator check' do
let(:content_type) { 'application/json' }
let(:http_method) { :post }
let(:request_path) { '/save_the_pets' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
let(:root) { OpenAPIParser.parse(petstore_with_discriminator_schema, {}) }
it 'throws error when sending unknown property key with no additionalProperties defined' do
body = {
"baskets" => [
{
"name" => "cats",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"milk_stock" => 10,
"unknown_key" => "value"
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistPropertyDefinition)
expect(e.message).to end_with("does not define properties: unknown_key")
end
end
it 'throws error when sending multiple unknown property keys with no additionalProperties defined' do
body = {
"baskets" => [
{
"name" => "cats",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"milk_stock" => 10,
"unknown_key" => "value",
"another_unknown_key" => "another_value"
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotExistPropertyDefinition)
expect(e.message).to end_with("does not define properties: unknown_key, another_unknown_key")
end
end
it 'succeeds with unknown property key if additionalProperties is true' do
body = {
"baskets" => [
{
"name" => "squirrels",
"content" => [
{
"name" => "Mrs. Squirrel",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Squirrel superhero",
"nut_stock" => 10,
"unknown_key" => "value"
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
it 'succeeds with typed additionalProperties with correct type' do
body = {
"baskets" => [
{
"name" => "rabbit",
"ears" => "floppy"
}
]
}
request_operation.validate_request_body(content_type, body)
end
it 'fails with typed additionalProperties with incorrect type' do
body = {
"baskets" => [
{
"name" => "rabbit",
"ears" => 2
}
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::ValidateError)
expect(e.message).to end_with("additionalProperties expected string, but received Integer: 2")
end
end
it 'throws error when sending nil disallowed in allOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"required_combat_style" => nil,
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::NotNullError)
expect(e.message).to end_with("does not allow null values")
end
end
it 'passing when sending nil nested to anyOf that is allowed' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"optional_combat_style" => nil,
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
it 'throws error when unknown attribute nested in allOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"required_combat_style" => {
"bo_color" => "brown",
"grappling_hook_length" => 10.2
},
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotAnyOf)).to eq true
expect(e.message).to match("^.*?(isn't any of).*?$")
end
end
it 'passes error with correct attributes nested in allOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"required_combat_style" => {
"bo_color" => "brown",
"shuriken_count" => 10
},
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
it 'throws error when unknown attribute nested in allOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"optional_combat_style" => {
"bo_color" => "brown",
"grappling_hook_length" => 10.2
},
}
]
},
]
}
expect { request_operation.validate_request_body(content_type, body) }.to raise_error do |e|
expect(e.kind_of?(OpenAPIParser::NotAnyOf)).to eq true
expect(e.message).to match("^.*?(isn't any of).*?$")
end
end
it 'passes error with correct attributes nested in anyOf' do
body = {
"baskets" => [
{
"name" => "turtles",
"content" => [
{
"name" => "Mr. Cat",
"born_at" => "2019-05-16T11:37:02.160Z",
"description" => "Cat gentleman",
"optional_combat_style" => {
"bo_color" => "brown",
"shuriken_count" => 10
},
}
]
},
]
}
request_operation.validate_request_body(content_type, body)
end
end
context 'properties number check' do
let(:root) { OpenAPIParser.parse(schema, {}) }
let(:schema) do
s = build_validate_test_schema(replace_schema)
obj = s['paths']['/validate_test']['post']['requestBody']['content']['application/json']['schema']
obj['maxProperties'] = 3
obj['minProperties'] = 1
s
end
let(:content_type) { 'application/json' }
let(:request_operation) { root.request_operation(:post, '/validate_test') }
let(:params) { { 'query_string' => 'query' } }
let(:replace_schema) { {} }
it { expect(request_operation.validate_request_body(content_type, params)).to eq(params) }
context 'invalid' do
context 'less than minProperties' do
let(:params) { {} }
it do
expect { expect(request_operation.validate_request_body(content_type, params)) }.to raise_error do |e|
expect(e).to be_kind_of(OpenAPIParser::LessThanMinProperties)
expect(e.message).to end_with("0 is less than minProperties value")
end
end
end
context 'more than maxProperties' do
let(:params) { super().merge({ a: 1, b: 1, c: 2 }) }
it do
expect { expect(request_operation.validate_request_body(content_type, params)) }.to raise_error do |e|
p e
expect(e).to be_kind_of(OpenAPIParser::MoreThanMaxProperties)
expect(e.message).to end_with("4 is more than maxProperties value")
end
end
end
end
end
context 'additional_properties check' do
subject { request_operation.validate_request_body(content_type, JSON.load(params.to_json)) }
let(:root) { OpenAPIParser.parse(schema, {}) }
let(:schema) { build_validate_test_schema(replace_schema) }
let(:content_type) { 'application/json' }
let(:http_method) { :post }
let(:request_path) { '/validate_test' }
let(:request_operation) { root.request_operation(http_method, request_path) }
let(:params) { {} }
context 'no additional_properties' do
let(:replace_schema) do
{
query_string: {
type: 'string',
},
}
end
let(:params) { { 'query_string' => 'query' } }
it { expect(subject).to eq({ 'query_string' => 'query'}) }
end
context 'additional_properties = default' do
let(:replace_schema) do
{
query_string: {
type: 'string',
},
}
end
let(:params) { { 'query_string' => 'query', 'unknown' => 1 } }
it { expect(subject).to eq({ 'query_string' => 'query', 'unknown' => 1 }) }
end
context 'additional_properties = false' do
let(:schema) do
s = build_validate_test_schema(replace_schema)
obj = s['paths']['/validate_test']['post']['requestBody']['content']['application/json']['schema']
obj['additionalProperties'] = { 'type' => 'string' }
s
end
let(:replace_schema) do
{
query_string: {
type: 'string',
},
}
end
let(:params) { { 'query_string' => 'query', 'unknown' => 1 } }
# TODO: we need to perform a validation based on schema.additional_properties here, if
it { expect(params).to eq({ 'query_string' => 'query', 'unknown' => 1 }) }
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser.rb | lib/openapi_parser.rb | require 'uri'
require 'time'
require 'json'
require 'psych'
require 'pathname'
require 'open-uri'
require 'openapi_parser/version'
require 'openapi_parser/config'
require 'openapi_parser/errors'
require 'openapi_parser/concern'
require 'openapi_parser/schemas'
require 'openapi_parser/path_item_finder'
require 'openapi_parser/request_operation'
require 'openapi_parser/schema_validator'
require 'openapi_parser/parameter_validator'
require 'openapi_parser/reference_expander'
module OpenAPIParser
class << self
# Load schema hash object. Uri is not set for returned schema.
# @return [OpenAPIParser::Schemas::OpenAPI]
def parse(schema, config = {})
load_hash(schema, config: Config.new(config), uri: nil, schema_registry: {})
end
# @param filepath [String] Path of the file containing the passed schema.
# Used for resolving remote $ref if provided.
# If file path is relative, it is resolved using working directory.
# @return [OpenAPIParser::Schemas::OpenAPI]
def parse_with_filepath(schema, filepath, config = {})
load_hash(schema, config: Config.new(config), uri: filepath && file_uri(filepath), schema_registry: {})
end
# Load schema in specified filepath. If file path is relative, it is resolved using working directory.
# @return [OpenAPIParser::Schemas::OpenAPI]
def load(filepath, config = {})
load_uri(file_uri(filepath), config: Config.new(config), schema_registry: {})
end
# Load schema located by the passed uri. Uri must be absolute.
# @return [OpenAPIParser::Schemas::OpenAPI]
def load_uri(uri, config:, schema_registry:)
# Open-uri doesn't open file scheme uri, so we try to open file path directly
# File scheme uri which points to a remote file is not supported.
uri_path = uri.path
raise "file not found" if uri_path.nil?
content = if uri.scheme == 'file'
open(uri_path)&.read
elsif uri.is_a?(OpenURI::OpenRead)
uri.open()&.read
end
extension = Pathname.new(uri_path).extname
load_hash(parse_file(content, extension), config: config, uri: uri, schema_registry: schema_registry)
end
private
def file_uri(filepath)
path = Pathname.new(filepath)
path = Pathname.getwd + path if path.relative?
URI.join("file:///", path.to_s)
end
def parse_file(content, ext)
case ext.downcase
when '.yaml', '.yml'
parse_yaml(content)
when '.json'
parse_json(content)
else
# When extension is something we don't know, try to parse as json first. If it fails, parse as yaml
begin
parse_json(content)
rescue JSON::ParserError
parse_yaml(content)
end
end
end
def parse_yaml(content)
Psych.safe_load(content, permitted_classes: [Date, Time])
end
def parse_json(content)
raise "json content is nil" unless content
JSON.parse(content)
end
def load_hash(hash, config:, uri:, schema_registry:)
root = Schemas::OpenAPI.new(hash, config, uri: uri, schema_registry: schema_registry)
OpenAPIParser::ReferenceExpander.expand(root, config.strict_reference_validation) if config.expand_reference
# TODO: use callbacks
root.paths&.path&.values&.each do | path_item |
path_item.set_path_item_to_operation
end
root
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/reference_expander.rb | lib/openapi_parser/reference_expander.rb | class OpenAPIParser::ReferenceExpander
class << self
# @param [OpenAPIParser::Schemas::OpenAPI] openapi
def expand(openapi, validate_references)
openapi.expand_reference(openapi, validate_references)
openapi.purge_object_cache
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/version.rb | lib/openapi_parser/version.rb | module OpenAPIParser
VERSION = '2.3.1'.freeze
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/errors.rb | lib/openapi_parser/errors.rb | module OpenAPIParser
class OpenAPIError < StandardError
def initialize(reference)
@reference = reference
end
end
class MissingReferenceError < OpenAPIError
def message
"'#{@reference}' was referenced but could not be found"
end
end
class ValidateError < OpenAPIError
def initialize(data, type, reference)
super(reference)
@data = data
@type = type
end
def message
"#{@reference} expected #{@type}, but received #{@data.class}: #{@data.inspect}"
end
class << self
# create ValidateError for SchemaValidator return data
# @param [Object] value
# @param [OpenAPIParser::Schemas::Base] schema
def build_error_result(value, schema)
[nil, OpenAPIParser::ValidateError.new(value, schema.type, schema.object_reference)]
end
end
end
class NotNullError < OpenAPIError
def message
"#{@reference} does not allow null values"
end
end
class NotExistRequiredKey < OpenAPIError
def initialize(keys, reference)
super(reference)
@keys = keys
end
def message
"#{@reference} missing required parameters: #{@keys.join(", ")}"
end
end
class NotExistPropertyDefinition < OpenAPIError
def initialize(keys, reference)
super(reference)
@keys = keys
end
def message
"#{@reference} does not define properties: #{@keys.join(", ")}"
end
end
class NotExistDiscriminatorMappedSchema < OpenAPIError
def initialize(mapped_schema_reference, reference)
super(reference)
@mapped_schema_reference = mapped_schema_reference
end
def message
"discriminator mapped schema #{@mapped_schema_reference} does not exist in #{@reference}"
end
end
class NotExistDiscriminatorPropertyName < OpenAPIError
def initialize(key, value, reference)
super(reference)
@key = key
@value = value
end
def message
"discriminator propertyName #{@key} does not exist in value #{@value.inspect} in #{@reference}"
end
end
class NotOneOf < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@value.inspect} isn't one of in #{@reference}"
end
end
class NotAnyOf < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@value.inspect} isn't any of in #{@reference}"
end
end
class NotEnumInclude < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@value.inspect} isn't part of the enum in #{@reference}"
end
end
class LessThanMinimum < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.inspect} is less than minimum value"
end
end
class LessThanExclusiveMinimum < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.inspect} cannot be less than or equal to exclusive minimum value"
end
end
class MoreThanMaximum < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.inspect} is more than maximum value"
end
end
class MoreThanExclusiveMaximum < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.inspect} cannot be more than or equal to exclusive maximum value"
end
end
class LessThanMinProperties < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.size} is less than minProperties value"
end
end
class MoreThanMaxProperties < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.size} is more than maxProperties value"
end
end
class InvalidPattern < OpenAPIError
def initialize(value, pattern, reference, example)
super(reference)
@value = value
@pattern = pattern
@example = example
end
def message
"#{@reference} pattern #{@pattern} does not match value: #{@value.inspect}#{@example ? ", example: #{@example}" : ""}"
end
end
class InvalidEmailFormat < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} email address format does not match value: #{@value.inspect}"
end
end
class InvalidUUIDFormat < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} Value: #{@value.inspect} is not conformant with UUID format"
end
end
class InvalidDateFormat < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} Value: #{@value.inspect} is not conformant with date format"
end
end
class InvalidDateTimeFormat < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} Value: #{@value.inspect} is not conformant with date-time format"
end
end
class NotExistStatusCodeDefinition < OpenAPIError
def message
"#{@reference} status code definition does not exist"
end
end
class NotExistContentTypeDefinition < OpenAPIError
def message
"#{@reference} response definition does not exist"
end
end
class MoreThanMaxLength < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.inspect} is longer than max length"
end
end
class LessThanMinLength < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.inspect} is shorter than min length"
end
end
class MoreThanMaxItems < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.inspect} contains more than max items"
end
end
class LessThanMinItems < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.inspect} contains fewer than min items"
end
end
class NotUniqueItems < OpenAPIError
def initialize(value, reference)
super(reference)
@value = value
end
def message
"#{@reference} #{@value.inspect} contains duplicate items"
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator.rb | lib/openapi_parser/schema_validator.rb | require_relative 'schema_validator/options'
require_relative 'schema_validator/enumable'
require_relative 'schema_validator/minimum_maximum'
require_relative 'schema_validator/properties_number'
require_relative 'schema_validator/base'
require_relative 'schema_validator/string_validator'
require_relative 'schema_validator/integer_validator'
require_relative 'schema_validator/float_validator'
require_relative 'schema_validator/boolean_validator'
require_relative 'schema_validator/object_validator'
require_relative 'schema_validator/array_validator'
require_relative 'schema_validator/any_of_validator'
require_relative 'schema_validator/all_of_validator'
require_relative 'schema_validator/one_of_validator'
require_relative 'schema_validator/nil_validator'
require_relative 'schema_validator/unspecified_type_validator'
class OpenAPIParser::SchemaValidator
# validate value by schema
# this module for SchemaValidators::Base
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
module Validatable
def validate_schema(value, schema, **keyword_args)
raise 'implement'
end
# validate integer value by schema
# this method use from float_validator because number allow float and integer
# @param [Object] _value
# @param [OpenAPIParser::Schemas::Schema] _schema
def validate_integer(_value, _schema)
raise 'implement'
end
end
include Validatable
class << self
# validate schema data
# @param [Hash] value
# @param [OpenAPIParser::Schemas:v:Schema]
# @param [OpenAPIParser::SchemaValidator::Options] options
# @return [Object] coerced or original params
def validate(value, schema, options)
new(value, schema, options).validate_data
end
end
# @param [Hash] value
# @param [OpenAPIParser::Schemas::Schema] schema
# @param [OpenAPIParser::SchemaValidator::Options] options
def initialize(value, schema, options)
@value = value
@schema = schema
@allow_empty_date_and_datetime = options.allow_empty_date_and_datetime
@coerce_value = options.coerce_value
@datetime_coerce_class = options.datetime_coerce_class
@date_coerce_class = options.date_coerce_class
end
# execute validate data
# @return [Object] coerced or original params
def validate_data
coerced, err = validate_schema(@value, @schema)
raise err if err
coerced
end
# validate value eby schema
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def validate_schema(value, schema, **keyword_args)
return [value, nil] unless schema
if (v = validator(value, schema))
if keyword_args.empty?
return v.coerce_and_validate(value, schema)
else
return v.coerce_and_validate(value, schema, **keyword_args)
end
end
# unknown return error
OpenAPIParser::ValidateError.build_error_result(value, schema)
end
# validate integer value by schema
# this method use from float_validator because number allow float and integer
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def validate_integer(value, schema)
integer_validator.coerce_and_validate(value, schema)
end
private
# @return [OpenAPIParser::SchemaValidator::Base, nil]
def validator(value, schema)
return any_of_validator if schema.any_of
return all_of_validator if schema.all_of
return one_of_validator if schema.one_of
return nil_validator if value.nil?
case schema.type
when 'string'
string_validator
when 'integer'
integer_validator
when 'boolean'
boolean_validator
when 'number'
float_validator
when 'object'
object_validator
when 'array'
array_validator
else
unspecified_type_validator
end
end
def string_validator
@string_validator ||= OpenAPIParser::SchemaValidator::StringValidator.new(self, @allow_empty_date_and_datetime, @coerce_value, @datetime_coerce_class, @date_coerce_class)
end
def integer_validator
@integer_validator ||= OpenAPIParser::SchemaValidator::IntegerValidator.new(self, @coerce_value)
end
def float_validator
@float_validator ||= OpenAPIParser::SchemaValidator::FloatValidator.new(self, @coerce_value)
end
def boolean_validator
@boolean_validator ||= OpenAPIParser::SchemaValidator::BooleanValidator.new(self, @coerce_value)
end
def object_validator
@object_validator ||= OpenAPIParser::SchemaValidator::ObjectValidator.new(self, @coerce_value)
end
def array_validator
@array_validator ||= OpenAPIParser::SchemaValidator::ArrayValidator.new(self, @coerce_value)
end
def any_of_validator
@any_of_validator ||= OpenAPIParser::SchemaValidator::AnyOfValidator.new(self, @coerce_value)
end
def all_of_validator
@all_of_validator ||= OpenAPIParser::SchemaValidator::AllOfValidator.new(self, @coerce_value)
end
def one_of_validator
@one_of_validator ||= OpenAPIParser::SchemaValidator::OneOfValidator.new(self, @coerce_value)
end
def nil_validator
@nil_validator ||= OpenAPIParser::SchemaValidator::NilValidator.new(self, @coerce_value)
end
def unspecified_type_validator
@unspecified_type_validator ||= OpenAPIParser::SchemaValidator::UnspecifiedTypeValidator.new(self, @coerce_value)
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas.rb | lib/openapi_parser/schemas.rb | require_relative 'schemas/classes'
require_relative 'schemas/base'
require_relative 'schemas/discriminator'
require_relative 'schemas/openapi'
require_relative 'schemas/paths'
require_relative 'schemas/path_item'
require_relative 'schemas/operation'
require_relative 'schemas/parameter'
require_relative 'schemas/reference'
require_relative 'schemas/request_body'
require_relative 'schemas/response'
require_relative 'schemas/responses'
require_relative 'schemas/components'
require_relative 'schemas/media_type'
require_relative 'schemas/schema'
require_relative 'schemas/header'
require_relative 'schemas/info'
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concern.rb | lib/openapi_parser/concern.rb | require_relative 'concerns/parser'
require_relative 'concerns/findable'
require_relative 'concerns/expandable'
require_relative 'concerns/media_type_selectable'
require_relative 'concerns/parameter_validatable'
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/config.rb | lib/openapi_parser/config.rb | class OpenAPIParser::Config
def initialize(config)
# TODO: This deprecation warning can be removed after we set the default to `true`
# in a later (major?) version update.
unless config.key?(:strict_reference_validation)
msg = "[DEPRECATION] strict_reference_validation config is not set. It defaults to `false` now, " +
"but will be `true` in a future version. Please explicitly set to `false` " +
"if you want to skip reference validation on schema load."
warn(msg)
end
@config = config
end
def allow_empty_date_and_datetime
@config.fetch(:allow_empty_date_and_datetime, false)
end
def datetime_coerce_class
@config[:datetime_coerce_class]
end
def date_coerce_class
@config[:date_coerce_class]
end
def coerce_value
@config[:coerce_value]
end
def expand_reference
@config.fetch(:expand_reference, true)
end
def strict_response_validation
# TODO: in a major version update, change this to default to `true`.
# https://github.com/ota42y/openapi_parser/pull/123/files#r767142217
@config.fetch(:strict_response_validation, false)
end
def strict_reference_validation
@config.fetch(:strict_reference_validation, false)
end
def validate_header
@config.fetch(:validate_header, true)
end
# @return [OpenAPIParser::SchemaValidator::Options]
def request_validator_options
@request_validator_options ||= OpenAPIParser::SchemaValidator::Options.new(allow_empty_date_and_datetime: allow_empty_date_and_datetime,
coerce_value: coerce_value,
datetime_coerce_class: datetime_coerce_class,
date_coerce_class: date_coerce_class,
validate_header: validate_header)
end
alias_method :request_body_options, :request_validator_options
alias_method :path_params_options, :request_validator_options
# @return [OpenAPIParser::SchemaValidator::ResponseValidateOptions]
def response_validate_options
@response_validate_options ||= OpenAPIParser::SchemaValidator::ResponseValidateOptions.
new(strict: strict_response_validation, validate_header: validate_header)
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/request_operation.rb | lib/openapi_parser/request_operation.rb | # binding request data and operation object
class OpenAPIParser::RequestOperation
class << self
# @param [OpenAPIParser::Config] config
# @param [OpenAPIParser::PathItemFinder] path_item_finder
# @return [OpenAPIParser::RequestOperation, nil]
def create(http_method, request_path, path_item_finder, config)
result = path_item_finder.operation_object(http_method, request_path)
return nil unless result
self.new(http_method, result, config)
end
end
# @!attribute [r] operation_object
# @return [OpenAPIParser::Schemas::Operation]
# @!attribute [r] path_params
# @return [Hash{String => String}]
# @!attribute [r] config
# @return [OpenAPIParser::Config]
# @!attribute [r] http_method
# @return [String]
# @!attribute [r] original_path
# @return [String]
# @!attribute [r] path_item
# @return [OpenAPIParser::Schemas::PathItem]
attr_reader :operation_object, :path_params, :config, :http_method, :original_path, :path_item
# @param [String] http_method
# @param [OpenAPIParser::PathItemFinder::Result] result
# @param [OpenAPIParser::Config] config
def initialize(http_method, result, config)
@http_method = http_method.to_s
@original_path = result.original_path
@operation_object = result.operation_object
@path_params = result.path_params || {}
@path_item = result.path_item_object
@config = config
end
def validate_path_params(options = nil)
options ||= config.path_params_options
operation_object&.validate_path_params(path_params, options)
end
# @param [String] content_type
# @param [Hash] params
# @param [OpenAPIParser::SchemaValidator::Options] options
def validate_request_body(content_type, params, options = nil)
options ||= config.request_body_options
operation_object&.validate_request_body(content_type, params, options)
end
# @param [OpenAPIParser::RequestOperation::ValidatableResponseBody] response_body
# @param [OpenAPIParser::SchemaValidator::ResponseValidateOptions] response_validate_options
def validate_response_body(response_body, response_validate_options = nil)
response_validate_options ||= config.response_validate_options
operation_object&.validate_response(response_body, response_validate_options)
end
# @param [Hash] params parameter hash
# @param [Hash] headers headers hash
# @param [OpenAPIParser::SchemaValidator::Options] options request validator options
def validate_request_parameter(params, headers, options = nil)
options ||= config.request_validator_options
operation_object&.validate_request_parameter(params, headers, options)
end
class ValidatableResponseBody
attr_reader :status_code, :response_data, :headers
def initialize(status_code, response_data, headers)
@status_code = status_code
@response_data = response_data
@headers = headers
end
def content_type
content_type_key = headers.keys.detect { |k| k.casecmp?('Content-Type') }
headers[content_type_key].to_s.split(';').first.to_s
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/path_item_finder.rb | lib/openapi_parser/path_item_finder.rb | class OpenAPIParser::PathItemFinder
# @param [OpenAPIParser::Schemas::Paths] paths
def initialize(paths)
@paths = paths
end
# find operation object and if not exist return nil
# @param [String, Symbol] http_method like (get, post .... allow symbol)
# @param [String] request_path
# @return [Result, nil]
def operation_object(http_method, request_path)
if (path_item_object = @paths.path[request_path])
if (op = path_item_object.operation(http_method))
return Result.new(path_item_object, op, request_path, {}) # find no path_params path
end
end
# check with path_params
parse_request_path(http_method, request_path)
end
class Result
attr_reader :path_item_object, :operation_object, :original_path, :path_params
# @!attribute [r] path_item_object
# @return [OpenAPIParser::Schemas::PathItem]
# @!attribute [r] operation_object
# @return [OpenAPIParser::Schemas::Operation]
# @!attribute [r] path_params
# @return [Hash{String => String}]
# @!attribute [r] original_path
# @return [String]
def initialize(path_item_object, operation_object, original_path, path_params)
@path_item_object = path_item_object
@operation_object = operation_object
@original_path = original_path
@path_params = path_params
end
end
def parse_path_parameters(schema_path, request_path)
parameters = path_parameters(schema_path)
return nil if parameters.empty?
# If there are regex special characters in the path, the regex will
# be too permissive, so escape the non-parameter parts.
components = []
unprocessed = schema_path.dup
parameters.each do |parameter|
parts = unprocessed.partition(parameter)
components << Regexp.escape(parts[0]) unless parts[0] == ''
components << "(?<#{param_name(parameter)}>.+)"
unprocessed = parts[2]
end
components << Regexp.escape(unprocessed) unless unprocessed == ''
regex = components.join('')
matches = request_path.match(regex)
return nil unless matches
# Match up the captured names with the captured values as a hash
matches.names.zip(matches.captures).to_h
end
private
def path_parameters(schema_path)
# OAS3 follows a RFC6570 subset for URL templates
# https://swagger.io/docs/specification/serialization/#uri-templates
# A URL template param can be preceded optionally by a "." or ";", and can be succeeded optionally by a "*";
# this regex returns a match of the full parameter name with all of these modifiers. Ex: {;id*}
parameters = schema_path.scan(/(\{[\.;]*[^\{\*\}]+\**\})/)
# The `String#scan` method returns an array of arrays; we want an array of strings
parameters.collect { |param| param[0] }
end
# check if there is a identical path in the schema (without any param)
def matches_directly?(request_path, http_method)
@paths.path[request_path]&.operation(http_method)
end
# used to filter paths with different depth or without given http method
def different_depth_or_method?(splitted_schema_path, splitted_request_path, path_item, http_method)
splitted_schema_path.size != splitted_request_path.size || !path_item.operation(http_method)
end
# check if the path item is a template
# EXAMPLE: path_template?('{id}') => true
def path_template?(schema_path_item)
schema_path_item.start_with?('{') && schema_path_item.end_with?('}')
end
# get the parameter name from the schema path item
# EXAMPLE: param_name('{id}') => 'id'
def param_name(schema_path_item)
schema_path_item[1..(schema_path_item.length - 2)]
end
# extract params by comparing the request path and the path from schema
# EXAMPLE:
# extract_params(['org', '1', 'user', '2', 'edit'], ['org', '{org_id}', 'user', '{user_id}'])
# => { 'org_id' => 1, 'user_id' => 2 }
# return nil if the schema does not match
def extract_params(splitted_request_path, splitted_schema_path)
splitted_request_path.zip(splitted_schema_path).reduce({}) do |result, zip_item|
request_path_item, schema_path_item = zip_item
params = parse_path_parameters(schema_path_item, request_path_item)
if params
result.merge!(params)
else
return if schema_path_item != request_path_item
end
result
end
end
# find all matching paths with parameters extracted
# EXAMPLE:
# [
# ['/user/{id}/edit', { 'id' => 1 }],
# ['/user/{id}/{action}', { 'id' => 1, 'action' => 'edit' }],
# ]
def matching_paths_with_params(request_path, http_method)
splitted_request_path = request_path.split('/')
@paths.path.reduce([]) do |result, item|
path, path_item = item
splitted_schema_path = path.split('/')
next result if different_depth_or_method?(splitted_schema_path, splitted_request_path, path_item, http_method)
extracted_params = extract_params(splitted_request_path, splitted_schema_path)
result << [path, extracted_params] if extracted_params
result
end
end
# find matching path and extract params
# EXAMPLE: find_path_and_params('get', '/user/1') => ['/user/{id}', { 'id' => 1 }]
def find_path_and_params(http_method, request_path)
return [request_path, {}] if matches_directly?(request_path, http_method)
matching = matching_paths_with_params(request_path, http_method)
# if there are many matching paths, return the one with the smallest number of params
# (prefer /user/{id}/action over /user/{param_1}/{param_2} )
matching.min_by { |match| match[1].size }
end
def parse_request_path(http_method, request_path)
original_path, path_params = find_path_and_params(http_method, request_path)
return nil unless original_path # # can't find
path_item_object = @paths.path[original_path]
obj = path_item_object.operation(http_method.to_s)
return nil unless obj
Result.new(path_item_object, obj, original_path, path_params)
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/parameter_validator.rb | lib/openapi_parser/parameter_validator.rb | class OpenAPIParser::ParameterValidator
class << self
# @param [Hash{String => Parameter}] parameters_hash
# @param [Hash] params
# @param [String] object_reference
# @param [OpenAPIParser::SchemaValidator::Options] options
# @param [Boolean] is_header is header or not (ignore params key case)
def validate_parameter(parameters_hash, params, object_reference, options, is_header = false)
no_exist_required_key = []
params_key_converted = params.keys.map { |k| [convert_key(k, is_header), k] }.to_h
parameters_hash.each do |k, v|
key = params_key_converted[convert_key(k, is_header)]
if params.include?(key)
coerced = v.validate_params(params[key], options)
params[key] = coerced if options.coerce_value
elsif v.required
no_exist_required_key << k
end
end
raise OpenAPIParser::NotExistRequiredKey.new(no_exist_required_key, object_reference) unless no_exist_required_key.empty?
params
end
private
def convert_key(k, is_header)
is_header ? k&.downcase : k
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/expandable.rb | lib/openapi_parser/concerns/expandable.rb | module OpenAPIParser::Expandable
# expand refs
# @param [OpenAPIParser::Schemas::Base] root
# @return nil
def expand_reference(root, validate_references)
expand_list_objects(root, self.class._openapi_attr_list_objects.keys, validate_references)
expand_objects(root, self.class._openapi_attr_objects.keys, validate_references)
expand_hash_objects(root, self.class._openapi_attr_hash_objects.keys, validate_references)
expand_hash_objects(root, self.class._openapi_attr_hash_body_objects.keys, validate_references)
nil
end
private
def expand_hash_objects(root, attribute_names, validate_references)
return unless attribute_names
attribute_names.each { |name| expand_hash_attribute(root, name, validate_references) }
end
def expand_hash_attribute(root, name, validate_references)
h = send(name)
return if h.nil?
update_values = h.map do |k, v|
new_object = expand_object(root, v, validate_references)
new_object.nil? ? nil : [k, new_object]
end
update_values.compact.each do |k, v|
_update_child_object(h[k], v)
h[k] = v
end
end
def expand_objects(root, attribute_names, validate_references)
return unless attribute_names
attribute_names.each do |name|
v = send(name)
next if v.nil?
new_object = expand_object(root, v, validate_references)
next if new_object.nil?
_update_child_object(v, new_object)
self.instance_variable_set("@#{name}", new_object)
end
end
def expand_list_objects(root, attribute_names, validate_references)
return unless attribute_names
attribute_names.each do |name|
l = send(name)
next if l.nil?
l.each_with_index do |v, idx|
new_object = expand_object(root, v, validate_references)
next if new_object.nil?
_update_child_object(v, new_object)
l[idx] = new_object
end
end
end
def expand_object(root, object, validate_references)
if object.kind_of?(OpenAPIParser::Schemas::Reference)
ref_object = referenced_object(root, object)
raise OpenAPIParser::MissingReferenceError.new(object.ref) if ref_object.nil? && validate_references
return ref_object
end
object.expand_reference(root, validate_references) if object.kind_of?(OpenAPIParser::Expandable)
nil
end
# @param [OpenAPIParser::Schemas::OpenAPI] root
# @param [OpenAPIParser::Schemas::Reference] reference
def referenced_object(root, reference)
obj = root.find_object(reference.ref)
obj.kind_of?(OpenAPIParser::Schemas::Reference) ? referenced_object(root, obj) : obj
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/parser.rb | lib/openapi_parser/concerns/parser.rb | module OpenAPIParser::Parser
end
require 'forwardable'
require_relative './parser/core'
require_relative './schema_loader'
module OpenAPIParser::Parser
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
extend Forwardable
def_delegators :_parser_core, :_openapi_attr_values, :openapi_attr_value, :openapi_attr_values
def_delegators :_parser_core, :_openapi_attr_objects, :openapi_attr_objects, :openapi_attr_object
def_delegators :_parser_core, :_openapi_attr_list_objects, :openapi_attr_list_object
def_delegators :_parser_core, :_openapi_attr_hash_objects, :openapi_attr_hash_object
def_delegators :_parser_core, :_openapi_attr_hash_body_objects, :openapi_attr_hash_body_objects
def _parser_core
@_parser_core ||= OpenAPIParser::Parser::Core.new(self)
end
end
# @param [OpenAPIParser::Schemas::Base] old
# @param [OpenAPIParser::Schemas::Base] new
def _update_child_object(old, new)
_openapi_all_child_objects[old.object_reference] = new
end
# @return [Hash{String => OpenAPIParser::Schemas::Base}]
def _openapi_all_child_objects
@_openapi_all_child_objects ||= {}
end
# load data by schema definition in core and set children to _openapi_all_child_objects
# @return nil
def load_data
loader = ::OpenAPIParser::SchemaLoader.new(self, self.class._parser_core)
@_openapi_all_child_objects = loader.load_data
nil
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/media_type_selectable.rb | lib/openapi_parser/concerns/media_type_selectable.rb | module OpenAPIParser::MediaTypeSelectable
private
# select media type by content_type (consider wild card definition)
# @param [String] content_type
# @param [Hash{String => OpenAPIParser::Schemas::MediaType}] content
# @return [OpenAPIParser::Schemas::MediaType, nil]
def select_media_type_from_content(content_type, content)
return nil unless content_type
return nil unless content
if (media_type = content[content_type])
return media_type
end
# application/json => [application, json]
splited = content_type.split('/')
if (media_type = content["#{splited.first}/*"])
return media_type
end
if (media_type = content['*/*'])
return media_type
end
nil
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/findable.rb | lib/openapi_parser/concerns/findable.rb | require 'cgi'
require 'uri'
module OpenAPIParser::Findable
# @param [String] reference
# @return [OpenAPIParser::Findable]
def find_object(reference)
return self if object_reference == reference
remote_reference = !reference.start_with?('#')
return find_remote_object(reference) if remote_reference
return nil unless reference.start_with?(object_reference)
unescaped_reference = CGI.unescape(reference)
@find_object_cache = {} unless defined? @find_object_cache
if (obj = @find_object_cache[unescaped_reference])
return obj
end
if (child = _openapi_all_child_objects[unescaped_reference])
@find_object_cache[unescaped_reference] = child
return child
end
_openapi_all_child_objects.values.each do |c|
if (obj = c.find_object(unescaped_reference))
@find_object_cache[unescaped_reference] = obj
return obj
end
end
nil
end
def purge_object_cache
@purged = false unless defined? @purged
return if @purged
@find_object_cache = {}
@purged = true
_openapi_all_child_objects.values.each(&:purge_object_cache)
end
private
def find_remote_object(reference)
uri, fragment = reference.split("#", 2)
reference_uri = URI(uri)
reference_uri.fragment = nil
root.load_another_schema(reference_uri)&.find_object("##{fragment}")
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/parameter_validatable.rb | lib/openapi_parser/concerns/parameter_validatable.rb | module OpenAPIParser::ParameterValidatable
# @param [Hash] path_params path parameters
# @param [OpenAPIParser::SchemaValidator::Options] options request validator options
def validate_path_params(path_params, options)
OpenAPIParser::ParameterValidator.validate_parameter(path_parameter_hash, path_params, object_reference, options)
end
# @param [Hash] params parameter hash
# @param [Hash] headers headers hash
# @param [OpenAPIParser::SchemaValidator::Options] options request validator options
def validate_request_parameter(params, headers, options)
validate_header_parameter(headers, object_reference, options) if options.validate_header
validate_query_parameter(params, object_reference, options)
end
# @param [PathItem] path_item parent
def set_parent_path_item(path_item)
@merged_parameter = (parameters || []) + (path_item.parameters || [])
nil
end
private
# @param [Hash] params query parameter hash
# @param [String] object_reference
# @param [OpenAPIParser::SchemaValidator::Options] options request validator options
def validate_query_parameter(params, object_reference, options)
OpenAPIParser::ParameterValidator.validate_parameter(query_parameter_hash, params, object_reference, options)
end
# @param [Hash] headers header hash
# @param [String] object_reference
# @param [OpenAPIParser::SchemaValidator::Options] options request validator options
def validate_header_parameter(headers, object_reference, options)
OpenAPIParser::ParameterValidator.validate_parameter(header_parameter_hash, headers, object_reference, options, true)
end
def header_parameter_hash
divided_parameter_hash['header'] || []
end
def path_parameter_hash
divided_parameter_hash['path'] || []
end
def query_parameter_hash
divided_parameter_hash['query'] || []
end
# @return [Hash{String => Hash{String => Parameter}}] hash[in][name] => Parameter
def divided_parameter_hash
@divided_parameter_hash ||=
(@merged_parameter || []).
group_by(&:in).
map { |in_type, params| # rubocop:disable Style/BlockDelimiters
[
in_type,
params.map { |param| [param.name, param] }.to_h,
]
}.to_h
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/schema_loader.rb | lib/openapi_parser/concerns/schema_loader.rb | class OpenAPIParser::SchemaLoader
end
require_relative './schema_loader/base'
require_relative './schema_loader/creator'
require_relative './schema_loader/values_loader'
require_relative './schema_loader/list_loader'
require_relative './schema_loader/objects_loader'
require_relative './schema_loader/hash_objects_loader'
require_relative './schema_loader/hash_body_loader'
# load data to target_object by schema definition in core
class OpenAPIParser::SchemaLoader
# @param [OpenAPIParser::Schemas::Base] target_object
# @param [OpenAPIParser::Parser::Core] core
def initialize(target_object, core)
@target_object = target_object
@core = core
@children = {}
end
# @!attribute [r] children
# @return [Array<OpenAPIParser::Schemas::Base>]
attr_reader :children
# execute load data
# return data is equal to :children
# @return [Array<OpenAPIParser::Schemas::Base>]
def load_data
all_loader.each { |l| load_data_by_schema_loader(l) }
children
end
private
attr_reader :core, :target_object
# @param [OpenAPIParser::SchemaLoader::Base] schema_loader
def load_data_by_schema_loader(schema_loader)
children = schema_loader.load_data(target_object, target_object.raw_schema)
children.each { |c| register_child(c) } if children
end
def register_child(object)
return unless object.kind_of?(OpenAPIParser::Parser)
@children[object.object_reference] = object
end
def all_loader
core._openapi_attr_values.values +
core._openapi_attr_objects.values +
core._openapi_attr_list_objects.values +
core._openapi_attr_hash_objects.values +
core._openapi_attr_hash_body_objects.values
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/schema_loader/creator.rb | lib/openapi_parser/concerns/schema_loader/creator.rb | # loader base class for create OpenAPI::Schemas::Base object
class OpenAPIParser::SchemaLoader::Creator < OpenAPIParser::SchemaLoader::Base
# @param [String] variable_name
# @param [Hash] options
def initialize(variable_name, options)
super(variable_name, options)
@klass = options[:klass]
@allow_reference = options[:reference] || false
@allow_data_type = options[:allow_data_type]
end
private
attr_reader :klass, :allow_reference, :allow_data_type
def build_object_reference_from_base(base, names)
names = [names] unless names.kind_of?(Array)
ref = names.map { |n| escape_reference(n) }.join('/')
"#{base}/#{ref}"
end
# @return Boolean
def check_reference_schema?(check_schema)
check_object_schema?(check_schema) && !check_schema['$ref'].nil?
end
def check_object_schema?(check_schema)
check_schema.kind_of?(::Hash)
end
def escape_reference(str)
str.to_s.gsub('/', '~1')
end
def build_openapi_object_from_option(target_object, ref, schema)
return nil if schema.nil?
if @allow_data_type && !check_object_schema?(schema)
schema
elsif @allow_reference && check_reference_schema?(schema)
OpenAPIParser::Schemas::Reference.new(ref, target_object, target_object.root, schema)
else
@klass.new(ref, target_object, target_object.root, schema)
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/schema_loader/values_loader.rb | lib/openapi_parser/concerns/schema_loader/values_loader.rb | # data type values loader
class OpenAPIParser::SchemaLoader::ValuesLoader < OpenAPIParser::SchemaLoader::Base
# @param [OpenAPIParser::Schemas::Base] target_object
# @param [Hash] raw_schema
# @return [Array<OpenAPIParser::Schemas::Base>, nil]
def load_data(target_object, raw_schema)
variable_set(target_object, variable_name, raw_schema[schema_key.to_s])
nil # this loader not return schema object
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/schema_loader/list_loader.rb | lib/openapi_parser/concerns/schema_loader/list_loader.rb | # list object loader
class OpenAPIParser::SchemaLoader::ListLoader < OpenAPIParser::SchemaLoader::Creator
# @param [OpenAPIParser::Schemas::Base] target_object
# @param [Hash] raw_schema
# @return [Array<OpenAPIParser::Schemas::Base>, nil]
def load_data(target_object, raw_schema)
create_attr_list_object(target_object, raw_schema[ref_name_base.to_s])
end
private
def create_attr_list_object(target_object, array_schema)
unless array_schema
variable_set(target_object, variable_name, nil)
return
end
data = array_schema.map.with_index do |s, idx|
ref = build_object_reference_from_base(target_object.object_reference, [ref_name_base, idx])
build_openapi_object_from_option(target_object, ref, s)
end
variable_set(target_object, variable_name, data)
data
end
alias_method :ref_name_base, :schema_key
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/schema_loader/hash_body_loader.rb | lib/openapi_parser/concerns/schema_loader/hash_body_loader.rb | # hash body object loader
class OpenAPIParser::SchemaLoader::HashBodyLoader < OpenAPIParser::SchemaLoader::Creator
# @param [String] variable_name
# @param [Hash] options
def initialize(variable_name, options)
super(variable_name, options)
@reject_keys = options[:reject_keys] ? options[:reject_keys].map(&:to_s) : []
end
# @param [OpenAPIParser::Schemas::Base] target_object
# @param [Hash] raw_schema
# @return [Array<OpenAPIParser::Schemas::Base>, nil]
def load_data(target_object, raw_schema)
# raw schema always exist because if not exist' this object don't create
create_hash_body_objects(target_object, raw_schema)
end
private
# for responses and paths object
def create_hash_body_objects(target_object, raw_schema)
object_list = raw_schema.reject { |k, _| reject_keys.include?(k) }.map do |child_name, child_schema|
ref = build_object_reference_from_base(target_object.object_reference, escape_reference(child_name))
[
child_name.to_s, # support string key only in OpenAPI3
build_openapi_object_from_option(target_object, ref, child_schema),
]
end
objects = object_list.to_h
variable_set(target_object, variable_name, objects)
objects.values
end
attr_reader :reject_keys
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/schema_loader/base.rb | lib/openapi_parser/concerns/schema_loader/base.rb | # loader base class
class OpenAPIParser::SchemaLoader::Base
# @param [String] variable_name
# @param [Hash] options
def initialize(variable_name, options)
@variable_name = variable_name
@schema_key = options[:schema_key] || variable_name
end
# @param [OpenAPIParser::Schemas::Base] _target_object
# @param [Hash] _raw_schema
# @return [Array<OpenAPIParser::Schemas::Base>, nil]
def load_data(_target_object, _raw_schema)
raise 'need implement'
end
private
attr_reader :variable_name, :schema_key
# create instance variable @variable_name using data
# @param [OpenAPIParser::Schemas::Base] target
# @param [String] variable_name
# @param [Object] data
def variable_set(target, variable_name, data)
target.instance_variable_set("@#{variable_name}", data)
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/schema_loader/hash_objects_loader.rb | lib/openapi_parser/concerns/schema_loader/hash_objects_loader.rb | # hash object loader
class OpenAPIParser::SchemaLoader::HashObjectsLoader < OpenAPIParser::SchemaLoader::Creator
# @param [OpenAPIParser::Schemas::Base] target_object
# @param [Hash] raw_schema
# @return [Array<OpenAPIParser::Schemas::Base>, nil]
def load_data(target_object, raw_schema)
create_attr_hash_object(target_object, raw_schema[ref_name_base.to_s])
end
private
def create_attr_hash_object(target_object, hash_schema)
unless hash_schema
variable_set(target_object, variable_name, nil)
return
end
data_list = hash_schema.map do |key, s|
ref = build_object_reference_from_base(target_object.object_reference, [ref_name_base, key])
[key, build_openapi_object_from_option(target_object, ref, s)]
end
data = data_list.to_h
variable_set(target_object, variable_name, data)
data.values
end
alias_method :ref_name_base, :schema_key
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/schema_loader/objects_loader.rb | lib/openapi_parser/concerns/schema_loader/objects_loader.rb | # Specific Object loader (defined by klass option)
class OpenAPIParser::SchemaLoader::ObjectsLoader < OpenAPIParser::SchemaLoader::Creator
# @param [OpenAPIParser::Schemas::Base] target_object
# @param [Hash] raw_schema
# @return [Array<OpenAPIParser::Schemas::Base>, nil]
def load_data(target_object, raw_schema)
obj = create_attr_object(target_object, raw_schema[schema_key.to_s])
[obj]
end
private
# @return [OpenAPIParser::Schemas::Base]
def create_attr_object(target_object, schema)
ref = build_object_reference_from_base(target_object.object_reference, schema_key)
data = build_openapi_object_from_option(target_object, ref, schema)
variable_set(target_object, variable_name, data)
data
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/parser/core.rb | lib/openapi_parser/concerns/parser/core.rb | require_relative './value'
require_relative './object'
require_relative './list'
require_relative './hash'
require_relative './hash_body'
class OpenAPIParser::Parser::Core
include OpenAPIParser::Parser::Value
include OpenAPIParser::Parser::Object
include OpenAPIParser::Parser::List
include OpenAPIParser::Parser::Hash
include OpenAPIParser::Parser::HashBody
def initialize(target_klass)
@target_klass = target_klass
end
private
attr_reader :target_klass
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/parser/value.rb | lib/openapi_parser/concerns/parser/value.rb | module OpenAPIParser::Parser::Value
def _openapi_attr_values
@_openapi_attr_values ||= {}
end
def openapi_attr_values(*names)
names.each { |name| openapi_attr_value(name) }
end
def openapi_attr_value(name, options = {})
target_klass.send(:attr_reader, name)
_openapi_attr_values[name] = OpenAPIParser::SchemaLoader::ValuesLoader.new(name, options)
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/parser/object.rb | lib/openapi_parser/concerns/parser/object.rb | module OpenAPIParser::Parser::Object
def _openapi_attr_objects
@_openapi_attr_objects ||= {}
end
def openapi_attr_objects(*names, klass)
names.each { |name| openapi_attr_object(name, klass) }
end
def openapi_attr_object(name, klass, options = {})
target_klass.send(:attr_reader, name)
_openapi_attr_objects[name] = OpenAPIParser::SchemaLoader::ObjectsLoader.new(name, options.merge(klass: klass))
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/parser/list.rb | lib/openapi_parser/concerns/parser/list.rb | module OpenAPIParser::Parser::List
def _openapi_attr_list_objects
@_openapi_attr_list_objects ||= {}
end
def openapi_attr_list_object(name, klass, options = {})
target_klass.send(:attr_reader, name)
_openapi_attr_list_objects[name] = OpenAPIParser::SchemaLoader::ListLoader.new(name, options.merge(klass: klass))
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/parser/hash_body.rb | lib/openapi_parser/concerns/parser/hash_body.rb | module OpenAPIParser::Parser::HashBody
def _openapi_attr_hash_body_objects
@_openapi_attr_hash_body_objects ||= {}
end
def openapi_attr_hash_body_objects(name, klass, options = {})
# options[:reject_keys] = options[:reject_keys] ? options[:reject_keys].map(&:to_s) : []
target_klass.send(:attr_reader, name)
_openapi_attr_hash_body_objects[name] = ::OpenAPIParser::SchemaLoader::HashBodyLoader.new(name, options.merge(klass: klass))
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/concerns/parser/hash.rb | lib/openapi_parser/concerns/parser/hash.rb | module OpenAPIParser::Parser::Hash
def _openapi_attr_hash_objects
@_openapi_attr_hash_objects ||= {}
end
def openapi_attr_hash_object(name, klass, options = {})
target_klass.send(:attr_reader, name)
_openapi_attr_hash_objects[name] = ::OpenAPIParser::SchemaLoader::HashObjectsLoader.new(name, options.merge(klass: klass))
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/reference.rb | lib/openapi_parser/schemas/reference.rb | module OpenAPIParser::Schemas
class Reference < Base
# @!attribute [r] ref
# @return [Base]
openapi_attr_value :ref, schema_key: '$ref'
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/path_item.rb | lib/openapi_parser/schemas/path_item.rb | # TODO: support servers
# TODO: support reference
module OpenAPIParser::Schemas
class PathItem < Base
openapi_attr_values :summary, :description
openapi_attr_objects :get, :put, :post, :delete, :options, :head, :patch, :trace, Operation
openapi_attr_list_object :parameters, Parameter, reference: true
# @return [Operation]
def operation(method)
public_send(method)
rescue NoMethodError
nil
end
def set_path_item_to_operation
[:get, :put, :post, :delete, :options, :head, :patch, :trace].each{ |method| operation(method)&.set_parent_path_item(self)}
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/discriminator.rb | lib/openapi_parser/schemas/discriminator.rb | module OpenAPIParser::Schemas
class Discriminator < Base
# @!attribute [r] property_name
# @return [String, nil]
openapi_attr_value :property_name, schema_key: :propertyName
# @!attribute [r] mapping
# @return [Hash{String => String]
openapi_attr_value :mapping
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/parameter.rb | lib/openapi_parser/schemas/parameter.rb | # TODO: support examples
module OpenAPIParser::Schemas
class Parameter < Base
openapi_attr_values :name, :in, :description, :required, :deprecated, :style, :explode, :example
openapi_attr_value :allow_empty_value, schema_key: :allowEmptyValue
openapi_attr_value :allow_reserved, schema_key: :allowReserved
# @!attribute [r] schema
# @return [Schema, Reference, nil]
openapi_attr_object :schema, Schema, reference: true
# @return [Object] coerced or original params
# @param [OpenAPIParser::SchemaValidator::Options] options
def validate_params(params, options)
::OpenAPIParser::SchemaValidator.validate(params, schema, options)
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/responses.rb | lib/openapi_parser/schemas/responses.rb | # TODO: support extended property
module OpenAPIParser::Schemas
class Responses < Base
# @!attribute [r] default
# @return [Response, Reference, nil] default response object
openapi_attr_object :default, Response, reference: true
# @!attribute [r] response
# @return [Hash{String => Response, Reference}, nil] response object indexed by status code. see: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#patterned-fields-1
openapi_attr_hash_body_objects 'response', Response, reject_keys: [:default], reference: true, allow_data_type: false
# validate params data by definition
# find response object by status_code and content_type
# https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#patterned-fields-1
# @param [OpenAPIParser::RequestOperation::ValidatableResponseBody] response_body
# @param [OpenAPIParser::SchemaValidator::ResponseValidateOptions] response_validate_options
def validate(response_body, response_validate_options)
return nil unless response
if (res = find_response_object(response_body.status_code))
return res.validate(response_body, response_validate_options)
end
raise ::OpenAPIParser::NotExistStatusCodeDefinition, object_reference if response_validate_options.strict
nil
end
private
# @param [Integer] status_code
# @return [Response]
def find_response_object(status_code)
if (res = response[status_code.to_s])
return res
end
wild_card = status_code_to_wild_card(status_code)
if (res = response[wild_card])
return res
end
default
end
# parse 400 -> 4xx
# OpenAPI3 allow 1xx, 2xx, 3xx... only, don't allow 41x
# @param [Integer] status_code
def status_code_to_wild_card(status_code)
top = status_code / 100
"#{top}XX"
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/response.rb | lib/openapi_parser/schemas/response.rb | # TODO: links
module OpenAPIParser::Schemas
class Response < Base
include OpenAPIParser::MediaTypeSelectable
openapi_attr_values :description
# @!attribute [r] content
# @return [Hash{String => MediaType}, nil] content_type to MediaType hash
openapi_attr_hash_object :content, MediaType, reference: false
# @!attribute [r] headers
# @return [Hash{String => Header}, nil] header string to Header
openapi_attr_hash_object :headers, Header, reference: true
# @param [OpenAPIParser::RequestOperation::ValidatableResponseBody] response_body
# @param [OpenAPIParser::SchemaValidator::ResponseValidateOptions] response_validate_options
def validate(response_body, response_validate_options)
validate_header(response_body.headers) if response_validate_options.validate_header
media_type = select_media_type(response_body.content_type)
unless media_type
if response_validate_options.strict && response_body_not_blank(response_body)
raise ::OpenAPIParser::NotExistContentTypeDefinition, object_reference
end
return true
end
options = ::OpenAPIParser::SchemaValidator::Options.new(**response_validate_options.validator_options)
media_type.validate_parameter(response_body.response_data, options)
end
# select media type by content_type (consider wild card definition)
# @param [String] content_type
# @return [OpenAPIParser::Schemas::MediaType, nil]
def select_media_type(content_type)
select_media_type_from_content(content_type, content)
end
private
# @param [OpenAPIParser::RequestOperation::ValidatableResponseBody]
def response_body_not_blank(response_body)
!(response_body.response_data.nil? || response_body.response_data.empty?)
end
# @param [Hash] response_headers
def validate_header(response_headers)
return unless headers
headers.each do |name, schema|
next unless response_headers.key?(name)
value = response_headers[name]
schema.validate(value)
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/components.rb | lib/openapi_parser/schemas/components.rb | # TODO: examples
# TODO: securitySchemes
# TODO: links
# TODO: callbacks
module OpenAPIParser::Schemas
class Components < Base
# @!attribute [r] parameters
# @return [Hash{String => Parameter}, nil]
openapi_attr_hash_object :parameters, Parameter, reference: true
# @!attribute [r] parameters
# @return [Hash{String => Parameter}, nil]
openapi_attr_hash_object :schemas, Schema, reference: true
# @!attribute [r] responses
# @return [Hash{String => Response}, nil]
openapi_attr_hash_object :responses, Response, reference: true
# @!attribute [r] request_bodies
# @return [Hash{String => RequestBody}, nil]
openapi_attr_hash_object :request_bodies, RequestBody, reference: true, schema_key: :requestBodies
# @!attribute [r] headers
# @return [Hash{String => Header}, nil] header objects
openapi_attr_hash_object :headers, Header, reference: true
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/classes.rb | lib/openapi_parser/schemas/classes.rb | # We want to use class name for DSL in class definition so we should define first...
module OpenAPIParser::Schemas
class Base; end
class Discriminator < Base; end
class OpenAPI < Base; end
class Operation < Base; end
class Parameter < Base; end
class PathItem < Base; end
class Paths < Base; end
class Reference < Base; end
class RequestBody < Base; end
class Responses < Base; end
class Response < Base; end
class MediaType < Base; end
class Schema < Base; end
class Components < Base; end
class Header < Base; end
class Info < Base; end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/paths.rb | lib/openapi_parser/schemas/paths.rb | module OpenAPIParser::Schemas
class Paths < Base
# @!attribute [r] path
# @return [Hash{String => PathItem, Reference}, nil]
openapi_attr_hash_body_objects 'path', PathItem, reference: true, allow_data_type: false
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/base.rb | lib/openapi_parser/schemas/base.rb | module OpenAPIParser::Schemas
class Base
include OpenAPIParser::Parser
include OpenAPIParser::Findable
include OpenAPIParser::Expandable
attr_reader :parent, :raw_schema, :object_reference, :root
# @param [OpenAPIParser::Schemas::Base]
def initialize(object_reference, parent, root, raw_schema)
@raw_schema = raw_schema
@parent = parent
@root = root
@object_reference = object_reference
load_data
after_init
end
# override
def after_init
end
def inspect
@object_reference
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/info.rb | lib/openapi_parser/schemas/info.rb | module OpenAPIParser::Schemas
class Info < Base
openapi_attr_values :title, :version
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/media_type.rb | lib/openapi_parser/schemas/media_type.rb | # TODO: example
# TODO: examples
# TODO: encoding
module OpenAPIParser::Schemas
class MediaType < Base
# @!attribute [r] schema
# @return [Schema, nil] OpenAPI3 Schema object
openapi_attr_object :schema, Schema, reference: true
# validate params by schema definitions
# @param [Hash] params
# @param [OpenAPIParser::SchemaValidator::Options] options
def validate_parameter(params, options)
OpenAPIParser::SchemaValidator.validate(params, schema, options)
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/request_body.rb | lib/openapi_parser/schemas/request_body.rb | # TODO: support extended property
module OpenAPIParser::Schemas
class RequestBody < Base
include OpenAPIParser::MediaTypeSelectable
# @!attribute [r] description
# @return [String] description data
# @!attribute [r] required
# @return [Boolean] required bool data
openapi_attr_values :description, :required
# @!attribute [r] content
# @return [Hash{String => MediaType}, nil] content type to MediaType object
openapi_attr_hash_object :content, MediaType, reference: false
# @param [String] content_type
# @param [Hash] params
# @param [OpenAPIParser::SchemaValidator::Options] options
def validate_request_body(content_type, params, options)
media_type = select_media_type(content_type)
return params unless media_type
media_type.validate_parameter(params, options)
end
# select media type by content_type (consider wild card definition)
# @param [String] content_type
# @return [OpenAPIParser::Schemas::MediaType, nil]
def select_media_type(content_type)
select_media_type_from_content(content_type, content)
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/operation.rb | lib/openapi_parser/schemas/operation.rb | # TODO: externalDocs
# TODO: callbacks
# TODO: security
# TODO: servers
module OpenAPIParser::Schemas
class Operation < Base
include OpenAPIParser::ParameterValidatable
openapi_attr_values :tags, :summary, :description, :deprecated
openapi_attr_value :operation_id, schema_key: :operationId
openapi_attr_list_object :parameters, Parameter, reference: true
# @!attribute [r] request_body
# @return [OpenAPIParser::Schemas::RequestBody, nil] return OpenAPI3 object
openapi_attr_object :request_body, RequestBody, reference: true, schema_key: :requestBody
# @!attribute [r] responses
# @return [OpenAPIParser::Schemas::Responses, nil] return OpenAPI3 object
openapi_attr_object :responses, Responses, reference: false
def validate_request_body(content_type, params, options)
request_body&.validate_request_body(content_type, params, options)
end
# @param [OpenAPIParser::RequestOperation::ValidatableResponseBody] response_body
# @param [OpenAPIParser::SchemaValidator::ResponseValidateOptions] response_validate_options
def validate_response(response_body, response_validate_options)
responses&.validate(response_body, response_validate_options)
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/header.rb | lib/openapi_parser/schemas/header.rb | module OpenAPIParser::Schemas
class Header < Base
openapi_attr_values :description, :required, :deprecated, :style, :explode, :example
openapi_attr_value :allow_empty_value, schema_key: :allowEmptyValue
openapi_attr_value :allow_reserved, schema_key: :allowReserved
# @!attribute [r] schema
# @return [Schema, Reference, nil]
openapi_attr_object :schema, Schema, reference: true
# validate by schema
# @param [Object] value
def validate(value)
OpenAPIParser::SchemaValidator.validate(value, schema, OpenAPIParser::SchemaValidator::Options.new)
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/openapi.rb | lib/openapi_parser/schemas/openapi.rb | # TODO: info object
# TODO: servers object
# TODO: tags object
# TODO: externalDocs object
module OpenAPIParser::Schemas
class OpenAPI < Base
def initialize(raw_schema, config, uri: nil, schema_registry: {})
super('#', nil, self, raw_schema)
@find_object_cache = {}
@path_item_finder = OpenAPIParser::PathItemFinder.new(paths) if paths # invalid definition
@config = config
@uri = uri
@schema_registry = schema_registry
# schema_registery is shared among schemas, and prevents a schema from being loaded multiple times
schema_registry[uri] = self if uri
end
# @!attribute [r] openapi
# @return [String, nil]
openapi_attr_values :openapi
# @!attribute [r] paths
# @return [Paths, nil]
openapi_attr_object :paths, Paths, reference: false
# @!attribute [r] components
# @return [Components, nil]
openapi_attr_object :components, Components, reference: false
# @!attribute [r] info
# @return [Info, nil]
openapi_attr_object :info, Info, reference: false
# @return [OpenAPIParser::RequestOperation, nil]
def request_operation(http_method, request_path)
OpenAPIParser::RequestOperation.create(http_method, request_path, @path_item_finder, @config)
end
# load another schema with shared config and schema_registry
# @return [OpenAPIParser::Schemas::OpenAPI]
def load_another_schema(uri)
resolved_uri = resolve_uri(uri)
return if resolved_uri.nil?
loaded = @schema_registry[resolved_uri]
return loaded if loaded
OpenAPIParser.load_uri(resolved_uri, config: @config, schema_registry: @schema_registry)
end
private
def resolve_uri(uri)
if uri.absolute?
uri
else
@uri&.merge(uri)
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schemas/schema.rb | lib/openapi_parser/schemas/schema.rb | # TODO: support 'not' because I need check reference...
# TODO: support 'xml', 'externalDocs'
# TODO: support extended property
module OpenAPIParser::Schemas
class Schema < Base
# @!attribute [r] title
# @return [String, nil]
# @!attribute [r] pattern
# @return [String, nil] regexp
# @!attribute [r] pattern
# @return [String, nil] regexp
# @!attribute [r] description
# @return [String, nil]
# @!attribute [r] format
# @return [String, nil]
# @!attribute [r] type
# @return [String, nil] multiple types doesn't supported in OpenAPI3
# @!attribute [r] maximum
# @return [Float, nil]
# @!attribute [r] multipleOf
# @return [Float, nil]
# @!attribute [r] maxLength
# @return [Integer, nil]
# @!attribute [r] minLength
# @return [Integer, nil]
# @!attribute [r] maxItems
# @return [Integer, nil]
# @!attribute [r] minItems
# @return [Integer, nil]
# @!attribute [r] maxProperties
# @return [Integer, nil]
# @!attribute [r] minProperties
# @return [Integer, nil]
# @!attribute [r] exclusiveMaximum
# @return [Boolean, nil]
# @!attribute [r] exclusiveMinimum
# @return [Boolean, nil]
# @!attribute [r] uniqueItems
# @return [Boolean, nil]
# @!attribute [r] nullable
# @return [Boolean, nil]
# @!attribute [r] deprecated
# @return [Boolean, nil]
# @!attribute [r] required
# @return [Array<String>, nil] at least one item included
# @!attribute [r] enum
# @return [Array, nil] any type array
# @!attribute [r] default
# @return [Object, nil]
# @!attribute [r] example
# @return [Object, nil]
openapi_attr_values :title, :multipleOf,
:maximum, :exclusiveMaximum, :minimum, :exclusiveMinimum,
:maxLength, :minLength,
:pattern,
:maxItems, :minItems, :uniqueItems,
:maxProperties, :minProperties,
:required, :enum,
:description,
:format,
:default,
:type,
:nullable,
:example,
:deprecated
# @!attribute [r] read_only
# @return [Boolean, nil]
openapi_attr_value :read_only, schema_key: :readOnly
# @!attribute [r] write_only
# @return [Boolean, nil]
openapi_attr_value :write_only, schema_key: :writeOnly
# @!attribute [r] all_of
# @return [Array<Schema, Reference>, nil]
openapi_attr_list_object :all_of, Schema, reference: true, schema_key: :allOf
# @!attribute [r] one_of
# @return [Array<Schema, Reference>, nil]
openapi_attr_list_object :one_of, Schema, reference: true, schema_key: :oneOf
# @!attribute [r] any_of
# @return [Array<Schema, Reference>, nil]
openapi_attr_list_object :any_of, Schema, reference: true, schema_key: :anyOf
# @!attribute [r] items
# @return [Schema, nil]
openapi_attr_object :items, Schema, reference: true
# @!attribute [r] properties
# @return [Hash{String => Schema}, nil]
openapi_attr_hash_object :properties, Schema, reference: true
# @!attribute [r] discriminator
# @return [Discriminator, nil]
openapi_attr_object :discriminator, Discriminator
# @!attribute [r] additional_properties
# @return [Boolean, Schema, Reference, nil]
openapi_attr_object :additional_properties, Schema, reference: true, allow_data_type: true, schema_key: :additionalProperties
# additional_properties have default value
# we should add default value feature in openapi_attr_object method, but we need temporary fix so override attr_reader
remove_method :additional_properties
def additional_properties
@additional_properties.nil? ? true : @additional_properties
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/all_of_validator.rb | lib/openapi_parser/schema_validator/all_of_validator.rb | # validate AllOf schema
class OpenAPIParser::SchemaValidator
class AllOfValidator < Base
# coerce and validate value
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def coerce_and_validate(value, schema, **keyword_args)
if value.nil? && schema.nullable
return [value, nil]
end
# if any schema return error, it's not a valid all_of
remaining_keys = value.kind_of?(Hash) ? value.keys : []
nested_additional_properties = false
schema.all_of.each do |s|
# We need to store the reference to all of, so we can perform strict check on allowed properties
_coerced, err = validatable.validate_schema(
value,
s,
:parent_all_of => true,
parent_discriminator_schemas: keyword_args[:parent_discriminator_schemas] || []
)
if s.type == "object"
remaining_keys -= (s.properties || {}).keys
nested_additional_properties = true if s.additional_properties
else
# If this is not allOf having array of objects inside, but e.g. having another anyOf/oneOf nested
remaining_keys.clear
end
return [nil, err] if err
end
# If there are nested additionalProperties, we allow not defined extra properties and lean on the specific
# additionalProperties validation
if !nested_additional_properties && !remaining_keys.empty?
return [nil, OpenAPIParser::NotExistPropertyDefinition.new(remaining_keys, schema.object_reference)]
end
[value, nil]
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/enumable.rb | lib/openapi_parser/schema_validator/enumable.rb | class OpenAPIParser::SchemaValidator
module Enumable
# check enum value by schema
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def check_enum_include(value, schema)
return [value, nil] unless schema.enum
return [value, nil] if schema.enum.include?(value)
[nil, OpenAPIParser::NotEnumInclude.new(value, schema.object_reference)]
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/minimum_maximum.rb | lib/openapi_parser/schema_validator/minimum_maximum.rb | class OpenAPIParser::SchemaValidator
module MinimumMaximum
# check minimum and maximum value by schema
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def check_minimum_maximum(value, schema)
include_min_max = schema.minimum || schema.maximum
return [value, nil] unless include_min_max
validate(value, schema)
[value, nil]
rescue OpenAPIParser::OpenAPIError => e
return [nil, e]
end
private
def validate(value, schema)
reference = schema.object_reference
if schema.minimum
if schema.exclusiveMinimum && value <= schema.minimum
raise OpenAPIParser::LessThanExclusiveMinimum.new(value, reference)
elsif value < schema.minimum
raise OpenAPIParser::LessThanMinimum.new(value, reference)
end
end
if schema.maximum
if schema.exclusiveMaximum && value >= schema.maximum
raise OpenAPIParser::MoreThanExclusiveMaximum.new(value, reference)
elsif value > schema.maximum
raise OpenAPIParser::MoreThanMaximum.new(value, reference)
end
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/nil_validator.rb | lib/openapi_parser/schema_validator/nil_validator.rb | class OpenAPIParser::SchemaValidator
class NilValidator < Base
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def coerce_and_validate(value, schema, **_keyword_args)
return [value, nil] if schema.nullable
[nil, OpenAPIParser::NotNullError.new(schema.object_reference)]
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/unspecified_type_validator.rb | lib/openapi_parser/schema_validator/unspecified_type_validator.rb | class OpenAPIParser::SchemaValidator
class UnspecifiedTypeValidator < Base
# @param [Object] value
def coerce_and_validate(value, _schema, **_keyword_args)
[value, nil]
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/options.rb | lib/openapi_parser/schema_validator/options.rb | class OpenAPIParser::SchemaValidator
class Options
# @!attribute [r] allow_empty_date_and_datetime
# @return [Boolean] allow empty date and datetime values option on/off
# @!attribute [r] coerce_value
# @return [Boolean] coerce value option on/off
# @!attribute [r] datetime_coerce_class
# @return [Object, nil] coerce datetime string by this Object class
# @!attribute [r] date_coerce_class
# @return [Object, nil] coerce date string by this Object class
# @!attribute [r] validate_header
# @return [Boolean] validate header or not
attr_reader :allow_empty_date_and_datetime, :coerce_value, :datetime_coerce_class, :validate_header, :date_coerce_class
def initialize(allow_empty_date_and_datetime: false, coerce_value: nil, datetime_coerce_class: nil, validate_header: true, date_coerce_class: nil)
@allow_empty_date_and_datetime = allow_empty_date_and_datetime
@coerce_value = coerce_value
@datetime_coerce_class = datetime_coerce_class
@date_coerce_class = date_coerce_class
@validate_header = validate_header
end
end
# response body validation option
class ResponseValidateOptions
# @!attribute [r] strict
# @return [Boolean] validate by strict (when not exist definition, raise error)
attr_reader :strict, :validate_header, :validator_options
def initialize(strict: false, validate_header: true, **validator_options)
@validator_options = validator_options
@strict = strict
@validate_header = validate_header
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/array_validator.rb | lib/openapi_parser/schema_validator/array_validator.rb | class OpenAPIParser::SchemaValidator
class ArrayValidator < Base
# @param [Array] value
# @param [OpenAPIParser::Schemas::Schema] schema
def coerce_and_validate(value, schema, **_keyword_args)
return OpenAPIParser::ValidateError.build_error_result(value, schema) unless value.kind_of?(Array)
value, err = validate_max_min_items(value, schema)
return [nil, err] if err
value, err = validate_unique_items(value, schema)
return [nil, err] if err
# array type have an schema in items property
items_schema = schema.items
coerced_values = value.map do |v|
coerced, err = validatable.validate_schema(v, items_schema)
return [nil, err] if err
coerced
end
value.each_index { |idx| value[idx] = coerced_values[idx] } if @coerce_value
[value, nil]
end
def validate_max_min_items(value, schema)
return [nil, OpenAPIParser::MoreThanMaxItems.new(value, schema.object_reference)] if schema.maxItems && value.length > schema.maxItems
return [nil, OpenAPIParser::LessThanMinItems.new(value, schema.object_reference)] if schema.minItems && value.length < schema.minItems
[value, nil]
end
def validate_unique_items(value, schema)
return [nil, OpenAPIParser::NotUniqueItems.new(value, schema.object_reference)] if schema.uniqueItems && value.length != value.uniq.length
[value, nil]
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/base.rb | lib/openapi_parser/schema_validator/base.rb | class OpenAPIParser::SchemaValidator
class Base
def initialize(validatable, coerce_value)
@validatable = validatable
@coerce_value = coerce_value
end
attr_reader :validatable
# need override
def coerce_and_validate(_value, _schema, **_keyword_args)
raise 'need implement'
end
def validate_discriminator_schema(discriminator, value, parent_discriminator_schemas: [])
property_name = discriminator.property_name
if property_name.nil? || !value.key?(property_name)
return [nil, OpenAPIParser::NotExistDiscriminatorPropertyName.new(discriminator.property_name, value, discriminator.object_reference)]
end
mapping_key = value[property_name]
# it's allowed to have discriminator without mapping, then we need to lookup discriminator.property_name
# but the format is not the full path, just model name in the components
mapping_target = discriminator.mapping&.[](mapping_key) || "#/components/schemas/#{mapping_key}"
# Find object does O(n) search at worst, then caches the result, so this is ok for repeated search
resolved_schema = discriminator.root.find_object(mapping_target)
unless resolved_schema
return [nil, OpenAPIParser::NotExistDiscriminatorMappedSchema.new(mapping_target, discriminator.object_reference)]
end
validatable.validate_schema(
value,
resolved_schema,
**{discriminator_property_name: discriminator.property_name, parent_discriminator_schemas: parent_discriminator_schemas}
)
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/integer_validator.rb | lib/openapi_parser/schema_validator/integer_validator.rb | class OpenAPIParser::SchemaValidator
class IntegerValidator < Base
include ::OpenAPIParser::SchemaValidator::Enumable
include ::OpenAPIParser::SchemaValidator::MinimumMaximum
# validate integer value by schema
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def coerce_and_validate(value, schema, **_keyword_args)
value = coerce(value) if @coerce_value
return OpenAPIParser::ValidateError.build_error_result(value, schema) unless value.kind_of?(Integer)
value, err = check_enum_include(value, schema)
return [nil, err] if err
check_minimum_maximum(value, schema)
end
private
def coerce(value)
return value if value.kind_of?(Integer)
begin
Integer(value)
rescue ArgumentError, TypeError
value
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/object_validator.rb | lib/openapi_parser/schema_validator/object_validator.rb | class OpenAPIParser::SchemaValidator
class ObjectValidator < Base
include ::OpenAPIParser::SchemaValidator::PropertiesNumber
# @param [Hash] value
# @param [OpenAPIParser::Schemas::Schema] schema
# @param [Boolean] parent_all_of true if component is nested under allOf
# @param [String, nil] discriminator_property_name discriminator.property_name to ignore checking additional_properties
def coerce_and_validate(value, schema, parent_all_of: false, parent_discriminator_schemas: [], discriminator_property_name: nil)
return OpenAPIParser::ValidateError.build_error_result(value, schema) unless value.kind_of?(Hash)
properties = schema.properties || {}
additional_properties = schema.additional_properties
required_set = schema.required ? schema.required.to_set : Set.new
remaining_keys = value.keys
if schema.discriminator && !parent_discriminator_schemas.include?(schema)
return validate_discriminator_schema(
schema.discriminator,
value,
parent_discriminator_schemas: parent_discriminator_schemas + [schema]
)
else
remaining_keys.delete('discriminator')
end
coerced_values = value.map do |name, v|
s = properties[name]
coerced, err = if s
remaining_keys.delete(name)
validatable.validate_schema(v, s)
# TODO: better handling for parent_all_of with additional_properties
elsif !parent_all_of && additional_properties.is_a?(OpenAPIParser::Schemas::Schema)
remaining_keys.delete(name)
validatable.validate_schema(v, additional_properties)
else
[v, nil]
end
return [nil, err] if err
required_set.delete(name)
[name, coerced]
end
remaining_keys.delete(discriminator_property_name) if discriminator_property_name
if !remaining_keys.empty? && !parent_all_of && !additional_properties
# If object is nested in all of, the validation is already done in allOf validator. Or if
# additionalProperties are defined, we will validate using that
return [nil, OpenAPIParser::NotExistPropertyDefinition.new(remaining_keys, schema.object_reference)]
end
return [nil, OpenAPIParser::NotExistRequiredKey.new(required_set.to_a, schema.object_reference)] unless required_set.empty?
value.merge!(coerced_values.to_h) if @coerce_value
check_properties_number(value, schema)
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/any_of_validator.rb | lib/openapi_parser/schema_validator/any_of_validator.rb | class OpenAPIParser::SchemaValidator
class AnyOfValidator < Base
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def coerce_and_validate(value, schema, **_keyword_args)
if value.nil? && schema.nullable
return [value, nil]
end
if schema.discriminator
return validate_discriminator_schema(schema.discriminator, value)
end
# in all schema return error (=true) not any of data
schema.any_of.each do |s|
coerced, err = validatable.validate_schema(value, s)
return [coerced, nil] if err.nil?
end
[nil, OpenAPIParser::NotAnyOf.new(value, schema.object_reference)]
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/properties_number.rb | lib/openapi_parser/schema_validator/properties_number.rb | class OpenAPIParser::SchemaValidator
module PropertiesNumber
# check minProperties and manProperties value by schema
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def check_properties_number(value, schema)
include_properties_num = schema.minProperties || schema.maxProperties
return [value, nil] unless include_properties_num
validate(value, schema)
[value, nil]
rescue OpenAPIParser::OpenAPIError => e
return [nil, e]
end
private
def validate(value, schema)
reference = schema.object_reference
if schema.minProperties && (value.size < schema.minProperties)
raise OpenAPIParser::LessThanMinProperties.new(value, reference)
end
if schema.maxProperties && (value.size > schema.maxProperties)
raise OpenAPIParser::MoreThanMaxProperties.new(value, reference)
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/float_validator.rb | lib/openapi_parser/schema_validator/float_validator.rb | class OpenAPIParser::SchemaValidator
class FloatValidator < Base
include ::OpenAPIParser::SchemaValidator::Enumable
include ::OpenAPIParser::SchemaValidator::MinimumMaximum
# validate float value by schema
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def coerce_and_validate(value, schema, **_keyword_args)
value = coerce(value) if @coerce_value
return validatable.validate_integer(value, schema) if value.kind_of?(Integer)
coercer_and_validate_numeric(value, schema)
end
private
def coercer_and_validate_numeric(value, schema)
return OpenAPIParser::ValidateError.build_error_result(value, schema) unless value.kind_of?(Numeric)
value, err = check_enum_include(value, schema)
return [nil, err] if err
check_minimum_maximum(value, schema)
end
def coerce(value)
Float(value)
rescue ArgumentError, TypeError
value
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/string_validator.rb | lib/openapi_parser/schema_validator/string_validator.rb | class OpenAPIParser::SchemaValidator
class StringValidator < Base
include ::OpenAPIParser::SchemaValidator::Enumable
def initialize(validator, allow_empty_date_and_datetime, coerce_value, datetime_coerce_class, date_coerce_class)
super(validator, coerce_value)
@allow_empty_date_and_datetime = allow_empty_date_and_datetime
@datetime_coerce_class = datetime_coerce_class
@date_coerce_class = date_coerce_class
end
def coerce_and_validate(value, schema, **_keyword_args)
unless value.kind_of?(String)
# Skip validation if the format is `binary`, even if the value is not an actual string.
# ref: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#data-types
if schema.format == 'binary'
# TODO:
# It would be better to check whether the value is an instance of `Rack::Multipart::UploadFile`,
# `ActionDispatch::Http::UploadedFile`, or another similar class.
return [value, nil]
end
return OpenAPIParser::ValidateError.build_error_result(value, schema)
end
value, err = check_enum_include(value, schema)
return [nil, err] if err
value, err = pattern_validate(value, schema)
return [nil, err] if err
value, err = validate_max_min_length(value, schema)
return [nil, err] if err
value, err = validate_email_format(value, schema)
return [nil, err] if err
value, err = validate_uuid_format(value, schema)
return [nil, err] if err
value, err = validate_date_format(value, schema)
return [nil, err] if err
value, err = validate_datetime_format(value, schema)
return [nil, err] if err
[value, nil]
end
private
# @param [OpenAPIParser::Schemas::Schema] schema
def pattern_validate(value, schema)
# pattern support string only so put this
return [value, nil] unless schema.pattern
return [value, nil] if value =~ /#{schema.pattern}/
[nil, OpenAPIParser::InvalidPattern.new(value, schema.pattern, schema.object_reference, schema.example)]
end
def validate_max_min_length(value, schema)
return [nil, OpenAPIParser::MoreThanMaxLength.new(value, schema.object_reference)] if schema.maxLength && value.size > schema.maxLength
return [nil, OpenAPIParser::LessThanMinLength.new(value, schema.object_reference)] if schema.minLength && value.size < schema.minLength
[value, nil]
end
def validate_email_format(value, schema)
return [value, nil] unless schema.format == 'email'
return [value, nil] if value.match?(URI::MailTo::EMAIL_REGEXP)
return [nil, OpenAPIParser::InvalidEmailFormat.new(value, schema.object_reference)]
end
def validate_uuid_format(value, schema)
return [value, nil] unless schema.format == 'uuid'
return [value, nil] if value.match(/^[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}$/)
return [nil, OpenAPIParser::InvalidUUIDFormat.new(value, schema.object_reference)]
end
def validate_date_format(value, schema)
if @allow_empty_date_and_datetime && value.to_s.empty?
return [value, nil] if schema.format == 'date'
end
return [value, nil] unless schema.format == 'date'
return [nil, OpenAPIParser::InvalidDateFormat.new(value, schema.object_reference)] unless value =~ /^\d{4}-\d{2}-\d{2}$/
begin
if @date_coerce_class.nil?
# validate only
Date.iso8601(value)
[value, nil]
else
# validate and coerce
[@date_coerce_class.iso8601(value), nil]
end
rescue ArgumentError
# when rfc3339(value) failed
[nil, OpenAPIParser::InvalidDateFormat.new(value, schema.object_reference)]
end
end
def validate_datetime_format(value, schema)
if @allow_empty_date_and_datetime && value.to_s.empty?
return [value, nil] if schema.format == 'date-time'
end
return [value, nil] unless schema.format == 'date-time'
begin
if @datetime_coerce_class.nil?
# validate only
DateTime.rfc3339(value)
[value, nil]
else
# validate and coerce
if @datetime_coerce_class == Time
[DateTime.rfc3339(value).to_time, nil]
else
[@datetime_coerce_class.rfc3339(value), nil]
end
end
rescue ArgumentError
# when rfc3339(value) failed
[nil, OpenAPIParser::InvalidDateTimeFormat.new(value, schema.object_reference)]
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/one_of_validator.rb | lib/openapi_parser/schema_validator/one_of_validator.rb | class OpenAPIParser::SchemaValidator
class OneOfValidator < Base
# @param [Object] value
# @param [OpenAPIParser::Schemas::Schema] schema
def coerce_and_validate(value, schema, **_keyword_args)
if value.nil? && schema.nullable
return [value, nil]
end
if schema.discriminator
return validate_discriminator_schema(schema.discriminator, value)
end
# if multiple schemas are satisfied, it's not valid
result = schema.one_of.one? do |s|
_coerced, err = validatable.validate_schema(value, s)
err.nil?
end
if result
[value, nil]
else
[nil, OpenAPIParser::NotOneOf.new(value, schema.object_reference)]
end
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
ota42y/openapi_parser | https://github.com/ota42y/openapi_parser/blob/e05fcd720c2c4dcaabe39c9f12c8384f3730294a/lib/openapi_parser/schema_validator/boolean_validator.rb | lib/openapi_parser/schema_validator/boolean_validator.rb | class OpenAPIParser::SchemaValidator
class BooleanValidator < Base
include ::OpenAPIParser::SchemaValidator::Enumable
TRUE_VALUES = ['true', '1'].freeze
FALSE_VALUES = ['false', '0'].freeze
def coerce_and_validate(value, schema, **_keyword_args)
value = coerce(value) if @coerce_value
return OpenAPIParser::ValidateError.build_error_result(value, schema) unless value.kind_of?(TrueClass) || value.kind_of?(FalseClass)
value, err = check_enum_include(value, schema)
return [nil, err] if err
[value, nil]
end
private
def coerce(value)
return true if TRUE_VALUES.include?(value)
return false if FALSE_VALUES.include?(value)
value
end
end
end
| ruby | MIT | e05fcd720c2c4dcaabe39c9f12c8384f3730294a | 2026-01-04T17:47:05.849147Z | false |
prognostikos/cb2 | https://github.com/prognostikos/cb2/blob/338cb29d8154a07128501044175eb90e087a7a00/spec/breaker_spec.rb | spec/breaker_spec.rb | require "spec_helper"
describe CB2::Breaker do
let(:breaker) do
CB2::Breaker.new(
strategy: :stub,
allow: false)
end
describe "#run" do
it "raises when the breaker is open" do
assert_raises(CB2::BreakerOpen) do
breaker.run { 1+1 }
end
end
it "returns the original value" do
breaker.strategy.allow = true
assert_equal 42, breaker.run { 42 }
end
end
describe "#open?" do
it "delegates to the strategy" do
assert breaker.open?
end
it "handles Redis errors, just consider the circuit closed" do
stub(breaker.strategy).open? { raise Redis::BaseError }
refute breaker.open?
end
end
end
| ruby | MIT | 338cb29d8154a07128501044175eb90e087a7a00 | 2026-01-04T17:47:11.173474Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.