Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix array coercion for array parameters with a $ref schema #274

Merged
merged 2 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions lib/JSON/Validator/Schema/OpenAPIv2.pm
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,10 @@ sub _bundle_ref_path_expand {

sub _coerce_arrays {
my ($self, $val, $param) = @_;
my $data_type = data_type $val->{value};
my $schema_type = schema_type $param->{schema} || $param; # $param->{schema} is for OpenAPIv3
my $data_type = data_type $val->{value};
my $schema = $param->{schema} || $param; # $param->{schema} is for OpenAPIv3
$schema = $self->get($schema->{'$ref'} =~ s!^#!!r) if $schema->{'$ref'};
my $schema_type = schema_type $schema;
return $val->{value} = [$val->{value}] if $schema_type eq 'array' and $data_type ne 'array';
return $val->{value} = @{$val->{value}} ? $val->{value}[-1] : undef
if $schema_type ne 'array' and $data_type eq 'array';
Expand Down
27 changes: 25 additions & 2 deletions t/openapiv3-coerce-array.t
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use JSON::Validator;
use Test::More;

my $schema = JSON::Validator->new->schema('data://main/openapi.yaml')->schema;
my ($body, @errors);
my ($body, $query, @errors);

subtest 'number to array' => sub {
$body = {exists => 1, value => {id => 42}};
Expand All @@ -23,9 +23,16 @@ subtest 'already an array' => sub {
is "@errors", "", "valid";
};

subtest 'parameter array schema is $ref' => sub {
$query = {exists => 1, value => [42, 43]};
@errors = $schema->validate_request([get => '/test'], {query => \&query});
is "@errors", "", "valid";
};

done_testing;

sub body {$body}
sub body {$body}
sub query {$query}

__DATA__
@@ openapi.yaml
Expand Down Expand Up @@ -53,3 +60,19 @@ paths:
responses:
200:
description: OK
get:
parameters:
- name: id
in: query
required: true
schema:
$ref: '#/components/schemas/IntArray'
responses:
200:
description: OK
components:
schemas:
IntArray:
type: array
items:
type: integer