TER1 (Statement): 100.00%
TER2 (Branch): 100.00%
TER3 (LCSAJ): 100.0% (1/1)
Approximate LCSAJ segments: 3
● Covered — this LCSAJ path was executed during testing.
● Not covered — this LCSAJ path was never executed. These are the paths to focus on.
Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:
start → end → jump
Uncovered paths show [NOT COVERED] in the tooltip.
1: package App::Test::Generator::Template; 2: 3: use strict; 4: use warnings; 5: use autodie qw(:all); 6: 7: use utf8; 8: use Carp qw(carp); 9: use Data::Section::Simple; 10: use Scalar::Util (); 11: 12: our $VERSION = '0.52'; 13: 14: =head1 NAME 15: 16: App::Test::Generator::Template - Template for the test files generated by App::Test::Generator 17: 18: =head1 VERSION 19: 20: Version 0.52 21: 22: =head1 SYNOPSIS 23: 24: The template for the test files generated by App::Test::Generator. 25: 26: =head1 METHODS 27: 28: =head2 get_data_section 29: 30: Returns a reference to the named template, read from this module's 31: C<__DATA__> section via L<Data::Section::Simple>. 32: 33: my $template_ref = App::Test::Generator::Template->get_data_section('test.tt'); 34: my $template_ref = App::Test::Generator::Template::get_data_section('test.tt'); 35: 36: =head3 Arguments 37: 38: =over 4 39: 40: =item * C<$template_file> 41: 42: The name of the C<@@>-delimited section to retrieve. The only value 43: currently defined in this module's C<__DATA__> section is C<test.tt>. 44: May be called either as a class method (C<< Template->get_data_section(...) >>, 45: in which case the leading class-name argument is stripped before lookup) 46: or as a plain function. 47: 48: =back 49: 50: =head3 Returns 51: 52: A scalar reference to the template content. If C<$template_file> does 53: not match a defined C<@@> section, returns a reference to C<undef>. 54: 55: =head3 Side Effects 56: 57: None. Does not write to disk or modify any global state. 58: 59: =head3 API specification 60: 61: =head4 input 62: 63: { 64: template_file => { type => SCALAR, optional => 1 }, 65: } 66: 67: =head4 output 68: 69: { type => SCALARREF } 70: 71: =cut 72: 73: sub get_data_section 74: {Mutants (Total: 1, Killed: 1, Survived: 0)
●75 → 75 → 79 75: if($_[0] && ($_[0] eq __PACKAGE__)) { 76: shift; 77: } 78:
Mutants (Total: 2, Killed: 2, Survived: 0)
79: return \Data::Section::Simple::get_data_section($_[0]); 80: } 81: 82: 1; 83: 84: =head1 AUTHOR 85: 86: Nigel Horne, C<< <njh at nigelhorne.com> >> 87: 88: Portions of this module's initial design and documentation were created with the 89: assistance of L<ChatGPT|https://openai.com/> (GPT-5), with final curation 90: and authorship by Nigel Horne. 91: 92: =cut 93: 94: __DATA__ 95: 96: @@ test.tt 97: #!/usr/bin/env perl 98: 99: use strict; 100: use warnings; 101: 102: use utf8; 103: use open qw(:std :encoding(UTF-8)); # https://github.com/nigelhorne/App-Test-Generator/issues/1 104: 105: use Carp; 106: use Data::Random qw(:all); 107: use Data::Random::String; 108: use Data::Random::String::Matches 0.02; 109: use Data::Random::Structure; 110: use Encode qw(decode_utf8); 111: use Unicode::Normalize (); 112: use Test::Most; 113: [% IF skip_reason %] 114: plan skip_all => '[% skip_reason %]'; 115: [% END %] 116: use Test::Returns 0.03; 117: use Unicode::GCString; 118: use Scalar::Util qw(looks_like_number); 119: 120: [% setup_code %] 121: 122: [% IF module %] 123: diag('[% module %]->[% function %] test case created by https://github.com/nigelhorne/App-Test-Generator'); 124: [% ELSE %] 125: diag('[% function %] test case created by https://github.com/nigelhorne/App-Test-Generator'); 126: [% END %] 127: 128: die_on_fail if($ENV{'DIE_ON_FAIL'}); 129: 130: # Edge-case maps injected from config (optional) 131: my %edge_cases = ( 132: [% edge_cases_code %] 133: ); 134: my @edge_case_array = ( 135: [% edge_case_array_code %] 136: ); 137: my %type_edge_cases = ( 138: [% type_edge_cases_code %] 139: ); 140: # Descriptor targets _leaked_fds() has accepted as held open on purpose 141: my %fds_held; 142: 143: my %config = ( 144: [% config_code %] 145: ); 146: 147: # Provenance markers, injected from App::Test::Generator::Provenance so the 148: # harness and the extractor cannot disagree about what they mean. 149: my %documented_sources = map { $_ => 1 } qw([% documented_sources %]); 150: my $type_checks_source = '[% type_checks_source %]'; 151: 152: if($^O ne 'MSWin32' && $config{close_stdin}) { 153: 154: close(STDIN); 155: open(STDIN, '<', '/dev/null'); 156: } 157: 158: # TODO: add more, and remove magic numbers 159: use constant { 160: PROB_LOWERCASE => $config{prob_lowercase} // 0.72, 161: PROB_EDGE_CASE => $config{prob_edge_case} // 0.4, 162: }; 163: 164: # Seed for reproducible fuzzing (if provided) 165: [% seed_code %] 166: 167: my %input = ( 168: [% input_code %] 169: ); 170: 171: # A parameter the routine tests with -d must name an existing directory: 172: # nothing generated from a string pattern can satisfy that, so point the 173: # field at a real temporary directory and let the value set do the work. 174: foreach my $field (keys %input) { 175: my $spec = $input{$field}; 176: next unless(ref($spec) eq 'HASH'); 177: next unless(($spec->{'semantic'} // '') eq 'directory'); 178: require File::Temp; 179: $spec->{'memberof'} = [ File::Temp::tempdir(CLEANUP => 1) ]; 180: delete $spec->{$_} for qw(matches min max semantic); 181: $spec->{'_directory'} = 1; 182: # The list is a harness fixture, not a documented domain: there is no 183: # outside value to expect a death from. 184: $spec->{'_fixture'} = 1; 185: } 186: 187: # A parameter the routine tests with -e or -f must name an existing file. 188: # The file is created once per harness and removed at exit; a constructor 189: # that only keeps the path is satisfied by any real file. 190: foreach my $field (keys %input) { 191: my $spec = $input{$field}; 192: next unless(ref($spec) eq 'HASH'); 193: next unless(($spec->{'semantic'} // '') eq 'existing_file'); 194: require File::Temp; 195: my ($fh, $path) = File::Temp::tempfile(SUFFIX => '.pm', UNLINK => 1); 196: close $fh; 197: $spec->{'memberof'} = [ $path ]; 198: # The list is a harness fixture, not a documentation claim: say so, so the 199: # run neither calls it a documented-only constraint nor tolerates a value 200: # outside it. 201: $spec->{'_constraint_source'} = { %{ $spec->{'_constraint_source'} || {} }, memberof => 'existing_file' }; 202: $spec->{'_fixture'} = 1; 203: delete $spec->{$_} for qw(matches min max semantic); 204: } 205: 206: my %output = ( 207: [% output_code %] 208: ); 209: 210: my %transforms = ( 211: [% transforms_code %] 212: ); 213: 214: my @relationships = ( 215: [% relationships_code %] 216: ); 217: 218: # Tolerance for documentation-only bounds is rare, so it must not be silent. 219: my %_documented_bound_logged; 220: 221: # A POD-derived constraint (bound, member list or pattern) is a claim about 222: # valid input. Fuzzing can contradict it in either direction: the routine can 223: # reject a value inside it, or accept one outside it. Outside values are run 224: # as advisory probes: a death means the routine keeps its documentation, and 225: # survival is recorded and reported once at the end. Advisory runs tolerate 226: # these findings; strict-documented turns them into failures. 227: my %_documented_constraint_contradictions; 228: my ($_documented_inside, $_documented_outside); 229: my $_current_input; 230: my $documented_tolerated = 0; 231: my $documented_constraint_probe = 0; 232: 233: # Candidates for regex comparisons 234: my @candidate_good = ('123', 'abc', 'A1B2', '0'); 235: my @candidate_bad = ( 236: "ð", # emoji 237: "ï¼ï¼ï¼", # full-width digits 238: "١٢٣", # Arabic digits 239: '..', # regex metachars 240: "a\nb", # newline in middle 241: "é", # E acute 242: 'x' x 5000, # huge string 243: *STDOUT, 244: ' ', # space 245: "\t", # tab 246: "\r", # carriage return 247: 248: # Added later if the configuration says so 249: # '', # empty 250: # undef, # undefined 251: # "\0", # null byte 252: ); 253: my $positions = populate_positions(\%input); 254: 255: # --- Fuzzer helpers --- 256: sub _pick_from { 257: my $arrayref = $_[0]; 258: return undef unless $arrayref && ref $arrayref eq 'ARRAY' && @{$arrayref}; 259: return $arrayref->[ int(rand(scalar @$arrayref)) ]; 260: } 261: 262: sub rand_ascii_str { 263: my $len = shift // int(rand(10)) + 1; 264: # join '', map { chr(97 + int(rand(26))) } 1..$len; 265: return Data::Random::String->create_random_string(length => $len, contains => 'alphanumeric'); 266: } 267: 268: my @unicode_codepoints = ( 269: 0x00A9, # © 270: 0x00AE, # ® 271: 0x03A9, # Ω 272: 0x20AC, # ⬠273: 0x2013, # â (en-dash) 274: 0x0301, # combining acute accent 275: 0x0308, # combining diaeresis 276: 0x1F600, # ð (emoji) 277: 0x1F62E, # ð® 278: 0x1F4A9, # ð© (yes) 279: ); 280: 281: # Tests for matches or nomatch 282: my @regex_tests = ( 283: 'match123', 284: 'nope', 285: '/fullpath', 286: '/', 287: '/etc/passwd', 288: '../../etc/passwd', 289: "/etc/passwd\0", 290: "D:\\dos_path", 291: "I:\\", 292: '/(?{ exit 1 })/', 293: ); 294: 295: # unified generator to randomly produces codepoint strings, 296: # grapheme clusters, ZWJ emoji sequences, or aggressive Unicode fuzz strings 297: sub rand_str 298: { 299: my $len = $_[0]; 300: if(!defined($len)) { 301: $len = int(rand(10)) + 1; # length random number between 1 and 10 302: } 303: 304: return '' if($len == 0); 305: 306: if(!($config{'test_non_ascii'} // 0)) { 307: return rand_ascii_str($len); 308: } 309: 310: # my $rc = _rand_str_basic($len); 311: # $rc = _rand_unicode_fuzzer($len); 312: # my $l = Unicode::GCString->new($rc)->length(); 313: # if($len > $l) { 314: # $rc .= 'a' x ($len - $l); # Why is this needed? 315: # } 316: 317: # return $rc; 318: 319: # TODO: length issues at the moment 320: my $mode = int(rand(5)); # 0..4 321: 322: my $rc = _rand_str_basic($len); 323: 324: $rc = _rand_str_basic($len) if $mode == 0; 325: $rc = _rand_codepoint_exact($len) if $mode == 1; 326: $rc = _rand_grapheme_exact($len) if $mode == 2; 327: $rc = _rand_unicode_fuzzer($len) if $mode == 3; 328: $rc = rand_ascii_str($len) if($mode == 4); 329: 330: my $rc_len = Unicode::GCString->new($rc)->length(); 331: if($rc_len > $len) { 332: my $gcstr = Unicode::GCString->new($rc); 333: $rc = $gcstr->substr(0, $len)->as_string(); 334: $rc_len = Unicode::GCString->new($rc)->length(); 335: } 336: if($len > $rc_len) { 337: $rc .= 'a' x ($len - $rc_len); 338: $rc_len = Unicode::GCString->new($rc)->length(); 339: } 340: 341: fail("BUG $rc_len != $len (mode == $mode)") if($rc_len != $len); 342: 343: return $rc; 344: } 345: 346: # Choose a random string that is valid for the declared string bounds: 347: # exact min when it is positive, exact max when only max is declared, and 348: # the empty string for a zero bound. No bound means a normal random string. 349: sub _random_string_with_length 350: { 351: my ($spec, $length) = @_; 352: 353: my $str = rand_str($length); 354: 355: # rand_str() measures Unicode strings in grapheme clusters. A declared 356: # max is measured in characters by validators and length(), so a 357: # multi-codepoint grapheme can otherwise push the result past the bound. 358: $str = substr($str, 0, $spec->{max}) 359: if defined($spec->{max}) && (length($str) > $spec->{max}); 360: 361: return $str; 362: } 363: 364: # The regex generator uses Perl's RNG, so seeding it here makes generated 365: # matching strings reproducible from the schema's seed. It is seeded once, 366: # not per call: reseeding before every string would return the same value for 367: # every case that shares a pattern. 368: my $_regex_generation_seeded = 0; 369: sub _seed_regex_generation 370: { 371: return if $_regex_generation_seeded++; 372: srand($seed) if defined($seed); 373: } 374: 375: # Cache of patterns whose generation failed or timed out, keyed by pattern and 376: # requested length. The first attempt pays the timeout; later cases reuse the 377: # fallback instead of waiting again. 378: my %_regex_generation_fallback; 379: 380: # Generate a string matching $re, bounded by config 'regex_timeout' seconds 381: # (default 5). `length` asks for exactly that many characters (boundary 382: # cases); `min_length`/`max_length` accept any length inside the schema's 383: # bounds (random data) and are not passed to the generator. A pattern that 384: # cannot be satisfied, or whose generator hangs, falls back to a fixed 385: # candidate that matches; when none does the case is skipped and the pattern 386: # is reported once rather than failing the run. 387: sub _random_string_matching 388: { 389: my ($re, %opts) = @_; 390: 391: $re = qr/$re/ if(ref($re) ne 'Regexp'); 392: my $pattern = "$re"; 393: my $cache_key = join('|', $pattern, map { $opts{$_} // '' } qw(length min_length max_length)); 394: 395: if(exists($_regex_generation_fallback{$cache_key})) { 396: my $cached = $_regex_generation_fallback{$cache_key}; 397: return defined($cached) ? $cached : undef; 398: } 399: 400: _seed_regex_generation(); 401: 402: my $timeout = $config{'regex_timeout'} // 5; 403: my $wanted = $opts{length}; 404: my $acceptable = sub { 405: my ($value) = @_; 406: 407: return 0 unless defined($value) && ($value =~ $re); 408: return 0 if defined($wanted) && (length($value) != $wanted); 409: return 0 if defined($opts{min_length}) && (length($value) < $opts{min_length}); 410: return 0 if defined($opts{max_length}) && (length($value) > $opts{max_length}); 411: return 1; 412: }; 413: 414: my %generator_opts = %opts; 415: delete @generator_opts{qw(min_length max_length)}; 416: $generator_opts{length} //= $opts{max_length} // $opts{min_length}; 417: 418: my $result; 419: my $remaining = alarm(0); 420: local $SIG{'ALRM'} = sub { die "__REGEX_TIMEOUT__\n" }; 421: alarm($timeout) if($timeout > 0); 422: my $ok = eval { 423: # The generator treats 'length' as a hint: with an open quantifier 424: # (\w+, [a-z]*) it can return a value outside the schema's bounds. 425: # Retry a bounded number of times rather than accepting one the 426: # schema does not allow. 427: for (1 .. 20) { 428: my $candidate = Data::Random::String::Matches->create_random_string({ %generator_opts, regex => $re }); 429: next unless $acceptable->($candidate); 430: $result = $candidate; 431: last; 432: } 433: 1; 434: }; 435: my $error = $@; 436: alarm(0); 437: alarm($remaining) if $remaining; 438: 439: return $result if($ok && defined($result)); 440: 441: # Fallback: a fixed value that matches, so a bad pattern costs one 442: # attempt rather than a hang or a failing case. 443: my $fallback; 444: foreach my $candidate (@candidate_good, '', 'x', '0', 'a') { 445: next unless $acceptable->($candidate); 446: $fallback = $candidate; 447: last; 448: } 449: 450: $_regex_generation_fallback{$cache_key} = $fallback; 451: 452: if(defined($fallback)) { 453: diag("regex generation for $pattern fell back to a fixed string" . ($ok ? '' : " ($error)")); 454: return $fallback; 455: } 456: 457: diag("cannot generate a string matching $pattern" . ($ok ? '' : " ($error)") . '; skipping that case'); 458: return undef; 459: } 460: 461: # Bounds for random pattern-generated values: any length the schema allows 462: # is valid, unlike a boundary case that must be exactly one length. 463: sub _length_bounds 464: { 465: my ($spec) = @_; 466: 467: return () unless ref($spec) eq 'HASH'; 468: 469: return ( 470: (defined($spec->{min}) ? (min_length => $spec->{min}) : ()), 471: (defined($spec->{max}) ? (max_length => $spec->{max}) : ()), 472: ); 473: } 474: 475: sub _random_string_for_spec 476: { 477: my ($spec, $default) = @_; 478: 479: if(defined(my $re = $spec->{matches})) { 480: $re = qr/$re/ if(ref($re) ne 'Regexp'); 481: my $str = _random_string_matching($re, _length_bounds($spec)); 482: return $str if defined($str); 483: } 484: 485: my $len = $spec->{min} // $spec->{max}; 486: return '' if defined($len) && ($len == 0); 487: return _random_string_with_length($spec, $len) if defined($len); 488: return $default if defined($default); 489: return rand_str(); 490: } 491: 492: # A byte string is data, not text: draw arbitrary octets so the high bytes a 493: # text generator never produces are exercised too. 494: sub rand_bytes 495: { 496: my $len = shift // int(rand(10)) + 1; 497: 498: return '' if($len <= 0); 499: 500: return join('', map { pack('C', int(rand(256))) } 1 .. $len); 501: } 502: 503: # As _random_string_for_spec(), but for a semantic => 'bytes' parameter: the 504: # value honours the declared length and holds octets rather than characters. 505: sub _random_bytes_for_spec 506: { 507: my ($spec) = @_; 508: 509: my $len = $spec->{min} // $spec->{max}; 510: return rand_bytes($len) if defined($len); 511: return rand_bytes(); 512: } 513: 514: # Choose a random number inside the declared bounds. A max-only spec is 515: # reached from the fixed max boundary, never from an unbounded random value, 516: # so a routine that enforces the maximum is not sent a value above it. 517: sub _random_number_for_spec 518: { 519: my ($spec, $integer) = @_; 520: 521: my $min = $spec->{min}; 522: # Generated data stops at sample_max: the documented maximum is the bound 523: # a value is checked against, not necessarily a value this run can afford 524: # to compute (a count of hashing rounds, say). 525: my $max = $spec->{sample_max} // $spec->{max}; 526: 527: if(defined($min) && defined($max)) { 528: return $integer 529: ? $min + int(rand($max - $min + 1)) 530: : $min + rand($max - $min); 531: } 532: if(defined($max)) { 533: return $integer ? $max - int(abs(rand_int())) : $max - abs(rand_num()); 534: } 535: if(defined($min)) { 536: return $integer ? $min + int(abs(rand_int())) : $min + abs(rand_num()); 537: } 538: return $integer ? rand_int() : rand_num(); 539: } 540: 541: # Generate one random value that satisfies a (possibly nested) schema. 542: # `schema` describes the elements of an arrayref, the values of a hashref, 543: # or (when it maps names to schemas instead of declaring a type) the fixed 544: # keys of a hashref. Element schemas may be any type, including another 545: # arrayref or hashref, and objects built from `isa` or `can`. 546: sub _random_value_for_spec 547: { 548: my ($spec) = @_; 549: 550: $spec = { type => $spec } if(defined($spec) && !ref($spec)); 551: $spec = {} unless ref($spec) eq 'HASH'; 552: my $type = $spec->{type} // 'string'; 553: 554: if($type eq 'string') { 555: if(defined(my $re = $spec->{matches})) { 556: $re = qr/$re/ if(ref($re) ne 'Regexp'); 557: my $str = _random_string_matching($re, _length_bounds($spec)); 558: return $str if defined($str); 559: } 560: # A documented list of values is the domain: any member is valid, and 561: # a generated string outside it is not. 562: if(_has_memberof($spec)) { 563: return _pick_from($spec->{memberof}); 564: } 565: return _random_string_for_spec($spec, 'test_value'); 566: } 567: return _random_number_for_spec($spec, 1) if($type eq 'integer'); 568: return _random_number_for_spec($spec, 0) if(($type eq 'number') || ($type eq 'float')); 569: return int(rand(2)) if($type eq 'boolean'); 570: return sub { } if($type eq 'coderef'); 571: return rand_ascii_str(8) if($type eq 'any'); 572: return _random_object_for_spec($spec) if($type eq 'object'); 573: return _random_array_for_spec($spec) if(($type eq 'arrayref') || ($type eq 'array')); 574: return _random_hash_for_spec($spec) if($type eq 'hashref'); 575: 576: carp("unhandled element type '$type'; using undef"); 577: return undef; 578: } 579: 580: sub _random_array_for_spec 581: { 582: my ($spec, $len) = @_; 583: 584: $spec = {} unless ref($spec) eq 'HASH'; 585: $len = $spec->{min} unless defined($len); 586: $len = 1 unless defined($len); 587: $len = int($len); 588: $len = 0 if($len < 0); 589: 590: # A constructor that refuses an empty list of live objects documents a 591: # minimum of one, and the stand-in is the only element it accepts. 592: my $stub = $spec->{_stub_elements}; 593: if(ref($stub) eq 'HASH') { 594: # An empty list is a real value here: it is the below-minimum case a 595: # routine that demands a non-empty list must reject. Only the 596: # elements are fixed, not the count. 597: return [] if($len == 0); 598: return [ map { _build_stub_object($stub) } 1 .. $len ]; 599: } 600: 601: my $element = $spec->{schema}; 602: # A schema that maps key names to element schemas describes a hash whose 603: # keys are fixed; _random_hash_for_spec() is the builder for that shape. 604: if((ref($element) eq 'HASH') && !exists($element->{type})) { 605: return [ map { _random_hash_for_spec({ schema => $element }) } 1 .. $len ]; 606: } 607: return [ map { _random_value_for_spec($element) } 1 .. $len ]; 608: } 609: 610: sub _random_hash_for_spec 611: { 612: my ($spec, $len) = @_; 613: 614: $spec = {} unless ref($spec) eq 'HASH'; 615: my $schema = $spec->{schema}; 616: 617: # A schema without a type maps key names to element schemas, so the hash 618: # has exactly those keys. A scalar type is shorthand for { type => ... }. 619: if((ref($schema) eq 'HASH') && !exists($schema->{type})) { 620: my %fixed; 621: foreach my $key (sort keys %{$schema}) { 622: my $value = $schema->{$key}; 623: $value = { type => $value } if(defined($value) && !ref($value)); 624: next unless ref($value) eq 'HASH'; 625: $fixed{$key} = _random_value_for_spec($value); 626: } 627: return \%fixed; 628: } 629: 630: $len = $spec->{min} unless defined($len); 631: $len = 1 unless defined($len); 632: $len = int($len); 633: $len = 0 if($len < 0); 634: 635: my %hash; 636: $hash{"key$_"} = _random_value_for_spec($schema) for 1 .. $len; 637: return \%hash; 638: } 639: 640: # Build a value for an object element schema. `isa` uses a no-argument 641: # constructor; `can` falls back to a Class::Simple mock with that method, the 642: # same way a top-level object parameter is mocked. 643: sub _random_object_for_spec 644: { 645: my ($spec) = @_; 646: 647: my $class = $spec->{isa}; 648: if(defined($class) && !ref($class)) { 649: # The class may already be loaded by the module under test. 650: eval { require $class; 1 } unless $class->can('new'); 651: my $object = eval { $class->new }; 652: return $object if(defined($object) && ref($object) && eval { $object->isa($class) }); 653: } 654: 655: my $method = $spec->{can}; 656: if(defined($method)) { 657: eval { require Class::Simple; 1 } 658: or carp("cannot build object element: Class::Simple is not available"); 659: my $object = eval { Class::Simple->new }; 660: return $object if(defined($object) && $object->can($method)); 661: } 662: 663: carp('cannot build object element: give a class with a no-argument constructor as isa, or a method name as can'); 664: return undef; 665: } 666: 667: # A stable text key for a stub description, so one package serves every 668: # identical description. No serialisation module is needed: a harness for a 669: # plain function should not carry a dependency it never uses. 670: sub _stub_key 671: { 672: my ($value) = @_; 673: 674: return 'undef' unless defined($value); 675: return 'a[' . join(',', map { _stub_key($_) } @{$value}) . ']' if ref($value) eq 'ARRAY'; 676: return 'h{' . join(',', map { $_ . '=' . _stub_key($value->{$_}) } sort keys %{$value}) . '}' if ref($value) eq 'HASH'; 677: return "$value"; 678: } 679: 680: # Build a stand-in for an object a constructor calls methods on. The schema 681: # names the base class (from the constructor's POD) and the canned result of 682: # each method, so the stand-in passes the constructor's isa/blessed checks 683: # and answers the calls it makes. One package is defined per distinct 684: # description; every call returns a fresh instance. 685: my %_stub_packages; 686: sub _build_stub_object 687: { 688: my ($spec) = @_; 689: 690: my $isa = $spec->{isa}; 691: my $methods = $spec->{methods} // {}; 692: 693: eval "require $isa; 1" or die "cannot stub $isa: $@"; 694: 695: my $key = _stub_key([ $isa, [ map { [ $_, $methods->{$_} ] } sort keys %{$methods} ] ]); 696: 697: my $pkg = $_stub_packages{$key}; 698: if(!defined($pkg)) { 699: $pkg = 'App::Test::Generator::Stub::' . scalar(keys %_stub_packages); 700: no strict 'refs'; 701: @{"${pkg}::ISA"} = ($isa); 702: for my $name (keys %{$methods}) { 703: my $canned = $methods->{$name}; 704: *{"${pkg}::$name"} = sub { 705: my $value = $canned; 706: return ref($value) eq 'ARRAY' ? [ @{$value} ] 707: : ref($value) eq 'HASH' ? { %{$value} } : $value; 708: }; 709: } 710: $_stub_packages{$key} = $pkg; 711: } 712: 713: return bless({}, $pkg); 714: } 715: 716: ##################################################### 717: # 1. EXACT-LENGTH CODEPOINT MODE 718: # Generate a random string: mostly ASCII, sometimes unicode, sometimes nul bytes or combining marks 719: ##################################################### 720: sub _rand_str_basic 721: { 722: my $len = $_[0]; 723: 724: my @chars; 725: for (1..$len) { 726: my $r = rand(); 727: if ($r < PROB_LOWERCASE) { 728: push @chars, chr(97 + int(rand(26))); # a-z 729: } elsif ($r < 0.88) { 730: push @chars, chr(65 + int(rand(26))); # A-Z 731: } elsif ($r < 0.95) { 732: push @chars, chr(48 + int(rand(10))); # 0-9 733: } elsif($r < 0.975) { 734: push @chars, _rand_unicode_char(); # occasional emoji/marks 735: } elsif($config{'test_nuls'}) { 736: push @chars, chr(0); # nul byte injection 737: } else { 738: push @chars, chr(97 + int(rand(26))); # a-z 739: } 740: } 741: 742: if (rand() < 0.08) { 743: # 8% chance to prepend combining acute accent (0301) 744: $chars[-1] = chr(0x0301); 745: } elsif (rand() < 0.08) { 746: # 8% chance to append combining diaeresis (0308) 747: $chars[-1] .= chr(0x0308); 748: } 749: return join('', @chars); 750: } 751: 752: ##################################################### 753: # 2. EXACT-LENGTH CODEPOINT MODE 754: # combining marks decorate characters 755: ##################################################### 756: sub _rand_codepoint_exact { 757: my $len = $_[0]; 758: my @chars; 759: 760: for (1..$len) { 761: my $c = _rand_base_char(); 762: if(rand() < 0.08) { 763: # prepend combining acute 764: $c = chr(0x0301) 765: } elsif(rand() < 0.08) { 766: # append combining dieresis 767: $c = chr(0x0308); 768: } 769: push @chars, $c; 770: } 771: 772: return join('', @chars); 773: } 774: 775: # helper for codepoint mode 776: sub _rand_base_char { 777: my $r = rand(); 778: 779: if ($r < 0.70) { return chr(97 + int(rand(26))); } 780: if ($r < 0.88) { return chr(65 + int(rand(26))); } 781: if ($r < 0.95) { return chr(48 + int(rand(10))); } 782: return _rand_unicode_char(); 783: } 784: 785: ##################################################### 786: # 3. EXACT-LENGTH GRAPHEME-CLUSTER MODE 787: # each "character" is a whole grapheme cluster: 788: # - emoji with ZWJ sequences 789: # - flags 790: # - skin-tone variants 791: # - accented characters 792: ##################################################### 793: sub _rand_grapheme_exact { 794: my $len = $_[0]; 795: my @clusters; 796: 797: my @emoji_base = qw( 798: ð ð ð 𤣠ð ð ð ð ð¡ 𥳠799: ð ð ð ð ð ð© ð§ â¤ï¸ ð« 800: ); 801: 802: my @skin_tones = ( 803: "\x{1F3FB}", "\x{1F3FC}", "\x{1F3FD}", "\x{1F3FE}", "\x{1F3FF}" 804: ); 805: 806: my @zwj_parts = ( 807: "\x{200D}\x{1F33A}", # ZWJ + Flower 808: "\x{200D}\x{1F4BB}", # ZWJ + Laptop 809: "\x{200D}\x{1F9D1}", # ZWJ + person 810: ); 811: 812: my @flags = ( 813: "\x{1F1FA}\x{1F1F8}", # US 814: "\x{1F1EC}\x{1F1E7}", # UK 815: "\x{1F1E8}\x{1F1E6}", # CA 816: "\x{1F1E6}\x{1F1FA}", # AU 817: ); 818: 819: for (1..$len) { 820: my $type = rand(); 821: 822: if ($type < 0.4) { 823: # base emoji 824: my $e = $emoji_base[ rand @emoji_base ]; 825: 826: # TODO 827: # maybe add skin tone 828: # $e .= $skin_tones[rand @skin_tones] if rand() < 0.3; 829: 830: # TODO 831: # maybe add zwj sequence 832: # $e .= $zwj_parts[rand @zwj_parts] if rand() < 0.15; 833: 834: push @clusters, $e; 835: } elsif ($type < 0.55) { 836: # flag (always 1 grapheme cluster) 837: push @clusters, $flags[rand @flags]; 838: } elsif ($type < 0.75) { 839: # accented letter (composed or decomposed) 840: my $base = chr(97 + int(rand(26))); # a-z 841: my $accented = $base . chr(0x0301); 842: $accented = Unicode::Normalize::NFC($accented) if rand() < 0.5; 843: push @clusters, $accented; 844: } else { 845: # fallback ASCII 846: push @clusters, chr(97 + int(rand(26))); 847: } 848: } 849: 850: return join('', @clusters); 851: } 852: 853: #################################################### 854: # 4. UNICODE FUZZER MODE 855: # Extremely aggressive: invalid sequences, NULs, bidirectional markers, Zalgo 856: # Exclude unpaired surrogates for now, since TAP::Harness complains about that 857: #################################################### 858: sub _rand_unicode_fuzzer { 859: my $len = $_[0]; 860: my @out; 861: 862: my @zalgo_up = map { chr($_) } (0x030D..0x036F); 863: my @bidi = ("\x{202A}", "\x{202B}", "\x{202D}", "\x{202E}", "\x{2066}", "\x{2067}"); 864: my @weird = $config{'test_nuls'} ? ("\x{0000}", "\x{FFFD}", "\x{FEFF}") : ("\x{FFFD}", "\x{FEFF}"); 865: 866: for (1..$len) { 867: my $r = rand(); 868: 869: if ($r < 0.25) { 870: # push @out, chr( int(rand(0x10FFFF)) ); # random codepoint will include surragates 871: # Generate random codepoint, excluding surrogate range 872: my $cp; 873: do { 874: $cp = int(rand(0x10FFFF)); 875: } while ($cp >= 0xD800 && $cp <= 0xDFFF); 876: push @out, chr($cp); 877: } elsif ($r < 0.40) { 878: push @out, chr(65 + int(rand(26))) . $zalgo_up[rand @zalgo_up]; # Zalgo 879: } elsif ($r < 0.55) { 880: push @out, $bidi[rand @bidi]; 881: } elsif ($r < 0.70) { 882: push @out, $weird[rand @weird]; 883: } else { 884: push @out, _rand_unicode_char(); 885: } 886: } 887: 888: return join('', @out); 889: } 890: 891: ################################################### 892: # Random Unicode character helper 893: ################################################### 894: sub _rand_unicode_char 895: { 896: if(rand() < 0.5) { 897: my $cp = $unicode_codepoints[ int(rand(@unicode_codepoints)) ]; 898: return chr($cp); 899: } 900: 901: my @pool = ( 902: 0x00A9, 0x00AE, 0x2600, 0x2601, 903: 0x1F600 + int(rand(200)), # emoji block 904: 0x0300 + int(rand(80)), # combining marks 905: ); 906: return chr( $pool[int rand @pool] ); 907: } 908: 909: # Random character either upper or lower case 910: # sub rand_char 911: # { 912: # return rand_chars(set => 'all', min => 1, max => 1); 913: 914: # my $char = ''; 915: # my $upper_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; 916: # my $lower_chars = 'abcdefghijklmnopqrstuvwxyz'; 917: # my $combined_chars = $upper_chars . $lower_chars; 918: 919: # # Generate a random index between 0 and the length of the string minus 1 920: # my $rand_index = int(rand(length($combined_chars))); 921: 922: # # Get the character at that index 923: # return substr($combined_chars, $rand_index, 1); 924: # } 925: 926: # Integer generator: mix typical small ints with large limits 927: sub rand_int { 928: my $r = rand(); 929: if ($r < 0.75) { 930: return int(rand(200)) - 100; # -100 .. 100 (usual) 931: } elsif ($r < 0.9) { 932: return int(rand(2**31)) - 2**30; # 32-bit-ish 933: } elsif ($r < 0.98) { 934: return (int(rand(2**63)) - 2**62); # 64-bit-ish 935: } else { 936: # very large/suspicious values 937: return 2**63 - 1; 938: } 939: } 940: sub rand_bool { rand() > 0.5 ? 1 : 0 } 941: 942: # Number generator (floating), includes tiny/huge floats 943: sub rand_num { 944: my $r = rand(); 945: if ($r < 0.7) { 946: return (rand() * 200 - 100); # -100 .. 100 947: } elsif ($r < 0.9) { 948: return (rand() * 1e12) - 5e11; # large-ish 949: } elsif ($r < 0.95) { 950: return -0.0; # Negative 0 951: } elsif ($r < 0.96) { 952: return (rand() * 1e308) - 5e307; # very large floats 953: } elsif($r < 0.97) { 954: return 9**9**9; # Infinity 955: } else { 956: return 1e-308 * (rand() * 1000); # tiny float, subnormal-like 957: } 958: } 959: 960: sub rand_arrayref { 961: my $len = shift || int(rand(3)) + 1; # small arrays 962: 963: return Data::Random::Structure->new(max_elements => $len, max_depth => 1)->generate_array(); 964: 965: # return [ map { rand_str() } 1..$len ]; 966: } 967: 968: sub rand_hashref { 969: my $len = shift || int(rand(3)) + 1; # small hashes 970: 971: return Data::Random::Structure->new(max_elements => $len, max_depth => 1)->generate_hash(); 972: 973: # my %h; 974: # for (1..$len) { 975: # $h{rand_str(3)} = rand_str(5); 976: # } 977: # return \%h; 978: } 979: 980: sub rand_email 981: { 982: my $len = shift || int(rand(10)); 983: my $l; 984: my @name; 985: my @tlds = qw(com org net edu gov io co uk de fr); 986: 987: for($l = 0; $l < $len; $l++) { 988: push @name, pack('c', (int(rand 26))+97); 989: } 990: push @name, '@'; 991: $len = rand(10); 992: for($l = 0; $l < $len; $l++) { 993: push @name, pack('c', (int(rand 26))+97); 994: } 995: push @name, '.'; 996: $len = rand($#tlds+1); 997: push @name, $tlds[$len]; 998: return join('', @name); 999: } 1000: 1001: sub fuzz_inputs 1002: { 1003: my @cases; 1004: 1005: # Are any options mandatory? 1006: my $all_optional = 1; 1007: my %mandatory_strings; # List of mandatory strings to be added to all tests, always put at start so it can be overwritten 1008: my %mandatory_objects; 1009: my %mandatory_numbers; 1010: my $class_simple_loaded; 1011: 1012: # Create a hash ref of the mandatory args 1013: foreach my $field (keys %input) { 1014: my $spec = $input{$field} || {}; 1015: if((ref($spec) eq 'HASH') && (!$spec->{optional})) { 1016: $all_optional = 0; 1017: if($spec->{'type'} eq 'string') { 1018: local $config{'test_undef'} = 0; 1019: local $config{'test_nuls'} = 0; 1020: local $config{'test_empty'} = 0; 1021: if(($spec->{'semantic'} // '') eq 'bytes') { 1022: # Every other case is built on this filler, so it must be a 1023: # byte string as well: handing a routine that reads octets a 1024: # text value failed the case for the wrong reason. 1025: $mandatory_strings{$field} = _random_bytes_for_spec($spec); 1026: } elsif($spec->{'matches'}) { 1027: # The field's declared length is what a validator will 1028: # enforce, so the shared value must honour it too. 1029: $mandatory_strings{$field} = _random_string_matching( 1030: $spec->{'matches'}, _length_bounds($spec), 1031: ) // ''; 1032: } elsif(defined $spec->{memberof}) { 1033: my @set = @{$spec->{memberof}}; 1034: $mandatory_strings{$field} = $set[-1]; 1035: } else { 1036: # Every case is built on this filler, so it has to satisfy 1037: # what the schema states: an empty one made every case of an 1038: # argument the code refuses when empty die for that reason 1039: # instead of the one under test. 1040: $mandatory_strings{$field} = rand_ascii_str($spec->{max} // $spec->{min} // 8); 1041: $mandatory_strings{$field} = 'value' 1042: if $spec->{'_not_empty'} && !length($mandatory_strings{$field}); 1043: } 1044: } elsif($spec->{'type'} eq 'object') { 1045: my $method = $spec->{'can'}; 1046: if(!defined($method)) { 1047: die "$field: type is object, but 'can' is not specified which is needed to mock the object"; 1048: } 1049: if(!$class_simple_loaded) { 1050: require_ok('Class::Simple'); 1051: eval { 1052: Class::Simple->import(); 1053: $class_simple_loaded = 1; 1054: }; 1055: } 1056: my $simple_obj = new_ok('Class::Simple'); 1057: $simple_obj->$method(1); 1058: $mandatory_objects{$field} = $simple_obj; 1059: } elsif(($spec->{'type'} eq 'float') || ($spec->{'type'} eq 'number') || ($spec->{'type'} eq 'integer')) { 1060: # As for strings: a value outside the list is not a valid filler 1061: $mandatory_numbers{$field} = _has_memberof($spec) 1062: ? $spec->{memberof}[-1] 1063: : _random_number_for_spec($spec, $spec->{'type'} eq 'integer'); 1064: } elsif($spec->{type} eq 'hashref') { 1065: $mandatory_objects{$field} = _random_hash_for_spec($spec, $spec->{min} // 1); 1066: } elsif(($spec->{type} eq 'arrayref') || ($spec->{type} eq 'array')) { 1067: # A filler must satisfy the declared minimum: an empty array 1068: # here contradicted the below-minimum cases, so a routine that 1069: # enforces min => 1 failed a case it was never given a chance 1070: # to pass. 1071: $mandatory_objects{$field} = _random_array_for_spec($spec, $spec->{min} // 0); 1072: } elsif($spec->{type} eq 'coderef') { 1073: # A callback is required, but its behaviour is not: a no-op 1074: # coderef satisfies the contract of the call being tested. 1075: $mandatory_objects{$field} = sub { }; 1076: } elsif($spec->{type} eq 'any') { 1077: $mandatory_strings{$field} = rand_ascii_str(8); 1078: } else { 1079: carp __PACKAGE__, ": unhandled mandatory-arg type '${\$spec->{'type'}}'; skipping field '$field'"; 1080: next; 1081: } 1082: } 1083: } 1084: 1085: # Don't do for now, until transform object code is added 1086: # my %mandatory_args; 1087: # if(my $foundation = _fill_foundation()) { 1088: # %mandatory_args = %{$foundation}; 1089: # } 1090: my %mandatory_args = (%mandatory_strings, %mandatory_objects, %mandatory_numbers); 1091: 1092: if(($all_optional) || ((scalar keys %input) > 1)) { 1093: # Basic test cases 1094: if(((scalar keys %input) == 1) && exists($input{'type'}) && !ref($input{'type'})) { 1095: # our %input = ( type => 'string' ); 1096: my $type = $input{'type'}; 1097: 1098: if($input{'enum'}) { 1099: if($input{'memberof'}) { 1100: die 'input has both enum and memberof'; 1101: } 1102: $input{'memberof'} = delete $input{'enum'}; 1103: } 1104: foreach my $field(keys %input) { 1105: next if($field =~ /^_/); # Ignore comments 1106: if(!grep({ $_ eq $field } ('type', 'min', 'max', 'sample_max', 'optional', 'matches', 'can', 'memberof', 'position', 'named'))) { 1107: carp "unhandled schema keyword '$field'; skipping"; 1108: next; 1109: } 1110: } 1111: 1112: if ($type eq 'string') { 1113: push @cases, @{_generate_string_cases('_input', \%input, \%mandatory_args, _LINE => __LINE__)}; 1114: # push @cases, { '_input' => "emoji \x{1F600}" }; 1115: } else { 1116: carp "unhandled single-input type '$type'; skipping test generation"; 1117: } 1118: } else { 1119: # our %input = ( str => { type => 'string' } ); 1120: 1121: foreach my $arg_name (keys %input) { 1122: my $spec = $input{$arg_name} || {}; 1123: my $type = lc((!ref($spec)) ? $spec : $spec->{type}) || 'string'; 1124: 1125: if(ref($spec) && $spec->{'enum'}) { 1126: if($spec->{'memberof'}) { 1127: die "$arg_name has both enum and memberof"; 1128: } 1129: $spec->{'memberof'} = delete $spec->{'enum'}; 1130: } 1131: foreach my $field(keys %{$spec}) { 1132: next if($field =~ /^_/); # Ignore comments 1133: if(!grep({ $_ eq $field } ('type', 'min', 'max', 'sample_max', 'optional', 'matches', 'can', 'memberof', 'position', 'named', 'isa'))) { 1134: diag(__LINE__, ": TODO: handle schema keyword '$field'"); 1135: } 1136: } 1137: 1138: # --- Type-based seeds --- 1139: if(($type eq 'number') || ($type eq 'float')) { 1140: push @cases, @{_generate_float_cases($arg_name, $spec, \%mandatory_args, _LINE => __LINE__)}; 1141: } elsif ($type eq 'integer') { 1142: # Probably duplicated below, but here as well just in case 1143: push @cases, @{_generate_integer_cases($arg_name, $spec, \%mandatory_args, _LINE => __LINE__)}; 1144: } elsif ($type eq 'string') { 1145: push @cases, @{_generate_string_cases($arg_name, $spec, \%mandatory_args, _LINE => __LINE__)}; 1146: } elsif ($type eq 'boolean') { 1147: push @cases, @{_generate_boolean_cases($arg_name, $spec, \%mandatory_args, _LINE => __LINE__)}; 1148: } elsif ($type eq 'hashref') { 1149: push @cases, { %mandatory_args, $arg_name => _random_hash_for_spec($spec) }; 1150: # A documented type is intent: only a routine that checks its 1151: # arguments promises to reject the wrong type. 1152: if(_spec_checks_types($spec)) { 1153: push @cases, 1154: { %mandatory_args, $arg_name => [], _STATUS => 'DIES' }, 1155: { %mandatory_args, $arg_name => 66, _STATUS => 'DIES' }, 1156: { %mandatory_args, $arg_name => sub { die 'fail' }, _STATUS => 'DIES' }, 1157: { %mandatory_args, $arg_name => 'scalar when hashref is needed', _STATUS => 'DIES' }, 1158: { %mandatory_args, $arg_name => \'scalarref when hashref is needed', _STATUS => 'DIES' }; 1159: } 1160: if($config{test_undef}) { 1161: push @cases, 1162: { %mandatory_args, $arg_name => { nested => { 'first', undef, 'third' } }, _DESCRIPTION => 'nested hash with undef' } if($config{test_undef}); 1163: } 1164: } elsif ($type eq 'arrayref') { 1165: push @cases, { %mandatory_args, $arg_name => _random_array_for_spec($spec, 2) }; 1166: if(_spec_checks_types($spec)) { 1167: push @cases, { %mandatory_args, $arg_name => { a => 1 }, _STATUS => 'DIES' }; 1168: } 1169: } elsif($type eq 'object') { 1170: if($spec->{'isa'}) { 1171: push @cases, { $arg_name => { a => 1 }, _STATUS => 'DIES', _LINE => __LINE__ }; 1172: push @cases, { $arg_name => [], _STATUS => 'DIES', _LINE => __LINE__ }; 1173: 1174: # Test dies when given the wrong type of object 1175: push @cases, { $arg_name => new_ok('MyTestPackage'), _STATUS => 'DIES', _LINE => __LINE__ }; 1176: 1177: use_ok($spec->{isa}); 1178: push @cases, { $arg_name => new_ok($spec->{isa}) }; 1179: } elsif(!$spec->{can}) { 1180: Carp::carp("neither 'isa' nor 'can' is defined - what type of object should be sent?"); 1181: } 1182: } elsif($type eq 'any') { 1183: push @cases, 1184: { %mandatory_args, $arg_name => 'string_value' }, 1185: { %mandatory_args, $arg_name => 42 }, 1186: { %mandatory_args, $arg_name => 3.14 }, 1187: { %mandatory_args, $arg_name => [] }, 1188: { %mandatory_args, $arg_name => {} }; 1189: if($config{test_undef}) { 1190: push @cases, { %mandatory_args, $arg_name => undef }; 1191: } 1192: } 1193: 1194: # --- matches (regex) --- 1195: if (defined $spec->{matches}) { 1196: my $regex = $spec->{matches}; 1197: for my $string(@regex_tests) { 1198: if($string =~ $regex) { 1199: push @cases, { %mandatory_args, ( $arg_name => $string ) }; 1200: } elsif(!_constraint_is_documented($spec, 'matches')) { 1201: push @cases, { %mandatory_args, ( $arg_name => $string, _STATUS => 'DIES' ) }; 1202: } 1203: } 1204: } 1205: 1206: # --- nomatch (regex) --- 1207: if (defined $spec->{nomatch}) { 1208: my $regex = $spec->{nomatch}; 1209: for my $string(@regex_tests) { 1210: if($string =~ $regex) { 1211: push @cases, { %mandatory_args, ( $arg_name => $string, _STATUS => 'DIES' ) }; 1212: } else { 1213: push @cases, { %mandatory_args, ( $arg_name => $string ) }; 1214: } 1215: } 1216: } 1217: 1218: # --- memberof --- 1219: push @cases, _memberof_cases($arg_name, $spec, \%mandatory_args) if _has_memberof($spec); 1220: 1221: # --- notmemberof --- 1222: if (defined $spec->{notmemberof}) { 1223: my @set = @{ $spec->{notmemberof} }; 1224: push @cases, { %mandatory_args, ( $arg_name => $set[0], _STATUS => 'DIES' ) } if @set; 1225: push @cases, { %mandatory_args, ( $arg_name => '_not_in_set_' ) }; 1226: } 1227: 1228: # --- semantic --- 1229: if(defined(my $semantic = $spec->{'semantic'})) { 1230: if($semantic eq 'unix_timestamp') { 1231: push @cases, { %mandatory_args, ( -1, _STATUS => 'DIES' ) }, 1232: { %mandatory_args, ( $arg_name => 0 ) }, 1233: { %mandatory_args, ( $arg_name => 1 ) }, 1234: { %mandatory_args, ( $arg_name => time ) }, 1235: { %mandatory_args, ( $arg_name => 2147483647 ) }, 1236: { %mandatory_args, ( 45.67, _STATUS => 'DIES', _DESCRIPTION => 'UNIX timestamp should not be a float' ) }, 1237: { %mandatory_args, ( $arg_name => 2147483648, _STATUS => 'DIES' ) }; 1238: } elsif($semantic eq 'bytes') { 1239: # A byte string holds arbitrary octets, not text: high bytes 1240: # are valid data, and nothing about them is a document 1241: # violation. 1242: push @cases, 1243: { %mandatory_args, ( $arg_name => "\x00\x01\xfe\xff" ) }, 1244: { %mandatory_args, ( $arg_name => join('', map { chr } 0 .. 255) ) }; 1245: } elsif($semantic eq 'email') { 1246: push @cases, 1247: { %mandatory_args, ( $arg_name => 'user@example.com' ) }, 1248: { %mandatory_args, ( $arg_name => 'user+tag@sub.example.co.uk' ) }, 1249: { %mandatory_args, ( $arg_name => '@nodomain', _STATUS => 'DIES' ) }, 1250: { %mandatory_args, ( $arg_name => 'noatsign', _STATUS => 'DIES' ) }, 1251: { %mandatory_args, ( $arg_name => 'user@', _STATUS => 'DIES' ) }, 1252: { %mandatory_args, ( $arg_name => '', _STATUS => 'DIES' ) }, 1253: { %mandatory_args, ( $arg_name => 'user@' . ('a' x 256) . '.com', _STATUS => 'DIES' ) }; 1254: } elsif($semantic eq 'filepath') { 1255: push @cases, 1256: { %mandatory_args, ( $arg_name => '/tmp/test.txt' ) }, 1257: { %mandatory_args, ( $arg_name => 'relative/path.txt' ) }, 1258: { %mandatory_args, ( $arg_name => '.' ) }, 1259: { %mandatory_args, ( $arg_name => '..' ) }, 1260: { %mandatory_args, ( $arg_name => '../../etc/passwd', _STATUS => 'DIES' ) }, 1261: { %mandatory_args, ( $arg_name => '/etc/passwd' . "\0", _STATUS => 'DIES' ) }, 1262: { %mandatory_args, ( $arg_name => '', _STATUS => 'DIES' ) }, 1263: { %mandatory_args, ( $arg_name => '/' . ('a' x 4096), _STATUS => 'DIES' ) }; 1264: if($^O eq 'MSWin32') { 1265: push @cases, 1266: { %mandatory_args, ( $arg_name => 'C:\\Users\\test\\file.txt' ) }, 1267: { %mandatory_args, ( $arg_name => 'D:\\' ) }, 1268: { %mandatory_args, ( $arg_name => 'relative\\path.txt' ) }, 1269: { %mandatory_args, ( $arg_name => 'C:\\..\\..\\Windows\\System32', _STATUS => 'DIES' ) }, 1270: { %mandatory_args, ( $arg_name => 'C:\\path\\' . "\0" . 'file', _STATUS => 'DIES' ) }, 1271: { %mandatory_args, ( $arg_name => 'COM1', _STATUS => 'DIES' ) }, # reserved device name 1272: { %mandatory_args, ( $arg_name => 'NUL', _STATUS => 'DIES' ) }, # reserved device name 1273: { %mandatory_args, ( $arg_name => 'C:\\path\\file?.txt', _STATUS => 'DIES' ) }, # wildcard 1274: { %mandatory_args, ( $arg_name => 'C:\\path\\file*.txt', _STATUS => 'DIES' ) }, # wildcard 1275: { %mandatory_args, ( $arg_name => '\\\\server\\share\\file.txt' ) }; # UNC path 1276: } 1277: } elsif($semantic eq 'date_string') { 1278: push @cases, 1279: { %mandatory_args, ( $arg_name => '2024-01-01' ) }, 1280: { %mandatory_args, ( $arg_name => '1970-01-01' ) }, 1281: { %mandatory_args, ( $arg_name => '2024-02-29' ) }, # leap day 1282: { %mandatory_args, ( $arg_name => '2023-02-29', _STATUS => 'DIES' ) }, # not a leap year 1283: { %mandatory_args, ( $arg_name => '2024-13-01', _STATUS => 'DIES' ) }, # month 13 1284: { %mandatory_args, ( $arg_name => '2024-00-01', _STATUS => 'DIES' ) }, # month 0 1285: { %mandatory_args, ( $arg_name => '01-01-2024', _STATUS => 'DIES' ) }, # wrong order 1286: { %mandatory_args, ( $arg_name => '2024/01/01', _STATUS => 'DIES' ) }, # wrong separator 1287: { %mandatory_args, ( $arg_name => 'not-a-date', _STATUS => 'DIES' ) }, 1288: { %mandatory_args, ( $arg_name => '', _STATUS => 'DIES' ) }; 1289: } elsif($semantic eq 'iso8601_string') { 1290: push @cases, 1291: { %mandatory_args, ( $arg_name => '2024-01-01T00:00:00Z' ) }, 1292: { %mandatory_args, ( $arg_name => '2024-06-15T12:30:45Z' ) }, 1293: { %mandatory_args, ( $arg_name => '2024-01-01T00:00:00+05:30' ) }, 1294: { %mandatory_args, ( $arg_name => '2024-01-01' ) }, # date only - check if accepted 1295: { %mandatory_args, ( $arg_name => '2024-01-01T25:00:00Z', _STATUS => 'DIES' ) }, # hour 25 1296: { %mandatory_args, ( $arg_name => '2024-01-01T00:61:00Z', _STATUS => 'DIES' ) }, # minute 61 1297: { %mandatory_args, ( $arg_name => 'not-a-datetime', _STATUS => 'DIES' ) }, 1298: { %mandatory_args, ( $arg_name => '', _STATUS => 'DIES' ) }; 1299: } else { 1300: diag("semantic type $semantic is not yet supported"); 1301: } 1302: } 1303: } 1304: } 1305: } 1306: 1307: # Optional deduplication 1308: # my %seen; 1309: # @cases = grep { !$seen{join '|', %$_}++ } @cases; 1310: 1311: # Random data test cases 1312: # Uses type_edge_cases sometimes 1313: if(scalar keys %input) { 1314: if(((scalar keys %input) == 1) && exists($input{'type'}) && !ref($input{'type'})) { 1315: # our %input = ( type => 'string' ); 1316: my $type = $input{'type'}; 1317: for (1..[% iterations_code %]) { 1318: my $case_input; 1319: if (@edge_case_array && rand() < PROB_EDGE_CASE) { 1320: # Sometimes pick a field-specific edge-case 1321: $case_input = _pick_from(\@edge_case_array); 1322: } elsif(exists $type_edge_cases{$type} && rand() < 0.3) { 1323: # Sometimes pick a type-level edge-case 1324: $case_input = _pick_from($type_edge_cases{$type}); 1325: } elsif($type eq 'string') { 1326: if($input{matches}) { 1327: $case_input = _random_string_matching($input{'matches'}, _length_bounds(\%input)); 1328: } else { 1329: $case_input = _random_string_for_spec(\%input); 1330: } 1331: } elsif($type eq 'integer') { 1332: $case_input = _random_number_for_spec(\%input, 1); 1333: # If it's takes an integer, a float should die 1334: # Adding 0.1 to a large integer is lost to floating point 1335: # precision, so only claim the value is a non-integer when 1336: # it actually is one. 1337: my $float_input = $case_input + 0.1; 1338: push @cases, { _input => $float_input, _STATUS => 'DIES', _LINE => __LINE__ } 1339: if(($float_input != int($float_input)) && _spec_type_is_enforced(\%input)); 1340: } elsif(($type eq 'number') || ($type eq 'float')) { 1341: $case_input = _random_number_for_spec(\%input, 0); 1342: } elsif($type eq 'boolean') { 1343: $case_input = rand_bool(); 1344: } else { 1345: carp "unhandled single-param type '$type'; skipping test generation"; 1346: next; 1347: } 1348: push @cases, { _input => $case_input, _STATUS => 'OK', _LINE => __LINE__ } if($case_input); 1349: } 1350: } else { 1351: # our %input = ( str => { type => 'string' } ); 1352: push @cases, @{generate_tests(\%input, \%mandatory_args, _LINE => __LINE__)}; 1353: 1354: } 1355: } 1356: 1357: # edge-cases 1358: if($config{'test_undef'}) { 1359: if($all_optional) { 1360: push @cases, { '_DESCRIPTION' => 'No args since all are optional' }; 1361: } else { 1362: # Note that this is set on the input rather than output 1363: push @cases, { '_STATUS' => 'DIES' }; # At least one argument is needed 1364: } 1365: } 1366: 1367: if(scalar keys %input) { 1368: push @cases, { '_STATUS' => 'DIES', map { $_ => undef } keys %input } if($config{'test_undef'}); 1369: } else { 1370: push @cases, { '_DESCRIPTION' => 'Takes no input' }; # Takes no input 1371: } 1372: 1373: # If it's not in mandatory_strings it sets to 'undef' which is the idea, to test { value => undef } in the args 1374: # _LINE has to go first or else the undef in there mucks up the hash format 1375: # Parentheses matter: without them the map also consumes the flattened 1376: # %mandatory_objects pairs, so a mandatory hashref/arrayref/coderef value 1377: # became a bogus 'HASH(0x...)' key and the field itself was overwritten 1378: # with undef. 1379: push @cases, { _LINE => __LINE__, (map { $_ => $mandatory_strings{$_} } keys %input), %mandatory_objects } if($config{'test_undef'} && !$positions); 1380: 1381: push @candidate_bad, '' if($config{'test_empty'}); 1382: push @candidate_bad, undef if($config{'test_undef'}); 1383: push @candidate_bad, "\0" if($config{'test_nuls'}); 1384: 1385: # Type-specific edge cases for the single-schema form. The named-field 1386: # form does the same work through _generate_type_cases(), below. 1387: if(((scalar keys %input) == 1) && exists($input{'type'}) && !ref($input{'type'})) { 1388: # our %input = ( type => 'string' ); 1389: _note_documented_constraint('_input', \%input); 1390: if(_has_memberof(\%input)) { 1391: push @cases, _memberof_cases('_input', \%input, \%mandatory_args); 1392: } else { 1393: push @cases, @{_generate_type_cases('_input', $input{type}, \%input, \%mandatory_args)}; 1394: 1395: # Test all edge cases 1396: foreach my $edge(@edge_case_array) { 1397: push @cases, { _input => $edge, _DESCRIPTION => 'edge case' }; 1398: } 1399: } 1400: } else { 1401: # our %input = ( str => { type => 'string' } ); 1402: push @cases, @{generate_tests(\%input, \%mandatory_args)}; 1403: } 1404: 1405: # A POD-derived bound is a hint for valid data, not a promise that values 1406: # outside it die. Explicit probes are kept and report acceptance as a 1407: # documentation contradiction. Some ordinary cases are built from fixed 1408: # samples rather than the bounds (e.g. a newline-containing string, or 1409: # 43.56); drop any that a documented bound excludes. A hand-written bound 1410: # keeps its strict outside cases. 1411: @cases = @{_filter_documented_bound_cases(\@cases, \%input)}; 1412: 1413: # fuzzing can easily generate repeats 1414: if($config{'dedup'}) { 1415: return _dedup_cases(\@cases); 1416: } 1417: 1418: # use Data::Dumper; 1419: # die(Dumper(@cases)); 1420: 1421: return \@cases; 1422: } 1423: 1424: # Functions to generate test cases 1425: sub _generate_integer_cases { 1426: my ($arg_name, $spec, $mandatory_args) = @_; 1427: my @cases; 1428: 1429: # Same rule as strings and arrays: a documented-only bound sizes valid 1430: # data and does not make an outside value an error. Each bound is decided 1431: # on its own, so a code-enforced one stays strict beside a documented one. 1432: my $min_strict = !_constraint_is_documented($spec, 'min'); 1433: my $max_strict = !_constraint_is_documented($spec, 'max'); 1434: 1435: foreach my $i (-42, -1, 42) { 1436: if(((!defined $spec->{min}) || ($spec->{min} <= $i)) && ((!defined($spec->{max})) || ($spec->{max} >= $i))) { 1437: push @cases, { %{$mandatory_args}, ( $arg_name => $i ) }; 1438: } elsif((defined($spec->{min}) && ($i < $spec->{min}) && $min_strict) 1439: || (defined($spec->{max}) && ($i > $spec->{max}) && $max_strict)) { 1440: push @cases, { %{$mandatory_args}, ( $arg_name => $i, _STATUS => 'DIES' ) }; 1441: } 1442: } 1443: 1444: [% IF module %] 1445: # Send wrong data type - builtins aren't good at checking this 1446: push @cases, 1447: _spec_type_is_enforced($spec) ? ( 1448: { %{$mandatory_args}, ( $arg_name => "test string in integer field $arg_name", _STATUS => 'DIES', _LINE => __LINE__ ) }, 1449: { %{$mandatory_args}, ( $arg_name => {}, _STATUS => 'DIES', _LINE => __LINE__ ) }, 1450: { %{$mandatory_args}, ( $arg_name => 3.14, _STATUS => 'DIES' ) }, # Float 1451: { %{$mandatory_args}, ( $arg_name => 'xyz', _STATUS => 'DIES' ) }, 1452: { %{$mandatory_args}, ( $arg_name => \42, _STATUS => 'DIES' ) }, # Scalar ref 1453: { %{$mandatory_args}, ( $arg_name => *STDOUT, _STATUS => 'DIES' ) }, # Global variable 1454: { %{$mandatory_args}, ( $arg_name => [], _STATUS => 'DIES', _LINE => __LINE__ ) } 1455: ) : (); 1456: [% END %] 1457: 1458: # min/max numeric boundaries 1459: if (defined $spec->{min}) { 1460: my $min = $spec->{min}; 1461: if($min_strict) { 1462: push @cases, { %{$mandatory_args}, ( $arg_name => $min - 1, _STATUS => 'DIES' ) }; 1463: } else { 1464: push @cases, _documented_constraint_probe_case( 1465: $mandatory_args, $arg_name, $min - 1, 'documented minimum probe' 1466: ); 1467: } 1468: push @cases, 1469: { %{$mandatory_args}, ( $arg_name => " $min ", _LINE => __LINE__ ) }, # border, padded integer 1470: { %{$mandatory_args}, ( $arg_name => $min, _LINE => __LINE__ ) }; # border 1471: push @cases, { %{$mandatory_args}, ( $arg_name => $min + 1 ) } # just inside 1472: if(!defined($spec->{max}) || (($min + 1) <= $spec->{max})); 1473: 1474: if(!defined $spec->{max}) { 1475: push @cases, { %{$mandatory_args}, ( $arg_name => int($min + abs(rand_int())) ), _LINE => __LINE__ }; 1476: } 1477: if($min <= 0) { 1478: push @cases, { %{$mandatory_args}, ( $arg_name => -0.0, _STATUS => 'OK' ) } # Negative 0 1479: if(!defined($spec->{max}) || ($spec->{max} >= 0)); 1480: } 1481: } else { 1482: # These fixed samples are only valid when no max excludes them. 1483: push @cases, { %{$mandatory_args}, ( $arg_name => 1e5, _STATUS => 'OK' ) } # Scientific notation 1484: if(!defined($spec->{max}) || ($spec->{max} >= 1e5)); 1485: push @cases, { %{$mandatory_args}, ( $arg_name => 1_000, _STATUS => 'OK' ) } # Underscored 1486: if(!defined($spec->{max}) || ($spec->{max} >= 1_000)); 1487: push @cases, { %{$mandatory_args}, ( $arg_name => ' 42 ', _STATUS => 'OK' ) } # Padded integer 1488: if(!defined($spec->{max}) || ($spec->{max} >= 42)); 1489: } 1490: 1491: if (defined $spec->{max}) { 1492: my $max = $spec->{max}; 1493: # Valid data stops at the sampling ceiling; the documented bound 1494: # still decides what counts as outside. 1495: my $sampled = $spec->{sample_max} // $max; 1496: push @cases, { %{$mandatory_args}, ( $arg_name => $sampled - 1 ) } 1497: if(!defined($spec->{min}) || (($sampled - 1) >= $spec->{min})); 1498: push @cases, { %{$mandatory_args}, ( $arg_name => $sampled ) } 1499: if(!defined($spec->{min}) || ($sampled >= $spec->{min})); 1500: if($max_strict) { 1501: push @cases, { %{$mandatory_args}, ( $arg_name => $max + 1, _STATUS => 'DIES' ) }; 1502: } else { 1503: push @cases, _documented_constraint_probe_case( 1504: $mandatory_args, $arg_name, $max + 1, 'documented maximum probe' 1505: ); 1506: } 1507: 1508: if(defined $spec->{min}) { 1509: # Test 0 only when it is inside the declared range 1510: push @cases, { %{$mandatory_args}, ( $arg_name => 0 ) } 1511: if(($spec->{'min'} <= 0) && (!defined($spec->{max}) || ($spec->{max} >= 0))); 1512: } else { 1513: push @cases, { %{$mandatory_args}, ( $arg_name => _random_number_for_spec($spec, 1) ), _DESCRIPTION => 'max is defined but min is not' }; 1514: if($max >= 0) { 1515: push @cases, { %{$mandatory_args}, ( $arg_name => -0.0, _STATUS => 'OK' ) }; # Negative 0 1516: if($max == 0) { 1517: push @cases, { %{$mandatory_args}, ( $arg_name => abs(rand_int()) * -1 ), _LINE => __LINE__ }; # Any negative integer 1518: } 1519: } 1520: } 1521: } elsif(!defined $spec->{min}) { 1522: # Can take any number, so give it one 1523: push @cases, 1524: { %{$mandatory_args}, ( $arg_name => rand_int() ), _LINE => __LINE__ }, 1525: { %{$mandatory_args}, ( $arg_name => 0) }; # 0 is in range 1526: } 1527: 1528: return \@cases; 1529: } 1530: 1531: sub _generate_float_cases { 1532: my ($arg_name, $spec, $mandatory_args) = @_; 1533: my @cases; 1534: 1535: my $min_strict = !_constraint_is_documented($spec, 'min'); 1536: my $max_strict = !_constraint_is_documented($spec, 'max'); 1537: 1538: if((!defined $spec->{min}) || ($spec->{min} <= -0.1)) { 1539: push @cases, { %{$mandatory_args}, ( $arg_name => -0.1, _LINE => __LINE__ ) } 1540: if(!defined($spec->{max}) || ($spec->{max} >= -0.1)); 1541: } 1542: if((!defined $spec->{min}) || ($spec->{min} <= 43.56)) { 1543: push @cases, { %{$mandatory_args}, ( $arg_name => 43.56 ) } 1544: if(!defined($spec->{max}) || ($spec->{max} >= 43.56)); 1545: } 1546: 1547: [% IF module %] 1548: # Send wrong data type - builtins aren't good at checking this 1549: push @cases, 1550: _spec_type_is_enforced($spec) ? ( 1551: { %{$mandatory_args}, ( $arg_name => "test string in float field $arg_name", _STATUS => 'DIES', _LINE => __LINE__ ) }, 1552: { %{$mandatory_args}, ( $arg_name => {}, _STATUS => 'DIES', _LINE => __LINE__ ) }, 1553: { %{$mandatory_args}, ( $arg_name => \42.1, _STATUS => 'DIES' ) }, # Scalar ref 1554: # NaN and Inf are valid according to looks_like_number() so we 1555: # cannot assume they die 1556: # { %{$mandatory_args}, ( $arg_name => "NaN", _STATUS => 'DIES' ) }, 1557: { %{$mandatory_args}, ( $arg_name => [], _STATUS => 'DIES', _LINE => __LINE__ ) } 1558: ) : (); 1559: [% END %] 1560: 1561: # min/max numeric boundaries 1562: if (defined $spec->{min}) { 1563: my $min = $spec->{min}; 1564: if($min_strict) { 1565: push @cases, { %{$mandatory_args}, ( $arg_name => $min - 0.001, _STATUS => 'DIES' ), _DESCRIPTION => 'float below minimum value is denied' }; 1566: } else { 1567: push @cases, _documented_constraint_probe_case( 1568: $mandatory_args, $arg_name, $min - 0.001, 'documented minimum probe' 1569: ); 1570: } 1571: push @cases, 1572: { %{$mandatory_args}, ( $arg_name => $min, _LINE => __LINE__ ), _DESCRIPTION => 'float minimum value is allowed' }; # border 1573: push @cases, { %{$mandatory_args}, ( $arg_name => $min + 0.001 ), _DESCRIPTION => 'float above minimum value is allowed' } # just inside 1574: if(!defined($spec->{max}) || (($min + 0.001) <= $spec->{max})); 1575: 1576: [% IF module %] 1577: push @cases, { %{$mandatory_args}, ( $arg_name => "-inf", _STATUS => 'DIES' ) } if $min_strict; 1578: [% END %] 1579: 1580: if(!defined $spec->{max}) { 1581: if($min <= 0) { 1582: push @cases, { %{$mandatory_args}, ( $arg_name => $min + abs(rand_num()) ), _LINE => __LINE__ }; # Any positive number 1583: } else { 1584: push @cases, { %{$mandatory_args}, ( $arg_name => $min + abs(rand_num()) ), _DESCRIPTION => 'min is defined but max is not' }; 1585: } 1586: } 1587: } 1588: if (defined $spec->{max}) { 1589: my $max = $spec->{max}; 1590: my $sampled = $spec->{sample_max} // $max; 1591: push @cases, { %{$mandatory_args}, ( $arg_name => $sampled - 0.000001 ) } 1592: if(!defined($spec->{min}) || (($sampled - 0.000001) >= $spec->{min})); 1593: push @cases, { %{$mandatory_args}, ( $arg_name => $sampled ) } 1594: if(!defined($spec->{min}) || ($sampled >= $spec->{min})); 1595: if($max_strict) { 1596: push @cases, { %{$mandatory_args}, ( $arg_name => $max + 0.000001, _STATUS => 'DIES' ) }; 1597: } else { 1598: push @cases, _documented_constraint_probe_case( 1599: $mandatory_args, $arg_name, $max + 0.000001, 'documented maximum probe' 1600: ); 1601: } 1602: 1603: [% IF module %] 1604: push @cases, 1605: { %{$mandatory_args}, ( $arg_name => "inf", _STATUS => 'DIES' ) }, 1606: { %{$mandatory_args}, ( $arg_name => 9**9**9, _STATUS => 'DIES' ) } if $max_strict; 1607: [% END %] 1608: 1609: if(defined $spec->{min}) { 1610: # Test 0 if it's in range 1611: push @cases, { %{$mandatory_args}, ( $arg_name => 0 ) } 1612: if(($spec->{'min'} >= 0) && ($max >= 0)); 1613: } else { 1614: push @cases, { %{$mandatory_args}, ( $arg_name => _random_number_for_spec($spec, 0) ), _LINE => __LINE__ }; 1615: if($max == 0) { 1616: push @cases, { %{$mandatory_args}, ( $arg_name => abs(rand_num()) * -0.00000001 ) }; # Any negative number 1617: } 1618: } 1619: } elsif(!defined $spec->{min}) { 1620: # Can take any number, so give it some 1621: push @cases, 1622: { %{$mandatory_args}, ( $arg_name => rand_num(), _LINE => __LINE__ ) }, 1623: { %{$mandatory_args}, ( $arg_name => 1.23 ) }, 1624: { %{$mandatory_args}, ( $arg_name => -42.1 ) }, 1625: { %{$mandatory_args}, ( $arg_name => -0.0 ) }, # -0 is in range 1626: { %{$mandatory_args}, ( $arg_name => 0 ) }; # 0 is in range 1627: } 1628: 1629: return \@cases; 1630: } 1631: 1632: # basic boolean edge cases 1633: sub _generate_boolean_cases { 1634: my ($arg_name, $spec, $mandatory_args) = @_; 1635: 1636: my @cases; 1637: 1638: if(_has_memberof($spec)) { 1639: # memberof already defines allowed booleans 1640: foreach my $val (@{$spec->{memberof}}) { 1641: push @cases, { %{$mandatory_args}, ( $arg_name => $val ) }; 1642: } 1643: } else { 1644: @cases = ( 1645: { %{$mandatory_args}, ( $arg_name => 0 ) }, 1646: { %{$mandatory_args}, ( $arg_name => 1 ) }, 1647: { %{$mandatory_args}, ( $arg_name => 'true' ) }, 1648: { %{$mandatory_args}, ( $arg_name => 'false' ) }, 1649: { %{$mandatory_args}, ( $arg_name => 'off' ) }, 1650: { %{$mandatory_args}, ( $arg_name => 'on' ) }, 1651: { %{$mandatory_args}, ( $arg_name => 'yes' ) }, 1652: { %{$mandatory_args}, ( $arg_name => 'no' ) }, 1653: ); 1654: push @cases, ( 1655: { %{$mandatory_args}, ( $arg_name => 'xyzzy', _STATUS => 'DIES' ) }, # invalid boolean 1656: { %{$mandatory_args}, ( $arg_name => -1, _STATUS => 'DIES' ) }, # invalid boolean 1657: { %{$mandatory_args}, ( $arg_name => 2, _STATUS => 'DIES' ) }, # invalid boolean 1658: { %{$mandatory_args}, ( $arg_name => bless({}, 'Evil::Class'), _STATUS => 'DIES', _LINE => __LINE__ ) }, 1659: { %{$mandatory_args}, ( $arg_name => [ 1 ], _STATUS => 'DIES' ) } # invalid boolean 1660: ) if(_spec_type_is_enforced($spec)); 1661: } 1662: 1663: push @cases, { %{$mandatory_args}, ( $arg_name => undef, _STATUS => 'DIES' ) } if($config{'test_undef'}); 1664: push @cases, { %{$mandatory_args}, ( $arg_name => "\0", _STATUS => 'DIES' ) } 1665: if($config{'test_nuls'} && _spec_type_is_enforced($spec)); 1666: 1667: return \@cases; 1668: } 1669: 1670: # The field's source decides whether the routine's own validator checks 1671: # types. Each constraint has its own provenance: a documented minimum and a 1672: # maximum confirmed in the code on the same field are separate decisions. 1673: sub _spec_source 1674: { 1675: my ($spec) = @_; 1676: 1677: return (ref($spec) eq 'HASH') ? ($spec->{_source} // '') : ''; 1678: } 1679: 1680: sub _constraint_source 1681: { 1682: my ($spec, $constraint) = @_; 1683: 1684: if((ref($spec) eq 'HASH') && (ref($spec->{_constraint_source}) eq 'HASH')) { 1685: my $source = $spec->{_constraint_source}{$constraint}; 1686: return $source if defined($source) && length($source); 1687: } 1688: 1689: return _spec_source($spec); 1690: } 1691: 1692: sub _constraint_is_documented 1693: { 1694: my $source = _constraint_source(@_); 1695: 1696: return $documented_sources{$source} ? 1 : 0; 1697: } 1698: 1699: 1700: sub _spec_checks_types 1701: { 1702: return _spec_source($_[0]) eq $type_checks_source; 1703: } 1704: 1705: # Whether the routine's own checks reject a value of the wrong type. A 1706: # hand-written schema carries no marker and keeps that expectation; a type 1707: # the extractor inferred only from the code, a signature or a field 1708: # declaration says the parameter exists, not that anything else dies. 1709: sub _spec_type_is_enforced 1710: { 1711: my $source = _spec_source($_[0]); 1712: 1713: return 1 unless defined($source) && length($source); 1714: return ($source eq $type_checks_source) ? 1 : 0; 1715: } 1716: 1717: # A documented string or numeric bound sizes the valid data. Some cases are 1718: # built from fixed samples rather than from the bound, so drop any that the 1719: # bound excludes; otherwise a routine that enforces its documented range 1720: # fails on a value the harness generated as expected-to-live. 1721: sub _filter_documented_bound_cases 1722: { 1723: my ($cases, $input) = @_; 1724: 1725: my @kept; 1726: CASE: 1727: foreach my $case (@{$cases}) { 1728: # Explicit out-of-bound probes are meant to be run and reported; they 1729: # must survive this filter even though their value is outside a bound. 1730: if($case->{_DOCUMENTED_CONSTRAINTS}) { 1731: push @kept, $case; 1732: next CASE; 1733: } 1734: 1735: foreach my $field (keys %{$input}) { 1736: my $spec = $input->{$field}; 1737: next unless(ref($spec) eq 'HASH'); 1738: next unless _constraint_is_documented($spec, 'min') 1739: || _constraint_is_documented($spec, 'max'); 1740: 1741: my $type = $spec->{type} // 'string'; 1742: next unless($type =~ /^(?:string|integer|number|float)$/); 1743: 1744: my ($value, $found); 1745: if(exists($case->{$field})) { 1746: ($value, $found) = ($case->{$field}, 1); 1747: } elsif((ref($case->{'_input'}) eq 'HASH') && exists($case->{'_input'}{$field})) { 1748: ($value, $found) = ($case->{'_input'}{$field}, 1); 1749: } elsif(($field eq '_input') && exists($case->{'_input'})) { 1750: ($value, $found) = ($case->{'_input'}, 1); 1751: } 1752: next unless $found; 1753: 1754: # References, undef and other type probes are not size or range 1755: # values, so the bound does not apply to them. 1756: next unless defined($value) && !ref($value); 1757: 1758: if($type eq 'string') { 1759: next CASE unless _string_length_in_documented_bounds($spec, length($value)); 1760: } else { 1761: next unless Scalar::Util::looks_like_number($value); 1762: next CASE if _constraint_is_documented($spec, 'min') 1763: && defined($spec->{min}) && ($value < $spec->{min}); 1764: next CASE if _constraint_is_documented($spec, 'max') 1765: && defined($spec->{max}) && ($value > $spec->{max}); 1766: } 1767: } 1768: 1769: push @kept, $case; 1770: } 1771: 1772: return \@kept; 1773: } 1774: 1775: sub _string_length_in_bounds 1776: { 1777: my ($spec, $length) = @_; 1778: 1779: return 0 if defined($spec->{min}) && ($length < $spec->{min}); 1780: return 0 if defined($spec->{max}) && ($length > $spec->{max}); 1781: return 1; 1782: } 1783: 1784: sub _string_length_in_documented_bounds 1785: { 1786: my ($spec, $length) = @_; 1787: 1788: return 0 if _constraint_is_documented($spec, 'min') 1789: && defined($spec->{min}) && ($length < $spec->{min}); 1790: return 0 if _constraint_is_documented($spec, 'max') 1791: && defined($spec->{max}) && ($length > $spec->{max}); 1792: return 1; 1793: } 1794: 1795: sub _has_memberof 1796: { 1797: my ($spec) = @_; 1798: 1799: return (ref($spec) eq 'HASH') && (ref($spec->{memberof}) eq 'ARRAY') && @{$spec->{memberof}}; 1800: } 1801: 1802: # A member list is the whole valid domain. A value outside a hand-written 1803: # list is an error the routine promised to reject; outside a documented list 1804: # it is simply not documented, so no must-die case is invented for it. 1805: sub _memberof_cases 1806: { 1807: my ($arg_name, $spec, $mandatory_args) = @_; 1808: 1809: my @set = @{$spec->{memberof}}; 1810: my @cases = map { { %{$mandatory_args}, ( $arg_name => $_ ) } } @set; 1811: 1812: # The harness injected this list itself (a temporary file or directory 1813: # the routine's -e/-f/-d test needs), so it is not the routine's domain 1814: # and a value outside it is not an error the routine promised to reject. 1815: return @cases if($spec->{'_fixture'}); 1816: 1817: my $type = $spec->{type} // 'string'; 1818: my $outside = ($type =~ /^(?:integer|number|float)$/) 1819: ? (sort { $a <=> $b } @set)[-1] + 1 1820: : 'INVALID_MEMBEROF'; 1821: 1822: if(_constraint_is_documented($spec, 'memberof')) { 1823: # Advisory: run the outside value. A death means the routine does 1824: # enforce the documented list; survival is reported as a documented 1825: # constraint the routine does not keep. 1826: push @cases, _documented_constraint_probe_case( 1827: $mandatory_args, $arg_name, $outside, 'documented memberof probe' 1828: ); 1829: return @cases; 1830: } 1831: 1832: push @cases, { %{$mandatory_args}, ( $arg_name => $outside, _STATUS => 'DIES' ) }; 1833: 1834: return @cases; 1835: } 1836: 1837: # Size bounds for an arrayref parameter. A documented bound is a probe that 1838: # may die; a hand-written one is an error the routine must report. 1839: sub _generate_arrayref_cases 1840: { 1841: my ($arg_name, $spec, $mandatory_args) = @_; 1842: 1843: my @cases; 1844: my $min_documented = _constraint_is_documented($spec, 'min'); 1845: my $max_documented = _constraint_is_documented($spec, 'max'); 1846: 1847: if(defined $spec->{min}) { 1848: my $len = $spec->{min}; 1849: push @cases, 1850: { %{$mandatory_args}, ( $arg_name => _random_array_for_spec($spec, $len + 1) ) }, # just inside 1851: { %{$mandatory_args}, ( $arg_name => _random_array_for_spec($spec, $len) ) }; # border 1852: if($len > 0) { 1853: push @cases, $min_documented 1854: ? _documented_constraint_probe_case($mandatory_args, $arg_name, _random_array_for_spec($spec, $len - 1), 'documented minimum probe') 1855: : { %{$mandatory_args}, ( $arg_name => _random_array_for_spec($spec, $len - 1), _STATUS => 'DIES' ) }; 1856: } 1857: } elsif($config{'test_empty'}) { 1858: push @cases, { %{$mandatory_args}, ( $arg_name => [] ) }; # No min, empty array is allowable 1859: } 1860: 1861: if(defined $spec->{max}) { 1862: my $len = $spec->{max}; 1863: push @cases, 1864: { %{$mandatory_args}, ( $arg_name => _random_array_for_spec($spec, $len - 1) ) }, # just inside 1865: { %{$mandatory_args}, ( $arg_name => _random_array_for_spec($spec, $len) ) }; # border 1866: push @cases, $max_documented 1867: ? _documented_constraint_probe_case($mandatory_args, $arg_name, _random_array_for_spec($spec, $len + 1), 'documented maximum probe') 1868: : { %{$mandatory_args}, ( $arg_name => _random_array_for_spec($spec, $len + 1), _STATUS => 'DIES' ) }; 1869: } 1870: 1871: return \@cases; 1872: } 1873: 1874: # The same for a hashref parameter's key count. 1875: sub _generate_hashref_cases 1876: { 1877: my ($arg_name, $spec, $mandatory_args) = @_; 1878: 1879: my @cases; 1880: my $min_documented = _constraint_is_documented($spec, 'min'); 1881: my $max_documented = _constraint_is_documented($spec, 'max'); 1882: my $hash_of = sub { my ($len) = @_; return _random_hash_for_spec($spec, $len); }; 1883: 1884: # A schema that maps key names to element schemas fixes the key set, so 1885: # there is no size to vary: one valid hash covers it. 1886: my $nested = $spec->{schema}; 1887: if((ref($nested) eq 'HASH') && !exists($nested->{type})) { 1888: return [ { %{$mandatory_args}, ( $arg_name => _random_hash_for_spec($spec) ) } ]; 1889: } 1890: 1891: if(defined $spec->{min}) { 1892: my $len = $spec->{min}; 1893: push @cases, 1894: { %{$mandatory_args}, ( $arg_name => $hash_of->($len + 1) ) }, 1895: { %{$mandatory_args}, ( $arg_name => $hash_of->($len) ) }; 1896: if($len > 0) { 1897: push @cases, $min_documented 1898: ? _documented_constraint_probe_case($mandatory_args, $arg_name, $hash_of->($len - 1), 'documented minimum probe') 1899: : { %{$mandatory_args}, ( $arg_name => $hash_of->($len - 1), _STATUS => 'DIES' ) }; 1900: } 1901: } elsif($config{'test_empty'}) { 1902: push @cases, { %{$mandatory_args}, ( $arg_name => {} ) }; # No min, empty hash is allowable 1903: } 1904: 1905: if(defined $spec->{max}) { 1906: my $len = $spec->{max}; 1907: push @cases, 1908: { %{$mandatory_args}, ( $arg_name => $hash_of->($len - 1) ) }, 1909: { %{$mandatory_args}, ( $arg_name => $hash_of->($len) ) }; 1910: push @cases, $max_documented 1911: ? _documented_constraint_probe_case($mandatory_args, $arg_name, $hash_of->($len + 1), 'documented maximum probe') 1912: : { %{$mandatory_args}, ( $arg_name => $hash_of->($len + 1), _STATUS => 'DIES' ) }; 1913: } 1914: 1915: return \@cases; 1916: } 1917: 1918: # One entry point for every parameter type, so the single-schema and 1919: # named-field forms cannot drift apart. 1920: sub _generate_type_cases 1921: { 1922: my ($arg_name, $type, $spec, $mandatory_args) = @_; 1923: 1924: return _generate_integer_cases($arg_name, $spec, $mandatory_args) if($type eq 'integer'); 1925: return _generate_float_cases($arg_name, $spec, $mandatory_args) if(($type eq 'number') || ($type eq 'float')); 1926: return _generate_string_cases($arg_name, $spec, $mandatory_args) if($type eq 'string'); 1927: return _generate_arrayref_cases($arg_name, $spec, $mandatory_args) if(($type eq 'arrayref') || ($type eq 'array')); 1928: return _generate_hashref_cases($arg_name, $spec, $mandatory_args) if($type eq 'hashref'); 1929: return _generate_boolean_cases($arg_name, $spec, $mandatory_args) if($type eq 'boolean'); 1930: 1931: return []; 1932: } 1933: 1934: # Build an out-of-bound case for a POD-derived bound. The case is run 1935: # like any other expected-to-live input, but a death is accepted; survival 1936: # is recorded as a documentation contradiction. _DOCUMENTED_CONSTRAINTS 1937: # marks the case as a documented-constraint probe: it is kept by 1938: # _filter_documented_bound_cases and reported rather than expected to die. 1939: sub _documented_constraint_probe_case 1940: { 1941: my ($mandatory_args, $field, $value, $description) = @_; 1942: 1943: return { 1944: %{$mandatory_args}, 1945: $field => $value, 1946: _DOCUMENTED_CONSTRAINTS => 1, 1947: _DESCRIPTION => $description, 1948: }; 1949: } 1950: 1951: # Record a documented-only constraint once per parameter. Every kind of 1952: # constraint is reported the same way: bounds, member lists and patterns. 1953: sub _note_documented_constraint 1954: { 1955: my ($name, $spec) = @_; 1956: 1957: return unless ref($spec) eq 'HASH'; 1958: my @documented; 1959: push @documented, 'min' if defined($spec->{min}) && _constraint_is_documented($spec, 'min'); 1960: push @documented, 'max' if defined($spec->{max}) && _constraint_is_documented($spec, 'max'); 1961: push @documented, 'memberof' if _has_memberof($spec) && _constraint_is_documented($spec, 'memberof'); 1962: push @documented, 'matches' if defined($spec->{matches}) && _constraint_is_documented($spec, 'matches'); 1963: return unless @documented; 1964: 1965: (my $shown = $name) =~ s/^_+//; 1966: my $which = join(', ', @documented); 1967: diag("documented-only constraint on '$shown' ($which) is not enforced (from POD); values outside it are not expected to die") 1968: unless $_documented_bound_logged{$shown}++; 1969: } 1970: 1971: # Measure the value against the kind of bound the spec declares. Non-values 1972: # such as undef, references sent to a scalar parameter and non-numeric strings 1973: # sent to a numeric parameter are type probes, not bound observations. 1974: sub _documented_bound_measure 1975: { 1976: my ($spec, $value) = @_; 1977: 1978: my $type = $spec->{type} // 'string'; 1979: if($type eq 'string') { 1980: return unless defined($value) && !ref($value); 1981: return (length($value), 'length'); 1982: } 1983: if(($type eq 'integer') || ($type eq 'number') || ($type eq 'float')) { 1984: return unless defined($value) && !ref($value) && looks_like_number($value); 1985: return (0 + $value, 'value'); 1986: } 1987: if(($type eq 'arrayref') || ($type eq 'array')) { 1988: return unless ref($value) eq 'ARRAY'; 1989: return (scalar(@{$value}), 'element count'); 1990: } 1991: if($type eq 'hashref') { 1992: return unless ref($value) eq 'HASH'; 1993: return (scalar(keys %{$value}), 'key count'); 1994: } 1995: return; 1996: } 1997: 1998: sub _documented_bound_range 1999: { 2000: my ($spec) = @_; 2001: 2002: my @bounds; 2003: push @bounds, "min $spec->{min}" 2004: if defined($spec->{min}) && _constraint_is_documented($spec, 'min'); 2005: push @bounds, "max $spec->{max}" 2006: if defined($spec->{max}) && _constraint_is_documented($spec, 'max'); 2007: return join(', ', @bounds); 2008: } 2009: 2010: sub _failure_context 2011: { 2012: my ($input) = @_; 2013: 2014: my $seed = defined($seed) ? $seed : 'none'; 2015: my $shown = eval { 2016: require Data::Dumper; 2017: local $Data::Dumper::Terse = 1; 2018: local $Data::Dumper::Indent = 0; 2019: local $Data::Dumper::Sortkeys = 1; 2020: Data::Dumper::Dumper($input); 2021: }; 2022: $shown = '?' unless defined($shown); 2023: $shown =~ s/\s+/ /g; 2024: $shown = substr($shown, 0, 300) . '...' if(length($shown) > 300); 2025: 2026: return "seed = $seed; input = $shown"; 2027: } 2028: 2029: sub _short_value 2030: { 2031: my ($value) = @_; 2032: 2033: return 'undef' unless defined($value); 2034: return ref($value) if ref($value); 2035: (my $shown = $value) =~ s/\s+/ /g; 2036: return (length($shown) > 40) ? substr($shown, 0, 37) . '...' : $shown; 2037: } 2038: 2039: # Split the case's observed values into those inside and outside their POD 2040: # constraints (bounds, member lists and patterns). A death is a contradiction 2041: # for the first list; survival is a contradiction for the second. 2042: sub _documented_constraint_findings 2043: { 2044: my ($input, $schema) = @_; 2045: 2046: my @checks; 2047: if((ref($schema) eq 'HASH') && exists($schema->{type}) && !ref($schema->{type})) { 2048: # A single scalar schema: type/min/max are the parameter's spec. 2049: push @checks, ['_input', $schema, $input]; 2050: } elsif((ref($input) eq 'HASH') && (ref($schema) eq 'HASH')) { 2051: foreach my $field (sort keys %{$schema}) { 2052: my $spec = $schema->{$field}; 2053: next unless ref($spec) eq 'HASH'; 2054: next unless exists($input->{$field}); 2055: push @checks, [$field, $spec, $input->{$field}]; 2056: } 2057: } 2058: 2059: my (@inside, @outside); 2060: foreach my $check (@checks) { 2061: my ($field, $spec, $value) = @{$check}; 2062: my $min_documented = _constraint_is_documented($spec, 'min') && defined($spec->{min}); 2063: my $max_documented = _constraint_is_documented($spec, 'max') && defined($spec->{max}); 2064: 2065: my $shown = $field; 2066: $shown =~ s/^_+//; 2067: 2068: if(($min_documented || $max_documented) && defined($value)) { 2069: my ($measured, $unit) = _documented_bound_measure($spec, $value); 2070: if(defined($measured)) { 2071: my $range = _documented_bound_range($spec); 2072: my $example = "$unit $measured"; 2073: my $inside = ((!$min_documented || ($measured >= $spec->{min})) && 2074: (!$max_documented || ($measured <= $spec->{max}))); 2075: if($inside) { 2076: push @inside, { 2077: key => "routine rejected a value inside the documented bound on '$shown' ($range)", 2078: example => $example, 2079: }; 2080: } else { 2081: push @outside, { 2082: key => "routine accepted a value outside the documented bound on '$shown' ($range)", 2083: example => $example, 2084: }; 2085: } 2086: } 2087: } 2088: 2089: # References and undef are type probes, not members or matches. 2090: next unless defined($value) && !ref($value); 2091: my $example = "value '" . _short_value($value) . "'"; 2092: 2093: if(_has_memberof($spec) && _constraint_is_documented($spec, 'memberof')) { 2094: my %member = map { $_ => 1 } @{$spec->{memberof}}; 2095: my $list = 'one of: ' . join(', ', @{$spec->{memberof}}); 2096: if($member{$value}) { 2097: push @inside, { 2098: key => "routine rejected a value inside the documented memberof list on '$shown' ($list)", 2099: example => $example, 2100: }; 2101: } else { 2102: push @outside, { 2103: key => "routine accepted a value outside the documented memberof list on '$shown' ($list)", 2104: example => $example, 2105: }; 2106: } 2107: } 2108: 2109: if(defined($spec->{matches}) && _constraint_is_documented($spec, 'matches')) { 2110: my $re = $spec->{matches}; 2111: $re = qr/$re/ if(ref($re) ne 'Regexp'); 2112: my $matched = eval { $value =~ $re ? 1 : 0 }; 2113: if(defined($matched) && $matched) { 2114: push @inside, { 2115: key => "routine rejected a value matching the documented pattern on '$shown' ($re)", 2116: example => $example, 2117: }; 2118: } elsif(defined($matched)) { 2119: push @outside, { 2120: key => "routine accepted a value that does not match the documented pattern on '$shown' ($re)", 2121: example => $example, 2122: }; 2123: } 2124: } 2125: 2126: if(defined($spec->{nomatch}) && _constraint_is_documented($spec, 'nomatch')) { 2127: my $re = $spec->{nomatch}; 2128: $re = qr/$re/ if(ref($re) ne 'Regexp'); 2129: my $matched = eval { $value =~ $re ? 1 : 0 }; 2130: if(defined($matched) && $matched) { 2131: push @outside, { 2132: key => "routine accepted a value matching the documented nomatch pattern on '$shown' ($re)", 2133: example => $example, 2134: }; 2135: } 2136: } 2137: } 2138: 2139: return (\@inside, \@outside); 2140: } 2141: 2142: sub _record_documented_constraint_contradictions 2143: { 2144: my ($findings) = @_; 2145: 2146: foreach my $finding (@{$findings}) { 2147: my $entry = $_documented_constraint_contradictions{$finding->{key}} ||= { 2148: count => 0, 2149: example => $finding->{example}, 2150: }; 2151: $entry->{count}++; 2152: } 2153: } 2154: 2155: # The replacement for lives_ok in cases whose arguments carry a documented 2156: # constraint. A case that dies on a value the POD says is valid is recorded 2157: # and tolerated instead of failing; a normal death still fails. An 2158: # outside-constraint probe that dies is expected and passes; one that survives 2159: # records a documentation contradiction, reported at the end of the run. 2160: sub _documented_lives_ok(&$) 2161: { 2162: my ($code, $name) = @_; 2163: 2164: local $@; 2165: my $ok = eval { $code->(); 1 }; 2166: my $err = $@; 2167: 2168: if($ok) { 2169: pass($name); 2170: _record_documented_constraint_contradictions($_documented_outside); 2171: return 1; 2172: } 2173: 2174: if($documented_constraint_probe && (!defined($err) || ($err !~ /__TIMEOUT__/))) { 2175: pass($name); 2176: return 1; 2177: } 2178: 2179: if((!defined($err) || ($err !~ /__TIMEOUT__/)) && @{$_documented_inside}) { 2180: _record_documented_constraint_contradictions($_documented_inside); 2181: $documented_tolerated = 1; 2182: pass($name); 2183: return 1; 2184: } 2185: 2186: fail($name); 2187: diag($err) if defined($err) && length($err); 2188: diag(_failure_context($_current_input)); 2189: return 0; 2190: } 2191: 2192: # The DIES counterpart of _documented_lives_ok: a case that should die but 2193: # survives fails and names the seed and input, so the run can be replayed. 2194: sub _dies_with_context(&$;$) 2195: { 2196: my ($code, $name, $allow_undef) = @_; 2197: 2198: local $@; 2199: my $died = !eval { $code->(); 1 }; 2200: my $err = $@; 2201: 2202: if($died) { 2203: pass($name); 2204: return $err; 2205: } 2206: 2207: # A routine whose contract reports invalid input by returning undef is 2208: # not also required to croak, so the caller records the tolerance with 2209: # its own pass rather than this call failing the case here. 2210: return if($allow_undef); 2211: 2212: fail($name); 2213: diag(_failure_context($_current_input)); 2214: return; 2215: } 2216: 2217: sub _report_documented_constraint_contradictions 2218: { 2219: return unless keys %_documented_constraint_contradictions; 2220: 2221: my @keys = sort keys %_documented_constraint_contradictions; 2222: diag('Documented-constraint contradictions found by fuzzing (advisory, seed ' 2223: . (defined($seed) ? $seed : 'none') . '):'); 2224: foreach my $key (@keys) { 2225: my $entry = $_documented_constraint_contradictions{$key}; 2226: my $times = ($entry->{count} == 1) ? '' : " ($entry->{count} times)"; 2227: diag(" $key$times; example: $entry->{example}"); 2228: } 2229: 2230: if($config{'strict_documented'}) { 2231: fail("strict-documented: $_ (seed " . (defined($seed) ? $seed : 'none') . ')') for @keys; 2232: } else { 2233: diag('These contradictions are tolerated; use --strict-documented to fail on them.'); 2234: } 2235: } 2236: 2237: sub _generate_string_cases 2238: { 2239: my ($arg_name, $spec, $mandatory_args) = @_; 2240: 2241: my @cases; 2242: 2243: # A constraint taken from POD sizes valid data; it does not promise that 2244: # the routine rejects what lies outside it. Each constraint is decided on 2245: # its own, so a code-enforced maximum stays strict on a field whose 2246: # minimum is only documented. 2247: my $min_strict = !_constraint_is_documented($spec, 'min'); 2248: my $max_strict = !_constraint_is_documented($spec, 'max'); 2249: my $matches_strict = !_constraint_is_documented($spec, 'matches'); 2250: 2251: return [ _memberof_cases($arg_name, $spec, $mandatory_args) ] if _has_memberof($spec); 2252: 2253: if(defined $spec->{min}) { 2254: my $len = $spec->{min}; 2255: my $re = $spec->{matches}; 2256: $re = qr/$re/ if defined($re) && (ref($re) ne 'Regexp'); 2257: 2258: if(defined($re)) { 2259: my $str = _random_string_matching($re, length => $len); 2260: push @cases, { %{$mandatory_args}, ( $arg_name => $str ) } 2261: if defined($str) && ($str =~ $re); 2262: } else { 2263: push @cases, { %{$mandatory_args}, ( $arg_name => _random_string_with_length($spec, $len) ) }; 2264: if($len > 1) { 2265: my $newline = "he\nlo"; 2266: push @cases, { %{$mandatory_args}, ( $arg_name => $newline, _LINE => __LINE__ ) } 2267: if _string_length_in_bounds($spec, length($newline)); 2268: } 2269: } 2270: 2271: if($min_strict) { 2272: if($len > 1) { 2273: push @cases, { %{$mandatory_args}, ( $arg_name => _random_string_with_length($spec, $len - 1), _STATUS => 'DIES' ) }; 2274: } elsif(($len == 1) && $config{'test_empty'}) { 2275: push @cases, { %{$mandatory_args}, ( $arg_name => '', _STATUS => 'DIES' ) }; 2276: } 2277: } elsif($len > 0) { 2278: my $short = ($len > 1) ? ('x' x ($len - 1)) : ''; 2279: push @cases, _documented_constraint_probe_case( 2280: $mandatory_args, $arg_name, $short, 'documented minimum probe' 2281: ); 2282: } 2283: 2284: if(!$spec->{'_directory'} && !defined($spec->{matches}) && !defined($spec->{nomatch}) && ($len <= 1)) { 2285: foreach my $sample (' ', "\n", " \n ") { 2286: push @cases, { %{$mandatory_args}, ( $arg_name => $sample, _LINE => __LINE__ ) } 2287: if _string_length_in_bounds($spec, length($sample)); 2288: } 2289: } 2290: 2291: if($len <= 0) { 2292: # A documented minimum of zero allows "0"; a hand-written 2293: # bound outside the accepted lengths still expects it to die. 2294: if(_string_length_in_bounds($spec, 1)) { 2295: push @cases, { %{$mandatory_args}, ( $arg_name => '0', _LINE => __LINE__ ) }; 2296: } elsif($min_strict) { 2297: push @cases, { %{$mandatory_args}, ( $arg_name => '0', _STATUS => 'DIES' ) }; 2298: } 2299: 2300: if($config{'test_security'}) { 2301: foreach my $sample ('<script>alert(1)</script>', "'; DROP TABLE foo --") { 2302: push @cases, { %{$mandatory_args}, ( $arg_name => $sample, _LINE => __LINE__ ) } 2303: if _string_length_in_bounds($spec, length($sample)); 2304: } 2305: } 2306: } 2307: } 2308: if(defined $spec->{max}) { 2309: my $len = $spec->{max}; 2310: if(!defined($spec->{min}) || ($spec->{min} != $len)) { 2311: my $re = $spec->{matches}; 2312: $re = qr/$re/ if defined($re) && (ref($re) ne 'Regexp'); 2313: 2314: if(defined($re)) { 2315: foreach my $count ($len - 1, $len) { 2316: next if $count < 0; 2317: next unless _string_length_in_bounds($spec, $count); 2318: my $str = _random_string_matching($re, length => $count); 2319: push @cases, { %{$mandatory_args}, ( $arg_name => $str, _LINE => __LINE__ ) } 2320: if defined($str) && ($str =~ $re); 2321: } 2322: } else { 2323: push @cases, { %{$mandatory_args}, ( $arg_name => _random_string_with_length($spec, $len - 1), _LINE => __LINE__ ) } 2324: if ($len > 0) && _string_length_in_bounds($spec, $len - 1); 2325: push @cases, { %{$mandatory_args}, ( $arg_name => _random_string_with_length($spec, $len), _LINE => __LINE__ ) }; 2326: } 2327: 2328: } 2329: if($max_strict) { 2330: push @cases, { %{$mandatory_args}, ( $arg_name => rand_str($len + 1), _LINE => __LINE__, _STATUS => 'DIES' ) }; 2331: } else { 2332: push @cases, _documented_constraint_probe_case( 2333: $mandatory_args, $arg_name, 'x' x ($len + 1), 'documented maximum probe' 2334: ); 2335: } 2336: } elsif(!$spec->{matches} && !$spec->{nomatch} && !$spec->{'_directory'}) { 2337: my $long = defined($spec->{min}) ? (($spec->{min} + 1) * 1_000) : 65_536; 2338: push @cases, { %{$mandatory_args}, ( $arg_name => rand_str($long), _LINE => __LINE__ ) }; 2339: # A byte string is not text: a wide character is not a value the 2340: # routine was asked to accept, so it gets no BOM probe. 2341: push @cases, { %{$mandatory_args}, ( $arg_name => "\x{FEFF}", _STATUS => 'OK', _LINE => __LINE__, _DESCRIPTION => 'Byte order marker' ) } 2342: unless (($spec->{'semantic'} // '') eq 'bytes'); 2343: } 2344: 2345: # A directory parameter gets no '' case: routines commonly read an empty 2346: # path as "not given" rather than as a directory that does not exist. 2347: # A minimum of zero already produced the empty string above, and a pattern 2348: # is not assumed to match it. 2349: if(!$spec->{'_directory'} && !defined($spec->{min}) && !defined($spec->{matches}) 2350: && (!defined($spec->{max}) || ($spec->{max} > 0))) { 2351: if($config{'test_empty'}) { 2352: # An empty value the code refuses is an error, not a survival case. 2353: push @cases, { %{$mandatory_args}, ( $arg_name => '', 2354: ($spec->{_not_empty} ? (_STATUS => 'DIES') : (_NAME => $arg_name)), 2355: _LINE => __LINE__ ) }; 2356: } 2357: } 2358: 2359: if(!$spec->{'_directory'} && !defined($spec->{min}) && !defined($spec->{max}) 2360: && !defined($spec->{matches}) && !defined($spec->{nomatch})) { 2361: push @cases, 2362: { %{$mandatory_args}, ( $arg_name => "\n" ) }, # new lines are fun 2363: { %{$mandatory_args}, ( $arg_name => ' ' ) }, 2364: { %{$mandatory_args}, ( $arg_name => " \n " ) }; 2365: } 2366: 2367: if(defined $spec->{matches}) { 2368: my $re = $spec->{matches}; 2369: 2370: # --- Positive controls --- 2371: foreach my $val (@candidate_good) { 2372: next unless $val =~ $re; 2373: next unless _string_length_in_bounds($spec, length($val)); 2374: push @cases, { %{$mandatory_args}, ( $arg_name => $val ) }; 2375: last; # one good match is enough 2376: } 2377: 2378: # --- Negative controls --- 2379: foreach my $val (@candidate_bad) { 2380: if(!defined($val)) { 2381: push @cases, { _input => undef, _STATUS => 'DIES', _LINE => __LINE__ } if($config{'test_undef'}); 2382: } elsif($matches_strict && ($val !~ $re)) { 2383: push @cases, { _input => $val, _STATUS => 'DIES', _LINE => __LINE__ }; 2384: } elsif($val !~ $re) { 2385: # Documented pattern: run one non-matching value as an 2386: # advisory probe instead of demanding that it dies. 2387: push @cases, _documented_constraint_probe_case( 2388: $mandatory_args, $arg_name, $val, 'documented pattern probe' 2389: ); 2390: last; 2391: } 2392: } 2393: push @cases, { $arg_name => undef, _STATUS => 'DIES' } if($config{'test_undef'}); 2394: } 2395: if(defined $spec->{nomatch}) { 2396: my $re = $spec->{nomatch}; 2397: 2398: # --- Positive controls --- 2399: foreach my $val (@candidate_good) { 2400: next if $val =~ $re; 2401: next unless _string_length_in_bounds($spec, length($val)); 2402: push @cases, { %{$mandatory_args}, ( $arg_name => $val ) }; 2403: last; # one good match is enough 2404: } 2405: 2406: # --- Negative controls --- 2407: foreach my $val (@candidate_bad) { 2408: next unless defined($val); 2409: next unless $val =~ $re; 2410: if(_constraint_is_documented($spec, 'nomatch')) { 2411: push @cases, _documented_constraint_probe_case( 2412: $mandatory_args, $arg_name, $val, 'documented nomatch probe' 2413: ); 2414: last; 2415: } 2416: push @cases, { $arg_name => $val, _STATUS => 'DIES' }; 2417: } 2418: } 2419: 2420: [% IF module %] 2421: # Send wrong data type - builtins aren't good at checking this, 2422: # and only where the routine's own validator enforces the type. 2423: # A type declared in POD is documentation, not a promise to 2424: # reject a reference, so asserting that it dies invents a 2425: # contract the routine never made. 2426: if(_spec_checks_types($spec)) { 2427: if($config{'test_nuls'}) { 2428: push @cases, 2429: { %{$mandatory_args}, $arg_name => "\0", _STATUS => 'DIES', _LINE => __LINE__ }, 2430: { %{$mandatory_args}, $arg_name => "nul\0", _STATUS => 'DIES', _LINE => __LINE__ }, 2431: { %{$mandatory_args}, $arg_name => "\0nul", _STATUS => 'DIES', _LINE => __LINE__ }; 2432: if(defined($spec->{matches})) { 2433: my $re = $spec->{matches}; 2434: foreach my $val (@candidate_good) { 2435: $val = "$val\0"; 2436: if ($val !~ $re) { 2437: push @cases, { %{$mandatory_args}, ( $arg_name => $val, _STATUS => 'DIES', _DESCRIPTION => 'Nul byte after regex' ) }; 2438: } 2439: $val = "\0$val"; 2440: if ($val !~ $re) { 2441: push @cases, { %{$mandatory_args}, ( $arg_name => $val, _STATUS => 'DIES', _DESCRIPTION => 'Nul byte before regex' ) }; 2442: } 2443: } 2444: } 2445: } 2446: if($config{'test_empty'}) { 2447: push @cases, 2448: { %{$mandatory_args}, ( $arg_name => [], _STATUS => 'DIES', _LINE => __LINE__ ) }, 2449: { %{$mandatory_args}, ( $arg_name => {}, _STATUS => 'DIES', _LINE => __LINE__ ) }; 2450: } 2451: push @cases, 2452: { %{$mandatory_args}, ( $arg_name => \'ref to scalar', _STATUS => 'DIES', _LINE => __LINE__ ) }, 2453: { %{$mandatory_args}, ( $arg_name => sub { die 'boom' }, _STATUS => 'DIES', _LINE => __LINE__ ) }, 2454: { %{$mandatory_args}, ( $arg_name => bless({}, 'Evil::Class'), _STATUS => 'DIES', _LINE => __LINE__ ) }, 2455: # { %{$mandatory_args}, ( $arg_name => [1, 2, 3], _STATUS => 'DIES', _LINE => __LINE__ ) }, # Generates false positives. Why? 2456: { %{$mandatory_args}, ( $arg_name => { a => 1 }, _STATUS => 'DIES', _LINE => __LINE__ ) }; 2457: } 2458: [% END %] 2459: 2460: return \@cases; 2461: } 2462: 2463: # dedup, fuzzing can easily generate repeats 2464: # FIXME: I don't think this catches them all 2465: # FIXME: Handle cases with Class::Simple calls 2466: # FIXME: The JSON encoding fails on various data types that are sent (e.g. scalar refs, objects) so don't bother 2467: sub _dedup_cases 2468: { 2469: my $cases = shift; 2470: 2471: # Do not use JSON::MaybeXS because it will fail on non utf-8 characters 2472: require JSON::PP; 2473: JSON::PP->import(); 2474: 2475: # return inside eval{} returns from the eval block, not from 2476: # _dedup_cases â the deduped result must be captured here, or 2477: # this always falls through to the unduplicated $cases below. 2478: # 2479: # encode_json() does not sort hash keys, so two structurally 2480: # identical case hashrefs can serialize with different key order 2481: # (Perl's per-hash iteration order randomisation) and dodge the 2482: # %seen check below â use ->canonical to make the dump order-stable. 2483: my $rc = eval { 2484: my $json = JSON::PP->new->canonical; 2485: my %seen; 2486: my @rc = grep { 2487: my $dump = $json->encode($_); 2488: !$seen{$dump}++ 2489: } @{$cases}; 2490: 2491: return \@rc; 2492: }; 2493: # Carp::carp(__PACKAGE__, ": disabling deduping: $@"); 2494: 2495: return $@ ? $cases : $rc; 2496: } 2497: 2498: sub generate_tests 2499: { 2500: my $input = $_[0]; 2501: my %mandatory_args = %{$_[1]}; 2502: 2503: my @cases; 2504: 2505: foreach my $field (keys %input) { 2506: my $spec = $input{$field} || {}; 2507: _note_documented_constraint($field, $spec); 2508: foreach my $field(keys %{$spec}) { 2509: next if($field =~ /^_/); # Ignore comments 2510: if(!grep({ $_ eq $field } ('type', 'min', 'max', 'sample_max', 'optional', 'matches', 'can', 'position', 'named', 'memberof', 'semantic', 'isa'))) { 2511: carp "unhandled schema keyword '$field'; skipping"; 2512: next; 2513: } 2514: } 2515: } 2516: 2517: # Build a test of the mandatory args 2518: push @cases, { _input => \%mandatory_args, status => 'OK' } if(keys %mandatory_args); 2519: 2520: for (1..[% iterations_code %]) { 2521: # One by one change each of the mandatory fields 2522: foreach my $field (keys %input) { 2523: my $spec = $input{$field} || {}; 2524: next if $spec->{'memberof'}; # Memberof data is created below 2525: my $type = $spec->{type} || 'string'; 2526: 2527: my %case_input = (%mandatory_args); 2528: # 1) Sometimes pick a field-specific edge-case 2529: if (exists $edge_cases{$field} && rand() < PROB_EDGE_CASE) { 2530: push @cases, { _input => {%case_input}, status => 'OK' } if(keys %case_input); 2531: $case_input{$field} = _pick_from($edge_cases{$field}); 2532: next; 2533: } 2534: 2535: # 2) Sometimes pick a type-level edge-case 2536: if (exists $type_edge_cases{$type} && rand() < 0.3) { 2537: $case_input{$field} = _pick_from($type_edge_cases{$type}); 2538: push @cases, { _input => \%case_input, status => 'OK' } if(keys %case_input); 2539: next; 2540: } 2541: 2542: # 3) Sormal random generation by type 2543: if ($type eq 'string') { 2544: if(my $re = $spec->{matches}) { 2545: if(ref($re) ne 'Regexp') { 2546: $re = qr/$re/; 2547: } 2548: my $generated = _random_string_matching($re, _length_bounds($spec)); 2549: # No string can satisfy this pattern: skip this case rather 2550: # than sending a value that cannot match it. 2551: next unless defined($generated); 2552: $case_input{$field} = $generated; 2553: } elsif(my $semantic = $spec->{'semantic'}) { 2554: if($semantic eq 'bytes') { 2555: # A byte string holds octets, not characters: leaving the 2556: # text filler in place never exercised a high byte. 2557: $case_input{$field} = _random_bytes_for_spec($spec); 2558: } elsif($semantic eq 'email') { 2559: $case_input{$field} = rand_email($spec->{'max'} // $spec->{'min'}); 2560: } else { 2561: diag(__LINE__, ": TODO: handle semantic type '$semantic'"); 2562: } 2563: } elsif(!$spec->{'memberof'}) { 2564: $case_input{$field} = _random_string_for_spec($spec); 2565: if($config{'test_empty'} && !defined($spec->{min}) && (!defined($spec->{max}) || $spec->{max} > 0)) { 2566: push @cases, { _input => {%case_input}, status => 'OK' } if(keys %case_input); 2567: my $non_empty = $case_input{$field}; 2568: $case_input{$field} = ''; 2569: if($spec->{'_not_empty'}) { 2570: # An empty value the code refuses is an error, not a 2571: # survival case. Leave the field non-empty for the 2572: # shared push below, which expects a clean return. 2573: push @cases, { _input => {%case_input}, _STATUS => 'DIES', _LINE => __LINE__ }; 2574: $case_input{$field} = $non_empty; 2575: } 2576: } 2577: } 2578: } elsif ($type eq 'integer') { 2579: $case_input{$field} = _random_number_for_spec($spec, 1); 2580: if(!defined($spec->{min}) && !defined($spec->{max})) { 2581: # Only claim a float when the fraction survives floating point: 2582: # rand_int() can return values large enough for +0.2 to be lost, 2583: # which would demand that an integral value be rejected. 2584: my $float_input = $case_input{$field} + 0.2; 2585: # These are cases for a single named parameter of a hash-style 2586: # API, so they must carry the field name. Passing the value as 2587: # _input would call a multi-parameter routine with one bare 2588: # positional argument, which tests the argument count instead 2589: # of the parameter's type. 2590: push @cases, 2591: # If it's takes an integer, a float should die 2592: (($float_input == int($float_input)) || !_spec_type_is_enforced($spec)) ? () : ({ %case_input, ($field => $float_input), _STATUS => 'DIES', _LINE => __LINE__ }), 2593: # Integers passed as a string 2594: { %case_input, ($field => "007"), _STATUS => 'OK', _LINE => __LINE__ }, 2595: # Not integer literals to Perl's number parser, so they must be 2596: # rejected; they were previously expected to survive, which no 2597: # validator that uses looks_like_number (Params::Validate::Strict 2598: # included) can satisfy 2599: !_spec_type_is_enforced($spec) ? () : ( 2600: { %case_input, ($field => "0x10"), _STATUS => 'DIES', _LINE => __LINE__ }, 2601: { %case_input, ($field => "1_000"), _STATUS => 'DIES', _LINE => __LINE__ }, 2602: ); 2603: } 2604: } elsif ($type eq 'boolean') { 2605: $case_input{$field} = rand_bool(); 2606: } elsif ($type eq 'number') { 2607: $case_input{$field} = _random_number_for_spec($spec, 0); 2608: } elsif ($type eq 'arrayref') { 2609: 2610: if(my $element_type = $input{element_type}) { 2611: if($element_type eq 'integer') { 2612: push @cases, 2613: { %mandatory_args, ($field => '0.3', _STATUS => 'DIES', _LINE => __LINE__, _DESCRIPTION => 'float in list of integers') }, 2614: { %mandatory_args, ($field => 'string in array of ints', _STATUS => 'DIES', _LINE => __LINE__, _DESCRIPTION => 'string in list of integers') }; 2615: } elsif($element_type eq 'boolean') { 2616: push @cases, 2617: { %mandatory_args, ($field => 2, _STATUS => 'DIES', _LINE => __LINE__, _DESCRIPTION => '2 list of booleans') }, 2618: { %mandatory_args, ($field => '0.3', _STATUS => 'DIES', _LINE => __LINE__, _DESCRIPTION => 'float in list of booleans') }, 2619: { %mandatory_args, ($field => 'string in array of bools', _STATUS => 'DIES', _LINE => __LINE__, _DESCRIPTION => 'string in list of booleans') }; 2620: } 2621: } 2622: 2623: push @cases, { %mandatory_args, (field => [ 'fred', undef, 'wilma' ], _LINE => __LINE__, _DESCRIPTION => 'undef element in array') } if($config{test_undef}); 2624: $case_input{$field} = _random_array_for_spec($spec); 2625: } elsif ($type eq 'hashref') { 2626: if($config{test_undef}) { 2627: push @cases, { %mandatory_args, (field => { 'fred' => 'wilma', 'undef' => undef, 'foo' => 'bar' }, _LINE => __LINE__, _DESCRIPTION => 'undef element in hashref') }; 2628: push @cases, { %mandatory_args, (field => { 'fred' => 'wilma', 'nested' => { 'first' => 'one', 'undef' => undef, 'third' => 'three' }, 'foo' => 'bar' }, _LINE => __LINE__, _DESCRIPTION => 'undef element in nested hashref') }; 2629: } 2630: $case_input{$field} = _random_hash_for_spec($spec); 2631: } elsif($config{'test_undef'}) { 2632: $case_input{$field} = undef; 2633: } 2634: 2635: # 4) occasionally drop optional fields 2636: if ($spec->{optional} && rand() < 0.25) { 2637: delete $case_input{$field}; 2638: } 2639: push @cases, { _input => \%case_input, status => 'OK' } if(keys %case_input); 2640: 2641: # A member list is handled where the field's valid values are 2642: # generated (see fuzz_inputs()); every other type gets its 2643: # edge cases from the shared dispatcher. 2644: push @cases, @{_generate_type_cases($field, $type, $spec, \%mandatory_args)}; 2645: 2646: # Add notmemberof tests 2647: if (defined $spec->{notmemberof}) { 2648: my @blacklist = @{$spec->{notmemberof}}; 2649: # Each blacklisted value should die 2650: foreach my $val (@blacklist) { 2651: push @cases, { %mandatory_args, ( $field => $val, _STATUS => 'DIES' ) }; 2652: } 2653: # Non-blacklisted value should pass 2654: push @cases, { %mandatory_args, ( $field => '_not_in_blacklist_' ) }; 2655: } 2656: 2657: # semantic tests 2658: if(defined(my $semantic = $spec->{'semantic'})) { 2659: if($semantic eq 'unix_timestamp') { 2660: push @cases, { %mandatory_args, ( -1, _STATUS => 'DIES' ) }, 2661: { %mandatory_args, ( 0 ) }, 2662: { %mandatory_args, ( 1 ) }, 2663: { %mandatory_args, ( time ) }, 2664: { %mandatory_args, ( 2147483647 ) }, 2665: { %mandatory_args, ( 45.67, _STATUS => 'DIES', _DESCRIPTION => 'UNIX timestamp should not be a float' ) }, 2666: { %mandatory_args, ( 2147483648, _STATUS => 'DIES' ) }; 2667: } else { 2668: diag("semantic type $semantic is not yet supported"); 2669: } 2670: } 2671: if(@relationships) { 2672: diag('Run relationship tests') if($ENV{'TEST_VERBOSE'}); 2673: 2674: foreach my $rel (@relationships) { 2675: my $type = $rel->{type}; 2676: 2677: if($type eq 'mutually_exclusive') { 2678: my ($p1, $p2) = @{ $rel->{params} }; 2679: # Both specified â should die 2680: run_test( 2681: { _STATUS => 'DIES', 2682: _DESCRIPTION => "mutually exclusive: $p1 and $p2 both given" }, 2683: { %mandatory_args, $p1 => 'val1', $p2 => 'val2' }, 2684: \%output, 2685: $positions 2686: ); 2687: # Each alone â should live 2688: run_test( 2689: { _DESCRIPTION => "mutually exclusive: only $p1 given" }, 2690: { %mandatory_args, $p1 => 'val1' }, 2691: \%output, 2692: $positions 2693: ); 2694: run_test( 2695: { _DESCRIPTION => "mutually exclusive: only $p2 given" }, 2696: { %mandatory_args, $p2 => 'val2' }, 2697: \%output, 2698: $positions 2699: ); 2700: 2701: } elsif($type eq 'required_group') { 2702: my @params = @{ $rel->{params} }; 2703: # None specified â should die 2704: my %none = map { $_ => undef } @params; 2705: run_test( 2706: { _STATUS => 'DIES', 2707: _DESCRIPTION => 'required_group: none of (' . join(', ', @params) . ') given' }, 2708: { %mandatory_args, %none }, 2709: \%output, 2710: $positions 2711: ); 2712: # Each alone â should live 2713: foreach my $p (@params) { 2714: run_test( 2715: { _DESCRIPTION => "required_group: only $p given" }, 2716: { %mandatory_args, $p => 'val' }, 2717: \%output, 2718: $positions 2719: ); 2720: } 2721: 2722: } elsif($type eq 'conditional_requirement') { 2723: my ($if_param, $then_param) = ($rel->{if}, $rel->{then_required}); 2724: # if_param set, then_param missing â should die 2725: run_test( 2726: { _STATUS => 'DIES', 2727: _DESCRIPTION => "conditional: $if_param set but $then_param missing" }, 2728: { %mandatory_args, $if_param => 'val', $then_param => undef }, 2729: \%output, 2730: $positions 2731: ); 2732: # Both set â should live 2733: run_test( 2734: { _DESCRIPTION => "conditional: $if_param and $then_param both set" }, 2735: { %mandatory_args, $if_param => 'val', $then_param => 'val' }, 2736: \%output, 2737: $positions 2738: ); 2739: # if_param absent â then_param absence should not matter 2740: run_test( 2741: { _DESCRIPTION => "conditional: $if_param absent so $then_param not required" }, 2742: { %mandatory_args, $then_param => undef }, 2743: \%output, 2744: $positions 2745: ); 2746: 2747: } elsif($type eq 'dependency') { 2748: my ($param, $requires) = ($rel->{param}, $rel->{requires}); 2749: # param set, requires missing â should die 2750: run_test( 2751: { _STATUS => 'DIES', 2752: _DESCRIPTION => "dependency: $param set but $requires missing" }, 2753: { %mandatory_args, $param => 'val', $requires => undef }, 2754: \%output, 2755: $positions 2756: ); 2757: # Both set â should live 2758: run_test( 2759: { _DESCRIPTION => "dependency: $param and $requires both set" }, 2760: { %mandatory_args, $param => 'val', $requires => 'val' }, 2761: \%output, 2762: $positions 2763: ); 2764: 2765: } elsif($type eq 'value_constraint') { 2766: my ($if_param, $then_param, $op, $val) = 2767: ($rel->{if}, $rel->{then}, $rel->{operator}, $rel->{value}); 2768: # if_param set, then_param wrong value â should die 2769: my $wrong_val = ($op eq '==') ? $val + 1 : $val - 1; 2770: run_test( 2771: { _STATUS => 'DIES', 2772: _DESCRIPTION => "value_constraint: $if_param set, $then_param = $wrong_val (wrong)" }, 2773: { %mandatory_args, $if_param => 'val', $then_param => $wrong_val }, 2774: \%output, 2775: $positions 2776: ); 2777: # if_param set, then_param correct value â should live 2778: run_test( 2779: { _DESCRIPTION => "value_constraint: $if_param set, $then_param = $val (correct)" }, 2780: { %mandatory_args, $if_param => 'val', $then_param => $val }, 2781: \%output, 2782: $positions 2783: ); 2784: 2785: } elsif($type eq 'value_conditional') { 2786: my ($if_param, $equals, $then_param) = 2787: ($rel->{if}, $rel->{equals}, $rel->{then_required}); 2788: # if_param equals trigger value, then_param missing â should die 2789: run_test( 2790: { _STATUS => 'DIES', 2791: _DESCRIPTION => "value_conditional: $if_param='$equals', $then_param missing" }, 2792: { %mandatory_args, $if_param => $equals, $then_param => undef }, 2793: \%output, 2794: $positions 2795: ); 2796: # if_param equals trigger value, then_param present â should live 2797: run_test( 2798: { _DESCRIPTION => "value_conditional: $if_param='$equals', $then_param present" }, 2799: { %mandatory_args, $if_param => $equals, $then_param => 'val' }, 2800: \%output, 2801: $positions 2802: ); 2803: # if_param different value â then_param absence should not matter 2804: run_test( 2805: { _DESCRIPTION => "value_conditional: $if_param != '$equals', $then_param not required" }, 2806: { %mandatory_args, $if_param => '__other__', $then_param => undef }, 2807: \%output, 2808: $positions 2809: ); 2810: } 2811: } 2812: } 2813: } 2814: } 2815: 2816: # The loop above skips member lists. fuzz_inputs() adds their cases 2817: # only when every argument is optional or there are several, so a 2818: # routine whose one argument is mandatory got none; dedup drops the 2819: # copies the other paths make. 2820: foreach my $field (keys %input) { 2821: my $spec = $input{$field}; 2822: push @cases, _memberof_cases($field, $spec, \%mandatory_args) if(_has_memberof($spec)); 2823: } 2824: 2825: return \@cases; 2826: } 2827: 2828: sub populate_positions 2829: { 2830: my $input = shift; 2831: 2832: my $rc; 2833: foreach my $arg (keys %{$input}) { 2834: my $spec = $input->{$arg} || {}; 2835: if(((ref($spec)) eq 'HASH') && defined($spec->{'position'})) { 2836: $rc->{$arg} = $spec->{'position'}; 2837: } 2838: } 2839: 2840: return unless $rc; # A named API has no positions 2841: 2842: # A parameter after the positional arguments is a named option, and has 2843: # to say so (named: 1): anything else is a forgotten position, which the 2844: # named call would silently turn into a key whose value is a string. 2845: foreach my $arg (keys %{$input}) { 2846: my $spec = $input->{$arg} || {}; 2847: next if((ref($spec)) eq 'HASH') && (defined($spec->{'position'}) || $spec->{'named'}); 2848: ::diag("$arg is missing a position parameter in its schema (or named: 1)"); 2849: return; 2850: } 2851: 2852: return $rc; 2853: } 2854: 2855: # The harness passes named arguments as a list, which is the shape the POD's 2856: # EXAMPLE sections document: a constructor written as `my ($class, %args) = 2857: # @_` receives a single hashref as one odd argument and reports every 2858: # parameter as missing. The keys the harness uses to drive a case are not 2859: # parameters and are removed here. 2860: sub _fuzz_args 2861: { 2862: my ($input) = @_; 2863: 2864: return $input unless(ref($input) eq 'HASH'); 2865: 2866: my %args = %{$input}; 2867: delete @args{qw(_STATUS _NAME _LINE _PROPERTIES _DESCRIPTION _DOCUMENTED_CONSTRAINTS)}; 2868: 2869: return %args; 2870: } 2871: 2872: sub run_test 2873: { 2874: my($case, $input, $output, $positions) = @_; 2875: 2876: if($ENV{'TEST_VERBOSE'}) { 2877: require Data::Dumper; 2878: diag('input: ', Data::Dumper::Dumper($input)); 2879: } 2880: 2881: $_current_input = (ref($input) eq 'HASH') ? { %{$input} } : $input; 2882: 2883: my $name = delete local $case->{'_NAME'}; 2884: my $properties = delete local $case->{_PROPERTIES}; 2885: my $description = delete local $case->{_DESCRIPTION}; 2886: $documented_constraint_probe = delete local $case->{'_DOCUMENTED_CONSTRAINTS'} ? 1 : 0; 2887: my $result; 2888: my $mess; 2889: my @alist = (); 2890: my $named_options = 0; 2891: 2892: # Snapshots for the documented-bound check must be taken before the 2893: # argument list below deletes values from $input. 2894: $documented_tolerated = 0; 2895: ($_documented_inside, $_documented_outside) = _documented_constraint_findings($input, \%input); 2896: if(defined($input) && !ref($input)) { 2897: # $mess is later used as a sprintf() format string further 2898: # below â a literal '%' in $name/$input must be escaped to 2899: # '%%' first, the same as the aggregate branch does for 2900: # $args, or a value like '%s' / '%n' corrupts the sprintf call. 2901: (my $safe_input = $input) =~ s/%/%%/g; 2902: if($name) { 2903: (my $safe_name = $name) =~ s/%/%%/g; 2904: $mess = "[% function %]($safe_name = '$safe_input') %s"; 2905: } else { 2906: $mess = "[% function %]('$safe_input') %s"; 2907: } 2908: # A scalar _input case is the only argument of a single-parameter 2909: # routine, so it has to be passed as that argument. Without this the 2910: # call below dropped @alist and invoked the routine with no arguments, 2911: # so the case tested nothing while still being reported by name. 2912: $alist[0] = $input if($positions && (scalar(keys %{$positions}) == 1)); 2913: } elsif(defined($input)) { 2914: if($positions) { 2915: # Positional args, then the named options that follow them 2916: # (`sub f { my ($x, %opts) = @_ }` is called f($x, key => value)) 2917: my @named; 2918: foreach my $key (keys %{$input}) { 2919: if(($key ne '_STATUS') && ($key ne '_NAME') && ($key ne '_LINE') && ($key ne '_PROPERTIES') && ($key ne '_DESCRIPTION')) { 2920: if(exists($positions->{$key})) { 2921: $alist[$positions->{$key}] = delete $input->{$key}; 2922: } elsif(ref($input{$key}) eq 'HASH' && $input{$key}{'named'}) { 2923: push @named, $key => delete $input->{$key}; 2924: } else { 2925: diag("Lost position number for $key"); 2926: } 2927: } 2928: } 2929: # Keep all slots up to the last defined position, preserving undef 2930: # holes for optional args that were intentionally omitted at lower 2931: # positions. Stripping ALL undefs (the old grep approach) caused 2932: # a mandatory arg at position N to shift to position N-1 when an 2933: # optional arg at an earlier position was absent â the shifted arg 2934: # was then passed to the wrong parameter and the call died. 2935: my $last_def = -1; 2936: for my $i (0..$#alist) { $last_def = $i if defined $alist[$i] } 2937: @alist = $last_def >= 0 ? @alist[0..$last_def] : (); 2938: push @alist, @named if @named; 2939: $named_options = scalar(@named) ? 1 : 0; 2940: $input = join(', ', @alist); 2941: } else { 2942: # Named args 2943: if(ref($input) ne 'HASH') { 2944: if($case->{'_STATUS'} ne 'DIES') { 2945: die('Input is missing list of arguments (perhaps you only listed types)'); 2946: } 2947: # e.g., we are passing a ref to a scalar to something that only takes a scalar, so it should cause the routine to die 2948: $positions = {}; 2949: $alist[0] = $input; 2950: } else { 2951: foreach my $key (sort keys %{$input}) { 2952: if(($key ne '_STATUS') && ($key ne '_NAME') && ($key ne '_LINE') && ($key ne '_PROPERTIES')) { 2953: if(defined($input->{$key})) { 2954: push @alist, "'$key' => '$input->{$key}'"; 2955: } else { 2956: push @alist, "'$key' => undef"; 2957: } 2958: } 2959: } 2960: } 2961: } 2962: my $args = join(', ', @alist); 2963: $args =~ s/%/%%/g; 2964: $mess = "[% function %]($args) %s"; 2965: } else { 2966: $mess = "[% function %] %s"; 2967: } 2968: 2969: my $status = delete $case->{'_STATUS'} || $output->{'_STATUS'}; 2970: # A routine whose contract reports invalid input by returning undef is 2971: # not also required to croak: a generated case that expects a death 2972: # accepts that documented signal instead. 2973: my $undef_error = (ref($output) eq 'HASH') 2974: && ((($output->{'_error_return'} // '') eq 'undef') 2975: || (ref($output->{'_error_handling'}) eq 'HASH' 2976: && $output->{'_error_handling'}{'undef_on_error'})); 2977: my $line = delete $case->{'_LINE'}; 2978: my %ENV_before = %ENV; 2979: my $cwd_before = Cwd::getcwd(); 2980: my $globals_before = _volatile_globals(); 2981: my %cwd_files_before = map { $_ => 1 } do { opendir(my $dh, '.') or die $!; readdir($dh) }; 2982: my $fds_before = _open_fds(); 2983: 2984: local $SIG{ALRM} = sub { die '__TIMEOUT__' }; 2985: if((!defined($config{timeout})) || ($config{timeout} > 0)) { 2986: alarm($config{'timeout'} // 10); 2987: } 2988: my $old_warn = $SIG{__WARN__}; 2989: my $old_die = $SIG{__DIE__}; 2990: my $ok = eval { 2991: if(defined($status)) { 2992: if($status eq 'DIES') { 2993: my $err; 2994: if($positions) { 2995: [% IF position_code %] 2996: if(defined($name)) { 2997: $err = _dies_with_context { [% position_code %] } sprintf($mess, "dies (position test) - $name (status = DIES)"), $undef_error; 2998: } else { 2999: $err = _dies_with_context { [% position_code %] } sprintf($mess, 'dies (position test, status = DIES)'), $undef_error; 3000: } 3001: [% ELSE %] 3002: ok(0, 'dies: position_code not defined'); 3003: [% END %] 3004: } else { 3005: $err = _dies_with_context { [% call_code %] } sprintf($mess, 'dies'), $undef_error; 3006: ok(!defined($result)); 3007: } 3008: if(!defined($err) && $undef_error) { 3009: pass(sprintf($mess, 'reports invalid input as undef (status = DIES)')); 3010: return; 3011: } 3012: ok(defined($err)); 3013: ok(length($err)); 3014: # autodie and exception classes die with a blessed object that 3015: # stringifies to its message; a bare reference is the only error 3016: # that carries nothing to report. 3017: ok(!ref($err) || Scalar::Util::blessed($err)); 3018: if(defined($name)) { 3019: unlike($err, qr/unitialized/, "$name doesn't involve an uninitialized variable"); 3020: } else { 3021: unlike($err, qr/unitialized/, "Test doesn't involve an uninitialized variable"); 3022: } 3023: return; # There should be no output to validate 3024: } elsif($status eq 'WARNS') { 3025: warnings_exist { [% call_code %] } qr/./, sprintf($mess, 'warns'); 3026: } else { 3027: carp 'unhandled properties in test case; continuing' if(scalar keys %{$properties}); 3028: if($positions) { 3029: [% IF position_code %] 3030: if(defined($name)) { 3031: _documented_lives_ok { [% position_code %] } sprintf($mess, "survives (position test) - $name (status = LIVES)"); 3032: } else { 3033: _documented_lives_ok { [% position_code %] } sprintf($mess, 'survives (position test, status = LIVES)'); 3034: } 3035: [% ELSE %] 3036: ok(0, 'position_code not defined'); 3037: [% END %] 3038: } elsif(defined($description)) { 3039: _documented_lives_ok { [% call_code %] } sprintf($mess, "survives ($description; status = LIVES)"); 3040: } elsif(defined($line)) { 3041: _documented_lives_ok { [% call_code %] } sprintf($mess, "survives (line = $line; status = LIVES)"); 3042: } else { 3043: _documented_lives_ok { [% call_code %] } sprintf($mess, 'survives (status = LIVES)'); 3044: } 3045: if(!$documented_tolerated && $properties->{idempotent}) { 3046: [% determinism_code %] 3047: } 3048: } 3049: } elsif($positions) { 3050: if(defined($name)) { 3051: _documented_lives_ok { [% position_code %] } sprintf($mess, "survives (position test) - $name"); 3052: if(!$documented_tolerated && $properties->{idempotent} && (scalar(@alist) == 1)) { 3053: [% UNLESS module %] 3054: ok([% function %]($alist[0]) eq [% function %]([% function %]($alist[0])), 'function is idempotent'); 3055: ok([% function %]($alist[0]) eq [% function %]($alist[0]), 'function is idempotent'); 3056: [% END %] 3057: } 3058: } else { 3059: carp 'unhandled properties in test case; continuing' if(scalar keys %{$properties}); 3060: _documented_lives_ok { [% position_code %] } sprintf($mess, 'survives (position test)'); 3061: 3062: # An extra argument should be ignored, except for getsetters, so only test if there's more than one arg. 3063: # A named option hash is not positional: a stray bare value 3064: # would become a hash key with an undef value instead. 3065: if(scalar(@alist) > 1 && !$named_options) { 3066: push(@alist, 'foo'); 3067: _documented_lives_ok { [% position_code %] } sprintf($mess, 'survives (position test, with extra argument)'); 3068: } 3069: } 3070: if(!$documented_tolerated && $properties->{idempotent}) { 3071: [% determinism_code %] 3072: } 3073: } else { 3074: # Status not given, assume set to LIVES 3075: carp 'unhandled properties in test case; continuing' if(scalar keys %{$properties}); 3076: if(defined($description)) { 3077: _documented_lives_ok { [% call_code %] } sprintf($mess, "survives ($description)"); 3078: } elsif(defined($line)) { 3079: _documented_lives_ok { [% call_code %] } sprintf($mess, "survives (line = $line)"); 3080: } else { 3081: _documented_lives_ok { [% call_code %] } sprintf($mess, 'survives'); 3082: } 3083: if(!$documented_tolerated && $properties->{idempotent}) { 3084: [% determinism_code %] 3085: } 3086: } 3087: 1; 3088: }; 3089: 3090: alarm 0; 3091: 3092: # Clean up any files the function created in cwd, keeping the list so the 3093: # test can report them. They are removed either way, so a routine that 3094: # writes the file it was asked to write cannot break the cases after it. 3095: my @leftovers = grep { !$cwd_files_before{$_} && -f $_ } do { opendir(my $dh, '.') or die $!; readdir($dh) }; 3096: unlink @leftovers; 3097: 3098: # Check the test did not timeout 3099: diag($@) if($@); 3100: ok((!defined($@)) || (length($@) == 0)); 3101: 3102: # Destructive testing: the call must not leave the caller's globals 3103: # changed. These are the ones a routine can clobber without any error 3104: # showing up: $_ left behind by a while() loop, $/ from slurping a file, 3105: # and $, and $; from an assignment that should have been local. A 3106: # routine that does this silently changes every later call in the test 3107: # file, so the call is not safe to repeat. 3108: is(_globals_changed($globals_before), '', 'caller globals unmodified'); 3109: 3110: # Global side effect detection 3111: is(Cwd::getcwd(), $cwd_before, 'cwd not modified'); 3112: is_deeply(_filtered_env(\%ENV), _filtered_env(\%ENV_before), 'ENV not modified'); 3113: is($SIG{__WARN__}, $old_warn, 'warn handler is not changed'); 3114: is($SIG{__DIE__}, $old_die, 'die handler is not changed'); 3115: 3116: # Destructive testing: what the routine leaves behind. A routine whose job 3117: # is to write a file has to fail here, so a schema can set 'check_files: 0' 3118: # (or 'check_fds: 0' for one that hands a filehandle back to its caller). 3119: if($config{'check_files'} // 1) { 3120: is_deeply(\@leftovers, [], 'no files left in cwd'); 3121: } 3122: my $fds_after = _open_fds(); 3123: if(defined($fds_before) && defined($fds_after) && ($config{'check_fds'} // 1)) { 3124: is(join(', ', _leaked_fds($fds_before, $fds_after)), '', 'no file descriptors leaked'); 3125: } 3126: 3127: delete local $output->{'_STATUS'}; 3128: 3129: # A 'void' output type means the routine returns nothing, so there is no 3130: # value to validate (and no type claim to check it against). 3131: if(!$documented_tolerated && scalar keys %{$output} && defined($output->{type}) && $output->{type} ne 'void') { 3132: if($ENV{'TEST_VERBOSE'}) { 3133: require Data::Dumper; 3134: diag('result: ', Data::Dumper::Dumper($result)); 3135: } 3136: if(($output->{type} // '') eq 'boolean') { 3137: # Perl has no boolean type: a routine documented to return a 3138: # boolean may return 1 or '' (defined() returns ''), and the 3139: # contract is truthiness. What it must not return is a 3140: # reference, which is what a strict 0/1 check was rejecting. 3141: ok(!ref($result), 'output is a boolean'); 3142: } else { 3143: returns_ok($result, $output, 'output validates'); 3144: } 3145: if(((!defined($status)) || ($status eq 'OK')) && defined($result)) { 3146: is( 3147: Unicode::Normalize::NFC($result), 3148: Unicode::Normalize::NFC(Unicode::Normalize::NFD($result)), 3149: 'Unicode normalization stable' 3150: ); 3151: } 3152: } 3153: } 3154: 3155: # What this process's file descriptors point at, as a map of target to the 3156: # number of descriptors open on it, or undef where the platform offers no way 3157: # to ask. A routine that opens files and never closes them costs every later 3158: # call in the same test file a descriptor, which eventually fails an unrelated 3159: # case. 3160: sub _open_fds 3161: { 3162: return unless -d '/proc/self/fd'; 3163: opendir(my $dh, '/proc/self/fd') or return; 3164: my %targets; 3165: foreach my $fd (readdir($dh)) { 3166: next if($fd =~ /^\./); 3167: my $target = readlink("/proc/self/fd/$fd") // 'unknown'; 3168: # socket:[12345] and pipe:[12345] differ on every open 3169: $target =~ s/:\[\d+\]$//; 3170: $targets{$target}++; 3171: } 3172: closedir($dh); 3173: 3174: return \%targets; 3175: } 3176: 3177: # The targets that gained descriptors between two _open_fds() snapshots. 3178: # The first descriptor ever opened on a target is not a leak: an object that 3179: # opens its log file or its connection on first use and keeps it is holding a 3180: # resource, not losing one. A leak opens the same thing again, so a target 3181: # that gains a descriptor a second time is reported, as is anything beyond a 3182: # handful of distinct targets (a new temporary file leaked on every call). 3183: sub _leaked_fds 3184: { 3185: my ($before, $after) = @_; 3186: 3187: my @leaked; 3188: foreach my $target (sort keys %{$after}) { 3189: my $was = $before->{$target} // 0; 3190: next if($after->{$target} <= $was); 3191: if(($was == 0) && ($after->{$target} == 1) && !$fds_held{$target} && (scalar(keys %fds_held) < 8)) { 3192: $fds_held{$target} = 1; 3193: diag("descriptor on $target opened and kept; taken as held, not leaked") if($ENV{'TEST_VERBOSE'}); 3194: next; 3195: } 3196: push @leaked, $target; 3197: } 3198: 3199: return @leaked; 3200: } 3201: 3202: # Snapshot of the globals a routine can clobber without returning anything 3203: # obviously wrong. Values are stringified so a change is visible even when 3204: # the replacement looks interchangeable; undef is kept distinct from ''. 3205: sub _volatile_globals 3206: { 3207: my %state; 3208: $state{'$_'} = defined($_) ? "$_" : undef; 3209: $state{'$/'} = defined($/) ? "$/" : undef; 3210: $state{'$,'} = defined($,) ? "$," : undef; 3211: $state{'$;'} = defined($;) ? "$;" : undef; 3212: $state{'@ARGV'} = join("\x1f", @ARGV); 3213: 3214: return \%state; 3215: } 3216: 3217: # Returns a comma-separated list of the globals whose value changed. 3218: sub _globals_changed 3219: { 3220: my ($before) = @_; 3221: 3222: my $after = _volatile_globals(); 3223: my @changed = sort grep { 3224: my ($was, $is) = ($before->{$_}, $after->{$_}); 3225: defined($was) != defined($is) || (defined($was) && $was ne $is) 3226: } keys %{$before}; 3227: 3228: return join(', ', @changed); 3229: } 3230: 3231: # On Windows $PWD etc are not stable 3232: sub _filtered_env 3233: { 3234: my %env = %{ shift() }; 3235: 3236: # An environment variable set to undef is unset: perl removes it from 3237: # %ENV, so it must not look like a change from a variable that was 3238: # never there. 3239: delete @env{ grep { !defined($env{$_}) } keys %env }; 3240: 3241: if($^O eq 'MSWin32') { 3242: delete @env{ 3243: qw( 3244: PWD 3245: OLDPWD 3246: _ 3247: SHLVL 3248: ) 3249: }; 3250: } 3251: 3252: return \%env; 3253: } 3254: 3255: diag('Run Fuzz Tests') if($ENV{'TEST_VERBOSE'}); 3256: 3257: foreach my $case (@{fuzz_inputs()}) { 3258: # my %params; 3259: # lives_ok { %params = get_params(\%input, %$case) } 'Params::Get input check'; 3260: # lives_ok { validate_strict(\%input, %params) } 'Params::Validate::Strict input check'; 3261: 3262: my $input; 3263: if((ref($case) eq 'HASH') && exists($case->{'_input'})) { 3264: $input = $case->{'_input'}; 3265: } else { 3266: $input = $case; 3267: } 3268: 3269: if(my $line = ($case->{'_LINE'} || $input{'_LINE'})) { 3270: diag("Test case from line number $line") if($ENV{'TEST_VERBOSE'}); 3271: } 3272: if(my $description = ($case->{'_DESCRIPTION'} || $input{'_DESCRIPTION'})) { 3273: diag("Test case $description") if($ENV{'TEST_VERBOSE'}); 3274: } 3275: 3276: { 3277: # local %ENV; 3278: run_test($case, $input, \%output, $positions); 3279: # delete $ENV{'LANG'}; 3280: # delete $ENV{'LC_ALL'}; 3281: # run_test($case, $input, \%output, $positions); 3282: # $ENV{'LANG'} = 'fr_FR.utf8'; 3283: # $ENV{'LC_ALL'} = 'fr_FR.utf8'; 3284: # run_test($case, $input, \%output, $positions); 3285: } 3286: } 3287: 3288: if(scalar(keys %transforms)) { 3289: diag('Run ', scalar(keys %transforms), ' transform tests'); 3290: } 3291: # diag('-' x 60); 3292: 3293: # Build the foundation - which is a basic test with sensible defaults in the field 3294: foreach my $transform (keys %transforms) { 3295: my $transform_input = $transforms{$transform}{'input'}; 3296: 3297: # A transform may describe a different call shape by introducing input 3298: # fields of its own. Use that shape only when it names at least one field 3299: # the top-level input does not; a transform that only adjusts the top-level 3300: # fields keeps the old behaviour. This lets one schema cover 3301: # NameCase([...]) at the top level and NameCase('A', 'B') in a transform, 3302: # while not changing transforms that narrow an existing field. 3303: my $test_input = \%input; 3304: if((ref($transform_input) eq 'HASH') && scalar(keys %{$transform_input})) { 3305: my $introduces_fields = grep { !exists $input{$_} } keys %{$transform_input}; 3306: $test_input = $transform_input if $introduces_fields; 3307: } 3308: 3309: my $foundation = _fill_foundation($test_input); # basic set of data with every field filled in with a sensible default value 3310: 3311: # The foundation should work 3312: my $case = { _NAME => "basic $transform test", _LINE => __LINE__ }; 3313: my $positions = populate_positions($test_input); 3314: run_test($case, { %{$foundation} }, \%output, $positions); 3315: 3316: # Generate transform tests 3317: # Don't generate invalid data, that's all already done, 3318: # this is about verifying the transorms 3319: my @tests; 3320: diag("tests for transform $transform") if($ENV{'TEST_VERBOSE'}); 3321: 3322: # Now modify the foundation with test code 3323: 3324: # BUILD CODE TO CALL FUNCTION 3325: # CALL FUNCTION 3326: # CHECK STATUS CORRECT 3327: # IF STATUS EQ LIVES 3328: # CHECK OUTPUT USING returns_ok 3329: # FI 3330: 3331: foreach my $field (keys %{$test_input}) { 3332: my $spec = $test_input->{$field} || {}; 3333: my $type = $spec->{type} || 'string'; 3334: 3335: # If there's a specific value, test that exact value 3336: if (exists $spec->{value}) { 3337: push @tests, { 3338: %{$foundation}, 3339: $field => $spec->{value}, 3340: _LINE => __LINE__, 3341: _DESCRIPTION => "$transform: $field=$spec->{value}" 3342: }; 3343: next; 3344: } 3345: 3346: # Generate edge cases based on type and contraints 3347: if($type eq 'integer') { 3348: push @tests, @{_generate_integer_cases($field, $spec, $foundation)}; 3349: } elsif(($type eq 'number') || ($type eq 'float')) { 3350: push @tests, @{_generate_float_cases($field, $spec, $foundation)}; 3351: } elsif($type eq 'string') { 3352: push @tests, @{_generate_string_cases($field, $spec, $foundation)}; 3353: } elsif($type eq 'boolean') { 3354: push @tests, @{_generate_boolean_cases($field, $spec, $foundation)}; 3355: } elsif ($type eq 'arrayref') { 3356: if(defined $spec->{min}) { 3357: push @tests, { %{$foundation}, ( $field => _random_array_for_spec($spec, $spec->{min} + 1) ) }; # just inside 3358: push @tests, { %{$foundation}, ( $field => _random_array_for_spec($spec, $spec->{min}) ) }; # border 3359: } else { 3360: push @tests, { %{$foundation}, ( $field => _random_array_for_spec($spec) ) }; 3361: } 3362: if(defined $spec->{max}) { 3363: push @tests, { %{$foundation}, ( $field => _random_array_for_spec($spec, $spec->{max} - 1) ) }; # just inside 3364: if((defined $spec->{min}) && ($spec->{'min'} != $spec->{'max'})) { 3365: push @tests, { %{$foundation}, ( $field => _random_array_for_spec($spec, $spec->{max}) ) }; # border 3366: } 3367: } elsif((defined $spec->{min}) || ($spec->{min} <= 3)) { 3368: push @tests, { %{$foundation}, ( $field => [ 'foo', undef, 'bar' ] ), _DESCRIPTION => 'undef in an arrayref', _LINE => __LINE__ } if($config{test_undef}); 3369: } 3370: } else { 3371: carp "unhandled transform type '$type' for test case; skipping"; 3372: next; 3373: } 3374: } 3375: 3376: if($config{dedup}) { 3377: @tests = @{_dedup_cases(\@tests)}; 3378: } 3379: 3380: { 3381: # local %ENV; 3382: my $transform_output = $transforms{$transform}{'output'} || {}; 3383: my $properties_array_ref = $transforms{$transform}{properties}; 3384: 3385: my $properties = {}; 3386: if($properties_array_ref) { 3387: $properties->{idempotent} = (grep { $_ eq 'idempotent'} @{$properties_array_ref}) ? 1 : 0; 3388: } 3389: 3390: foreach my $test(@tests) { 3391: if(my $line = (delete $test->{'_LINE'} || delete $input{'_LINE'})) { 3392: diag("Test case from line number $line") if($ENV{'TEST_VERBOSE'}); 3393: } 3394: 3395: run_test({ _NAME => $transform, _PROPERTIES => $properties }, $test, $transform_output, $positions); 3396: # delete $ENV{'LANG'}; 3397: # delete $ENV{'LC_ALL'}; 3398: # run_test({ _NAME => $transform }, $test, \%output, $positions); 3399: # $ENV{'LANG'} = 'de_DE.utf8'; 3400: # $ENV{'LC_ALL'} = 'de_DE.utf8'; 3401: # run_test({ _NAME => $transform }, $test, \%output, $positions); 3402: } 3403: } 3404: } 3405: 3406: sub _fill_foundation 3407: { 3408: my ($input) = @_; 3409: $input ||= \%input; 3410: 3411: my $foundation; 3412: 3413: foreach my $field (keys %{$input}) { 3414: my $spec = $input->{$field} || {}; 3415: my $type = $spec->{type} || 'string'; 3416: 3417: if(($type eq 'number') || ($type eq 'float')) { 3418: if(defined $spec->{min}) { 3419: if(defined $spec->{max}) { 3420: $foundation->{$field} = $spec->{max}; # border 3421: } else { 3422: $foundation->{$field} = abs(rand_num()) + $spec->{'min'}; 3423: } 3424: } else { 3425: if(defined $spec->{max}) { 3426: $foundation->{$field} = $spec->{max}; # border 3427: } else { 3428: $foundation->{$field} = -0.01; # No min, so -0.01 should be allowable 3429: } 3430: } 3431: } elsif($type eq 'string') { 3432: $foundation->{$field} = _random_string_for_spec($spec, 'test_value'); 3433: } elsif ($type eq 'integer') { 3434: if (defined $spec->{min}) { 3435: $foundation->{$field} = $spec->{min}; 3436: } elsif (defined $spec->{max}) { 3437: $foundation->{$field} = rand_int() + $spec->{max}; 3438: } else { 3439: $foundation->{$field} = rand_int(); 3440: } 3441: } elsif ($type eq 'boolean') { 3442: $foundation->{$field} = 1; 3443: } elsif ($type eq 'arrayref') { 3444: $foundation->{$field} = _random_array_for_spec($spec, 3445: defined($spec->{'min'}) ? $spec->{'min'} : ($spec->{'max'} // 5)); 3446: } elsif ($type eq 'hashref') { 3447: $foundation->{$field} = _random_hash_for_spec($spec, $spec->{min} // 5); 3448: } else { 3449: carp "unhandled transform type '$type' for foundation; skipping field '$field'"; 3450: next; 3451: } 3452: } 3453: return $foundation; 3454: } 3455: 3456: [% IF use_properties %] 3457: # ============================================================ 3458: # Property-Based Transform Tests (Test::LectroTest) 3459: # ============================================================ 3460: 3461: use Test::LectroTest::Compat; 3462: use Test::LectroTest::Generator qw(:common); 3463: use Scalar::Util qw(looks_like_number); 3464: 3465: diag('Run property-based transform tests') if($ENV{'TEST_VERBOSE'}); 3466: 3467: [% transform_properties_code %] 3468: 3469: [% END %] 3470: 3471: [% corpus_code %] 3472: 3473: _report_documented_constraint_contradictions(); 3474: 3475: done_testing(); 3476: 3477: 1; 3478: 3479: package MyTestPackage; 3480: 3481: sub new { return bless {}, 'MyTestPackage' } 3482: 3483: 1; 3484: __END__