jhthorsen / json-validator

:cop: Validate data against a JSON schema
https://metacpan.org/release/JSON-Validator
56 stars 57 forks source link

Missing compile step when using JSON::Validator::Joi->array #249

Closed hannaeko closed 3 years ago

hannaeko commented 3 years ago

Steps to reproduce the behavior

Hello,

When using JSON::Validator::Joi to create a schema the items within an array are not compiled automatically. While it can go unnoticed for some types as the properties don't change, when using object with ->strict mode the additionalProperties is missing in the resulting schema. This allows some validation to succeed when they should not.

Code example:

use strict;
use warnings;

use JSON::Validator::Joi;
use JSON::Validator;
use Data::Dumper;

my sub joi {
        return JSON::Validator::Joi->new
}

my $test1 = joi->object->strict->props ({
        ns => joi->string->required
});

#print Dumper($test1->compile);
my @error = $test1->validate({
                ns => "plop",
                toto => "plouf",
        });
print "Inner object validation working: @error\n";

my $test2 = joi->array->strict->items($test1);
#print Dumper($test2->compile);
@error = $test2->validate([{
                ns => "plop",
                toto => "plouf",
        }]);
print "Without compile: @error\n";

my $test3 = joi->array->strict->items($test1->compile);
#print Dumper($test3->compile);
@error = $test3->validate([{
                ns => "plop",
                toto => "plouf",
        }]);
print "With compile: @error\n";

Output:

Inner object validation working: /: Properties not allowed: toto.
Without compile:
With compile: /0: Properties not allowed: toto.

Expected behavior

Calling joi->array->items should compile the schema as do props.

Actual behavior

The schema is not fully compile when validating an array.

jhthorsen commented 3 years ago

Thanks for reporting in! The fix will soon be available on CPAN.