Skip to content

Commit

Permalink
Support oneOf in arrays (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
mkon authored Jun 2, 2022
1 parent 97130d6 commit d959e49
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 9 deletions.
21 changes: 12 additions & 9 deletions lib/openapi_contracts/doc/parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def parse(path = 'openapi.yaml')

def parse_file(path, translate: true)
schema = YAML.safe_load(File.read(path))
translate ? translate_paths(schema, Pathname(path).parent) : schema
translate ? translate_paths!(schema, Pathname(path).parent) : schema
end

def join_partials(cwd, data)
Expand Down Expand Up @@ -67,14 +67,17 @@ def merge_components
data
end

def translate_paths(data, cwd)
data.each_with_object({}) do |(key, val), m|
if val.is_a?(Hash)
m[key] = translate_paths(val, cwd)
elsif key == '$ref' && val !~ %r{^#/}
m[key] = json_pointer(cwd.join(val), '#/')
else
m[key] = val
def translate_paths!(data, cwd)
case data
when Array
data.each { |v| translate_paths!(v, cwd) }
when Hash
data.each_pair do |k, v|
if k == '$ref' && v !~ %r{^#/}
v.replace json_pointer(cwd.join(v), '#/')
else
translate_paths!(v, cwd)
end
end
end
end
Expand Down
6 changes: 6 additions & 0 deletions spec/fixtures/openapi/components/schemas/Address.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
type: object
properties:
street:
type: string
city:
type: string
4 changes: 4 additions & 0 deletions spec/fixtures/openapi/components/schemas/User.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ properties:
name:
type: string
nullable: true
addresses:
type: array
oneOf:
- $ref: './Address.yaml'
email:
$ref: './Email.yaml'
additionalProperties: false
Expand Down
12 changes: 12 additions & 0 deletions spec/integration/rspec_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,16 @@

it { is_expected.to_not match_openapi_doc(doc) }
end

context 'when an attribute does match type oneOf' do
before { response_body[:data][:attributes][:addresses] = {street: 'Somestreet'} }

it { is_expected.to_not match_openapi_doc(doc) }
end

context 'when an attribute does not match type oneOf' do
before { response_body[:data][:attributes][:addresses] = {foo: 'bar'} }

it { is_expected.to_not match_openapi_doc(doc) }
end
end

0 comments on commit d959e49

Please sign in to comment.