Debian Codegraph @

lib/Test/JSON/Schema/Acceptance.pm

raw
1 use strict;
2 use warnings;
3 package Test::JSON::Schema::Acceptance; # git description: v1.038-4-g8b3b4d1
4 # vim: set ts=8 sts=2 sw=2 tw=100 et :
5 # ABSTRACT: Acceptance testing for JSON-Schema based validators
6
7 our $VERSION = '1.039';
8
9 use 5.020;
10 use Moo;
11 use strictures 2;
12 use stable 0.031 'postderef';
13 use experimental 'signatures';
14 no autovivification warn => qw(fetch store exists delete);
15 use if "$]" >= 5.022, experimental => 're_strict';
16 no if "$]" >= 5.031009, feature => 'indirect';
17 no if "$]" >= 5.033001, feature => 'multidimensional';
18 no if "$]" >= 5.033006, feature => 'bareword_filehandles';
19 no if "$]" >= 5.041009, feature => 'smartmatch';
20 no feature 'switch';
21 use Test2::API ();
22 use Test2::Todo;
23 use Test2::Tools::Compare ();
24 use Mojo::JSON (); # for JSON_XS, MOJO_NO_JSON_XS environment variables
25 use File::ShareDir 'dist_dir';
26 use Feature::Compat::Try;
27 use MooX::TypeTiny 0.002002;
28 use Types::Standard 1.016003 qw(Str InstanceOf ArrayRef HashRef Dict Any HasMethods Bool Optional Slurpy Enum);
29 use Types::Common::Numeric 'PositiveOrZeroInt';
30 use Path::Tiny 0.069;
31 use List::Util 1.33 qw(any max sum0);
32 use Git::Wrapper;
33 use B;
34 use namespace::clean;
35
36 # specification version => metaschema URI
37 use constant METASCHEMA => {
38 'v1' => 'https://json-schema.org/v1',
39 'draft2020-12' => 'https://json-schema.org/draft/2020-12/schema',
40 'draft2019-09' => 'https://json-schema.org/draft/2019-09/schema',
41 'draft7' => 'http://json-schema.org/draft-07/schema#',
42 'draft6' => 'http://json-schema.org/draft-06/schema#',
43 'draft4' => 'http://json-schema.org/draft-04/schema#',
44 'draft3' => 'http://json-schema.org/draft-03/schema#',
45 };
46
47 my $spec_type = Enum[sort keys METASCHEMA->%*];
48 has specification => (
49 is => 'ro',
50 isa => $spec_type,
51 lazy => 1,
52 default => 'draft2020-12',
53 predicate => '_has_specification',
54 );
55
56 has supported_specifications => (
57 is => 'ro',
58 isa => ArrayRef[$spec_type],
59 lazy => 1,
60 default => sub { [ shift->specification ] },
61 );
62
63 # this comes from the tests/<spec version> directories in the JSON-Schema-Test-Suite repository
64 has test_dir => (
65 is => 'ro',
66 isa => InstanceOf['Path::Tiny'],
67 coerce => sub { path($_[0])->absolute('.') },
68 lazy => 1,
69 builder => '_build_test_dir',
70 predicate => '_has_test_dir',
71 );
72 sub _build_test_dir { path(dist_dir('Test-JSON-Schema-Acceptance'), 'tests', $_[0]->specification) };
73
74 # this comes from the remotes/ directory in the JSON-Schema-Test-Suite repository
75 has additional_resources => (
76 is => 'ro',
77 isa => InstanceOf['Path::Tiny'],
78 coerce => sub { path($_[0])->absolute('.') },
79 lazy => 1,
80 default => sub { $_[0]->test_dir->parent->parent->child('remotes') },
81 );
82
83 has verbose => (
84 is => 'ro',
85 isa => Bool,
86 default => 0,
87 );
88
89 has include_optional => (
90 is => 'ro',
91 isa => Bool,
92 default => 0,
93 );
94
95 has skip_dir => (
96 is => 'ro',
97 isa => ArrayRef[Str],
98 coerce => sub { ref($_[0]) ? $_[0] : [ $_[0] ] },
99 lazy => 1,
100 default => sub { [] },
101 );
102
103 has test_schemas => (
104 is => 'ro',
105 isa => Bool,
106 );
107
108 has results => (
109 is => 'rwp',
110 init_arg => undef,
111 isa => ArrayRef[Dict[
112 file => InstanceOf['Path::Tiny'],
113 map +($_ => PositiveOrZeroInt), qw(pass todo_fail fail),
114 ]],
115 );
116
117 has results_text => (
118 is => 'ro',
119 init_arg => undef,
120 isa => Str,
121 lazy => 1,
122 builder => '_build_results_text',
123 );
124
125 around BUILDARGS => sub ($orig, $class, @args) {
126 my %args = @args % 2 ? ( specification => 'draft'.$args[0] ) : @args;
127 $args{specification} = 'draft2020-12' if ($args{specification} // '') eq 'latest';
128 $class->$orig(\%args);
129 };
130
131 sub BUILD ($self, @) {
132 -d $self->test_dir or die 'test_dir does not exist: '.$self->test_dir;
133 }
134
135 sub acceptance {
136 my $self = shift;
137 my $options = +{ ref $_[0] eq 'CODE' ? (validate_json_string => @_) : @_ };
138
139 die 'require one or the other of "validate_data", "validate_json_string"'
140 if not $options->{validate_data} and not $options->{validate_json_string};
141
142 die 'cannot provide both "validate_data" and "validate_json_string"'
143 if $options->{validate_data} and $options->{validate_json_string};
144
145 warn "'skip_tests' option is deprecated" if $options->{skip_tests}
146 and (not ref $options->{skip_tests} eq 'ARRAY' or not (grep +ref, $options->{skip_tests}->@*));
147
148 my $ctx = Test2::API::context;
149
150 if ($options->{add_resource} and -d $self->additional_resources) {
151 # this is essentially what `bin/jsonschema_suite remote` does: resolves the filename against the
152 # base uri to determine the absolute schema location of each resource.
153 my $base = 'http://localhost:1234';
154 my %note_seen;
155 my $resource_basename = $self->additional_resources->basename; # "remotes"
156 $self->additional_resources->visit(
157 sub ($path, @) {
158 return if not $path->is_file or $path !~ /\.json$/;
159
160 # version-specific resources are stored in a subdirectory by version:
161 # skip resource files that are marked as being for an unsupported draft
162 my $relative_path = $path->relative($self->additional_resources);
163 my ($topdir, $rest) = split qr{/}, $relative_path, 2;
164 return if $topdir =~ /^(?:draft(?:[3467]|2019-09|2020-12)|v1)\z/ and not grep $topdir eq $_, $self->supported_specifications->@*;
165
166 $ctx->note('adding resource'.($rest//'' =~ m{/} ? 's' : '').' from '.$resource_basename.'/'.$topdir.' with the base URI "'.$base.'"...')
167 if not $note_seen{$resource_basename.'/'.$topdir}++;
168
169 my $data = $self->json_deserialize($path->slurp_raw);
170 my $uri = $base.'/'.$relative_path;
171 $options->{add_resource}->($uri => $data,
172 # ensure the evaluator parses this resource using its specified version
173 $topdir =~ /^draft/ ? (specification_version => $topdir) : ());
174 },
175 { recurse => 1 },
176 );
177 }
178
179 $ctx->note('running tests in '.$self->test_dir.' against '
180 .($self->_has_specification ? $self->specification : 'unknown version').'...');
181 my $tests = $self->_test_data;
182
183 # [ { file => .., pass => .., fail => .. }, ... ]
184 my @results;
185
186 foreach my $one_file (@$tests) {
187 my %results;
188 next if $options->{tests} and $options->{tests}{file}
189 and not grep $_ eq $one_file->{file},
190 (ref $options->{tests}{file} eq 'ARRAY'
191 ? $options->{tests}{file}->@* : $options->{tests}{file});
192
193 $ctx->note('');
194
195 SKIP:
196 foreach my $test_group ($one_file->{json}->@*) {
197 next if $options->{tests} and $options->{tests}{group_description}
198 and not grep $_ eq $test_group->{description},
199 (ref $options->{tests}{group_description} eq 'ARRAY'
200 ? $options->{tests}{group_description}->@* : $options->{tests}{group_description});
201
202 my $todo;
203 $todo = Test2::Todo->new(reason => 'Test marked TODO via "todo_tests"')
204 if $options->{todo_tests}
205 and any {
206 my $o = $_;
207 (not $o->{file} or grep $_ eq $one_file->{file}, (ref $o->{file} eq 'ARRAY' ? $o->{file}->@* : $o->{file}))
208 and
209 (not $o->{group_description} or grep $_ eq $test_group->{description}, (ref $o->{group_description} eq 'ARRAY' ? $o->{group_description}->@* : $o->{group_description}))
210 and not $o->{test_description}
211 }
212 $options->{todo_tests}->@*;
213
214 $ctx->skip('SKIP', 'Test marked skip via "skip_tests"'), next SKIP
215 if $options->{skip_tests}
216 and ref $options->{skip_tests} eq 'ARRAY'
217 and not (grep +!ref, $options->{skip_tests}->@*)
218 and any {
219 my $o = $_;
220 (not $o->{file} or grep $_ eq $one_file->{file}, (ref $o->{file} eq 'ARRAY' ? $o->{file}->@* : $o->{file}))
221 and
222 (not $o->{group_description} or grep $_ eq $test_group->{description}, (ref $o->{group_description} eq 'ARRAY' ? $o->{group_description}->@* : $o->{group_description}))
223 and not $o->{test_description}
224 }
225 $options->{skip_tests}->@*;
226
227 my $schema_fails;
228 if ($self->test_schemas) {
229 die 'specification_version unknown: cannot evaluate schema against metaschema'
230 if not $self->_has_specification;
231
232 my $metaschema_uri = ref $test_group->{schema} eq 'HASH' && $test_group->{schema}{'$schema'}
233 ? $test_group->{schema}{'$schema'}
234 : METASCHEMA->{$self->specification};
235 my $metaschema_schema = $metaschema_uri;
236 my $result = $options->{validate_data}
237 ? $options->{validate_data}->($metaschema_schema, $test_group->{schema})
238 : $options->{validate_json_string}->($metaschema_schema, $self->json_serialize($test_group->{schema}));
239 if (not $result) {
240 $ctx->fail('schema for '.$one_file->{file}.': "'.$test_group->{description}.'" fails to validate against '.$metaschema_uri.':');
241 $ctx->note($self->json_prettyprint($result));
242 $schema_fails = 1;
243 }
244 }
245
246 foreach my $test ($test_group->{tests}->@*) {
247 next if $options->{tests} and $options->{tests}{test_description}
248 and not grep $_ eq $test->{description},
249 (ref $options->{tests}{test_description} eq 'ARRAY'
250 ? $options->{tests}{test_description}->@* : $options->{tests}{test_description});
251
252 my $todo;
253 $todo = Test2::Todo->new(reason => 'Test marked TODO via deprecated "skip_tests"')
254 if ref $options->{skip_tests} eq 'ARRAY'
255 and not (grep +ref, $options->{skip_tests}->@*)
256 and grep +(($test_group->{description}.' - '.$test->{description}) =~ /$_/),
257 $options->{skip_tests}->@*;
258
259 $todo = Test2::Todo->new(reason => 'Test marked TODO via "todo_tests"')
260 if $options->{todo_tests}
261 and any {
262 my $o = $_;
263 (not $o->{file} or grep $_ eq $one_file->{file}, (ref $o->{file} eq 'ARRAY' ? $o->{file}->@* : $o->{file}))
264 and
265 (not $o->{group_description} or grep $_ eq $test_group->{description}, (ref $o->{group_description} eq 'ARRAY' ? $o->{group_description}->@* : $o->{group_description}))
266 and
267 (not $o->{test_description} or grep $_ eq $test->{description}, (ref $o->{test_description} eq 'ARRAY' ? $o->{test_description}->@* : $o->{test_description}))
268 }
269 $options->{todo_tests}->@*;
270
271 my $result = $self->_run_test($one_file, $test_group, $test, $options);
272 $result = 0 if $schema_fails;
273
274 ++$results{ $result ? 'pass' : $todo ? 'todo_fail' : 'fail' };
275 }
276 }
277
278 push @results, { file => $one_file->{file}, pass => 0, 'todo_fail' => 0, fail => 0, %results };
279 }
280
281 $self->_set_results(\@results);
282
283 my $diag = $self->verbose ? 'diag' : 'note';
284 $ctx->$diag("\n".$self->results_text."\n");
285
286 if ($self->test_dir !~ m{\boptional\b}
287 and grep +($_->{file} !~ m{^optional/} && $_->{todo_fail} + $_->{fail}), @results) {
288 # non-optional test failures will always be visible, even when not in verbose mode.
289 $ctx->diag('WARNING: some non-optional tests are failing! This implementation is not fully compliant with the specification!');
290 $ctx->diag('');
291 }
292 else {
293 $ctx->$diag('Congratulations, all non-optional tests are passing!');
294 $ctx->$diag('');
295 }
296
297 $ctx->release;
298 }
299
300 sub _run_test ($self, $one_file, $test_group, $test, $options) {
301 my $test_name = $one_file->{file}.': "'.$test_group->{description}.'" - "'.$test->{description}.'"';
302
303 my $pass; # ignores TODO status
304
305 Test2::API::run_subtest($test_name,
306 sub {
307 my ($result_bool, $result, $schema_before, $data_before, $schema_after, $data_after);
308 try {
309 ($schema_before, $data_before) = map $self->json_serialize($_),
310 $test_group->{schema}, $test->{data};
311
312 ($result_bool, $result) = $options->{validate_data}
313 ? $options->{validate_data}->($test_group->{schema}, $test->{data})
314 : $options->{validate_json_string}->($test_group->{schema}, $self->json_serialize($test->{data}));
315
316 ($schema_after, $data_after) = map $self->json_serialize($_),
317 $test_group->{schema}, $test->{data};
318
319 my $ctx = Test2::API::context;
320
321 # skip the ugly matrix comparison
322 my $expected = $test->{valid} ? 'true' : 'false';
323 if ($result_bool xor $test->{valid}) {
324 $ctx->fail('evaluation result is incorrect', 'expected '.$expected.'; got '.($result_bool ? 'true' : 'false'));
325 $ctx->${ $self->verbose ? \'diag' : \'note' }('schema: '.$self->json_prettyprint($test_group->{schema}));
326 $ctx->${ $self->verbose ? \'diag' : \'note' }('data: '.$self->json_prettyprint($test->{data})
327 .(ref $test->{data} ? 'reference to '.ref $test->{data} : ''));
328
329 # for backwards compatibility, if only one value is returned, it might be possible to
330 # jsonify it to access the full results
331 $ctx->${ $self->verbose ? \'diag' : \'note' }('result: '.$self->json_prettyprint($result // $result_bool));
332 $pass = 0;
333 }
334 else {
335 $ctx->ok(1, 'test passes: data is valid: '.$expected);
336 $pass = 1;
337 }
338
339 my @mutated_data_paths = $self->_mutation_check($test->{data});
340 my @mutated_schema_paths = $self->_mutation_check($test_group->{schema});
341
342 # string check path check behaviour
343 # 0 0 ::is(), and note. $pass = 0
344 # 0 1 ::is(). $pass = 0
345 # 1 0 ->fail and note. $pass = 0
346 # 1 1 no test. $pass does not change.
347
348 if ($data_before ne $data_after) {
349 Test2::Tools::Compare::is($data_after, $data_before, 'evaluator did not mutate data');
350 $pass = 0;
351 }
352 elsif (@mutated_data_paths) {
353 $ctx->fail('evaluator did not mutate data');
354 $pass = 0
355 }
356
357 $ctx->note('mutated data at location'.(@mutated_data_paths > 1 ? 's' : '').': '.join(', ', @mutated_data_paths)) if @mutated_data_paths;
358
359 if ($schema_before ne $schema_after) {
360 Test2::Tools::Compare::is($schema_after, $schema_before, 'evaluator did not mutate schema');
361 $pass = 0;
362 }
363 elsif (@mutated_schema_paths) {
364 $ctx->fail('evaluator did not mutate schema');
365 $pass = 0;
366 }
367
368 $ctx->note('mutated schema at location'.(@mutated_schema_paths > 1 ? 's' : '').': '.join(', ', @mutated_schema_paths)) if @mutated_schema_paths;
369
370 $ctx->release;
371 }
372 catch ($e) {
373 chomp(my $exception = $e);
374 my $ctx = Test2::API::context;
375 $ctx->fail('died: '.$exception);
376 $ctx->release;
377 };
378 },
379 { buffered => 1, inherit_trace => 1 },
380 );
381
382 return $pass;
383 }
384
385 sub _mutation_check ($self, $data) {
386 my @error_paths;
387
388 # [ path => data ]
389 my @nodes = ([ '', $data ]);
390 while (my $node = shift @nodes) {
391 if (not defined $node->[1]) {
392 next;
393 }
394 if (ref $node->[1] eq 'ARRAY') {
395 push @nodes, map [ $node->[0].'/'.$_, $node->[1][$_] ], 0 .. $node->[1]->$#*;
396 push @error_paths, $node->[0] if tied($node->[1]->@*);
397 }
398 elsif (ref $node->[1] eq 'HASH') {
399 push @nodes, map [ $node->[0].'/'.(s!~!~0!gr =~ s!/!~1!gr), $node->[1]{$_} ], keys $node->[1]->%*;
400 push @error_paths, $node->[0] if tied($node->[1]->%*);
401 }
402 elsif (ref $node->[1]) {
403 next; # boolean or bignum
404 }
405 else {
406 my $flags = B::svref_2object(\$node->[1])->FLAGS;
407 push @error_paths, $node->[0]
408 if not ($flags & B::SVf_POK xor $flags & (B::SVf_IOK | B::SVf_NOK));
409 }
410 }
411
412 return @error_paths;
413 }
414
415 use constant _JSON_BACKEND => Mojo::JSON::JSON_XS ? 'Cpanel::JSON::XS' : 'JSON::PP';
416
417 # used for internal serialization/deserialization; does not prettify the string.
418 has _json_serializer => (
419 is => 'ro',
420 isa => HasMethods[qw(encode decode)],
421 handles => {
422 json_serialize => 'encode',
423 json_deserialize => 'decode',
424 },
425 lazy => 1,
426 default => sub { _JSON_BACKEND->new->allow_nonref(1)->utf8(1)->allow_blessed(1)->allow_bignum(1)->canonical(1) },
427
428 );
429
430 # used for displaying diagnostics only
431 has _json_prettyprinter => (
432 is => 'ro',
433 isa => HasMethods['encode'],
434 lazy => 1,
435 handles => {
436 json_prettyprint => 'encode',
437 },
438 default => sub {
439 my $encoder = _JSON_BACKEND->new->allow_nonref(1)->utf8(0)->allow_blessed(1)->allow_bignum(1)->canonical(1)->convert_blessed(1)->pretty(1)->space_before(0);
440 $encoder->indent_length(2) if $encoder->can('indent_length');
441 $encoder;
442 },
443 );
444
445 # backcompat shims
446 sub _json_decoder { shift->_json_serializer(@_) }
447 sub json_decoder { shift->_json_serializer(@_) }
448 sub _json_encoder { shift->_json_prettyprinter(@_) }
449 sub json_encoder { shift->_json_prettyprinter(@_) }
450
451 # see JSON::MaybeXS::is_bool
452 my $json_bool = InstanceOf[qw(JSON::XS::Boolean Cpanel::JSON::XS::Boolean JSON::PP::Boolean)];
453
454 has _test_data => (
455 is => 'lazy',
456 isa => ArrayRef[Dict[
457 file => InstanceOf['Path::Tiny'],
458 json => ArrayRef[Dict[
459 # id => Optional[Str],
460 # specification => Optional[Str],
461 description => Str,
462 comment => Optional[Str],
463 schema => $json_bool|HashRef,
464 tests => ArrayRef[Dict[
465 # id => Optional[Str],
466 data => Any,
467 description => Str,
468 comment => Optional[Str],
469 valid => $json_bool,
470 Slurpy[Any],
471 ]],
472 Slurpy[Any],
473 ]],
474 ]],
475 );
476
477 sub _build__test_data ($self) {
478 my @test_groups;
479
480 $self->test_dir->visit(
481 sub {
482 my ($path) = @_;
483 return if any { $self->test_dir->child($_)->subsumes($path) } $self->skip_dir->@*;
484 return if not $path->is_file;
485 return if $path !~ /\.json$/;
486 my $data = $self->json_deserialize($path->slurp_raw);
487 return if not @$data; # placeholder files for renamed tests
488 my $file = $path->relative($self->test_dir);
489 push @test_groups, [
490 scalar(split('/', $file)),
491 {
492 file => $file,
493 json => $data,
494 },
495 ];
496 },
497 { recurse => $self->include_optional },
498 );
499
500 return [
501 map $_->[1],
502 sort { $a->[0] <=> $b->[0] || $a->[1]{file} cmp $b->[1]{file} }
503 @test_groups
504 ];
505 }
506
507 sub _build_results_text ($self) {
508 my @lines;
509 sub _pad ($s, $rest) { sprintf('%-29s', $s) . $rest }
510 push @lines, _pad('generated with:', ref($self).' '.$self->VERSION);
511 push @lines, _pad('on perl: ', $^V);
512
513 my $test_dir = $self->test_dir;
514 my $orig_dir = $self->_build_test_dir;
515
516 my $submodule_status = path(dist_dir('Test-JSON-Schema-Acceptance'), 'submodule_status');
517 if ($submodule_status->exists and $submodule_status->parent->subsumes($self->test_dir)) {
518 chomp(my ($commit, $url) = $submodule_status->lines);
519 push @lines, _pad('with commit:', $commit);
520 push @lines, _pad('from repository:', $url);
521 }
522 elsif ($test_dir eq $orig_dir and not -d '.git') {
523 die 'submodule_status file is missing - packaging error? cannot continue';
524 }
525
526 push @lines, _pad('specification version:', $self->specification//'unknown');
527
528 if ($test_dir ne $orig_dir) {
529 my $local;
530 if ($orig_dir->subsumes($test_dir)) {
531 $test_dir = '<base test directory>/'.substr($test_dir, length($orig_dir)+1);
532 }
533 elsif (Path::Tiny->cwd->subsumes($test_dir)) {
534 $test_dir = $test_dir->relative;
535 $local = 1;
536 }
537 push @lines, _pad('using custom test directory:', $test_dir);
538
539 eval {
540 my $git = Git::Wrapper->new($test_dir);
541 my @ref = $git->describe({ all => 1, long => 1, always => 1 });
542 push @lines, _pad('at ref:', $ref[0]);
543 } if not $local;
544 }
545 push @lines, _pad('optional tests included:', $self->include_optional ? 'yes' : 'no');
546 push @lines, map _pad('skipping directory:', $_), $self->skip_dir->@*;
547
548 push @lines, '';
549 my $length = max(40, map length $_->{file}, $self->results->@*);
550
551 push @lines, sprintf('%-'.$length.'s pass todo-fail fail', 'filename');
552 push @lines, '-'x($length + 23);
553 push @lines, map sprintf('%-'.$length.'s % 5d % 4d % 4d', $_->@{qw(file pass todo_fail fail)}),
554 $self->results->@*;
555
556 my $total = +{ map do { my $type = $_; $type => sum0(map $_->{$type}, $self->results->@*) }, qw(pass todo_fail fail) };
557 push @lines, '-'x($length + 23);
558 push @lines, sprintf('%-'.$length.'s % 5d % 5d % 5d', 'TOTAL', $total->@{qw(pass todo_fail fail)});
559
560 return join("\n", @lines, '');
561 }
562
563 1;
564
565 __END__
566
567 =pod
568
569 =encoding UTF-8
570
571 =for stopwords validators Schemas ANDed ORed TODO
572
573 =head1 NAME
574
575 Test::JSON::Schema::Acceptance - Acceptance testing for JSON-Schema based validators
576
577 =head1 VERSION
578
579 version 1.039
580
581 =head1 SYNOPSIS
582
583 This module allows the
584 L<JSON Schema Test Suite|https://github.com/json-schema/JSON-Schema-Test-Suite> tests to be used in
585 perl to test a module that implements the JSON Schema specification ("json-schema"). These are the
586 same tests that many modules (libraries, plugins, packages, etc.) use to confirm support of
587 json-schema. Using this module to confirm support gives assurance of interoperability with other
588 modules that run the same tests in different languages.
589
590 In the JSON::Schema::Modern module, a test could look like the following:
591
592 use Test2::V0;
593 use JSON::Schema::Modern;
594 use Test::JSON::Schema::Acceptance;
595
596 my $accepter = Test::JSON::Schema::Acceptance->new(specification => 'draft7');
597
598 $accepter->acceptance(
599 validate_data => sub ($schema, $input_data) {
600 return JSON::Schema::Modern->new($schema)->validate($input_data);
601 },
602 todo_tests => [ { file => 'dependencies.json' } ],
603 skip_tests => [ { file => 'bad_tests.json' } ],
604 );
605
606 done_testing();
607
608 This would determine if JSON::Schema::Modern's C<validate> method returns the right result for all
609 of the cases in the JSON Schema Test Suite, except for those listed in C<skip_tests>.
610
611 =head1 DESCRIPTION
612
613 L<JSON Schema|http://json-schema.org> is an IETF draft (at time of writing) which allows you to
614 define the structure of JSON.
615
616 From the overview of the L<draft 2020-12 version of the
617 specification|https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.3>:
618
619 =over 4
620
621 This document proposes a new media type "application/schema+json" to identify a JSON Schema for
622 describing JSON data. It also proposes a further optional media type,
623 "application/schema-instance+json", to provide additional integration features. JSON Schemas are
624 themselves JSON documents. This, and related specifications, define keywords allowing authors to
625 describe JSON data in several ways.
626
627 JSON Schema uses keywords to assert constraints on JSON instances or annotate those instances with
628 additional information. Additional keywords are used to apply assertions and annotations to more
629 complex JSON data structures, or based on some sort of condition.
630
631 =back
632
633 This module allows other perl modules (for example JSON::Schema::Modern) to test that they are JSON
634 Schema-compliant, by running the tests from the official test suite, without having to manually
635 convert them to perl tests.
636
637 You are unlikely to want this module, unless you are attempting to write a module which implements
638 JSON Schema the specification, and want to test your compliance.
639
640 =head1 CONSTRUCTOR
641
642 Test::JSON::Schema::Acceptance->new(specification => $specification_version)
643
644 Create a new instance of Test::JSON::Schema::Acceptance.
645
646 Available options (which are also available as accessor methods on the object) are:
647
648 =head2 specification
649
650 This determines the draft version of the schema to confirm compliance to.
651 Possible values are:
652
653 =over 4
654
655 =item *
656
657 C<draft3>
658
659 =item *
660
661 C<draft4>
662
663 =item *
664
665 C<draft6>
666
667 =item *
668
669 C<draft7>
670
671 =item *
672
673 C<draft2019-09>
674
675 =item *
676
677 C<draft2020-12>
678
679 =item *
680
681 C<latest> (alias for C<draft2020-12>)
682
683 =item *
684
685 C<v1>
686
687 =back
688
689 The default is C<latest>, but in the synopsis example, L<JSON::Schema::Modern> is testing draft 7
690 compliance.
691
692 (For backwards compatibility, C<new> can be called with a single numeric argument of 3 to 7, which
693 maps to C<draft3> through C<draft7>.)
694
695 =head2 supported_specifications
696
697 The version(s) that the implementation supports; used to skip adding remote resources that reference
698 unsupported schema versions (for cross-schema tests). Defaults to C<< [ $self->specification ] >>.
699
700 =head2 test_dir
701
702 Instead of specifying a draft specification to test against, which will select the most appropriate
703 tests, you can pass in the name of a directory of tests to run directly. Files in this directory
704 should be F<.json> files following the format described in
705 L<https://github.com/json-schema-org/JSON-Schema-Test-Suite/blob/main/README.md>.
706
707 =head2 additional_resources
708
709 A directory of additional resources which should be made available to the implementation under the
710 base URI C<http://localhost:1234>. This dataset is automatically provided if you did not override
711 L</test_dir>; otherwise, you need to supply it yourself, if any tests require it (for example by
712 containing C<< {"$ref": "http://localhost:1234/foo.json/#a/b/c"} >>). If you supply an
713 L</add_resource> value to L</acceptance> (see below), this will be done for you.
714
715 =head2 verbose
716
717 Optional. When true, prints version information and the test result table such that it is visible
718 during C<make test> or C<prove>.
719
720 =head2 include_optional
721
722 Optional. When true, tests in subdirectories (most notably F<optional/> are also included.
723
724 =head2 skip_dir
725
726 Optional. Pass a string or arrayref consisting of relative path name(s) to indicate directories
727 (within the test directory as specified above with L</specification> or L</test_dir>) which will be
728 skipped. Note that this is only useful currently with C<< include_optional => 1 >>, as otherwise all
729 subdirectories would be skipped anyway.
730
731 =head2 results
732
733 After calling L</acceptance>, a list of test results are provided here. It is an arrayref of
734 hashrefs with four keys:
735
736 =over 4
737
738 =item *
739
740 file - the filename
741
742 =item *
743
744 pass - the number of pass results for that file
745
746 =item *
747
748 todo_fail - the number of fail results for that file that were marked TODO
749
750 =item *
751
752 fail - the number of fail results for that file (not including TODO tests)
753
754 =back
755
756 =head2 results_text
757
758 After calling L</acceptance>, a text string tabulating the test results are provided here. This is
759 the same table that is printed at the end of the test run.
760
761 =head2 test_schemas
762
763 =for stopwords metaschema
764
765 Optional. A boolean that, when true, will test every schema against its
766 specification metaschema. (When set, L</specification> must also be set.)
767
768 This normally should not be set as the official test suite has already been
769 sanity-tested, but you may want to set this in development environments if you
770 are using your own test files.
771
772 Defaults to false.
773
774 =head1 SUBROUTINES/METHODS
775
776 =head2 acceptance
777
778 =for stopwords truthy falsey JSONified
779
780 Accepts a hash of options as its arguments.
781
782 (Backwards-compatibility mode: accepts a subroutine which is used as L</validate_json_string>,
783 and a hashref of arguments.)
784
785 Available options are:
786
787 =head3 validate_data
788
789 A subroutine reference, which is passed two arguments: the JSON Schema, and the B<inflated> data
790 structure to be validated. This is the main entry point to your JSON Schema library being tested.
791
792 The subroutine can return either one value or two:
793
794 =over 4
795
796
797
798 =back
799
800 * a boolean value indicating whether the schema was valid for the input or not (required)
801 * a value containing the result of the evaluation (which will be JSONified in the test output) (optional)
802
803 Either L</validate_data> or L</validate_json_string> is required.
804
805 =head3 validate_json_string
806
807 A subroutine reference, which is passed two arguments: the JSON Schema, and the B<JSON string>
808 containing the data to be validated. This is an alternative to L</validate_data> above, if your
809 library only accepts JSON strings.
810
811 The subroutine can return either one value or two:
812
813 =over 4
814
815
816
817 =back
818
819 * a boolean value indicating whether the schema was valid for the input or not (required)
820 * a value containing the result of the evaluation (which will be JSONified in the test output) (optional)
821
822 Exactly one of L</validate_data> or L</validate_json_string> is required.
823
824 =head3 add_resource
825
826 Optional. A subroutine reference, which will be called at the start of L</acceptance> multiple
827 times, with the arguments:
828
829 =over 4
830
831 =item *
832
833 a URI (string): the canonical uri to use for the new resource
834
835 =item *
836
837 a data structure containing schema data to be associated with that URI, for use in some tests that use additional resources (see above).
838
839 =item *
840
841 a list of key-value pairs (optional), containing additional options to be passed to the subroutine: keys currently limited to C<specification_version>.
842
843 =back
844
845 If you do
846 not provide this option, you will be responsible for ensuring that those additional resources are
847 made available to your implementation for the successful execution of the tests that rely on them.
848
849 For more information, see <https://json-schema.org/draft/2020-12/json-schema-core.html#rfc.section.9.1.2>.
850
851 =head3 tests
852
853 Optional. Restricts tests to just those mentioned (the conditions are ANDed together, not ORed).
854 The syntax can take one of many forms:
855
856 # run tests in this file
857 tests => { file => 'dependencies.json' }
858
859 # run tests in these files
860 tests => { file => [ 'dependencies.json', 'refRemote.json' ] }
861
862 # run tests in this file with this group description
863 tests => {
864 file => 'refRemote.json',
865 group_description => 'remote ref',
866 }
867
868 # run tests in this file with these group descriptions
869 tests => {
870 file => 'const.json',
871 group_description => [ 'const validation', 'const with object' ],
872 }
873
874 # run tests in this file with this group description and test description
875 tests => {
876 file => 'const.json',
877 group_description => 'const validation',
878 test_description => 'another type is invalid',
879 }
880
881 # run tests in this file with this group description and these test descriptions
882 tests => {
883 file => 'const.json',
884 group_description => 'const validation',
885 test_description => [ 'same value is valid', 'another type is invalid' ],
886 }
887
888 =head3 todo_tests
889
890 Optional. Mentioned tests will run as if in a L<"TODO"|Test::More/TODO: BLOCK>. Uses arrayrefs of
891 the same hashref structure as L</tests> above, which are ORed together.
892
893 todo_tests => [
894 # all tests in this file are TODO
895 { file => 'dependencies.json' },
896 # just some tests in this file are TODO
897 { file => 'boolean_schema.json', test_description => 'array is invalid' },
898 # .. etc
899 ]
900
901 =head3 skip_tests
902
903 Optional. Mentioned tests will run as if in a L<""|Test::More/SKIP: BLOCK>. Uses arrayrefs of
904 the same hashref structure as L</tests> above, which are ORed together.
905
906 skip_tests => [
907 # all tests in this file are SKIPped
908 { file => 'dependencies.json' },
909 # just some tests in this file are SKIPped
910 { file => 'boolean_schema.json', test_description => 'array is invalid' },
911 # .. etc
912 ]
913
914 =head2 json_prettyprint
915
916 JSON-encodes a data structure in a format suitable for human view, used for printing test diagnostics.
917
918 =head2 json_encoder
919
920 Provides access to the object that provides the L</json_prettyprint> method.
921
922 =for stopwords OpenAPI
923
924 =head1 GIVING THANKS
925
926 =for stopwords MetaCPAN GitHub
927
928 If you found this module to be useful, please show your appreciation by
929 adding a +1 in L<MetaCPAN|https://metacpan.org/dist/Test-JSON-Schema-Acceptance>
930 and a star in L<GitHub|https://github.com/karenetheridge/Test-JSON-Schema-Acceptance>.
931
932 =head1 SUPPORT
933
934 Bugs may be submitted through L<https://github.com/karenetheridge/Test-JSON-Schema-Acceptance/issues>.
935
936 You can also find me on the L<JSON Schema Slack server|https://json-schema.slack.com> and L<OpenAPI Slack
937 server|https://open-api.slack.com>, which are also great resources for finding help.
938
939 =head1 AUTHOR
940
941 Ben Hutton (@relequestual) <[email protected]>
942
943 =head1 CONTRIBUTORS
944
945 =for stopwords Karen Etheridge Daniel Perrett
946
947 =over 4
948
949 =item *
950
951 Karen Etheridge <[email protected]>
952
953 =item *
954
955 Daniel Perrett <[email protected]>
956
957 =back
958
959 =head1 COPYRIGHT AND LICENCE
960
961 This software is Copyright (c) 2015 by Ben Hutton.
962
963 This is free software, licensed under:
964
965 The MIT (X11) License
966
967 This distribution includes data from the L<https://json-schema.org> test suite, which carries its own
968 licence (see F<share/LICENSE>).
969
970 Permission is explicitly B<NOT> granted to repackage or redistribute this distribution with any
971 files altered or added (such as with a different set of test data) than what was originally
972 published to the Perl Programming Authors Upload Server (PAUSE), as dependencies of this
973 distribution have specific expectations as to the contents of this test data depending on version.
974 If it is desired to use a different dataset at runtime, please refer to the L</test_dir>
975 configuration option.
976
977 =for Pod::Coverage BUILDARGS BUILD json_decoder METASCHEMA
978
979 =cut