Skip to content

Commit 2914d2e

Browse files
authored
Merge pull request ota42y#154 from sasamuku/add_unique_items_validator
Support for uniqueItems in array
2 parents ed39372 + 991d6d5 commit 2914d2e

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

lib/openapi_parser/errors.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,4 +272,15 @@ def message
272272
"#{@reference} #{@value.inspect} contains fewer than min items"
273273
end
274274
end
275+
276+
class NotUniqueItems < OpenAPIError
277+
def initialize(value, reference)
278+
super(reference)
279+
@value = value
280+
end
281+
282+
def message
283+
"#{@reference} #{@value.inspect} contains duplicate items"
284+
end
285+
end
275286
end

lib/openapi_parser/schema_validator/array_validator.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ def coerce_and_validate(value, schema, **_keyword_args)
88
value, err = validate_max_min_items(value, schema)
99
return [nil, err] if err
1010

11+
value, err = validate_unique_items(value, schema)
12+
return [nil, err] if err
13+
1114
# array type have an schema in items property
1215
items_schema = schema.items
1316
coerced_values = value.map do |v|
@@ -28,5 +31,11 @@ def validate_max_min_items(value, schema)
2831

2932
[value, nil]
3033
end
34+
35+
def validate_unique_items(value, schema)
36+
return [nil, OpenAPIParser::NotUniqueItems.new(value, schema.object_reference)] if schema.uniqueItems && value.length != value.uniq.length
37+
38+
[value, nil]
39+
end
3140
end
3241
end

spec/openapi_parser/schema_validator/array_validator_spec.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
type: 'array',
2020
items: { 'type': 'integer' },
2121
maxItems: 2,
22-
minItems: 1
22+
minItems: 1,
23+
uniqueItems: true
2324
},
2425
}
2526
end
@@ -53,6 +54,18 @@
5354
end
5455
end
5556
end
57+
58+
context 'unique items breached' do
59+
let(:invalid_array) { [1, 1] }
60+
let(:params) { { 'ids' => invalid_array } }
61+
62+
it do
63+
expect { subject }.to raise_error do |e|
64+
expect(e).to be_kind_of(OpenAPIParser::NotUniqueItems)
65+
expect(e.message).to end_with("#{invalid_array} contains duplicate items")
66+
end
67+
end
68+
end
5669
end
5770
end
5871
end

0 commit comments

Comments
 (0)