Skip to content

Commit

Permalink
Merge pull request #154 from sasamuku/add_unique_items_validator
Browse files Browse the repository at this point in the history
Support for uniqueItems in array
  • Loading branch information
ota42y committed Oct 9, 2023
2 parents ed39372 + 991d6d5 commit 2914d2e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
11 changes: 11 additions & 0 deletions lib/openapi_parser/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -272,4 +272,15 @@ 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
9 changes: 9 additions & 0 deletions lib/openapi_parser/schema_validator/array_validator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ def coerce_and_validate(value, schema, **_keyword_args)
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|
Expand All @@ -28,5 +31,11 @@ def validate_max_min_items(value, schema)

[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
15 changes: 14 additions & 1 deletion spec/openapi_parser/schema_validator/array_validator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
type: 'array',
items: { 'type': 'integer' },
maxItems: 2,
minItems: 1
minItems: 1,
uniqueItems: true
},
}
end
Expand Down Expand Up @@ -53,6 +54,18 @@
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

0 comments on commit 2914d2e

Please sign in to comment.