libjson-validator-perl-0.66+dfsg.orig/0000755000175000017500000000000012660423447017210 5ustar gregoagregoalibjson-validator-perl-0.66+dfsg.orig/MANIFEST0000644000175000017500000000172612660423447020347 0ustar gregoagregoa.perltidyrc .ship.conf .travis.yml Changes cpanfile lib/JSON/Validator.pm Makefile.PL MANIFEST This list of files README t/00-basic.t t/acceptance.t t/booleans-xs.t t/booleans.t t/coerce-args.t t/deep-mixed-ref.t t/definitions/age.json t/definitions/unit.json t/definitions/weight.json t/invalid-ref.t t/jv-allof.t t/jv-anyof.t t/jv-array.t t/jv-basic.t t/jv-enum.t t/jv-formats.t t/jv-integer.t t/jv-not.t t/jv-object.t t/jv-oneof.t t/jv-required.t t/jv-string.t t/load-data.t t/load-http.t t/load-json.t t/load-yaml.t t/petstore.t t/recursion.t t/relative-ref.t t/resolve.t t/spec/invalid-ref.t t/spec/person.json t/spec/petstore.json t/spec/with-deep-mixed-ref.json t/spec/with-relative-ref.json t/swagger-validate-response-object.t t/swagger2-issues-50.t t/to-json.t t/validate-json.t t/validate-recursive.t META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) libjson-validator-perl-0.66+dfsg.orig/Changes0000644000175000017500000000600612656421311020476 0ustar gregoagregoaRevision history for perl distribution JSON-Validator 0.66 2016-02-09T18:32:57+0100 - Fix validating recursive datastructures 0.65 2016-01-07T15:31:37+0100 - Fix t/swagger-validate-response-object.t require Swagger2 0.66 #14 0.64 2015-12-18T16:03:09+0800 - Fix treating JSON::PP::Boolean objects as boolean #13 Contributor: Krasimir Berov - Allow hash reference as arguments to coerce #13 Contributor: Krasimir Berov 0.63 2015-11-28T08:17:59+0100 - Fix skip test in t/booleans.t 0.62 2015-11-27T12:13:08+0100 - Remove support for YAML.pm #jhthorsen/swagger2#50 - Remove support for YAML::Tiny #jhthorsen/swagger2#50 0.61 2015-11-11T21:01:13+0100 - Fix use of TO_JSON() on objects inside arrays #12 0.60 2015-11-09T14:35:56+0000 - Can use TO_JSON() when validating perl objects 0.59 2015-10-14T17:19:53+0200 - Move "collectionFormat" support to Swagger2 0.58 2015-10-13T14:47:25+0200 - Fix string "0" is not detected as boolean 0.57 2015-10-11T13:20:45+0200 - Trust guesswork if input data is undefined 0.56 2015-09-30T11:43:49+0200 - Can read YAML::XS booleans automatically #8 - Change coerce() into a method. #8 - Remove EXPERIMENTAL coerce attribute #8 - Remove EXPERIMENTAL JSON_VALIDATOR_COERCE_VALUES and SWAGGER_COERCE_VALUES #8 0.55 2015-09-29T19:01:05+0200 - Fix "required" cannot be a boolean on properties - Improved documentation of error object - Change anyOf/allOf/oneOf error message 0.54 2015-09-27T13:33:02+0200 - Add support for $ref to relative path #3 #4 #5 - Removed Swagger specific type "file" - Removed Swagger specific formats: "byte", "date", "double", "float", "int32" and "int64". 0.53 2015-09-13T10:52:16+0200 - Fix properties, patternProperties, additionalProperties interaction - patternProperty invalidates property - Fix validation for a keyword and instance SHOULD succeed when keywords does not match primitive type - Fix allOf with base schema - mismatch base schema - Fix checking for a boolean "required" 0.52 2015-09-05T13:52:39+0200 - Add guessing of schema type, based on other attributes - More strict on what is validated as "boolean" - Fix additionalItems are allowed by default - Fix additionalProperties allows a schema which should validate - Fix validating "enum" - Fix validating "array" against "additionalItems" - Fix bugs after running https://github.com/Relequestual/Test-JSON-Schema-Acceptance to validate 0.51 2015-08-24T16:19:06+0200 - Fix "$ref" pointing to a file on disk #1 0.50 2015-08-23T15:07:08+0200 - Fix missing namespace when registering new document - Made cache_dir() public - Bundled spec for json-schema and swagger 0.49 2015-08-23T00:51:08+0200 - Fix loading schema from files 0.48 2015-08-22T21:23:55+0200 - Merged core functionality from Swagger2 and Swagger2::SchemaValidator into this module, JSON::Validator See https://metacpan.org/source/JHTHORSEN/Swagger2-0.47/Changes for previous Changes (<=0.47) - Fix coercing collectionFormat strings into integers and numbers - Add support for reading schemas from __DATA__ section libjson-validator-perl-0.66+dfsg.orig/.ship.conf0000644000175000017500000000050412566023511021070 0ustar gregoagregoa# Generated by git-ship. See 'git-ship --man' for help or https://github.com/jhthorsen/app-git-ship class = App::git::ship::perl project_name = homepage = https://github.com/jhthorsen/json-validator bugtracker = https://github.com/jhthorsen/json-validator/issues license = artistic_2 build_test_options = # Example: -l -j8 libjson-validator-perl-0.66+dfsg.orig/.perltidyrc0000644000175000017500000000072012566025501021363 0ustar gregoagregoa-pbp # Start with Perl Best Practices -w # Show all warnings -iob # Ignore old breakpoints -l=120 # 120 characters per line -mbl=2 # No more than 2 blank lines -i=2 # Indentation is 2 columns -ci=2 # Continuation indentation is 2 columns -vt=0 # Less vertical tightness -pt=2 # High parenthesis tightness -bt=2 # High brace tightness -sbt=2 # High square bracket tightness -isbc # Don't indent comments without leading space libjson-validator-perl-0.66+dfsg.orig/cpanfile0000644000175000017500000000061612652632416020716 0ustar gregoagregoa# You can install this projct with curl -L http://cpanmin.us | perl - https://github.com/jhthorsen/json-validator/archive/master.tar.gz requires "Mojolicious" => "6.00"; recommends "Data::Validate::Domain" => "0.10"; recommends "Data::Validate::IP" => "0.24"; recommends "YAML::XS" => "0.59"; test_requires "Test::More" => "0.88"; test_requires "Test::Warnings" => "0.016"; libjson-validator-perl-0.66+dfsg.orig/README0000644000175000017500000001727212656421311020072 0ustar gregoagregoaNAME JSON::Validator - Validate data against a JSON schema VERSION 0.66 SYNOPSIS use JSON::Validator; my $validator = JSON::Validator->new; # Define a schema - http://json-schema.org/examples.html # You can also load schema from disk or web $validator->schema( { type => "object", required => ["firstName", "lastName"], properties => { firstName => {type => "string"}, lastName => {type => "string"}, age => {type => "integer", minimum => 0, description => "Age in years"} } } ); # Validate your data @errors = $validator->validate({firstName => "Jan Henning", lastName => "Thorsen", age => -42}); # Do something if any errors was found die "@errors" if @errors; DESCRIPTION JSON::Validator is a class for validating data against JSON schemas. You might want to use this instead of JSON::Schema if you need to validate data against draft 4 of the specification. This module is currently EXPERIMENTAL. Hopefully nothing drastic will change, but it needs to fit together nicely with Swagger2 - Since this is a spin-off project. Supported schema formats JSON::Validator can load JSON schemas in multiple formats: Plain perl data structured (as shown in "SYNOPSIS") or files on disk/web in the JSON/YAML format. The JSON parsing is done using Mojo::JSON, while the YAML parsing is done with an optional modules which need to be installed manually. JSON::Validator will look for the YAML modules in this order: YAML::XS, YAML::Syck. The order is set by which module that performs the best, so it might change in the future. Resources Here are some resources that are related to JSON schemas and validation: * * * * Swagger2 ERROR OBJECT Overview The method "validate" and the function "validate_json" returns error objects when the input data violates the "schema". Each of the objects looks like this: bless { message => "Some description", path => "/json/path/to/node", }, "JSON::Validator::Error" Operators The error object overloads the following operators: * bool Returns a true value. * string Returns the "path" and "message" part as a string: "$path: $message". Special cases Have a look at the test suite for documented examples of the error cases. Especially look at "jv-allof.t", "jv-anyof.t" and "jv-oneof.t". The special cases for "allOf", "anyOf" and "oneOf" will contain the error messages from all the failing rules below. It can be a bit hard to read, so if the error message is long, then you might want to run a smaller test with "JSON_VALIDATOR_DEBUG=1". Example error object: bless { message => "[0] String is too long: 8/5. [1] Expected number - got string.", path => "/json/path/to/node", }, "JSON::Validator::Error" Note that these error messages are subject for change. Any suggestions are most welcome! FUNCTIONS validate_json use JSON::Validator "validate_json"; @errors = validate_json $data, $schema; This can be useful in web applications: @errors = validate_json $c->req->json, "data://main/spec.json"; See also "validate" and "ERROR OBJECT" for more details. ATTRIBUTES cache_dir $self = $self->cache_dir($path); $path = $self->cache_dir; Path to where downloaded spec files should be cached. Defaults to "JSON_VALIDATOR_CACHE_DIR" or the bundled spec files that are shipped with this distribution. formats $hash_ref = $self->formats; $self = $self->formats(\%hash); Holds a hash-ref, where the keys are supported JSON type "formats", and the values holds a code block which can validate a given format. Note! The modules mentioned below are optional. * date-time An RFC3339 timestamp in UTC time. This is formatted as "YYYY-MM-DDThh:mm:ss.fffZ". The milliseconds portion (".fff") is optional * email Validated against the RFC5322 spec. * hostname Will be validated using Data::Validate::Domain if installed. * ipv4 Will be validated using Data::Validate::IP if installed or fall back to a plain IPv4 IP regex. * ipv6 Will be validated using Data::Validate::IP if installed. * uri Validated against the RFC3986 spec. ua $ua = $self->ua; $self = $self->ua(Mojo::UserAgent->new); Holds a Mojo::UserAgent object, used by "schema" to load a JSON schema from remote location. Note that the default Mojo::UserAgent will detect proxy settings and have "max_redirects" in Mojo::UserAgent set to 3. (These settings are EXPERIMENTAL and might change without a warning) METHODS coerce $self = $self->coerce(booleans => 1, numbers => 1, strings => 1); $self = $self->coerce({booleans => 1, numbers => 1, strings => 1}); $self = $self->coerce(1) # enable all $hash = $self->coerce; Set the given type to coerce. Before enabling coercion this module is very strict when it comes to validating types. Example: The string "1" is not the same as the number 1, unless you have coercion enabled. WARNING! Enabling coercion might hide bugs in your api, which would have been detected if you were strict. For example JavaScript is very picky on a number being an actual number. This module tries it best to convert the data on the fly into the proper value, but this means that you unit tests might be ok, but the client side libraries (that care about types) might break. Loading a YAML document will enable "booleans" automatically. This feature is experimental, but was added since YAML has no real concept of booleans, such as Mojo::JSON or other JSON parsers. The coercion rules are EXPERIMENTAL and will be tighten/loosen if bugs are reported. See for more details. schema $self = $self->schema(\%schema); $self = $self->schema($url); $schema = $self->schema; Used to set a schema from either a data structure or a URL. $schema will be a Mojo::JSON::Pointer object when loaded, and "undef" by default. The $url can take many forms, but needs to point to a text file in the JSON or YAML format. * http://... or https://... A web resource will be fetched using the Mojo::UserAgent, stored in "ua". * data://Some::Module/file.name This version will use "data_section" in Mojo::Loader to load "file.name" from the module "Some::Module". * /path/to/file An URL (without a recognized scheme) will be loaded from disk. singleton $self = $class->singleton; Returns the JSON::Validator object used by "validate_json". validate @errors = $self->validate($data); Validates $data against a given JSON "schema". @errors will contain validation error objects or be an empty list on success. See "ERROR OBJECT" for details. COPYRIGHT AND LICENSE Copyright (C) 2014-2015, Jan Henning Thorsen This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0. AUTHOR Jan Henning Thorsen - "jhthorsen@cpan.org" libjson-validator-perl-0.66+dfsg.orig/t/0000755000175000017500000000000012656421312017445 5ustar gregoagregoalibjson-validator-perl-0.66+dfsg.orig/t/00-basic.t0000644000175000017500000000213412566037111021130 0ustar gregoagregoause Test::More; use File::Find; if(($ENV{HARNESS_PERL_SWITCHES} || '') =~ /Devel::Cover/) { plan skip_all => 'HARNESS_PERL_SWITCHES =~ /Devel::Cover/'; } if(!eval 'use Test::Pod; 1') { *Test::Pod::pod_file_ok = sub { SKIP: { skip "pod_file_ok(@_) (Test::Pod is required)", 1 } }; } if(!eval 'use Test::Pod::Coverage; 1') { *Test::Pod::Coverage::pod_coverage_ok = sub { SKIP: { skip "pod_coverage_ok(@_) (Test::Pod::Coverage is required)", 1 } }; } if(!eval 'use Test::CPAN::Changes; 1') { *Test::CPAN::Changes::changes_file_ok = sub { SKIP: { skip "changes_ok(@_) (Test::CPAN::Changes is required)", 4 } }; } find( { wanted => sub { /\.pm$/ and push @files, $File::Find::name }, no_chdir => 1 }, -e 'blib' ? 'blib' : 'lib', ); plan tests => @files * 3 + 4; for my $file (@files) { my $module = $file; $module =~ s,\.pm$,,; $module =~ s,.*/?lib/,,; $module =~ s,/,::,g; ok eval "use $module; 1", "use $module" or diag $@; Test::Pod::pod_file_ok($file); Test::Pod::Coverage::pod_coverage_ok($module, { also_private => [ qr/^[A-Z_]+$/ ], }); } Test::CPAN::Changes::changes_file_ok(); libjson-validator-perl-0.66+dfsg.orig/t/booleans-xs.t0000644000175000017500000000123412634736637022103 0ustar gregoagregoaBEGIN { $ENV{TEST_XS} = eval "require Cpanel::JSON::XS;require Mojo::JSON::MaybeXS;1"; } use Mojo::Base -strict; use Test::More; use JSON::Validator; plan skip_all => 'Cpanel::JSON::XS and Mojo::JSON::MaybeXS is required.' unless $ENV{TEST_XS}; my $schema = {properties => {disabled => {type => "boolean"}}}; my $validator = JSON::Validator->new->schema($schema); my $objects = [{disabled => 1}, {disabled => 0}]; my @errors; for my $o (@$objects) { $o->{disabled} = $o->{disabled} ? Mojo::JSON->true : Mojo::JSON->false; @errors = $validator->validate($o); ok !@errors, "boolean via Mojo::JSON::MaybeXS ($o->{disabled}). (@errors)"; } done_testing; libjson-validator-perl-0.66+dfsg.orig/t/acceptance.t0000644000175000017500000000204012602534467021723 0ustar gregoagregoause Mojo::Base -strict; use Mojo::JSON qw(encode_json decode_json ); use Mojo::Util 'dumper'; use Test::More; use JSON::Validator 'validate_json'; plan skip_all => 'cpanm Test::JSON::Schema::Acceptance' unless eval 'use Test::JSON::Schema::Acceptance; 1'; my $opts = { only_test => $ENV{ACCEPTANCE_TEST}, skip_tests => [ 'Unicode code point', # Valid unicode won't pass Mojo::JSON 'dependencies', # TODO 'valid definition schema', # This module does not validate the schema, it only validates data 'ref', # No way to fetch http://localhost:1234/... ], }; my @drafts = qw( 4 ); # ( 3 4 ) for my $draft (@drafts) { my $accepter = Test::JSON::Schema::Acceptance->new($draft); $accepter->acceptance( sub { my $schema = shift; my $input = decode_json shift; my @errors = validate_json $input, $schema; diag dumper([$input, $schema, @errors]) if $ENV{ACCEPTANCE_TEST}; return @errors ? 0 : 1; }, $opts, ); } done_testing(); libjson-validator-perl-0.66+dfsg.orig/t/recursion.t0000644000175000017500000000127612656377544021672 0ustar gregoagregoause Mojo::Base -strict; use Test::Mojo; use Test::More; use JSON::Validator 'validate_json'; my $data = {}; $data->{rec} = $data; $SIG{ALRM} = sub { die 'Recursion!' }; alarm 2; my @errors = ('i_will_be_removed'); eval { @errors = validate_json {top => $data}, 'data://main/spec.json' }; is $@, '', 'no error'; is_deeply(\@errors, [], 'avoided recursion'); done_testing; __DATA__ @@ spec.json { "properties": { "top": { "$ref": "#/definitions/again" } }, "definitions": { "again": { "anyOf": [ {"type": "string"}, { "type": "object", "properties": { "rec": {"$ref": "#/definitions/again"} } } ] } } } libjson-validator-perl-0.66+dfsg.orig/t/jv-allof.t0000644000175000017500000000141712602533105021342 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my $schema = {allOf => [{type => "string", maxLength => 5}, {type => "number", minimum => 0}]}; my @errors; @errors = $validator->validate("short", $schema); is "@errors", "/: allOf failed: (Expected number - got string.)", "got string"; @errors = $validator->validate(12, $schema); is "@errors", "/: allOf failed: (Expected string - got number.)", "got number"; $schema = {allOf => [{type => "string", maxLength => 7}, {type => "string", maxLength => 5}]}; @errors = $validator->validate("toolong", $schema); is "@errors", "/: allOf failed: ([1] String is too long: 7/5.)", "too long"; @errors = $validator->validate("short", $schema); is "@errors", "", "success"; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/jv-formats.t0000644000175000017500000000447312575271303021735 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my $schema = {type => 'object', properties => {v => {type => 'string'}}}; my @errors; { $schema->{properties}{v}{format} = 'date-time'; @errors = $validator->validate({v => '2014-12-09T20:49:37Z'}, $schema); is "@errors", "", "date-time valid"; @errors = $validator->validate({v => '20:46:02'}, $schema); is "@errors", "/v: Does not match date-time format.", "date-time invalid"; } { local $schema->{properties}{v}{format} = 'email'; @errors = $validator->validate({v => 'jhthorsen@cpan.org'}, $schema); is "@errors", "", "email valid"; @errors = $validator->validate({v => 'foo'}, $schema); is "@errors", "/v: Does not match email format.", "email invalid"; } if (JSON::Validator::VALIDATE_HOSTNAME) { local $schema->{properties}{v}{format} = 'hostname'; @errors = $validator->validate({v => 'mojolicio.us'}, $schema); is "@errors", "", "hostname valid"; @errors = $validator->validate({v => '[]'}, $schema); is "@errors", "/v: Does not match hostname format.", "hostname invalid"; } else { diag "Data::Validate::Domain is not installed"; } { local $schema->{properties}{v}{format} = 'ipv4'; @errors = $validator->validate({v => '255.100.30.1'}, $schema); is "@errors", "", "ipv4 valid"; @errors = $validator->validate({v => '300.0.0.0'}, $schema); is "@errors", "/v: Does not match ipv4 format.", "ipv4 invalid"; } if (JSON::Validator::VALIDATE_IP) { local $schema->{properties}{v}{format} = 'ipv6'; @errors = $validator->validate({v => '::1'}, $schema); is "@errors", "", "ipv6 valid"; @errors = $validator->validate({v => '300.0.0.0'}, $schema); is "@errors", "/v: Does not match ipv6 format.", "ipv6 invalid"; } else { diag "Data::Validate::IP is not installed"; } { local $schema->{properties}{v}{format} = 'uri'; @errors = $validator->validate({v => 'http://mojolicio.us/?ø=123'}, $schema); is "@errors", "", "uri valid"; local $TODO = "Not sure how to make an invalid URI"; @errors = $validator->validate({v => 'anything'}, $schema); is "@errors", "/v: Does not match uri format.", "uri invalid"; } { local $schema->{properties}{v}{format} = 'unknown'; @errors = $validator->validate({v => 'whatever'}, $schema); is "@errors", "", "unknown is always valid"; } done_testing; libjson-validator-perl-0.66+dfsg.orig/t/swagger2-issues-50.t0000644000175000017500000000067512626035072023117 0ustar gregoagregoause Mojo::Base -strict; use Test::More; my $i = 0; my $doc = <<'HERE'; --- foo: - '$ref': '#/parameters/Foo' HERE for my $module (qw( YAML::XS YAML::Syck )) { next unless eval "require $module;1"; my $loader = eval "\\\&$module\::Load"; is_deeply eval { $loader->($doc) } || undef, {foo => [{'$ref' => '#/parameters/Foo'}]}, "loaded with $module"; $i++; } plan skip_all => 'No YAML module was installed' unless $i; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/definitions/0000755000175000017500000000000012660423447021766 5ustar gregoagregoalibjson-validator-perl-0.66+dfsg.orig/t/definitions/weight.json0000644000175000017500000000023512601751064024142 0ustar gregoagregoa{ "type": "object", "description": "Weight with Units", "properties": { "mass": { "type": "integer" }, "unit": { "$ref": "./unit.json" } } } libjson-validator-perl-0.66+dfsg.orig/t/definitions/age.json0000644000175000017500000000011112601743073023401 0ustar gregoagregoa{ "type": "integer", "minimum": 0, "description": "Age in years" } libjson-validator-perl-0.66+dfsg.orig/t/definitions/unit.json0000644000175000017500000000012312601750442023625 0ustar gregoagregoa{ "type": "string", "description": "Unit of Mass", "pattern": "^kg|st|lb$" } libjson-validator-perl-0.66+dfsg.orig/t/petstore.t0000644000175000017500000000137512601742662021511 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; $validator->schema(File::Spec->catfile(qw( t spec petstore.json ))); is_deeply( $validator->schema->get('/paths/~1pets/get/responses/200/schema/items'), { required => ["id", "name"], properties => {id => {type => "integer", format => "int64"}, name => {type => "string"}, tag => {type => "string"}} }, 'expanded /paths/~1pets/get/responses/200/schema/items' ); ok !find_key($validator->schema->data, '$ref'), 'no $ref in schema'; done_testing; sub find_key { my ($data, $needle) = @_; for my $k (keys %$data) { return 1 if $k eq $needle; return 1 if ref $data->{$k} eq 'HASH' and find_key($data->{$k}, $needle); } return 0; } libjson-validator-perl-0.66+dfsg.orig/t/jv-array.t0000644000175000017500000000367212607465344021406 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; use Mojo::JSON; my $validator = JSON::Validator->new; my @errors; my $simple = {type => "array", items => {type => "number"}}; my $length = {type => "array", minItems => 2, maxItems => 2}; my $unique = {type => 'array', uniqueItems => 1, items => {type => 'integer'}}; my $tuple = { type => "array", items => [ {type => "number"}, {type => "string"}, {type => "string", enum => ["Street", "Avenue", "Boulevard"]}, {type => "string", enum => ["NW", "NE", "SW", "SE"]} ] }; @errors = $validator->validate([1], $simple); is "@errors", "", "simple: success"; @errors = $validator->validate([1, "foo"], $simple); is "@errors", "/1: Expected number - got string.", "simple: got string"; @errors = $validator->validate([1], $length); is "@errors", "/: Not enough items: 1/2.", "length: not enough"; @errors = $validator->validate([1, 2], $length); is "@errors", "", "length: success"; @errors = $validator->validate([1, 2, 3], $length); is "@errors", "/: Too many items: 3/2.", "length: too many"; @errors = $validator->validate([123, 124], $unique); is "@errors", "", "unique: success"; @errors = $validator->validate([1, 2, 1], $unique); is "@errors", "/: Unique items required.", "unique: fail"; @errors = $validator->validate([1600, "Pennsylvania", "Avenue", "NW"], $tuple); is "@errors", "", "tuple: success"; @errors = $validator->validate([24, "Sussex", "Drive"], $tuple); is "@errors", "", "tuple: invalid"; @errors = $validator->validate([10, "Downing", "Street"], $tuple); is "@errors", "", "tuple: not complete length"; @errors = $validator->validate([1600, "Pennsylvania", "Avenue", "NW", "Washington"], $tuple); is "@errors", "", "tuple: too many"; $tuple->{additionalItems} = Mojo::JSON->false; @errors = $validator->validate([1600, "Pennsylvania", "Avenue", "NW", "Washington"], $tuple); is "@errors", "/: Invalid number of items: 5/4.", "tuple: additionalItems"; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/load-yaml.t0000644000175000017500000000146512566143724021527 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; plan skip_all => $@ unless eval { JSON::Validator::_load_yaml("---\nfoo: bar") }; my $validator = JSON::Validator->new; my @errors = $validator->schema('data://Some::Module/s_pec-/-ficaTion')->validate({firstName => 'yikes!'}); is int(@errors), 1, 'one error'; is $errors[0]->path, '/lastName', 'lastName'; is $errors[0]->message, 'Missing property.', 'required'; is_deeply $errors[0]->TO_JSON, {path => '/lastName', message => 'Missing property.'}, 'TO_JSON'; done_testing; package Some::Module; __DATA__ @@ s_pec-/-ficaTion --- title: Example Schema type: object required: - firstName - lastName properties: firstName: type: string lastName: type: string age: type: integer minimum: 0 description: Age in years libjson-validator-perl-0.66+dfsg.orig/t/jv-basic.t0000644000175000017500000000200412606442472021331 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; use Mojo::JSON; my $validator = JSON::Validator->new; my @errors; for (undef, [], {}, 123, "foo") { my $type = $_; @errors = $validator->validate(j($_), {type => 'any'}); $type //= 'null'; is "@errors", "", "any $type"; } @errors = $validator->validate(j(undef), {type => 'null'}); is "@errors", "", "null"; @errors = $validator->validate(j(1), {type => 'null'}); is "@errors", "/: Not null.", "not null"; @errors = $validator->validate(j(Mojo::JSON->false), {type => 'boolean'}); is "@errors", "", "boolean false"; @errors = $validator->validate(j(Mojo::JSON->true), {type => 'boolean'}); is "@errors", "", "boolean true"; @errors = $validator->validate(j("foo"), {type => 'boolean'}); is "@errors", "/: Expected boolean - got string.", "not boolean"; @errors = $validator->validate(undef, {properties => {}}); is "@errors", "/: Expected object - got null.", "undef"; done_testing; sub j { Mojo::JSON::decode_json(Mojo::JSON::encode_json($_[0])); } libjson-validator-perl-0.66+dfsg.orig/t/jv-required.t0000644000175000017500000000157612602533105022073 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator 'validate_json'; my $schema0 = {type => 'object', properties => {mynumber => {type => 'string', required => 1}}}; my $schema1 = {type => 'object', properties => {mynumber => {type => 'string'}}, required => ['mynumber']}; my $schema2 = {type => 'object', properties => {mynumber => {type => 'string'}}}; my $data1 = {mynumber => "yay"}; my $data2 = {mynumbre => "err"}; my @errors = validate_json $data1, $schema1; is "@errors", "", "data1, schema1"; @errors = validate_json $data2, $schema0; is "@errors", "", "cannot have required on properties"; @errors = validate_json $data2, $schema1; is "@errors", "/mynumber: Missing property.", "data2, schema1"; @errors = validate_json $data1, $schema2; is "@errors", "", "data1, schema2"; @errors = validate_json $data2, $schema2; is "@errors", "", "data2, schema2"; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/relative-ref.t0000644000175000017500000000135012600036722022212 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; use Mojo::Util qw( slurp spurt ); my $file = File::Spec->catfile(File::Basename::dirname(__FILE__), 'spec', 'with-relative-ref.json'); my $validator = JSON::Validator->new->schema($file); is $validator->schema->get('/properties/age/type'), 'integer', 'loaded age.json from disk'; use Mojolicious::Lite; push @{app->static->paths}, File::Basename::dirname(__FILE__); $validator->ua(app->ua); $validator->schema(app->ua->server->url->clone->path('/spec/with-relative-ref.json')); is $validator->schema->get('/properties/age/type'), 'integer', 'loaded age.json from http'; my @errors = $validator->validate({age => 'not a number'}); is int(@errors), 1, 'invalid age'; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/booleans.t0000644000175000017500000000230412635120730021430 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new->schema( {properties => {required => {type => "boolean", enum => [Mojo::JSON->true, Mojo::JSON->false]}}}); my @errors = $validator->validate({required => '0'}); is $errors[1]->{message}, 'Expected boolean - got string.', 'string 0 is not detected as boolean'; $validator->coerce(booleans => 1); for my $value (!!1, !!0) { my @errors = $validator->validate({required => $value}); ok !@errors, "boolean ($value). (@errors)"; } for my $value (1, "1", "0", "") { my @errors = $validator->validate({required => $value}); ok @errors, "not boolean ($value). @errors"; } for my $value ("true", "false") { my @errors = $validator->validate({required => $value}); ok !@errors, "boolean ($value). (@errors)"; } SKIP: { skip 'YAML::XS is not installed', 1 unless eval 'require YAML::XS;1'; $validator->coerce(booleans => 0); # see that _load_schema_from_text() turns it back on my @errors = $validator->validate($validator->_load_schema_from_text("---\nrequired: true\n")); ok !@errors, "true in YAML::XS is boolean. (@errors)"; ok $validator->coerce->{booleans}, 'coerce booleans'; } done_testing; libjson-validator-perl-0.66+dfsg.orig/t/jv-oneof.t0000644000175000017500000000234312602533105021352 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my $schema = {oneOf => [{type => "string", maxLength => 5}, {type => "number", minimum => 0}]}; my @errors; @errors = $validator->validate("short", $schema); is "@errors", "", "string"; @errors = $validator->validate(12, $schema); is "@errors", "", "number"; $schema = {oneOf => [{type => "number", multipleOf => 5}, {type => "number", multipleOf => 3}]}; @errors = $validator->validate(10, $schema); is "@errors", "", "n:10"; @errors = $validator->validate(9, $schema); is "@errors", "", "n:9"; @errors = $validator->validate(15, $schema); is "@errors", "/: All of the oneOf rules match.", "n:15"; # Alternative oneOf # http://json-schema.org/latest/json-schema-validation.html#anchor79 $schema = {type => 'object', properties => {x => {type => ['string', 'null'], format => 'date-time'}}}; @errors = $validator->validate({x => 'foo'}, $schema); is "@errors", "/x: ([0] Does not match date-time format. [1] Not null.)", "foo"; @errors = $validator->validate({x => '2015-04-21T20:30:43.000Z'}, $schema); is "@errors", "", "YYYY-MM-DDThh:mm:ss.fffZ"; @errors = $validator->validate({x => undef}, $schema); is "@errors", "", "null"; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/swagger-validate-response-object.t0000644000175000017500000000474212643473220026170 0ustar gregoagregoause Mojo::Base -strict; use Test::Mojo; use Test::More; # # This test used to fail with error messages such as: # /paths/~1commands/get/responses/default: Expected only one to match. # /info/title: Missing property. # /definitions/Error/properties/errors/items: [0] Properties not allowed: message, path. [1] Expected array - got object. # The message that tripped me off was "Expected only one to match." which # made me believe there was a bug in JSON::Validator. The real reason was # however that spec.json contained an invalid spec. Such as "required":true, # instead of "required":["message"]. # I think it would be nice to have better error messages, but at right now I # don't have the capacity to figure out how to make those. # # - Jan Henning Thorsen # plan skip_all => 'Swagger2 0.66+ is required' unless eval 'require Swagger2;Swagger2->VERSION >= 0.66'; my $swagger = Swagger2->new('data://main/spec.json'); my @errors = $swagger->validate; ok !@errors, 'no errors in spec.json' or diag join "\n", @errors; done_testing; __DATA__ @@ spec.json { "swagger": "2.0", "info": { "title": "(part of) Convos API specification", "version": "0.87" }, "host": "demo.convos.by", "basePath": "/1.0", "schemes": [ "http" ], "paths": { "/commands": { "get": { "responses": { "200": { "description": "List of commands.", "schema": { "type": "object", "properties": { "commands": { "type": "array", "$ref": "#/definitions/Command" } } } }, "default": { "description": "Error.", "schema": { "$ref": "#/definitions/Error" } } } } } }, "definitions": { "Command": { "required": ["id", "command"], "properties": { "id": { "type": "string", "description": "jhthorsen: Cannot remember what 'id' is." }, "command": { "type": "string", "description": "A command to be sent to backend" } } }, "Error": { "properties": { "errors": { "type": "array", "items": { "type": "object", "required": ["message"], "properties": { "message": { "type": "string", "description": "Human readable description of the error" }, "path": { "type": "string", "description": "JSON pointer to the input data where the error occur" } } } } } } } } libjson-validator-perl-0.66+dfsg.orig/t/load-json.t0000644000175000017500000000145512600036722021521 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; use Mojo::Util qw( slurp spurt ); my $file = File::Spec->catfile(File::Basename::dirname(__FILE__), 'spec', 'person.json'); my $validator = JSON::Validator->new->schema($file); my @errors = $validator->validate({firstName => 'yikes!'}); is int(@errors), 1, 'one error'; is $errors[0]->path, '/lastName', 'lastName'; is $errors[0]->message, 'Missing property.', 'required'; is_deeply $errors[0]->TO_JSON, {path => '/lastName', message => 'Missing property.'}, 'TO_JSON'; my $spec = slurp $file; $spec =~ s!"#!"person.json#! or die "Invalid spec: $spec"; spurt $spec => "$file.2"; ok eval { JSON::Validator->new->schema("$file.2") }, 'test issue #1 where $ref could not point to a file' or diag $@; unlink "$file.2"; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/invalid-ref.t0000644000175000017500000000054112601742662022036 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; eval { $validator->schema('data://main/spec.json') }; like $@, qr{Could not find "\#/definitions/Pet"}, 'missing definition'; done_testing; __DATA__ @@ spec.json { "schema": { "type": "array", "items": { "$ref": "#/definitions/Pet" } } } libjson-validator-perl-0.66+dfsg.orig/t/load-http.t0000644000175000017500000000071112566140134021525 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; plan skip_all => 'TEST_ONLINE=1' unless $ENV{TEST_ONLINE}; my $validator = JSON::Validator->new; $validator->schema('http://swagger.io/v2/schema.json'); isa_ok($validator->schema, 'Mojo::JSON::Pointer'); like $validator->schema->get('/title'), qr{swagger}i, 'got swagger spec'; ok $validator->schema->get('/patternProperties/^x-/description'), 'resolved vendorExtension $ref'; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/jv-string.t0000644000175000017500000000227312566053364021571 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; use utf8; my $validator = JSON::Validator->new; my $schema = {type => 'object', properties => {nick => {type => 'string', minLength => 3, maxLength => 10, pattern => qr{^\w+$}}}}; my @errors = $validator->validate({nick => 'batman'}, $schema); is "@errors", "", "batman"; @errors = $validator->validate({nick => 1000}, $schema); is "@errors", "/nick: Expected string - got number.", "integer"; @errors = $validator->validate({nick => '1000'}, $schema); is "@errors", "", "number as string"; @errors = $validator->validate({nick => 'aa'}, $schema); is "@errors", "/nick: String is too short: 2/3.", "too short"; @errors = $validator->validate({nick => 'a' x 11}, $schema); is "@errors", "/nick: String is too long: 11/10.", "too long"; @errors = $validator->validate({nick => '[nick]'}, $schema); like "@errors", qr{/nick: String does not match}, "pattern"; delete $schema->{properties}{nick}{pattern}; @errors = $validator->validate({nick => 'Déjà vu'}, $schema); is "@errors", "", "unicode"; $validator->coerce(1); @errors = $validator->validate({nick => 1000}, $schema); is "@errors", "", "coerced integer into string"; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/resolve.t0000644000175000017500000000142512601730124021305 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; # from http://json-schema.org/latest/json-schema-core.html#anchor30 $validator->schema( { id => 'http://my.site/myschema#', definitions => {schema1 => {id => 'schema1', type => 'integer'}, schema2 => {type => 'array', items => {'$ref' => 'schema1'}}} } ); is_deeply( $validator->schema->get('/definitions/schema2'), {type => 'array', items => {type => 'integer'}}, 'expanded schema2' ); ok !find_key($validator->schema->data, '$ref'), 'no $ref'; done_testing; sub find_key { my ($data, $needle) = @_; for my $k (keys %$data) { return 1 if $k eq $needle; return 1 if ref $data->{$k} eq 'HASH' and find_key($data->{$k}, $needle); } return 0; } libjson-validator-perl-0.66+dfsg.orig/t/jv-enum.t0000644000175000017500000000145212572256552021226 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my $male = {type => 'object', properties => {chromosomes => {enum => [[qw( X Y )], [qw( Y X )]]}}}; my $female = {type => 'object', properties => {chromosomes => {enum => [[qw( X X )]]}}}; ok $validator->validate({name => "Kate", chromosomes => [qw( X X )]}, $male), "it's short for Bob"; ok !$validator->validate({name => "Kate", chromosomes => [qw( X X )]}, $female); ok !$validator->validate({name => "Dave", chromosomes => [qw( X Y )]}, $male); ok !$validator->validate({name => "Arnie", chromosomes => [qw( Y X )]}, $male); ok $validator->validate({name => "Eddie", chromosomes => [qw( X Y Y )]}, $male); ok $validator->validate({name => "Steve", chromosomes => 'XY'}, $male); done_testing; libjson-validator-perl-0.66+dfsg.orig/t/spec/0000755000175000017500000000000012660423447020405 5ustar gregoagregoalibjson-validator-perl-0.66+dfsg.orig/t/spec/petstore.json0000644000175000017500000000226412601742662023147 0ustar gregoagregoa{ "parameters": { "limit": { "name": "limit", "in": "query", "description": "How many items to return at one time (max 100)", "required": false, "type": "integer", "format": "int32" } }, "paths": { "/pets": { "get": { "tags": [ "pets" ], "parameters": [ { "$ref": "#/parameters/limit" } ], "responses": { "200": { "description": "pet response", "schema": { "type": "array", "items": { "$ref": "#/definitions/Pet" } } }, "default": { "description": "unexpected error", "schema": { "$ref": "#/definitions/Error" } } } } } }, "definitions": { "Pet": { "required": [ "id", "name" ], "properties": { "id": { "type": "integer", "format": "int64" }, "name": { "type": "string" }, "tag": { "type": "string" } } }, "Error": { "required": [ "code", "message" ], "properties": { "code": { "type": "integer", "format": "int32" }, "message": { "type": "string" } } } } } libjson-validator-perl-0.66+dfsg.orig/t/spec/person.json0000644000175000017500000000053012601015652022572 0ustar gregoagregoa{ "title": "Example Schema", "type": "object", "required": ["firstName", "lastName"], "properties": { "firstName": { "type": "string" }, "lastName": { "type": "string" }, "age": { "$ref": "#/definitions/age" } }, "definitions": { "age": { "type": "integer", "minimum": 0, "description": "Age in years" } } } libjson-validator-perl-0.66+dfsg.orig/t/spec/invalid-ref.t0000644000175000017500000000000012601742662022756 0ustar gregoagregoalibjson-validator-perl-0.66+dfsg.orig/t/spec/with-deep-mixed-ref.json0000644000175000017500000000042412601751064025036 0ustar gregoagregoa{ "type": "object", "properties": { "age": { "$ref": "../definitions/age.json#" }, "weight": { "$ref": "../definitions/weight.json" }, "height": { "$ref": "#/definitions/height" } }, "definitions": { "height": { "type": "integer", "minimum": 5 } } } libjson-validator-perl-0.66+dfsg.orig/t/spec/with-relative-ref.json0000644000175000017500000000014012601015653024620 0ustar gregoagregoa{ "type": "object", "properties": { "age": { "$ref": "../definitions/age.json#" } } } libjson-validator-perl-0.66+dfsg.orig/t/jv-anyof.t0000644000175000017500000000126012602533105021355 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my $schema = {anyOf => [{type => "string", maxLength => 5}, {type => "number", minimum => 0}]}; my @errors; @errors = $validator->validate("short", $schema); is "@errors", "", "short"; @errors = $validator->validate("too long", $schema); is "@errors", "/: anyOf failed: ([0] String is too long: 8/5. [1] Expected number - got string.)", "too long"; @errors = $validator->validate(12, $schema); is "@errors", "", "number"; @errors = $validator->validate(-1, $schema); is "@errors", "/: anyOf failed: ([0] Expected string - got number. [1] -1 < minimum(0))", "negative"; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/jv-not.t0000644000175000017500000000053212566053364021057 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my $schema = {not => {type => "string"}}; my @errors; @errors = $validator->validate(12, $schema); is "@errors", "", "not string"; @errors = $validator->validate("str", $schema); is "@errors", "/: Should not match.", "is string"; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/jv-integer.t0000644000175000017500000000261712602727313021713 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my $schema = {type => 'object', properties => {mynumber => {type => 'integer', minimum => 1, maximum => 4}}}; my @errors = $validator->validate({mynumber => 1}, $schema); is "@errors", "", "min"; @errors = $validator->validate({mynumber => 4}, $schema); is "@errors", "", "max"; @errors = $validator->validate({mynumber => 2}, $schema); is "@errors", "", "in the middle"; @errors = $validator->validate({mynumber => 0}, $schema); is "@errors", "/mynumber: 0 < minimum(1)", 'too small'; @errors = $validator->validate({mynumber => -1}, $schema); is "@errors", "/mynumber: -1 < minimum(1)", 'too small and neg'; @errors = $validator->validate({mynumber => 5}, $schema); is "@errors", "/mynumber: 5 > maximum(4)", "too big"; @errors = $validator->validate({mynumber => "2"}, $schema); is "@errors", "/mynumber: Expected integer - got string.", "a string"; $schema->{properties}{mynumber}{multipleOf} = 2; @errors = $validator->validate({mynumber => 3}, $schema); is "@errors", "/mynumber: Not multiple of 2.", "multipleOf"; $validator->coerce(numbers => 1); @errors = $validator->validate({mynumber => "2"}, $schema); is "@errors", "", "coerced string into integer"; @errors = $validator->validate({mynumber => "2xyz"}, $schema); is "@errors", "/mynumber: Expected integer - got string.", "a string"; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/load-data.t0000644000175000017500000000142112566141200021451 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my @errors = $validator->schema('data://Some::Module/spec.json')->validate({firstName => 'yikes!'}); is int(@errors), 1, 'one error'; is $errors[0]->path, '/lastName', 'lastName'; is $errors[0]->message, 'Missing property.', 'required'; is_deeply $errors[0]->TO_JSON, {path => '/lastName', message => 'Missing property.'}, 'TO_JSON'; done_testing; package Some::Module; __DATA__ @@ spec.json { "title": "Example Schema", "type": "object", "required": ["firstName", "lastName"], "properties": { "firstName": { "type": "string" }, "lastName": { "type": "string" }, "age": { "type": "integer", "minimum": 0, "description": "Age in years" } } } libjson-validator-perl-0.66+dfsg.orig/t/coerce-args.t0000644000175000017500000000065112634734704022036 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my %coerce = (booleans => 1); is_deeply($validator->coerce(%coerce)->coerce, {booleans => 1}, 'hash is accepted'); is_deeply($validator->coerce(\%coerce)->coerce, {booleans => 1}, 'hash reference is accepted'); is_deeply($validator->coerce(1)->coerce, {%coerce, numbers => 1, strings => 1}, '1 is accepted'); done_testing; libjson-validator-perl-0.66+dfsg.orig/t/deep-mixed-ref.t0000644000175000017500000000167712601751064022440 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $file = File::Spec->catfile(File::Basename::dirname(__FILE__), 'spec', 'with-deep-mixed-ref.json'); my $validator = JSON::Validator->new->schema($file); is $validator->schema->get('/properties/age/type'), 'integer', 'loaded age.json from disk'; is $validator->schema->get('/properties/height/minimum'), '5', 'loaded height from file'; is $validator->schema->get('/properties/weight/properties/unit/type'), 'string', 'loaded weight-unit type from file'; use Mojolicious::Lite; push @{app->static->paths}, File::Basename::dirname(__FILE__); $validator->ua(app->ua); $validator->schema(app->ua->server->url->clone->path('/spec/with-relative-ref.json')); is $validator->schema->get('/properties/age/type'), 'integer', 'loaded age.json from http'; my @errors = $validator->validate({age => 'not a number'}); is int(@errors), 1, 'invalid age'; done_testing; libjson-validator-perl-0.66+dfsg.orig/t/validate-recursive.t0000644000175000017500000000214412607176523023440 0ustar gregoagregoause Mojo::Base -strict; use Test::Mojo; use Test::More; use JSON::Validator 'validate_json'; { use Mojolicious::Lite; post '/' => sub { my $c = shift; my @errors = validate_json $c->req->json, 'data://main/spec.json'; $c->render(status => @errors ? 400 : 200, json => \@errors); }; } my $t = Test::Mojo->new; $t->post_ok('/', json => {})->status_is(400)->content_like(qr{/person}); $t->post_ok('/', json => {person => {name => "foo"}})->status_is(200); $t->post_ok('/', json => {person => {name => "foo", children => [{}]}})->status_is(400)->json_is('/0/path' => '/person/children/0/name'); done_testing; __DATA__ @@ spec.json { "type": "object", "properties": { "person": { "$ref": "#/definitions/person" } }, "required": [ "person" ], "definitions": { "person": { "type": "object", "properties": { "name": { "type": "string" }, "children": { "type": "array", "items": { "$ref": "#/definitions/person" } } }, "required": [ "name" ] } } } libjson-validator-perl-0.66+dfsg.orig/t/to-json.t0000644000175000017500000000223312620717126021225 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator 'validate_json'; my @errors = validate_json(bless({path => '', message => 'yikes'}, 'JSON::Validator::Error'), 'data://main/spec.json'); ok !@errors, 'TO_JSON on objects' or diag join ', ', @errors; @errors = validate_json( { valid => Mojo::JSON->false, errors => [ bless({path => '', message => 'foo'}, 'JSON::Validator::Error'), bless({path => '', message => 'bar'}, 'JSON::Validator::Error') ] }, 'data://main/spec_array.json' ); ok !@errors, 'TO_JSON on objects inside arrays' or diag join ', ', @errors; done_testing; __DATA__ @@ spec.json { "type": "object", "properties": { "message": { "type": "string" } }, "required": ["message"] } @@ spec_array.json { "type": "object", "properties": { "valid": { "type": "boolean" }, "errors": { "type": "array", "items": { "type": "object", "properaties": { "message": { "type": "string" }, "path": { "type": "string" } }, "required": [ "message" ] } } }, "required": [ "errors" ] } libjson-validator-perl-0.66+dfsg.orig/t/validate-json.t0000644000175000017500000000112312575230331022366 0ustar gregoagregoause Mojo::Base -strict; use Test::Mojo; use Test::More; use JSON::Validator 'validate_json'; { use Mojolicious::Lite; post '/' => sub { my $c = shift; my @errors = validate_json $c->req->json, 'data://main/spec.json'; $c->render(status => @errors ? 400 : 200, text => "@errors"); }; } my $t = Test::Mojo->new; $t->post_ok('/', json => {})->status_is(400)->content_like(qr{/name}); $t->post_ok('/', json => {name => "foo"})->status_is(200); done_testing; __DATA__ @@ spec.json { "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] } libjson-validator-perl-0.66+dfsg.orig/t/jv-object.t0000644000175000017500000000637512566053364021540 0ustar gregoagregoause Mojo::Base -strict; use Test::More; use JSON::Validator; my $validator = JSON::Validator->new; my ($schema, @errors); { $schema = {type => 'object'}; @errors = $validator->validate({mynumber => 1}, $schema); is "@errors", "", "object"; @errors = $validator->validate([1], $schema); is "@errors", "/: Expected object - got array.", "got array"; } { $schema->{properties} = { number => {type => "number"}, street_name => {type => "string"}, street_type => {type => "string", enum => ["Street", "Avenue", "Boulevard"]} }; local $schema->{patternProperties} = {"^S_" => {type => "string"}, "^I_" => {type => "integer"}}; @errors = $validator->validate({number => 1600, street_name => "Pennsylvania", street_type => "Avenue"}, $schema); is "@errors", "", "object with properties"; @errors = $validator->validate({number => "1600", street_name => "Pennsylvania", street_type => "Avenue"}, $schema); is "@errors", "/number: Expected number - got string.", "object with invalid number"; @errors = $validator->validate({number => 1600, street_name => "Pennsylvania"}, $schema); is "@errors", "", "object with missing properties"; @errors = $validator->validate({number => 1600, street_name => "Pennsylvania", street_type => "Avenue", direction => "NW"}, $schema); is "@errors", "", "object with additional properties"; @errors = $validator->validate({"S_25" => "This is a string", "I_0" => 42}, $schema); is "@errors", "", "S_25 I_0"; @errors = $validator->validate({"S_0" => 42}, $schema); is "@errors", "/S_0: Expected string - got number.", "S_0"; } { local $schema->{additionalProperties} = 0; @errors = $validator->validate({number => 1600, street_name => "Pennsylvania", street_type => "Avenue", direction => "NW"}, $schema); is "@errors", "/: Properties not allowed: direction.", "additionalProperties=0"; $schema->{additionalProperties} = {type => "string"}; @errors = $validator->validate({number => 1600, street_name => "Pennsylvania", street_type => "Avenue", direction => "NW"}, $schema); is "@errors", "", "additionalProperties=object"; } { local $schema->{required} = ["number", "street_name"]; @errors = $validator->validate({number => 1600, street_type => "Avenue"}, $schema); is "@errors", "/street_name: Missing property.", "object with required"; } { $schema = {type => 'object', minProperties => 2, maxProperties => 3,}; @errors = $validator->validate({a => 1}, $schema); is "@errors", "/: Not enough properties: 1/2.", "not enough properties"; @errors = $validator->validate({a => 1, b => 2}, $schema); is "@errors", "", "object with required"; @errors = $validator->validate({a => 1, b => 2, c => 3, d => 4}, $schema); is "@errors", "/: Too many properties: 4/3.", "too many properties"; } { local $TODO = 'Add support for dependencies'; $schema = { type => "object", properties => {name => {type => "string"}, credit_card => {type => "number"}, billing_address => {type => "string"}}, required => ["name"], dependencies => {credit_card => ["billing_address"]} }; @errors = $validator->validate({name => "John Doe", credit_card => 5555555555555555}, $schema); is "@errors", "/credit_card: Missing billing_address.", "credit_card"; } done_testing; libjson-validator-perl-0.66+dfsg.orig/lib/0000755000175000017500000000000012660423447017756 5ustar gregoagregoalibjson-validator-perl-0.66+dfsg.orig/lib/JSON/0000755000175000017500000000000012660423447020527 5ustar gregoagregoalibjson-validator-perl-0.66+dfsg.orig/lib/JSON/Validator.pm0000644000175000017500000007334712656421311023021 0ustar gregoagregoapackage JSON::Validator; =head1 NAME JSON::Validator - Validate data against a JSON schema =head1 VERSION 0.66 =head1 SYNOPSIS use JSON::Validator; my $validator = JSON::Validator->new; # Define a schema - http://json-schema.org/examples.html # You can also load schema from disk or web $validator->schema( { type => "object", required => ["firstName", "lastName"], properties => { firstName => {type => "string"}, lastName => {type => "string"}, age => {type => "integer", minimum => 0, description => "Age in years"} } } ); # Validate your data @errors = $validator->validate({firstName => "Jan Henning", lastName => "Thorsen", age => -42}); # Do something if any errors was found die "@errors" if @errors; =head1 DESCRIPTION L is a class for validating data against JSON schemas. You might want to use this instead of L if you need to validate data against L of the specification. This module is currently EXPERIMENTAL. Hopefully nothing drastic will change, but it needs to fit together nicely with L - Since this is a spin-off project. =head2 Supported schema formats L can load JSON schemas in multiple formats: Plain perl data structured (as shown in L) or files on disk/web in the JSON/YAML format. The JSON parsing is done using L, while the YAML parsing is done with an optional modules which need to be installed manually. L will look for the YAML modules in this order: L, L. The order is set by which module that performs the best, so it might change in the future. =head2 Resources Here are some resources that are related to JSON schemas and validation: =over 4 =item * L =item * L =item * L =item * L =back =head1 ERROR OBJECT =head2 Overview The method L and the function L returns error objects when the input data violates the L. Each of the objects looks like this: bless { message => "Some description", path => "/json/path/to/node", }, "JSON::Validator::Error" =head2 Operators The error object overloads the following operators: =over 4 =item * bool Returns a true value. =item * string Returns the "path" and "message" part as a string: "$path: $message". =back =head2 Special cases Have a look at the L for documented examples of the error cases. Especially look at C, C and C. The special cases for "allOf", "anyOf" and "oneOf" will contain the error messages from all the failing rules below. It can be a bit hard to read, so if the error message is long, then you might want to run a smaller test with C. Example error object: bless { message => "[0] String is too long: 8/5. [1] Expected number - got string.", path => "/json/path/to/node", }, "JSON::Validator::Error" Note that these error messages are subject for change. Any suggestions are most welcome! =cut use Mojo::Base -base; use Exporter 'import'; use Mojo::JSON; use Mojo::JSON::Pointer; use Mojo::URL; use Mojo::Util; use B; use Cwd (); use File::Basename (); use File::Spec; use Scalar::Util; use constant VALIDATE_HOSTNAME => eval 'require Data::Validate::Domain;1'; use constant VALIDATE_IP => eval 'require Data::Validate::IP;1'; use constant DEBUG => $ENV{JSON_VALIDATOR_DEBUG} || $ENV{SWAGGER2_DEBUG} || 0; use constant WARN_ON_MISSING_FORMAT => $ENV{JSON_VALIDATOR_WARN_ON_MISSING_FORMAT} || $ENV{SWAGGER2_WARN_ON_MISSING_FORMAT} ? 1 : 0; our $VERSION = '0.66'; our @EXPORT_OK = qw( validate_json ); my $HTTP_SCHEME_RE = qr{^https?:}; sub E { bless {path => $_[0] || '/', message => $_[1]}, 'JSON::Validator::Error'; } sub S { Mojo::Util::md5_sum(Data::Dumper->new([@_])->Sortkeys(1)->Useqq(1)->Dump); } =head1 FUNCTIONS =head2 validate_json use JSON::Validator "validate_json"; @errors = validate_json $data, $schema; This can be useful in web applications: @errors = validate_json $c->req->json, "data://main/spec.json"; See also L and L for more details. =cut sub validate_json { __PACKAGE__->singleton->schema($_[1])->validate($_[0]); } =head1 ATTRIBUTES =head2 cache_dir $self = $self->cache_dir($path); $path = $self->cache_dir; Path to where downloaded spec files should be cached. Defaults to C or the bundled spec files that are shipped with this distribution. =head2 formats $hash_ref = $self->formats; $self = $self->formats(\%hash); Holds a hash-ref, where the keys are supported JSON type "formats", and the values holds a code block which can validate a given format. Note! The modules mentioned below are optional. =over 4 =item * date-time An RFC3339 timestamp in UTC time. This is formatted as "YYYY-MM-DDThh:mm:ss.fffZ". The milliseconds portion (".fff") is optional =item * email Validated against the RFC5322 spec. =item * hostname Will be validated using L if installed. =item * ipv4 Will be validated using L if installed or fall back to a plain IPv4 IP regex. =item * ipv6 Will be validated using L if installed. =item * uri Validated against the RFC3986 spec. =back =head2 ua $ua = $self->ua; $self = $self->ua(Mojo::UserAgent->new); Holds a L object, used by L to load a JSON schema from remote location. Note that the default L will detect proxy settings and have L set to 3. (These settings are EXPERIMENTAL and might change without a warning) =cut has cache_dir => sub { $ENV{JSON_VALIDATOR_CACHE_DIR} || File::Spec->catdir(File::Basename::dirname(__FILE__), qw( JSON Validator )); }; has formats => sub { shift->_build_formats }; has ua => sub { require Mojo::UserAgent; my $ua = Mojo::UserAgent->new; $ua->proxy->detect; $ua->max_redirects(3); $ua; }; =head1 METHODS =head2 coerce $self = $self->coerce(booleans => 1, numbers => 1, strings => 1); $self = $self->coerce({booleans => 1, numbers => 1, strings => 1}); $self = $self->coerce(1) # enable all $hash = $self->coerce; Set the given type to coerce. Before enabling coercion this module is very strict when it comes to validating types. Example: The string C<"1"> is not the same as the number C<1>, unless you have coercion enabled. WARNING! Enabling coercion might hide bugs in your api, which would have been detected if you were strict. For example JavaScript is very picky on a number being an actual number. This module tries it best to convert the data on the fly into the proper value, but this means that you unit tests might be ok, but the client side libraries (that care about types) might break. Loading a YAML document will enable "booleans" automatically. This feature is experimental, but was added since YAML has no real concept of booleans, such as L or other JSON parsers. The coercion rules are EXPERIMENTAL and will be tighten/loosen if bugs are reported. See L for more details. =cut sub coerce { my $self = shift; return $self->{coerce} ||= {} unless @_; $self->{coerce} = $_[0] eq '1' ? {booleans => 1, numbers => 1, strings => 1} : ref $_[0] ? {%{$_[0]}} : {@_}; $self; } =head2 schema $self = $self->schema(\%schema); $self = $self->schema($url); $schema = $self->schema; Used to set a schema from either a data structure or a URL. C<$schema> will be a L object when loaded, and C by default. The C<$url> can take many forms, but needs to point to a text file in the JSON or YAML format. =over 4 =item * http://... or https://... A web resource will be fetched using the L, stored in L. =item * data://Some::Module/file.name This version will use L to load "file.name" from the module "Some::Module". =item * /path/to/file An URL (without a recognized scheme) will be loaded from disk. =back =cut sub schema { my ($self, $schema) = @_; if (@_ == 1) { return $self->{schema}; } elsif (ref $schema eq 'HASH') { $schema->{id} ||= $self->_default_id($schema); warn "[JSON::Validator] Schema from hash. id=$schema->{id}\n" if DEBUG; $schema = $self->_register_document($schema, $schema->{id}); } else { $schema = Cwd::abs_path($schema) if -e $schema; $schema = $self->_load_schema($schema); } $self->{schema} = $self->_resolve_schema($schema, $schema->data->{id}); $self; } =head2 singleton $self = $class->singleton; Returns the L object used by L. =cut sub singleton { state $validator = shift->new } =head2 validate @errors = $self->validate($data); Validates C<$data> against a given JSON L. C<@errors> will contain validation error objects or be an empty list on success. See L for details. =cut sub validate { my ($self, $data, $schema) = @_; local $self->{seen} = {}; $schema ||= $self->schema->data; # back compat with Swagger2::SchemaValidator return E '/', 'No validation rules defined.' unless $schema and %$schema; return $self->_validate($data, '', $schema); } sub _build_formats { return { 'date-time' => \&_is_date_time, 'email' => \&_is_email, 'hostname' => VALIDATE_HOSTNAME ? \&Data::Validate::Domain::is_domain : \&_is_domain, 'ipv4' => VALIDATE_IP ? \&Data::Validate::IP::is_ipv4 : \&_is_ipv4, 'ipv6' => VALIDATE_IP ? \&Data::Validate::IP::is_ipv6 : \&_is_ipv6, 'uri' => \&_is_uri, }; } sub _load_schema { my ($self, $url, $parent) = @_; my ($namespace, $scheme) = ("$url", "file"); my $doc; if ($namespace =~ $HTTP_SCHEME_RE) { $url = Mojo::URL->new($url); ($namespace, $scheme) = ($url->clone->fragment(undef)->to_string, $url->scheme); } elsif ($namespace =~ m!^data://(.*)!) { $scheme = 'data'; } elsif ($parent and $parent =~ $HTTP_SCHEME_RE) { $parent = Mojo::URL->new($parent); $url =~ s!#.*!!; $url = $parent->path($parent->path->merge($url)->canonicalize); ($namespace, $scheme) = ($url->to_string, $url->scheme); } elsif ($parent) { $url =~ s!#.*!!; $url = File::Spec->catfile(File::Basename::dirname($parent), split '/', $url); $namespace = Cwd::abs_path($url) || $url; } # Make sure we create the correct namespace if not already done by Mojo::URL $namespace =~ s!#.*$!! if $namespace eq $url; return $self->{cached}{$namespace} if $self->{cached}{$namespace}; return eval { warn "[JSON::Validator] Loading schema $url namespace=$namespace scheme=$scheme\n" if DEBUG; $doc = $scheme eq 'file' ? Mojo::Util::slurp($namespace) : $scheme eq 'data' ? $self->_load_schema_from_data($url, $namespace) : $self->_load_schema_from_url($url, $namespace); $self->_register_document($self->_load_schema_from_text($doc), $namespace); } || do { $doc ||= ''; die "Could not load document from $url: $@ ($doc)" if DEBUG; die "Could not load document from $url: $@"; }; } sub _load_schema_from_data { my ($self, $url, $namespace) = @_; require Mojo::Loader; $namespace =~ m!^data://([^/]+)/(.*)$!; Mojo::Loader::data_section($1 || 'main', $2 || $namespace); } sub _load_schema_from_text { return Mojo::JSON::decode_json($_[1]) if $_[1] =~ /^\s*\{/s; $_[0]->{coerce}{booleans} = 1; # internal coercion _load_yaml($_[1]); } sub _load_schema_from_url { my ($self, $url, $namespace) = @_; my $cache_file = File::Spec->catfile($self->cache_dir, Mojo::Util::md5_sum($namespace)); return Mojo::Util::slurp($cache_file) if -r $cache_file; my $doc = $self->ua->get($url)->res->body; Mojo::Util::spurt($doc, $cache_file) if $self->cache_dir and -w $self->cache_dir; return $doc; } sub _default_id { my $path = Cwd::abs_path($0); state $id = 0; $path = File::Basename::dirname($path) if $path; $path = Cwd::getcwd unless $path; return File::Spec->catfile($path, sprintf 'json-validator-%s.json', ++$id); } sub _register_document { my ($self, $doc, $namespace) = @_; $doc = Mojo::JSON::Pointer->new($doc); $namespace = Mojo::URL->new($namespace) unless ref $namespace; $namespace->fragment(undef); $self->{cached}{$namespace} = $doc; $doc->data->{id} ||= "$namespace"; $self->{cached}{$doc->data->{id}} = $doc; warn "[JSON::Validator] Register id=$doc->{data}{id} namespace=$namespace\n" if DEBUG; return $doc; } sub _resolve_schema { my ($self, $schema, $namespace) = @_; my (@items, @refs); return $self->{resolved}{$namespace} if $self->{resolved}{$namespace}; warn "[JSON::Validator] Resolving schema $namespace\n" if DEBUG; $self->{resolved}{$namespace} = Mojo::JSON::Pointer->new({%{$schema->data}}); @items = ($self->{resolved}{$namespace}->data); # First step: Make copy and find $ref while (@items) { my $topic = shift @items; if (ref $topic eq 'HASH') { while (my ($k, $v) = each %$topic) { $topic->{$k} = [@$v] if ref $v eq 'ARRAY'; $topic->{$k} = {%$v} if ref $v eq 'HASH'; push @refs, $topic if $k eq '$ref' and !ref $v; push @items, $topic->{$k}; } } elsif (ref $topic eq 'ARRAY') { push @items, @$topic; } } # Seconds step: Resolve $ref for my $topic (@refs) { my $ref = $topic->{'$ref'} or next; # already resolved? $ref = "#/definitions/$ref" if $ref =~ /^\w+$/; # TODO: Figure out if this could be removed $ref = Mojo::URL->new($namespace)->fragment($ref) if $ref =~ s!^\#!!; $ref = Mojo::URL->new($ref) unless ref $ref; warn "[JSON::Validator] Resolving ref $ref defined in $namespace\n" if DEBUG == 2; my $look_in = $self->{resolved}{$ref->clone->fragment(undef)}; if (!$look_in) { $look_in = $self->_load_schema($ref, $namespace); $look_in = $self->_resolve_schema($look_in, $look_in->data->{id} || $namespace); warn "[JSON::Validator] Will look for $ref in $look_in->{data}{id}\n" if DEBUG == 2; } $ref = $look_in->get($ref->fragment || '') || die qq[Could not find "$topic->{'$ref'}" ($ref). Typo in schema "$namespace"?]; %$topic = %$ref; delete $topic->{id} unless ref $topic->{id}; # TODO: Is this correct? } return $self->{resolved}{$namespace}; } sub _validate { my ($self, $data, $path, $schema) = @_; my $type = $schema->{type} || _guess_schema_type($schema, $data); my @errors; # Avoid recursion return if ref $data and $self->{seen}{"$schema\:$data"}++; # Make sure we validate plain data and not a perl object if (UNIVERSAL::can($data, 'TO_JSON')) { $data = $data->TO_JSON; } # Test base schema before allOf, anyOf or oneOf if (ref $type eq 'ARRAY') { for my $type (@$type) { my $method = sprintf '_validate_type_%s', $type; my @e = $self->$method($data, $path, $schema); warn "[JSON::Validator] type @{[$path||'/']} => $method [@e]\n" if DEBUG == 2; push @errors, @e; next if @e; @errors = (); last; } @errors = E $path, $self->_merge_errors($path, @errors) if @errors; } elsif ($type) { my $method = sprintf '_validate_type_%s', $type; @errors = $self->$method($data, $path, $schema); warn "[JSON::Validator] type @{[$path||'/']} $method [@errors]\n" if DEBUG == 2; return @errors if @errors; } if (my $rules = $schema->{not}) { push @errors, $self->_validate($data, $path, $rules); warn "[JSON::Validator] not @{[$path||'/']} == [@errors]\n" if DEBUG == 2; return @errors ? () : (E $path, 'Should not match.'); } if (my $rules = $schema->{allOf}) { push @errors, $self->_validate_all_of($data, $path, $rules); } elsif ($rules = $schema->{anyOf}) { push @errors, $self->_validate_any_of($data, $path, $rules); } elsif ($rules = $schema->{oneOf}) { push @errors, $self->_validate_one_of($data, $path, $rules); } return @errors; } sub _merge_errors { my ($self, $root) = (shift, quotemeta shift); my $i = 0; my (%err, @messages); for my $e (@_) { if ($e and $e->{message} =~ m!Expected ([^\.]+)\ - got ([^\.]+)\.!) { push @{$err{$e->{path}}}, [$i, $e->{message}, $1, $2]; } elsif ($e) { push @{$err{$e->{path}}}, [$i, $e->{message}]; } $i++; } for my $p (sort keys %err) { my $prefix = $p; my (@e, %uniq); @e = grep { !$uniq{$_->[1]}++ } @{$err{$p}}; $prefix =~ s!^$root/?!!; $prefix = "/$prefix: " if $prefix; if (@e == grep { defined $_->[2] } @e) { push @messages, sprintf '%sExpected %s - got %s.', $prefix, join(', ', map { $_->[2] } @e), $e[0][3]; } else { push @messages, join ' ', map {"[$_->[0]] $prefix$_->[1]"} @e; } } return sprintf '(%s)', join ' ', @messages; } sub _validate_all_of { my ($self, $data, $path, $rules) = @_; my @errors; for my $rule (@$rules) { my @e = $self->_validate($data, $path, $rule); push @errors, @e ? @e : (undef); } warn "[JSON::Validator] allOf @{[$path||'/']} == [@errors]\n" if DEBUG == 2; return E $path, sprintf 'allOf failed: %s', $self->_merge_errors($path, @errors) if grep {$_} @errors; return; } sub _validate_any_of { my ($self, $data, $path, $rules) = @_; my $failed = 0; my @errors; for my $rule (@$rules) { my @e = $self->_validate($data, $path, $rule); push @errors, @e ? @e : (undef); $failed++ if @e; } if ($failed < @$rules) { warn "[JSON::Validator] anyOf @{[$path||'/']} == success\n" if DEBUG == 2; return; } else { warn "[JSON::Validator] anyOf @{[$path||'/']} == [@errors]\n" if DEBUG == 2; return E $path, sprintf 'anyOf failed: %s', $self->_merge_errors($path, @errors) if grep {$_} @errors; } } sub _validate_one_of { my ($self, $data, $path, $rules) = @_; my $failed = 0; my @errors; for my $rule (@$rules) { my @e = $self->_validate($data, $path, $rule); push @errors, @e ? (@e) : (undef); $failed++ if @e; } if ($failed + 1 == @$rules) { warn "[JSON::Validator] oneOf @{[$path||'/']} == success\n" if DEBUG == 2; return; } warn "[JSON::Validator] oneOf @{[$path||'/']} == failed=$failed/@{[int @$rules]} / @errors\n" if DEBUG == 2; return E $path, 'All of the oneOf rules match.' unless $failed; return E $path, sprintf 'oneOf failed: %s', $self->_merge_errors($path, @errors) if grep {$_} @errors; } sub _validate_type_enum { my ($self, $data, $path, $schema) = @_; my $enum = $schema->{enum}; my $m = S $data; for my $i (@$enum) { return if !$self->_validate_type_boolean($data, $path) and _is_true($data) == _is_true($i); return if $m eq S $i; } local $" = ', '; return E $path, "Not in enum list: @$enum."; } sub _validate_format { my ($self, $value, $path, $schema) = @_; my $code = $self->formats->{$schema->{format}}; unless ($code) { warn "Format rule for '$schema->{format}' is missing" if WARN_ON_MISSING_FORMAT; return; } return if $code->($value); return E $path, "Does not match $schema->{format} format."; } sub _validate_type_any { return; } sub _validate_type_array { my ($self, $data, $path, $schema) = @_; my @errors; if (ref $data ne 'ARRAY') { return E $path, _expected(array => $data); } if (defined $schema->{minItems} and $schema->{minItems} > @$data) { push @errors, E $path, sprintf 'Not enough items: %s/%s.', int @$data, $schema->{minItems}; } if (defined $schema->{maxItems} and $schema->{maxItems} < @$data) { push @errors, E $path, sprintf 'Too many items: %s/%s.', int @$data, $schema->{maxItems}; } if ($schema->{uniqueItems}) { my %uniq; for (@$data) { next if !$uniq{S($_)}++; push @errors, E $path, 'Unique items required.'; last; } } if (ref $schema->{items} eq 'ARRAY') { my $additional_items = $schema->{additionalItems} // {type => 'any'}; my @v = @{$schema->{items}}; if ($additional_items) { push @v, $additional_items while @v < @$data; } if (@v == @$data) { for my $i (0 .. @v - 1) { push @errors, $self->_validate($data->[$i], "$path/$i", $v[$i]); } } elsif (!$additional_items) { push @errors, E $path, sprintf "Invalid number of items: %s/%s.", int(@$data), int(@v); } } elsif (ref $schema->{items} eq 'HASH') { for my $i (0 .. @$data - 1) { push @errors, $self->_validate($data->[$i], "$path/$i", $schema->{items}); } } return @errors; } sub _validate_type_boolean { my ($self, $value, $path, $schema) = @_; return if UNIVERSAL::isa($value, 'JSON::PP::Boolean'); return if Scalar::Util::blessed($value) and ("$value" eq "1" or !$value); if ( defined $value and $self->{coerce}{booleans} and (B::svref_2object(\$value)->FLAGS & B::SVp_NOK or $value =~ /^(true|false)$/)) { $_[1] = $value ? Mojo::JSON->true : Mojo::JSON->false; return; } return E $path, _expected(boolean => $value); } sub _validate_type_integer { my ($self, $value, $path, $schema) = @_; my @errors = $self->_validate_type_number($value, $path, $schema, 'integer'); return @errors if @errors; return if $value =~ /^-?\d+$/; return E $path, "Expected integer - got number."; } sub _validate_type_null { my ($self, $value, $path, $schema) = @_; return E $path, 'Not null.' if defined $value; return; } sub _validate_type_number { my ($self, $value, $path, $schema, $expected) = @_; my @errors; $expected ||= 'number'; if (!defined $value or ref $value) { return E $path, _expected($expected => $value); } unless (B::svref_2object(\$value)->FLAGS & (B::SVp_IOK | B::SVp_NOK) and 0 + $value eq $value and $value * 0 == 0) { return E $path, "Expected $expected - got string." if !$self->{coerce}{numbers} or $value =~ /\D/; $_[1] = 0 + $value; # coerce input value } if ($schema->{format}) { push @errors, $self->_validate_format($value, $path, $schema); } if (my $e = _cmp($schema->{minimum}, $value, $schema->{exclusiveMinimum}, '<')) { push @errors, E $path, "$value $e minimum($schema->{minimum})"; } if (my $e = _cmp($value, $schema->{maximum}, $schema->{exclusiveMaximum}, '>')) { push @errors, E $path, "$value $e maximum($schema->{maximum})"; } if (my $d = $schema->{multipleOf}) { unless (int($value / $d) == $value / $d) { push @errors, E $path, "Not multiple of $d."; } } return @errors; } sub _validate_type_object { my ($self, $data, $path, $schema) = @_; my %required = map { ($_ => 1) } @{$schema->{required} || []}; my ($additional, @errors, %rules); if (ref $data ne 'HASH') { return E $path, _expected(object => $data); } if (defined $schema->{maxProperties} and $schema->{maxProperties} < keys %$data) { push @errors, E $path, sprintf 'Too many properties: %s/%s.', int(keys %$data), $schema->{maxProperties}; } if (defined $schema->{minProperties} and $schema->{minProperties} > keys %$data) { push @errors, E $path, sprintf 'Not enough properties: %s/%s.', int(keys %$data), $schema->{minProperties}; } while (my ($k, $r) = each %{$schema->{properties}}) { push @{$rules{$k}}, $r if exists $data->{$k} or $required{$k}; } while (my ($p, $r) = each %{$schema->{patternProperties}}) { push @{$rules{$_}}, $r for grep { $_ =~ /$p/ } keys %$data; } # special case used internally $rules{id} ||= [{type => 'string'}] if !$path and $data->{id}; $additional = exists $schema->{additionalProperties} ? $schema->{additionalProperties} : {}; if ($additional) { $additional = {} unless ref $additional eq 'HASH'; $rules{$_} ||= [$additional] for keys %$data; } elsif (my @keys = grep { !$rules{$_} } keys %$data) { local $" = ', '; return E $path, "Properties not allowed: @keys."; } for my $k (keys %required) { next if exists $data->{$k}; push @errors, E _path($path, $k), 'Missing property.'; delete $rules{$k}; } for my $k (keys %rules) { for my $r (@{$rules{$k}}) { if (!exists $data->{$k} and exists $schema->{default}) { $data->{$k} = $r->{default}; } else { push @errors, $self->_validate_type_enum($data->{$k}, _path($path, $k), $r) if $r->{enum}; push @errors, $self->_validate($data->{$k}, _path($path, $k), $r); } } } return @errors; } sub _validate_type_string { my ($self, $value, $path, $schema) = @_; my @errors; if (!defined $value or ref $value) { return E $path, _expected(string => $value); } if (B::svref_2object(\$value)->FLAGS & (B::SVp_IOK | B::SVp_NOK) and 0 + $value eq $value and $value * 0 == 0) { return E $path, "Expected string - got number." unless $self->{coerce}{strings}; $_[1] = "$value"; # coerce input value } if ($schema->{format}) { push @errors, $self->_validate_format($value, $path, $schema); } if (defined $schema->{maxLength}) { if (length($value) > $schema->{maxLength}) { push @errors, E $path, sprintf "String is too long: %s/%s.", length($value), $schema->{maxLength}; } } if (defined $schema->{minLength}) { if (length($value) < $schema->{minLength}) { push @errors, E $path, sprintf "String is too short: %s/%s.", length($value), $schema->{minLength}; } } if (defined $schema->{pattern}) { my $p = $schema->{pattern}; unless ($value =~ /$p/) { push @errors, E $path, "String does not match '$p'"; } } return @errors; } # FUNCTIONS ================================================================== sub _cmp { return undef if !defined $_[0] or !defined $_[1]; return "$_[3]=" if $_[2] and $_[0] >= $_[1]; return $_[3] if $_[0] > $_[1]; return ""; } sub _expected { my $type = _guess_data_type($_[1]); return "Expected $_[0] - got different $type." if $_[0] =~ /\b$type\b/; return "Expected $_[0] - got $type."; } sub _guess_data_type { local $_ = $_[0]; my $ref = ref; my $blessed = Scalar::Util::blessed($_[0]); return 'object' if $ref eq 'HASH'; return lc $ref if $ref and !$blessed; return 'null' if !defined; return 'boolean' if $blessed and ("$_" eq "1" or !"$_"); return 'number' if B::svref_2object(\$_)->FLAGS & (B::SVp_IOK | B::SVp_NOK) and 0 + $_ eq $_ and $_ * 0 == 0; return $blessed || 'string'; } sub _guess_schema_type { return _guessed_right($_[1], 'object') if $_[0]->{additionalProperties}; return _guessed_right($_[1], 'object') if $_[0]->{patternProperties}; return _guessed_right($_[1], 'object') if $_[0]->{properties}; return _guessed_right($_[1], 'object') if defined $_[0]->{maxProperties} or defined $_[0]->{minProperties}; return _guessed_right($_[1], 'array') if $_[0]->{additionalItems}; return _guessed_right($_[1], 'array') if $_[0]->{items}; return _guessed_right($_[1], 'array') if $_[0]->{uniqueItems}; return _guessed_right($_[1], 'array') if defined $_[0]->{maxItems} or defined $_[0]->{minItems}; return _guessed_right($_[1], 'string') if $_[0]->{pattern}; return _guessed_right($_[1], 'string') if defined $_[0]->{maxLength} or defined $_[0]->{minLength}; return _guessed_right($_[1], 'number') if $_[0]->{multipleOf}; return _guessed_right($_[1], 'number') if defined $_[0]->{maximum} or defined $_[0]->{minimum}; return 'enum' if $_[0]->{enum}; return undef; } sub _guessed_right { return $_[1] unless defined $_[0]; return _guess_data_type($_[0]) eq $_[1] ? $_[1] : undef; } sub _is_date_time { $_[0] =~ qr/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+(?:\.\d+)?)(?:Z|([+-])(\d+):(\d+))?$/io; } sub _is_domain { warn "Data::Validate::Domain is not installed"; return; } sub _is_email { state $email_rfc5322_re = do { my $atom = qr;[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+;o; my $quoted_string = qr/"(?:\\[^\r\n]|[^\\"])*"/o; my $domain_literal = qr/\[(?:\\[\x01-\x09\x0B-\x0c\x0e-\x7f]|[\x21-\x5a\x5e-\x7e])*\]/o; my $dot_atom = qr/$atom(?:[.]$atom)*/o; my $local_part = qr/(?:$dot_atom|$quoted_string)/o; my $domain = qr/(?:$dot_atom|$domain_literal)/o; qr/$local_part\@$domain/o; }; return $_[0] =~ $email_rfc5322_re; } sub _is_ipv4 { my (@octets) = $_[0] =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; return 4 == grep { $_ >= 0 && $_ <= 255 && $_ !~ /^0\d{1,2}$/ } @octets; } sub _is_ipv6 { warn "Data::Validate::IP is not installed"; return; } sub _is_true { local $_ = $_[0]; return 0 + $_ if ref $_ and !Scalar::Util::blessed($_); return 0 if !$_ or /^(n|false|off)/i; return 1; } sub _is_uri { $_[0] =~ qr!^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?!o; } # Please report if you need to manually monkey patch this function # https://github.com/jhthorsen/json-validator/issues sub _load_yaml { require List::Util; my @YAML_MODULES = qw( YAML::XS YAML::Syck ); # subject to change my $YAML_MODULE = (List::Util::first { eval "require $_;1" } @YAML_MODULES)[0]; die "Need to install one of these YAML modules: @YAML_MODULES (YAML::XS is recommended)" unless $YAML_MODULE; warn "[JSON::Validator] Using $YAML_MODULE to parse YAML\n" if DEBUG; Mojo::Util::monkey_patch(__PACKAGE__, _load_yaml => eval "\\\&$YAML_MODULE\::Load"); _load_yaml(@_); } sub _path { local $_ = $_[1]; s!~!~0!g; s!/!~1!g; "$_[0]/$_"; } package # hide from JSON::Validator::Error; use overload q("") => sub { sprintf '%s: %s', @{$_[0]}{qw( path message )} }, bool => sub {1}, fallback => 1; sub message { shift->{message} } sub path { shift->{path} } sub TO_JSON { {message => $_[0]->{message}, path => $_[0]->{path}} } =head1 COPYRIGHT AND LICENSE Copyright (C) 2014-2015, Jan Henning Thorsen This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0. =head1 AUTHOR Jan Henning Thorsen - C =cut 1; libjson-validator-perl-0.66+dfsg.orig/Makefile.PL0000644000175000017500000000142312656421311021153 0ustar gregoagregoa# Generated by git-ship. See 'git-ship --man' for help or https://github.com/jhthorsen/app-git-ship use ExtUtils::MakeMaker; WriteMakefile( NAME => 'JSON::Validator', AUTHOR => 'Jan Henning Thorsen ', LICENSE => 'artistic_2', ABSTRACT_FROM => 'lib/JSON/Validator.pm', VERSION_FROM => 'lib/JSON/Validator.pm', EXE_FILES => [qw( )], META_MERGE => { resources => { bugtracker => 'https://github.com/jhthorsen/json-validator/issues', homepage => 'https://github.com/jhthorsen/json-validator', repository => 'https://github.com/jhthorsen/json-validator.git', }, }, BUILD_REQUIRES => { 'Test::More' => '0.88', 'Test::Warnings' => '0.016' } , PREREQ_PM => { 'Mojolicious' => '6.00' } , test => { TESTS => 't/*.t' }, ); libjson-validator-perl-0.66+dfsg.orig/META.yml0000664000175000017500000000134512656421312020460 0ustar gregoagregoa--- abstract: 'Validate data against a JSON schema' author: - 'Jan Henning Thorsen ' build_requires: Test::More: '0.88' Test::Warnings: '0.016' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.0401, CPAN::Meta::Converter version 2.150001' license: artistic_2 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: JSON-Validator no_index: directory: - t - inc requires: Mojolicious: '6.00' resources: bugtracker: https://github.com/jhthorsen/json-validator/issues homepage: https://github.com/jhthorsen/json-validator repository: https://github.com/jhthorsen/json-validator.git version: '0.66' libjson-validator-perl-0.66+dfsg.orig/META.json0000664000175000017500000000231412656421312020625 0ustar gregoagregoa{ "abstract" : "Validate data against a JSON schema", "author" : [ "Jan Henning Thorsen " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.0401, CPAN::Meta::Converter version 2.150001", "license" : [ "artistic_2" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "JSON-Validator", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "Test::More" : "0.88", "Test::Warnings" : "0.016" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Mojolicious" : "6.00" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/jhthorsen/json-validator/issues" }, "homepage" : "https://github.com/jhthorsen/json-validator", "repository" : { "url" : "https://github.com/jhthorsen/json-validator.git" } }, "version" : "0.66" } libjson-validator-perl-0.66+dfsg.orig/.travis.yml0000644000175000017500000000036612600247714021321 0ustar gregoagregoalanguage: perl perl: - "5.20" - "5.16" - "5.10" env: - "HARNESS_OPTIONS=j6" install: - "cpanm -n Test::Pod Test::Pod::Coverage Data::Validate::Domain Data::Validate::IP YAML" - "cpanm -n --installdeps ." notifications: email: false