lib/App/Test/Generator.pm

filter: Statementstmt 89.3% 883 / 988 Branchbran 79.9% 499 / 624 Conditioncond 69.5% 254 / 365 MC/DCmcdc 52.3% 112 / 214 Subroutinesub 100% 74 / 74 Podpod 75.0% 6 / 8 totaltotal 80.4% 1828 / 2273 CC 481 SCAR 57.4
CC
481
Cov
83%
generate
860.7
_schema_to_lectrotest_generator
41.1
_detect_transform_properties
36.9
CRAP 311.4
↑ Summary bin/fuzz-harness-generator »
1 package App::Test::Generator;
2  
3 # FIXME: SchemaExtractor does not strip comments before scanning for a sub's parameters,
4 # so a comment that quotes a parameter-declaration idiom is read as a real declaration
5 # and fails --strict-pod=fatal (seen in generate(); the comment there was reworded)
6 # FIXME: Schema extraction is not deterministic: SchemaExtractor::_build_schema_from_meta
7 # extracts its output type as hashref on some runs and string on others (hash order)
8 # TODO: Test validator from Params::Validate::Strict 0.16
9 # TODO: positional args - when config_undef is set, see what happens when not all args are given
10 # TODO: The Dup and TER1/2/3 columns should be moved from the Mutation table
11 # to a new table called Metrics. Add Halstead and McCabes metrics to
12 # this new Metrics table. Include links to the definitions of TER1/2/3,
13 # Halstead and McCabes metrics, perhaps from Wikipedia
14 # TODO: Template.pm public API (27/28 subs) lacks POD documentation; add =head2 sections
15 # with =head4 input / =head4 output formal specs for each public sub
16 # TODO: SchemaExtractor does not traverse @ISA for inherited constructors; if a module's
17 # constructor is defined in a parent class, extract_all() may miss representative
18 # constructor args and emit new:~ (unenrichable) instead of inferring from the base class
19 # TODO: Magic-number probability constants in Template.pm (e.g. rand() < 0.3) should be
20 # Readonly module-level constants with ALL_CAPS_SNAKE names for maintainability
21 # TODO: Difficulty constants are duplicated between bin/test-generator-mutate and Mutator.pm;
22 # consolidate into a single source of truth (e.g. Readonly constants in Mutator.pm,
23 # imported by the CLI)
24 # TODO: validate_email in Sample::Module needs a matches: regex in its formal input spec
25 # so fuzz-harness-generator can generate structurally valid email inputs and the harness
26 # can be removed from %no_fuzz in t/self-fuzz.t
27  
28 226 ▶use 5.036;
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 226 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 226 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 226 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
33  
34 226 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
35 226 ▶use open qw(:std :encoding(UTF-8));
Subroutine BEGIN: called CC=1 SCAR=0.0
36  
37 226 ▶use App::Test::Generator::Provenance ();
Subroutine BEGIN: called CC=1 SCAR=0.0
38 226 ▶use App::Test::Generator::Template;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 226 ▶use Carp qw(carp croak confess);
Subroutine BEGIN: called CC=1 SCAR=0.0
40 226 ▶use Config::Abstraction 0.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 226 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 226 ▶use Data::Section::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 226 ▶use File::Basename qw(basename);
Subroutine BEGIN: called CC=1 SCAR=0.0
44 226 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 226 ▶use Module::Load::Conditional qw(check_install can_load);
Subroutine BEGIN: called CC=1 SCAR=0.0
46 226 ▶use Params::Get;
Subroutine BEGIN: called CC=1 SCAR=0.0
47 226 ▶use Params::Validate::Strict 0.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
48 226 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
49 226 ▶use Readonly::Values::Boolean;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 226 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
51 226 ▶use re 'regexp_pattern';
Subroutine BEGIN: called CC=1 SCAR=0.0
52 226 ▶use Template;
Subroutine BEGIN: called CC=1 SCAR=0.0
53 226 ▶use YAML::XS qw(LoadFile);
Subroutine BEGIN: called CC=1 SCAR=0.0
54  
55 226 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
56  
57 226 our @EXPORT_OK = qw(generate);
58  
59 226 our $VERSION = '0.50';
60  
61 226 Readonly my $DEFAULT_ITERATIONS => 30;
62 226 Readonly my $DEFAULT_PROPERTY_TRIALS => 1000;
63  
64 # Hash for O(1) lookup rather than a list needing grep O(n)
65 226 Readonly my %VALID_CONFIG_KEYS => map { $_ => 1 } qw(
66 test_nuls test_undef test_empty test_non_ascii
67 dedup properties close_stdin test_security timeout regex_timeout
68 check_files check_fds check_accessors
69 );
70  
71 # --------------------------------------------------
72 # Delimiter pairs tried in order when wrapping a
73 # string with q{} — bracket forms are preferred as
74 # they are most readable in generated test code
75 # --------------------------------------------------
76 226 Readonly my @Q_BRACKET_PAIRS => (
77 ['{', '}'],
78 ['(', ')'],
79 ['[', ']'],
80 ['<', '>'],
81 );
82  
83 # --------------------------------------------------
84 # Single-character delimiters tried when no bracket
85 # pair is usable — each is tried in order and the
86 # first one not present in the string is used.
87 # The # character is last since it starts comments
88 # in many contexts and is least readable
89 # --------------------------------------------------
90 226 Readonly my @Q_SINGLE_DELIMITERS => (
91 '~', '!', '%', '^', '=', '+', ':', ',', ';', '|', '/', '#'
92 );
93  
94 # --------------------------------------------------
95 # Sentinel returned by index() when the search
96 # string is not found — used to make the >= 0
97 # boundary check self-documenting and to prevent
98 # NumericBoundary mutants from surviving
99 # --------------------------------------------------
100 226 Readonly my $INDEX_NOT_FOUND => -1;
101  
102 # --------------------------------------------------
103 # Readonly constants for schema validation
104 # --------------------------------------------------
105 226 Readonly my $CONFIG_PROPERTIES_KEY => 'properties';
106 226 Readonly my $LEGACY_PERL_KEY_1 => '$module';
107 226 Readonly my $LEGACY_PERL_KEY_2 => 'our $module';
108 226 Readonly my $SOURCE_KEY => '_source';
109  
110 # --------------------------------------------------
111 # Readonly constants for render_hash key detection
112 # --------------------------------------------------
113 226 Readonly my $KEY_MATCHES => 'matches';
114 226 Readonly my $KEY_NOMATCH => 'nomatch';
115  
116 # --------------------------------------------------
117 # Reserved module name indicating a Perl builtin
118 # function rather than a CPAN or user module
119 # --------------------------------------------------
120 226 Readonly my $MODULE_BUILTIN => 'builtin';
121  
122 # --------------------------------------------------
123 # Regex pattern matched against transform names to
124 # detect the positive/non-negative idempotence
125 # heuristic in _detect_transform_properties
126 # --------------------------------------------------
127 226 Readonly my $TRANSFORM_POSITIVE_PATTERN => 'positive';
128  
129 # --------------------------------------------------
130 # Default type assumed for schema fields that declare
131 # no explicit type — used in generator selection and
132 # dominant-type detection
133 # --------------------------------------------------
134 226 Readonly my $DEFAULT_FIELD_TYPE => 'string';
135  
136 # --------------------------------------------------
137 # Default range used by the LectroTest float/integer
138 # generators when no min or max constraint is given.
139 # Chosen to provide a useful spread without producing
140 # values so large they overflow downstream arithmetic.
141 # --------------------------------------------------
142 226 Readonly my $DEFAULT_GENERATOR_RANGE => 1000;
143  
144 # --------------------------------------------------
145 # Default upper bound on the number of elements in
146 # generated arrayrefs and hashrefs when no max is
147 # declared in the schema.
148 # --------------------------------------------------
149 226 Readonly my $DEFAULT_MAX_COLLECTION_SIZE => 10;
150  
151 # --------------------------------------------------
152 # Default upper bound on generated string length
153 # when no max is declared in the schema.
154 # --------------------------------------------------
155 226 Readonly my $DEFAULT_MAX_STRING_LEN => 100;
156  
157 # --------------------------------------------------
158 # Sentinel for the zero boundary used in float
159 # generator selection — comparing min/max against
160 # this constant makes the boundary intent explicit
161 # and prevents NumericBoundary mutants from surviving.
162 # --------------------------------------------------
163 226 Readonly my $ZERO_BOUNDARY => 0;
164  
165 # --------------------------------------------------
166 # Environment variable names used to control verbose
167 # output and optional load validation in
168 # _validate_module. Centralised here so they are
169 # easy to find and consistent across the codebase.
170 # --------------------------------------------------
171 226 Readonly my $ENV_TEST_VERBOSE => 'TEST_VERBOSE';
172 226 Readonly my $ENV_GENERATOR_VERBOSE => 'GENERATOR_VERBOSE';
173 226 Readonly my $ENV_VALIDATE_LOAD => 'GENERATOR_VALIDATE_LOAD';
174  
175 =encoding utf8
176  
177 =head1 NAME
178  
179 App::Test::Generator - Fuzz Testing, Mutation Testing, LCSAJ Metrics and Test Dashboard for Perl modules
180  
181 =head1 VERSION
182  
183 Version 0.50
184  
185 =head1 SYNOPSIS
186  
187 C<App::Test::Generator> is a suite to help the testing of CPAN modules.
188 It consists of 6 subsystems:
189  
190 =over 4
191  
192 =item * Fuzz Tester
193  
194 =item * Mutation Testing
195  
196 =item * LCSAJ Metrics
197  
198 =item * Test Dashboard
199  
200 =item * Benchmark Generation
201  
202 =item * Workflow Deployment
203  
204 =back
205  
206 From the command line:
207  
208 # Takes the formal definition of a routine, creates tests against that routine, and runs the test
209 fuzz-harness-generator -r t/conf/abs.yml
210  
211 # Attempt to create a formal definition from a routine package, then run tests against that formal definition
212 # This is the Holy Grail of test generation, a set of tests is automatically created directly from the source code,
213 extract-schemas lib/App/Test/Generator/Sample/Module.pm && fuzz-harness-generator -r schemas/greet.yml
214  
215 # Fuzz a module and keep the corpus bounded: trim to the minimum subset that still covers every branch
216 extract-schemas --fuzz --minimize-corpus lib/My/Module.pm
217  
218 # Generate round-trip tests that run every code example in a module's POD and verify the results
219 pod-example-tester lib/My/Module.pm --output t/pod_examples.t
220  
221 # Generate a Benchmark::cmpthese script from a schema; each transform becomes one timed variant
222 benchmark-generator -i schemas/abs.yml -o benchmarks/abs.pl
223  
224 # Copy dashboard.yml and mutate.yml into a module repository's .github/workflows/ directory
225 deploy-workflows --target /path/to/my-module
226  
227 From Perl:
228  
229 use App::Test::Generator qw(generate);
230 use App::Test::Generator::SchemaExtractor;
231  
232 # Generate to STDOUT
233 App::Test::Generator->generate("t/conf/abs.yml");
234  
235 # Generate directly to a file
236 App::Test::Generator->generate('t/conf/abs.yml', 't/add_fuzz.t');
237  
238 # Holy grail mode - read a Perl file, generate tests, and run them
239 # This is a long way away yet, but see t/schema_input.t for a proof of concept
240 my $extractor = App::Test::Generator::SchemaExtractor->new(
241 input_file => 'lib/App/Test/Generator/Template.pm',
242 output_dir => '/tmp',
243 );
244 my $schemas = $extractor->extract_all();
245 use File::Temp qw(tempfile);
246 foreach my $schema(keys %{$schemas}) {
247 my ($fh, $tempfile) = tempfile(SUFFIX => '.t', UNLINK => 1);
248 close $fh;
249 App::Test::Generator->generate(
250 schema => $schemas->{$schema},
251 output_file => $tempfile,
252 );
253 system($^X, '-Ilib', $tempfile);
254 }
255  
256 =head1 OVERVIEW
257  
258 This module takes a formal input/output specification for a routine or
259 method and automatically generates test cases. In effect, it allows you
260 to easily add comprehensive black-box tests in addition to the more
261 common white-box tests that are typically written for CPAN modules and other
262 subroutines.
263  
264 The generated tests combine:
265  
266 =over 4
267  
268 =item * Random fuzzing based on input types
269  
270 =item * Deterministic edge cases for min/max constraints
271  
272 =item * Static corpus tests defined in Perl or YAML
273  
274 =back
275  
276 This approach strengthens your test suite by probing both expected and
277 unexpected inputs, helping you to catch boundary errors, invalid data
278 handling, and regressions without manually writing every case.
279  
280 =head1 TOOLS
281  
282 The distribution ships the following command-line tools:
283  
284 =over 4
285  
286 =item * L<benchmark-generator> - generate a self-contained L<Benchmark> C<cmpthese> script from a YAML schema. Each transform in the schema becomes one named variant; representative input values are derived from each parameter's type and range constraints.
287  
288 =item * L<deploy-workflows> - copy C<dashboard.yml> and C<mutate.yml> into the target repository's C<.github/workflows/> directory. Both files are embedded verbatim in the script, so no ATG source tree is needed after installation. Supports C<--target>, C<--force>, and C<--dry-run>.
289  
290 To add a test dashboard to your CPAN module: copy these scripts into your C<.github/workflows> directory,
291 then commit the changes to GitHub and enable the page through C<Settings-Pages-branch = gh_pages>:
292  
293 =over 4
294  
295 =item * L<https://github.com/nigelhorne/App-Test-Generator/blob/master/.github/workflows/dashboard.yml>
296  
297 =item * L<https://github.com/nigelhorne/App-Test-Generator/blob/master/.github/workflows/mutate.yml>
298  
299 =back
300  
301 =item * L<extract-schemas> - heuristically extract YAML parameter schemas from a C<.pm> file, with optional coverage-guided fuzzing (C<--fuzz>) and corpus minimization (C<--minimize-corpus>).
302  
303 =item * L<fuzz-harness-generator> - generate a C<Test::Most> fuzzing harness from a YAML schema.
304  
305 =item * L<pod-example-tester> - generate a C<Test::Most> round-trip test file from a module's POD code examples. Annotated examples (C<# returns value> / C<< # => value >>) get C<is()> assertions; unannotated verbatim blocks are wrapped in C<eval{}> and checked for no exception.
306  
307 =item * L<test-generator-mutate> - run mutation testing against a module's test suite.
308  
309 =item * L<test-generator-index> - generate the HTML test-quality dashboard, combining Devel::Cover statement/branch data, LCSAJ path coverage, mutation results, and CPAN Testers failure analysis. For each CPAN Testers FAIL report, also writes a self-contained shell script (C<cover_html/reproduce/reproduce-GUID.sh>) that pins every installed module at its exact failing version, enabling local reproduction of the failure environment.
310  
311 =back
312  
313 =head1 DESCRIPTION
314  
315 This module implements the logic behind L<fuzz-harness-generator>.
316 It parses configuration files (fuzz and/or corpus YAML), and
317 produces a ready-to-run F<.t> test script to run through C<prove>.
318  
319 It reads configuration files in any format,
320 and optional YAML corpus files.
321 All of the examples in this documentation are in C<YAML> format,
322 other formats may not work as they aren't so heavily tested.
323 It then generates a L<Test::Most>-based fuzzing harness combining:
324  
325 =over 4
326  
327 =item * Randomized fuzzing of inputs (with edge cases)
328  
329 =item * Optional static corpus tests from Perl C<%cases> or YAML file (C<yaml_cases> key)
330  
331 =item * Functional or OO mode (via C<$new>)
332  
333 =item * Reproducible runs via C<$seed> and configurable iterations via C<$iterations>
334  
335 =back
336  
337 =head1 MUTATION-GUIDED TEST GENERATION
338  
339 C<App::Test::Generator> includes a pipeline that automatically closes the
340 feedback loop between mutation testing, schema extraction, and fuzz
341 testing. The goal is that surviving mutants drive the creation of new
342 tests that kill them on the next run, without manual intervention.
343  
344 =head2 The Pipeline
345  
346 mutation survivor
347 |
348 v
349 SchemaExtractor extracts the schema for the enclosing sub
350 |
351 v
352 Schema augmented with boundary values from the mutant
353 |
354 v
355 Augmented schema written to t/conf/
356 |
357 v
358 t/fuzz.t picks up the new schema and runs fuzz tests
359 |
360 v
361 Mutation killed on next run
362  
363 =head2 How to Use It
364  
365 The pipeline is driven by three flags passed to
366 C<bin/test-generator-index>, which is invoked automatically by
367 C<bin/generate-test-dashboard> on each CI push.
368  
369 =head3 Step 1: Generate TODO stubs for all survivors
370  
371 bin/test-generator-index --generate_mutant_tests=t
372  
373 Produces C<t/mutant_YYYYMMDD_HHMMSS.t> containing:
374  
375 =over 4
376  
377 =item * TODO stubs for HIGH and MEDIUM difficulty survivors, with
378 boundary value suggestions, environment variable hints, and the
379 enclosing subroutine name for navigation context.
380  
381 =item * Comment-only hints for LOW difficulty survivors.
382  
383 =back
384  
385 Multiple mutations on the same source line are deduplicated into one
386 stub. One good test kills all variants on that line.
387  
388 =head3 Step 2: Generate runnable schemas for NUM_BOUNDARY survivors
389  
390 bin/test-generator-index \
391 --generate_mutant_tests=t \
392 --generate_test=mutant
393  
394 For each NUM_BOUNDARY survivor, calls
395 L<App::Test::Generator::SchemaExtractor> to extract the schema for
396 the enclosing subroutine. If the confidence level is sufficient, the
397 schema is augmented with the boundary value from the mutant (plus one
398 value either side) and written to C<t/conf/> as a runnable YAML file.
399 L<t/fuzz.t> picks it up automatically on the next test run.
400  
401 Falls back to a TODO stub if:
402  
403 =over 4
404  
405 =item * SchemaExtractor cannot parse the file
406  
407 =item * The enclosing sub cannot be determined
408  
409 =item * The extracted schema confidence is C<very_low> or C<none>
410  
411 =back
412  
413 =head3 Step 3: Augment existing schemas with survivor boundary values
414  
415 bin/test-generator-index \
416 --generate_mutant_tests=t \
417 --generate_test=mutant \
418 --generate_fuzz
419  
420 Scans C<t/conf/> for existing YAML schema files (hand-written or
421 previously generated) and writes augmented copies with boundary values
422 from surviving NUM_BOUNDARY mutants merged in. The original schema is
423 never modified. Augmented copies are written as
424 C<t/conf/mutant_fuzz_YYYYMMDD_HHMMSS_FUNCTION.yml> and picked up
425 automatically by C<t/fuzz.t>.
426  
427 Schemas whose filename already starts with C<mutant_fuzz_> are skipped
428 to prevent cascading augmentation. Schemas with no matching survivors
429 are skipped, with a note if C<--verbose> is active.
430  
431 =head3 Putting It All Together
432  
433 The recommended invocation in C<bin/generate-test-dashboard>
434 Step 7 runs all three stages together:
435  
436 bin/test-generator-index \
437 --generate_mutant_tests=t \
438 --generate_test=mutant \
439 --generate_fuzz
440  
441 The GitHub Actions workflow in C<.github/workflows/dashboard.yml>
442 then commits any new C<t/mutant_*.t> and C<t/conf/mutant_*.yml> files
443 to the repository so they accumulate over time as the test suite
444 improves.
445  
446 =head2 Confidence Levels
447  
448 L<App::Test::Generator::SchemaExtractor> assigns a confidence level
449 to each extracted schema:
450  
451 =over 4
452  
453 =item * C<high> / C<medium> / C<low> - Schema is used for test generation
454  
455 =item * C<very_low> / C<none> - Falls back to TODO stub
456  
457 =back
458  
459 Confidence is based on how much type and constraint information could
460 be inferred from the source code and its POD documentation. Methods
461 with explicit parameter validation (L<Params::Validate::Strict>,
462 L<Params::Get>) or comprehensive POD will produce higher-confidence
463 schemas.
464  
465 =head2 Files Produced
466  
467 =over 4
468  
469 =item * C<t/mutant_YYYYMMDD_HHMMSS.t>
470  
471 TODO stub file for all survivors. Committed to the repository by the
472 GitHub Actions workflow.
473  
474 =item * C<t/conf/mutant_MODNAME_FUNCTION_YYYYMMDD_HHMMSS.yml>
475  
476 Runnable YAML schema for a NUM_BOUNDARY survivor where SchemaExtractor
477 confidence was sufficient. Picked up by C<t/fuzz.t>.
478  
479 =item * C<t/conf/mutant_fuzz_YYYYMMDD_HHMMSS_FUNCTION.yml>
480  
481 Augmented copy of an existing schema with survivor boundary values
482 merged in. Picked up by C<t/fuzz.t>.
483  
484 =back
485  
486 =head2 See Also
487  
488 =over 4
489  
490 =item * L<App::Test::Generator::SchemaExtractor> - Schema extraction
491 from Perl source code
492  
493 =item * L<bin/test-generator-index> - Dashboard generator and
494 pipeline driver
495  
496 =item * L<bin/generate-test-dashboard> - Full pipeline runner
497  
498 =back
499  
500 =head1 CONFIGURATION
501  
502 The configuration file,
503 for each set of tests to be produced,
504 is a file containing a schema that can be read by L<Config::Abstraction>.
505  
506 =head2 SCHEMA
507  
508 The schema is split into several sections.
509  
510 =head3 C<%input> - input params with keys => type/optional specs
511  
512 When using named parameters
513  
514 input:
515 name:
516 type: string
517 optional: false
518 age:
519 type: integer
520 optional: true
521  
522 Supported basic types used by the fuzzer: C<string>, C<integer>, C<float>, C<number>, C<boolean>, C<arrayref>, C<hashref>.
523 See also L<Params::Validate::Strict>.
524 You can add more custom types using properties.
525  
526 A nested C<schema> describes the elements of an C<arrayref> or the values of a
527 C<hashref>. Element schemas are full specs, so they carry their own
528 constraints and can nest again:
529  
530 input:
531 words:
532 type: arrayref
533 min: 1
534 max: 3
535 schema:
536 type: string
537 min: 3
538 max: 10
539 scores:
540 type: hashref
541 schema:
542 type: integer
543 min: 0
544 max: 100
545 record:
546 type: hashref
547 schema:
548 name:
549 type: string
550 min: 2
551 max: 20
552 age: integer
553 grid:
554 type: arrayref
555 schema:
556 type: arrayref
557 min: 1
558 max: 2
559 schema:
560 type: integer
561 min: 0
562 max: 9
563 things:
564 type: arrayref
565 schema:
566 type: object
567 isa: My::Thing # needs a no-argument constructor
568 # or: can: label # mocked with Class::Simple
569  
570 A hashref C<schema> without a C<type> is a map of fixed key names to element
571 schemas, so generated valid data uses those keys instead of random filler.
572 Generated element values satisfy the element's own constraints.
573  
574 For routines with one unnamed parameter
575  
576 input:
577 type: string
578  
579 For routines with more than one named parameter, use the C<position> keyword.
580  
581 module: Math::Simple::MinMax
582 fuction: max
583  
584 input:
585 left:
586 type: number
587 position: 0
588 right:
589 type: number
590 position: 1
591  
592 output:
593 type: number
594  
595 The keyword C<undef> is used to indicate that the C<function> takes no arguments.
596  
597 =head3 C<%output> - output param types for L<Return::Set> checking
598  
599 output:
600 type: string
601  
602 If the output hash contains the key _STATUS, and if that key is set to DIES,
603 the routine should die with the given arguments; otherwise, it should live.
604 If it's set to WARNS,
605 the routine should warn with the given arguments.
606 The output can be set to the string 'undef' if the routine should return the undefined value:
607  
608 ---
609 module: Scalar::Util
610 function: blessed
611  
612 input:
613 type: string
614  
615 output: undef
616  
617 The keyword C<undef> is used to indicate that the C<function> returns nothing.
618  
619 For methods that return a list (rather than a reference), use C<type: array>.
620 The generated test captures the result in list context and validates it as an
621 arrayref, which requires L<Test::Returns> 0.03 or later:
622  
623 output:
624 type: array
625  
626 =head3 C<%config> - optional hash of configuration.
627  
628 The current supported variables are
629  
630 =over 4
631  
632 =item * C<close_stdin>
633  
634 Tests should not attempt to read from STDIN (default: 1).
635 This is ignored on Windows, when never closes STDIN.
636  
637 =item * C<test_nuls>, inject NUL bytes into strings (default: 1)
638  
639 With this test enabled, the function is expected to die when a NUL byte is passed in.
640  
641 =item * C<test_undef>, test with undefined value (default: 1)
642  
643 =item * C<test_empty>, test with empty strings (default: 1)
644  
645 =item * C<test_non_ascii>, test with strings that contain non ascii characters (default: 1)
646  
647 =item * C<timeout>, ensure tests don't hang (default: 10)
648  
649 =item * C<regex_timeout>, seconds allowed for generating one string that
650 matches a regex pattern (default: 5)
651  
652 A pattern the generator cannot satisfy, or one that makes it search for too
653 long, falls back to a fixed matching value; when none exists the pattern's
654 cases are skipped and reported once instead of failing the run. Matching
655 strings are generated from the seeded RNG, so a schema's C<seed> makes them
656 reproducible.
657  
658 Setting this to 0 disables timeout testing.
659  
660 =item * C<check_files>, assert the routine leaves no files in the working
661 directory (default: 1)
662  
663 Every call is checked for files it created. They are removed afterwards
664 whatever the setting, so a routine that writes a file cannot break the cases
665 that follow it; set this to 0 for a routine whose purpose is to write one.
666 C<extract-schemas> sets it to 0 when the routine's POD documents creating or
667 writing a file in its SIDE EFFECTS section.
668  
669 =item * C<check_fds>, assert the routine leaks no file descriptors
670 (default: 1)
671  
672 Only checked where F</proc/self/fd> exists. Set this to 0 for a routine that
673 returns a filehandle to its caller, which still holds a descriptor.
674  
675 The first descriptor a call opens on a given file (or its first socket or
676 pipe) is taken as a resource held on purpose, such as a log file an object
677 opens on first use, and is not reported. A later call that opens the same
678 target again is.
679  
680 =item * C<check_accessors>, assert an accessor leaves the object it was called
681 on alone (default: 1)
682  
683 The object is deep copied before each call and the state it was handed
684 compared afterwards. A getter that overwrites or deletes that state fails
685 "getter leaves its object unmodified"; a getset that changes anything but the
686 property it is named for fails "setter changes nothing but its property".
687 Values the call fills in where it was handed undef, and keys it adds, are
688 ignored, so a getter that memoises what it computed is not reported. Set this
689 to 0 for an accessor whose purpose is to change state, such as an iterator's
690 C<next()>; a getter that declares no input is called with no arguments either
691 way.
692  
693 =item * C<dedup>, fuzzing can create duplicate tests, go some way to remove duplicates (default: 1)
694  
695 =item * C<properties>, enable L<Test::LectroTest> Property tests (default: 0)
696  
697 *item * C<test_security>, send some security string based tests (default: 0)
698  
699 =back
700  
701 All values default to C<true>.
702  
703 =head3 C<%accessor> - this is an accessor routine
704  
705 accessor:
706 property: ua
707 type: getset
708  
709 Has two mandatory elements:
710  
711 =over 4
712  
713 =item * C<property>
714  
715 The name of the property in the object that the routine controls.
716  
717 =item * C<type>
718  
719 One of C<getter>, C<setter>, C<getset>.
720  
721 =back
722  
723 =head3 C<%transforms> - list of transformations from input sets to output sets
724  
725 Transforms allow you to define how input data should be transformed into output data.
726 This is useful for testing functions that convert between formats, normalize data,
727 or apply business logic transformations on a set of data to different set of data.
728 It takes a list of subsets of the input and output definitions,
729 and verifies that data from each input subset is correctly transformed into data from the matching output subset.
730  
731 A transform whose input names at least one field that the top-level input does not
732 introduces its own call shape: its test cases are built from those fields rather
733 than the top-level ones. This lets one schema cover two calls, such as an
734 arrayref argument and a list of scalar arguments. A transform whose input only
735 names fields that are already at the top level adjusts the top-level input and
736 keeps the usual behaviour.
737  
738 =head4 Transform Validation Rules
739  
740 For each transform:
741  
742 =over 4
743  
744 =item 1. Generate test cases using the transform's input schema
745  
746 =item 2. Call the function with those inputs
747  
748 =item 3. Validate the output matches the transform's output schema
749  
750 =item 4. If output has a specific 'value', check exact match
751  
752 =item 5. If output has constraints (min/max), validate within bounds
753  
754 =back
755  
756 =head4 Example 1
757  
758 ---
759 module: builtin
760 function: abs
761  
762 config:
763 test_undef: no
764 test_empty: no
765 test_nuls: no
766 test_non_ascii: no
767  
768 input:
769 number:
770 type: number
771 position: 0
772  
773 output:
774 type: number
775 min: 0
776  
777 transforms:
778 positive:
779 input:
780 number:
781 type: number
782 position: 0
783 min: 0
784 output:
785 type: number
786 min: 0
787 negative:
788 input:
789 number:
790 type: number
791 position: 0
792 max: 0
793 output:
794 type: number
795 min: 0
796 error:
797 input:
798 undef
799 output:
800 _STATUS: DIES
801  
802 If the output hash contains the key _STATUS, and if that key is set to DIES,
803 the routine should die with the given arguments; otherwise, it should live.
804 If it's set to WARNS, the routine should warn with the given arguments.
805  
806 The keyword C<undef> is used to indicate that the C<function> returns nothing.
807  
808 =head4 Example 2
809  
810 ---
811 module: Math::Utils
812 function: normalize_number
813  
814 input:
815 value:
816 type: number
817 position: 0
818  
819 output:
820 type: number
821  
822 transforms:
823 positive_stays_positive:
824 input:
825 value:
826 type: number
827 min: 0
828 max: 1000
829 output:
830 type: number
831 min: 0
832 max: 1
833  
834 negative_becomes_zero:
835 input:
836 value:
837 type: number
838 max: 0
839 output:
840 type: number
841 value: 0
842  
843 preserves_zero:
844 input:
845 value:
846 type: number
847 value: 0
848 output:
849 type: number
850 value: 0
851  
852 =head3 C<$module>
853  
854 The name of the module (optional).
855  
856 Using the reserved word C<builtin> means you're testing a Perl builtin function.
857  
858 If omitted, the generator will guess from the config filename:
859 C<My-Widget.conf> -> C<My::Widget>.
860  
861 =head3 C<$function>
862  
863 The function/method to test.
864  
865 This defaults to C<run>.
866  
867 =head3 C<%new>
868  
869 An optional hashref of args to pass to the module's constructor.
870  
871 new:
872 api_key: ABC123
873 verbose: true
874  
875 To ensure C<new()> is called with no arguments, you still need to define new, thus:
876  
877 module: MyModule
878 function: my_function
879  
880 new:
881  
882 =head3 C<%cases>
883  
884 An optional Perl static corpus, when the output is a simple string (expected => [ args... ]).
885  
886 Maps the expected output string to the input and _STATUS
887  
888 cases:
889 ok:
890 input: ping
891 _STATUS: OK
892 error:
893 input: ""
894 _STATUS: DIES
895  
896 =head3 C<$yaml_cases>
897  
898 An optional path to a YAML file with the same shape as C<%cases>.
899  
900 =head3 C<$seed>
901  
902 An optional integer.
903 When provided, the generated C<t/fuzz.t> will call C<srand($seed)> so fuzz runs are reproducible.
904  
905 =head3 C<$iterations>
906  
907 An optional integer controlling how many fuzz iterations to perform (default 30).
908  
909 =head3 C<%edge_cases>
910  
911 An optional hash mapping of extra values to inject.
912  
913 # Two named parameters
914 edge_cases:
915 name: [ '', 'a' x 1024, \"\x{263A}" ]
916 age: [ -1, 0, 99999999 ]
917  
918 # Takes a string input
919 edge_cases: [ 'foo', 'bar' ]
920  
921 Values can be strings or numbers; strings will be properly quoted.
922 Note that this only works with routines that take named parameters.
923  
924 =head3 C<%type_edge_cases>
925  
926 An optional hash mapping types to arrayrefs of extra values to try for any field of that type:
927  
928 type_edge_cases:
929 string: [ '', ' ', "\t", "\n", "\0", 'long' x 1024, chr(0x1F600) ]
930 number: [ 0, 1.0, -1.0, 1e308, -1e308, 1e-308, -1e-308, 'NaN', 'Infinity' ]
931 integer: [ 0, 1, -1, 2**31-1, -(2**31), 2**63-1, -(2**63) ]
932  
933 =head3 C<%edge_case_array>
934  
935 Specify edge case values for routines that accept a single unnamed parameter.
936 This is specifically designed for simple functions that take one argument without a parameter name.
937 These edge cases supplement the normal random string generation, ensuring specific problematic values are always tested.
938 During fuzzing iterations, there's a 40% probability that a test case will use a value from edge_case_array instead of randomly generated data.
939  
940 ---
941 module: Text::Processor
942 function: sanitize
943  
944 input:
945 type: string
946 min: 1
947 max: 1000
948  
949 edge_case_array:
950 - "<script>alert('xss')</script>"
951 - "'; DROP TABLE users; --"
952 - "\0null\0byte"
953 - "emoji\U0001F60Atest"
954 - ""
955 - " "
956  
957 seed: 42
958 iterations: 30
959  
960 =head3 Semantic Data Generators
961  
962 For property-based testing with L<Test::LectroTest>,
963 you can use semantic generators to create realistic test data.
964  
965 C<unix_timestamp> is currently fully supported,
966 other fuzz testing support for C<semantic> entries is being developed.
967  
968 input:
969 email:
970 type: string
971 semantic: email
972  
973 user_id:
974 type: string
975 semantic: uuid
976  
977 phone:
978 type: string
979 semantic: phone_us
980  
981 =head4 Available Semantic Types
982  
983 =over 4
984  
985 =item * C<email> - Valid email addresses (user@domain.tld)
986  
987 =item * C<url> - HTTP/HTTPS URLs
988  
989 =item * C<uuid> - UUIDv4 identifiers
990  
991 =item * C<phone_us> - US phone numbers (XXX-XXX-XXXX)
992  
993 =item * C<phone_e164> - International E.164 format (+XXXXXXXXXXXX)
994  
995 =item * C<ipv4> - IPv4 addresses (0.0.0.0 - 255.255.255.255)
996  
997 =item * C<ipv6> - IPv6 addresses
998  
999 =item * C<username> - Alphanumeric usernames with _ and -
1000  
1001 =item * C<slug> - URL slugs (lowercase-with-hyphens)
1002  
1003 =item * C<hex_color> - Hex color codes (#RRGGBB)
1004  
1005 =item * C<iso_date> - ISO 8601 dates (YYYY-MM-DD)
1006  
1007 =item * C<iso_datetime> - ISO 8601 datetimes (YYYY-MM-DDTHH:MM:SSZ)
1008  
1009 =item * C<semver> - Semantic version strings (major.minor.patch)
1010  
1011 =item * C<jwt> - JWT-like tokens (base64url format)
1012  
1013 =item * C<json> - Simple JSON objects
1014  
1015 =item * C<base64> - Base64-encoded strings
1016  
1017 =item * C<md5> - MD5 hashes (32 hex chars)
1018  
1019 =item * C<sha256> - SHA-256 hashes (64 hex chars)
1020  
1021 =item * C<directory> - The path of an existing, writable directory
1022  
1023 The harness creates a temporary directory and passes its path, because no
1024 pattern can describe "a directory that exists".
1025 No empty-string case is generated for such a parameter, since routines
1026 commonly read an empty path as "not given".
1027 L<App::Test::Generator::SchemaExtractor> sets this for a parameter that the
1028 routine tests with C<-d>.
1029  
1030 =item * C<existing_file> - The path of an existing file
1031  
1032 The harness creates a temporary file and passes its path, because no pattern
1033 can describe "a file that exists". L<App::Test::Generator::SchemaExtractor>
1034 sets this for a parameter that the routine tests with C<-e> or C<-f> but does
1035 not read.
1036  
1037 =item * C<unix_timestamp>
1038  
1039 =back
1040  
1041 =head2 EDGE CASE GENERATION
1042  
1043 In addition to purely random fuzz cases, the harness generates
1044 deterministic edge cases for parameters that declare C<min>, C<max> or C<len> in their schema definitions.
1045  
1046 For each constraint, three edge cases are added:
1047  
1048 =over 4
1049  
1050 =item * Just inside the allowable range
1051  
1052 This case should succeed, since it lies strictly within the bounds.
1053  
1054 =item * Exactly on the boundary
1055  
1056 This case should succeed, since it meets the constraint exactly.
1057  
1058 =item * Just outside the boundary
1059  
1060 This case is annotated with C<_STATUS = 'DIES'> in the corpus and
1061 should cause the harness to fail validation or croak.
1062  
1063 A constraint that came only from L<extract-schemas> reading POD (marked
1064 with C<_source: pod> for prose or C<_source: input_spec> for a formal spec)
1065 is a claim about valid input, not a check the routine has been seen to make.
1066 The constraint still sizes the valid data that is generated. It also gets
1067 explicit out-of-bound probes: a probe that dies is accepted as enforcement
1068 of the documented limit, while one that survives is recorded as a
1069 documentation contradiction. Provenance is tracked per constraint in
1070 C<_constraint_source>, so a documented minimum does not make a maximum that
1071 the code enforces tolerant on the same field. This applies to array and hash sizes, string
1072 lengths and numeric ranges, to constraints parsed from POD prose
1073 (C<3-50>, C<at least 5>), and to C<memberof> lists and C<matches> patterns.
1074 Every documented constraint gets an outside value as an advisory probe; in
1075 the normal advisory mode a probe that survives is reported as a routine
1076 accepting a value its POD says is invalid, without failing the run. A
1077 constraint written by hand in a schema is still required to die outside
1078 it. Because tolerance reduces what the
1079 harness proves, every tolerated bound is reported with C<diag>, so a
1080 passing run never hides the concession. Without this, a routine whose POD
1081 says C<min =E<gt> 1> but which accepts an empty list failed every harness
1082 run.
1083  
1084 Fuzzing can still reveal a contradiction in either direction: a routine may
1085 reject a value inside a documented constraint, or accept one outside it. The
1086 harness records those observations and reports them together at the end of
1087 the run. Advisory mode tolerates them, so POD-derived documentation cannot
1088 fail a routine that merely documents differently; pass C<--strict-documented>
1089 to C<fuzz-harness-generator> to make each recorded contradiction a failing
1090 test. The strict choice is embedded in the generated harness, so a later
1091 C<prove> run behaves the same way.
1092  
1093 =back
1094  
1095 Supported constraint types:
1096  
1097 =over 4
1098  
1099 =item * C<number>, C<integer>, C<float>
1100  
1101 Uses numeric values one below, equal to, and one above the boundary.
1102  
1103 =item * C<string>
1104  
1105 Uses strings of lengths one below, equal to, and one above the boundary.
1106  
1107 =item * C<arrayref>
1108  
1109 Uses references to arrays of with the number of elements one below, equal to, and one above the boundary.
1110  
1111 =item * C<hashref>
1112  
1113 Uses hashes with key counts one below, equal to, and one above the
1114 boundary (C<min> = minimum number of keys, C<max> = maximum number
1115 of keys).
1116  
1117 =item * C<memberof> - arrayref of allowed values for a parameter
1118  
1119 This example is for a routine called C<input()> that takes two arguments: C<status> and C<level>.
1120 C<status> is a string that must have the value C<ok>, C<error> or C<pending>.
1121 The C<level> argument is an integer that must be one of C<1>, C<5> or C<111>.
1122  
1123 ---
1124 input:
1125 status:
1126 type: string
1127 memberof:
1128 - ok
1129 - error
1130 - pending
1131 level:
1132 type: integer
1133 memberof:
1134 - 1
1135 - 5
1136 - 111
1137  
1138 The generator will automatically create test cases for each allowed value (inside the member list),
1139 and at least one value outside the list (which should die or C<croak>, C<_STATUS = 'DIES'>).
1140 This works for strings, integers, and numbers.
1141  
1142 =item * C<enum> - synonym of C<memberof>
1143  
1144 =item * C<boolean> - automatic boundary tests for boolean fields
1145  
1146 input:
1147 flag:
1148 type: boolean
1149  
1150 The generator will automatically create test cases for 0 and 1; true and false; off and on, and values that should trigger C<_STATUS = 'DIES'>.
1151  
1152 =back
1153  
1154 These edge cases are inserted automatically, in addition to the random
1155 fuzzing inputs, so each run will reliably probe boundary conditions
1156 without relying solely on randomness.
1157  
1158 =head1 EXAMPLES
1159  
1160 See the files in C<t/conf> for examples.
1161  
1162 =head2 Adding Scheduled fuzz Testing with GitHub Actions to Your Code
1163  
1164 To automatically create and run tests on a regular basis on GitHub Actions,
1165 you need to create a configuration file for each method and subroutine that you're testing,
1166 and a GitHub Actions configuration file.
1167  
1168 This example takes you through testing the online_render method of L<HTML::Genealogy::Map>.
1169  
1170 =head3 t/conf/online_render.yml
1171  
1172 ---
1173  
1174 module: HTML::Genealogy::Map
1175 function: onload_render
1176  
1177 input:
1178 gedcom:
1179 type: object
1180 can: individuals
1181 geocoder:
1182 type: object
1183 can: geocode
1184 debug:
1185 type: boolean
1186 optional: true
1187 google_key:
1188 type: string
1189 optional: true
1190 min: 39
1191 max: 39
1192 matches: "^AIza[0-9A-Za-z_-]{35}$"
1193  
1194 config:
1195 test_undef: 0
1196  
1197 =head3 .github/actions/fuzz.t
1198  
1199 ---
1200 name: Fuzz Testing
1201  
1202 permissions:
1203 contents: read
1204  
1205 on:
1206 push:
1207 branches: [main, master]
1208 pull_request:
1209 branches: [main, master]
1210 schedule:
1211 - cron: '29 5 14 * *'
1212  
1213 jobs:
1214 generate-fuzz-tests:
1215 strategy:
1216 fail-fast: false
1217 matrix:
1218 os:
1219 - macos-latest
1220 - ubuntu-latest
1221 - windows-latest
1222 perl: ['5.42', '5.40', '5.38', '5.36', '5.34', '5.32', '5.30', '5.28', '5.22']
1223  
1224 runs-on: ${{ matrix.os }}
1225 name: Fuzz testing with perl ${{ matrix.perl }} on ${{ matrix.os }}
1226  
1227 steps:
1228 - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
1229  
1230 - name: Set up Perl
1231 uses: shogo82148/actions-setup-perl@8b574cdc2dffdae49f803204a4f2b716a2fa1db7 # v1.44.2
1232 with:
1233 perl-version: ${{ matrix.perl }}
1234  
1235 - name: Install App::Test::Generator this module's dependencies
1236 run: |
1237 cpanm App::Test::Generator
1238 cpanm --installdeps .
1239  
1240 - name: Make Module
1241 run: |
1242 perl Makefile.PL
1243 make
1244 env:
1245 AUTOMATED_TESTING: 1
1246 NONINTERACTIVE_TESTING: 1
1247  
1248 - name: Generate fuzz tests
1249 run: |
1250 mkdir t/fuzz
1251 find t/conf -name '*.yml' | while read config; do
1252 test_name=$(basename "$config" .conf)
1253 fuzz-harness-generator "$config" > "t/fuzz/${test_name}_fuzz.t"
1254 done
1255  
1256 - name: Run generated fuzz tests
1257 run: |
1258 prove -lr t/fuzz/
1259 env:
1260 AUTOMATED_TESTING: 1
1261 NONINTERACTIVE_TESTING: 1
1262  
1263 =head2 Fuzz Testing your CPAN Module
1264  
1265 Running fuzz tests when you run C<make test> in your CPAN module.
1266  
1267 Create a directory <t/conf> which contains the schemas.
1268  
1269 Then create this file as <t/fuzz.t>:
1270  
1271 #!/usr/bin/env perl
1272  
1273 use strict;
1274 use warnings;
1275  
1276 use FindBin qw($Bin);
1277 use IPC::Run3;
1278 use IPC::System::Simple qw(system);
1279 use Test::Needs 'App::Test::Generator';
1280 use Test::Most;
1281  
1282 my $dirname = "$Bin/conf";
1283  
1284 if((-d $dirname) && opendir(my $dh, $dirname)) {
1285 while (my $filename = readdir($dh)) {
1286 # Skip '.' and '..' entries and vi temporary files
1287 next if ($filename eq '.' || $filename eq '..') || ($filename =~ /\.swp$/);
1288  
1289 my $filepath = "$dirname/$filename";
1290  
1291 if(-f $filepath) { # Check if it's a regular file
1292 my ($stdout, $stderr);
1293 run3 ['fuzz-harness-generator', '-r', $filepath], undef, \$stdout, \$stderr;
1294  
1295 ok($? == 0, 'Generated test script exits successfully');
1296  
1297 if($? == 0) {
1298 ok($stdout =~ /^Result: PASS/ms);
1299 if($stdout =~ /Files=1, Tests=(\d+)/ms) {
1300 diag("$1 tests run");
1301 }
1302 } else {
1303 diag("$filepath: STDOUT:\n$stdout");
1304 diag($stderr) if(length($stderr));
1305 diag("$filepath Failed");
1306 last;
1307 }
1308 diag($stderr) if(length($stderr));
1309 }
1310 }
1311 closedir($dh);
1312 }
1313  
1314 done_testing();
1315  
1316 =head2 Property-Based Testing with Transforms
1317  
1318 The generator can create property-based tests using L<Test::LectroTest> when the
1319 C<properties> configuration option is enabled.
1320 This provides more comprehensive
1321 testing by automatically generating thousands of test cases and verifying that
1322 mathematical properties hold across all inputs.
1323  
1324 =head3 Basic Property-Based Transform Example
1325  
1326 Here's a complete example testing the C<abs> builtin function:
1327  
1328 B<t/conf/abs.yml>:
1329  
1330 ---
1331 module: builtin
1332 function: abs
1333  
1334 config:
1335 test_undef: no
1336 test_empty: no
1337 test_nuls: no
1338 properties:
1339 enable: true
1340 trials: 1000
1341  
1342 input:
1343 number:
1344 type: number
1345 position: 0
1346  
1347 output:
1348 type: number
1349 min: 0
1350  
1351 transforms:
1352 positive:
1353 input:
1354 number:
1355 type: number
1356 min: 0
1357 output:
1358 type: number
1359 min: 0
1360  
1361 negative:
1362 input:
1363 number:
1364 type: number
1365 max: 0
1366 output:
1367 type: number
1368 min: 0
1369  
1370 This configuration:
1371  
1372 =over 4
1373  
1374 =item * Enables property-based testing with 1000 trials per property
1375  
1376 =item * Defines two transforms: one for positive numbers, one for negative
1377  
1378 =item * Automatically generates properties that verify C<abs()> always returns non-negative numbers
1379  
1380 =back
1381  
1382 Generate the test:
1383  
1384 fuzz-harness-generator t/conf/abs.yml > t/abs_property.t
1385  
1386 The generated test will include:
1387  
1388 =over 4
1389  
1390 =item * Traditional edge-case tests for boundary conditions
1391  
1392 =item * Random fuzzing with 30 iterations (or as configured)
1393  
1394 =item * Property-based tests that verify the transforms with 1000 trials each
1395  
1396 =back
1397  
1398 =head3 What Properties Are Tested?
1399  
1400 The generator automatically detects and tests these properties based on your transform specifications:
1401  
1402 =over 4
1403  
1404 =item * B<Range constraints> - If output has C<min> or C<max>, verifies results stay within bounds
1405  
1406 =item * B<Type preservation> - Ensures numeric inputs produce numeric outputs
1407  
1408 =item * B<Definedness> - Verifies the function doesn't return C<undef> unexpectedly
1409  
1410 =item * B<Specific values> - If output specifies a C<value>, checks exact equality
1411  
1412 =back
1413  
1414 For the C<abs> example above, the generated properties verify:
1415  
1416 # For the "positive" transform:
1417 - Given a positive number, abs() returns >= 0
1418 - The result is a valid number
1419 - The result is defined
1420  
1421 # For the "negative" transform:
1422 - Given a negative number, abs() returns >= 0
1423 - The result is a valid number
1424 - The result is defined
1425  
1426 =head3 Advanced Example: String Normalization
1427  
1428 Here's a more complex example testing a string normalization function:
1429  
1430 B<t/conf/normalize.yml>:
1431  
1432 ---
1433 module: Text::Processor
1434 function: normalize_whitespace
1435  
1436 config:
1437 properties:
1438 enable: true
1439 trials: 500
1440  
1441 input:
1442 text:
1443 type: string
1444 min: 0
1445 max: 1000
1446 position: 0
1447  
1448 output:
1449 type: string
1450 min: 0
1451 max: 1000
1452  
1453 transforms:
1454 empty_preserved:
1455 input:
1456 text:
1457 type: string
1458 value: ""
1459 output:
1460 type: string
1461 value: ""
1462  
1463 single_space:
1464 input:
1465 text:
1466 type: string
1467 min: 1
1468 matches: '^\S+(\s+\S+)*$'
1469 output:
1470 type: string
1471 matches: '^\S+( \S+)*$'
1472  
1473 length_bounded:
1474 input:
1475 text:
1476 type: string
1477 min: 1
1478 max: 100
1479 output:
1480 type: string
1481 min: 1
1482 max: 100
1483  
1484 This tests that the normalization function:
1485  
1486 =over 4
1487  
1488 =item * Preserves empty strings (C<empty_preserved> transform)
1489  
1490 =item * Collapses multiple spaces into single spaces (C<single_space> transform)
1491  
1492 =item * Maintains length constraints (C<length_bounded> transform)
1493  
1494 =back
1495  
1496 =head3 Interpreting Property Test Results
1497  
1498 When property-based tests run, you'll see output like:
1499  
1500 ok 123 - negative property holds (1000 trials)
1501 ok 124 - positive property holds (1000 trials)
1502  
1503 If a property fails, Test::LectroTest will attempt to find the minimal failing
1504 case and display it:
1505  
1506 not ok 123 - positive property holds (47 trials)
1507 # Property failed
1508 # Reason: counterexample found
1509  
1510 This helps you quickly identify edge cases that your function doesn't handle correctly.
1511  
1512 =head3 Configuration Options for Property-Based Testing
1513  
1514 In the C<config> section:
1515  
1516 config:
1517 properties:
1518 enable: true # Enable property-based testing (default: false)
1519 trials: 1000 # Number of test cases per property (default: 1000)
1520  
1521 You can also disable traditional fuzzing and only use property-based tests:
1522  
1523 config:
1524 properties:
1525 enable: true
1526 trials: 5000
1527  
1528 iterations: 0 # Disable random fuzzing, use only property tests
1529  
1530 =head3 When to Use Property-Based Testing
1531  
1532 Property-based testing with transforms is particularly useful for:
1533  
1534 =over 4
1535  
1536 =item * Mathematical functions (C<abs>, C<sqrt>, C<min>, C<max>, etc.)
1537  
1538 =item * Data transformations (encoding, normalization, sanitization)
1539  
1540 =item * Parsers and formatters
1541  
1542 =item * Functions with clear input-output relationships
1543  
1544 =item * Code that should satisfy mathematical properties (commutativity, associativity, idempotence)
1545  
1546 =back
1547  
1548 =head3 Requirements
1549  
1550 Property-based testing requires both L<Test::LectroTest> and
1551 L<Test::LectroTest::Compat> to be installed:
1552  
1553 cpanm Test::LectroTest Test::LectroTest::Compat
1554  
1555 L<Test::LectroTest::Compat> provides the C<use_ok> bridge between
1556 L<Test::LectroTest> and L<Test::Most>; it is used in every generated
1557 property-based test file. Both are declared in the distribution's
1558 C<TEST_REQUIRES> so they are installed automatically during C<make test>.
1559  
1560 If not installed, the generated tests will automatically skip the property-based
1561 portion with a message.
1562  
1563 =head3 Testing Email Validation
1564  
1565 ---
1566 module: Email::Valid
1567 function: rfc822
1568  
1569 config:
1570 properties:
1571 enable: true
1572 trials: 200
1573 close_stdin: true
1574 test_undef: no
1575 test_empty: no
1576 test_nuls: no
1577  
1578 input:
1579 email:
1580 type: string
1581 semantic: email
1582 position: 0
1583  
1584 output:
1585 type: boolean
1586  
1587 transforms:
1588 valid_emails:
1589 input:
1590 email:
1591 type: string
1592 semantic: email
1593 output:
1594 type: boolean
1595  
1596 This generates 200 realistic email addresses for testing, rather than random strings.
1597  
1598 =head3 Combining Semantic with Regex
1599  
1600 You can combine semantic generators with regex validation:
1601  
1602 input:
1603 corporate_email:
1604 type: string
1605 semantic: email
1606 matches: '@company\.com$'
1607  
1608 The semantic generator creates realistic emails, and the regex ensures they match your domain.
1609  
1610 =head3 Custom Properties for Transforms
1611  
1612 You can define additional properties that should hold for your transforms beyond
1613 the automatically detected ones.
1614  
1615 =head4 Using Built-in Properties
1616  
1617 transforms:
1618 positive:
1619 input:
1620 number:
1621 type: number
1622 min: 0
1623 output:
1624 type: number
1625 min: 0
1626 properties:
1627 - idempotent # f(f(x)) == f(x)
1628 - non_negative # result >= 0
1629 - positive # result > 0
1630  
1631 Available built-in properties:
1632  
1633 =over 4
1634  
1635 =item * C<idempotent> - Function is idempotent: f(f(x)) == f(x)
1636  
1637 =item * C<non_negative> - Result is always >= 0
1638  
1639 =item * C<positive> - Result is always > 0
1640  
1641 =item * C<non_empty> - String result is never empty
1642  
1643 =item * C<length_preserved> - Output length equals input length
1644  
1645 =item * C<uppercase> - Result is all uppercase
1646  
1647 =item * C<lowercase> - Result is all lowercase
1648  
1649 =item * C<trimmed> - No leading/trailing whitespace
1650  
1651 =item * C<sorted_ascending> - Array is sorted ascending
1652  
1653 =item * C<sorted_descending> - Array is sorted descending
1654  
1655 =item * C<unique_elements> - Array has no duplicates
1656  
1657 =item * C<preserves_keys> - Hash has same keys as input
1658  
1659 =back
1660  
1661 =head4 Custom Property Code
1662  
1663 Custom properties allows the definition additional invariants and relationships that should hold for their transforms,
1664 beyond what's auto-detected.
1665 For example:
1666  
1667 =over 4
1668  
1669 =item * Idempotence: f(f(x)) == f(x)
1670  
1671 =item * Commutativity: f(x, y) == f(y, x)
1672  
1673 =item * Associativity: f(f(x, y), z) == f(x, f(y, z))
1674  
1675 =item * Inverse relationships: decode(encode(x)) == x
1676  
1677 =item * Domain-specific invariants: Custom business logic
1678  
1679 =back
1680  
1681 Define your own properties with custom Perl code:
1682  
1683 transforms:
1684 normalize:
1685 input:
1686 text:
1687 type: string
1688 output:
1689 type: string
1690 properties:
1691 - name: single_spaces
1692 description: "No multiple consecutive spaces"
1693 code: $result !~ / /
1694  
1695 - name: no_leading_space
1696 description: "No space at start"
1697 code: $result !~ /^\s/
1698  
1699 - name: reversible
1700 description: "Can be reversed back"
1701 code: length($result) == length($text)
1702  
1703 The code has access to:
1704  
1705 =over 4
1706  
1707 =item * C<$result> - The function's return value
1708  
1709 =item * Input variables - All input parameters (e.g., C<$text>, C<$number>)
1710  
1711 =item * The function itself - Can call it again for idempotence checks
1712  
1713 =back
1714  
1715 =head4 Combining Auto-detected and Custom Properties
1716  
1717 The generator automatically detects properties from your output spec, and adds
1718 your custom properties:
1719  
1720 transforms:
1721 sanitize:
1722 input:
1723 html:
1724 type: string
1725 output:
1726 type: string
1727 min: 0 # Auto-detects: defined, min_length >= 0
1728 max: 10000
1729 properties: # Additional custom checks:
1730 - name: no_scripts
1731 code: $result !~ /<script/i
1732 - name: no_iframes
1733 code: $result !~ /<iframe/i
1734  
1735 =head2 GENERATED OUTPUT
1736  
1737 The generated test:
1738  
1739 =over 4
1740  
1741 =item * Seeds RND (if configured) for reproducible fuzz runs
1742  
1743 =item * Uses edge cases (per-field and per-type) with configurable probability
1744  
1745 =item * Runs C<$iterations> fuzz cases plus appended edge-case runs
1746  
1747 =item * Validates inputs with Params::Get / Params::Validate::Strict
1748  
1749 =item * Asserts that a wrong-typed argument dies, where the type is enforced
1750  
1751 Passing a reference where a string is declared is only expected to die for a
1752 parameter whose input spec sets C<_source: validator>.
1753 L<App::Test::Generator::SchemaExtractor> sets that source when the routine
1754 checks its arguments with a validator such as L<Params::Validate::Strict>.
1755 A type taken from POD, or inferred from the code, documents intent but does not
1756 promise rejection, so no such case is generated for it.
1757 Add the source by hand to a schema whose routine does check its argument types.
1758  
1759 =item * Validates outputs with L<Return::Set>
1760  
1761 =item * Runs static C<is(... )> corpus tests from Perl and/or YAML corpus
1762  
1763 =item * Runs L<Test::LectroTest> tests
1764  
1765 =back
1766  
1767 =cut
1768  
1769 =head1 METHODS
1770  
1771 =head2 generate
1772  
1773 Takes a schema file and produces a test file (or STDOUT).
1774  
1775 # Modern named API
1776 App::Test::Generator->generate(
1777 schema_file => 'schemas/foo.yml',
1778 output_file => 'test/foo.t',
1779 );
1780  
1781 # Feed surviving mutants into the generated harness
1782 App::Test::Generator->generate(
1783 schema_file => 'schemas/foo.yml',
1784 mutation_results => 'mutation.json',
1785 output_file => 'test/foo.t',
1786 );
1787  
1788 # Legacy positional API
1789 App::Test::Generator->generate($schema_file, $test_file);
1790  
1791 =head3 API SPECIFICATION
1792  
1793 =head4 Input
1794  
1795 {
1796 schema_file => { type => 'string', optional => 0 },
1797 input_file => { type => 'string', optional => 1 },
1798 output_file => { type => 'string', optional => 1, max => 255 },
1799 strict_documented => { type => 'boolean', optional => 1 },
1800 mutation_results => { type => 'string', optional => 1 },
1801 }
1802  
1803 C<mutation_results> is the JSON report written by
1804 C<test-generator-mutate --json>. Surviving numeric-boundary mutants are
1805 converted into C<min> or C<max> constraints on the matching input field, so
1806 the harness generates data either side of the boundary the survivor exposed.
1807 Existing constraints are never replaced. See
1808 L<App::Test::Generator::Mutation::Feedback>.
1809  
1810 =head4 Output
1811  
1812 { type => 'boolean' }
1813  
1814 Always 1. The test source itself is written to C<output_file>, or printed
1815 on STDOUT when no output file is given; it is not returned.
1816  
1817 The mathematical description is in L</FORMAL SPECIFICATION>.
1818  
1819 =cut
1820  
1821 sub generate
1822 442 ▶{
Subroutine generate: called CC=193 SCAR=67.6
Pod documented
1823 442 ▶ croak 'Usage: generate(schema_file [, outfile])' if(scalar(@_) == 0);
Branch: 1 branch
BranchTrueFalseTotal
if scalar @_ == 0 0 442 442
1824  
1825 # Accept both class-method call (App::Test::Generator->generate(...))
1826 # and plain-function call with a hashref (generate({...})).
1827 # In the method form the first arg is the class name (a plain string);
1828 # in the function form with a hashref the first arg IS the hashref.
1829 442 ▶ my $class = (ref($_[0]) ne 'HASH') ? shift : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ne 'HASH' ? : 442 0 442
1830 442 my ($schema_file, $test_file, $schema);
1831 # Globals loaded from the user's conf (all optional except function maybe)
1832 442 my ($module, $function, $new, $yaml_cases);
1833 442 my ($seed, $iterations);
1834 442 my $strict_documented = 0;
1835  
1836 442 ▶ if((ref($_[0]) eq 'HASH') || defined($_[2])) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'HASH' or defined $_[2]) { } 326 116 442
Condition100%3/3
ref $_[0] eq "HASH" or defined $_[2]
l!l&&r!l&&!r
184142116
MC/DC100%2/2
ref $_[0] eq "HASH" or defined $_[2]
ref $_[0] eq "HASH" defined $_[2]
Truth table100%3/3
A or B
A= ref $_[0] eq "HASH"B= defined $_[2]
ABresult
1X1
011
000
1837 # Modern API
1838 326 my $params = Params::Validate::Strict::validate_strict({
1839 args => Params::Get::get_params(undef, \@_),
1840 schema => {
1841 input_file => { type => 'string', optional => 1 },
1842 schema_file => { type => 'string', optional => 1 },
1843 output_file => { type => 'string', optional => 1 },
1844 schema => { type => 'hashref', optional => 1 },
1845 quiet => { type => 'boolean', optional => 1 }, # Not yet used
1846 strict_documented => { type => 'boolean', optional => 1 },
1847 mutation_results => { type => 'string', optional => 1 },
1848 }
1849 });
1850 326 ▶ $strict_documented = $params->{'strict_documented'} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$params->{'strict_documented'} ? : 4 322 326
1851 326 ▶ if($params->{'schema_file'}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($params->{'schema_file'}) { } 117 209 326
elsif ($params->{'input_file'}) { } 180 29 209
elsif ($params->{'schema'}) { } 29 0 29
1852 117 $schema_file = $params->{'schema_file'};
1853 } elsif($params->{'input_file'}) {
1854 180 $schema_file = $params->{'input_file'};
1855 } elsif($params->{'schema'}) {
1856 29 $schema = $params->{'schema'};
1857 } else {
1858 0 croak(__PACKAGE__, ': Usage: generate(input_file|schema [, output_file]');
1859 }
1860 326 ▶ if(defined($schema_file)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $schema_file) 297 29 326
1861 297 $schema = _load_schema($schema_file);
1862 }
1863 326 ▶ if($params->{'mutation_results'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($params->{"mutation_results"}) 2 324 326
1864 # Surviving mutants add constraints the schema is missing, so
1865 # the harness exercises the boundary that survived the suite.
1866 2 require App::Test::Generator::Mutation::Feedback;
1867 my $feedback = App::Test::Generator::Mutation::Feedback->new(
1868 mutation_results => $params->{'mutation_results'},
1869 2 ▶ (defined($schema->{module}) ? (module => $schema->{module}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
defined $schema->{'module'} ? : 2 0 2
1870 );
1871 2 $feedback->apply_to_schema($schema);
1872 }
1873 326 $test_file = $params->{'output_file'};
1874 } else {
1875 # Legacy API
1876 116 ($schema_file, $test_file) = @_;
1877 116 ▶ if(defined($schema_file)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $schema_file) { } 110 6 116
1878 110 $schema = _load_schema($schema_file);
1879 } else {
1880 6 croak 'Usage: generate(schema_file [, outfile])';
1881 }
1882 }
1883  
1884 # Parse the schema file and load into our structures
1885 433 my %input = %{_load_schema_section($schema, 'input', $schema_file)};
1886 432 my %output = %{_load_schema_section($schema, 'output', $schema_file)};
1887 431 my %transforms = %{_load_schema_section($schema, 'transforms', $schema_file)};
1888 430 my %accessor = %{_load_schema_section($schema, 'accessor', $schema_file)};
1889  
1890 430 ▶ my %cases = %{$schema->{cases}} if(exists($schema->{cases}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"cases"} 2 428 430
1891 0 ▶ my %edge_cases = %{$schema->{edge_cases}} if(exists($schema->{edge_cases}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"edge_cases"} 0 430 430
1892 430 ▶ my %type_edge_cases = %{$schema->{type_edge_cases}} if(exists($schema->{type_edge_cases}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"type_edge_cases"} 1 429 430
1893  
1894 430 ▶ $module = $schema->{module} if(exists($schema->{module}) && length($schema->{module}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"module"} and length $schema->{"module"} 423 7 430
Condition66%2/3
exists $schema->{"module"} and length $schema->{"module"}
!ll&&!rl&&r
70423
MC/DC50%1/2
exists $schema->{"module"} and length $schema->{"module"}
exists $schema->{"module"} length $schema->{"module"}
Truth table66%2/3
A and B
A= exists $schema->{"module"}B= length $schema->{"module"}
ABresult
0X0
100
111
1895 430 ▶ $function = $schema->{function} if(exists($schema->{function}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"function"} 428 2 430
1896 430 ▶ if(exists($schema->{new})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $schema->{"new"}) 133 297 430
1897 133 ▶ $new = defined($schema->{'new'}) ? $schema->{new} : '_UNDEF';
Branch: 1 branch
BranchTrueFalseTotal
defined $schema->{'new'} ? : 109 24 133
1898 }
1899 430 ▶ $yaml_cases = $schema->{yaml_cases} if(exists($schema->{yaml_cases}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"yaml_cases"} 5 425 430
1900 430 ▶ $seed = $schema->{seed} if(exists($schema->{seed}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"seed"} 14 416 430
1901 430 ▶ $iterations = $schema->{iterations} if(exists($schema->{iterations}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"iterations"} 117 313 430
1902  
1903 430 ▶ my @edge_case_array = @{$schema->{edge_case_array}} if(exists($schema->{edge_case_array}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"edge_case_array"} 3 427 430
1904 430 _validate_config($schema);
1905  
1906 425 ▶ my %config = %{$schema->{config}} if(exists($schema->{config}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $schema->{"config"} 335 90 425
1907  
1908 425 _normalize_config(\%config);
1909 425 $config{'strict_documented'} = $strict_documented;
1910  
1911 # Guess module name from config file if not set
1912 425 ▶ if(!$module) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $module) { } 5 420 425
elsif ($module eq $MODULE_BUILTIN) { } 55 365 420
1913 5 ▶ if($schema_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema_file) 4 1 5
1914 4 ($module = basename($schema_file)) =~ s/\.(conf|pl|pm|yml|yaml)$//;
1915 4 $module =~ s/-/::/g;
1916 # Guard against Perl builtin function names being mistaken
1917 # for module names — builtins have no module to load
1918 4 ▶ if(_is_perl_builtin($module)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_perl_builtin($module)) 1 3 4
1919 1 undef $module;
1920 }
1921 }
1922 } elsif($module eq $MODULE_BUILTIN) {
1923 55 undef $module;
1924 }
1925  
1926 425 ▶ if($module && length($module) && ($module ne 'builtin')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($module and length $module and $module ne "builtin") 368 57 425
Condition66%4/6
$module and length $module and $module ne "builtin"
!ll&&!rl&&r
570368
$module and length $module
!ll&&!rl&&r
570368
MC/DC33%1/3
$module and length $module and $module ne "builtin"
$module length $module $module ne "builtin"
Truth table50%2/4
A and B and C
A= $moduleB= length $moduleC= $module ne "builtin"
ABCresult
0XX0
10X0
1100
1111
1927 368 _validate_module($module, $schema_file);
1928 }
1929  
1930 # $module/$function are spliced unescaped into generated test
1931 # source below (use_ok, new_ok, ->$function, $module::$function)
1932 # — reject anything that isn't identifier-shaped before that happens.
1933 425 ▶ _assert_identifier($module, 'module', package => 1) if defined($module) && length($module);
Branch: 1 branch
BranchTrueFalseTotal
if defined $module and length $module 368 57 425
Condition66%2/3
defined $module and length $module
!ll&&!rl&&r
570368
MC/DC50%1/2
defined $module and length $module
defined $module length $module
Truth table66%2/3
A and B
A= defined $moduleB= length $module
ABresult
0X0
100
111
1934  
1935 # sensible defaults
1936 424 ▶ $function ||= 'run';
Condition50%1/2
$function ||= "run"
l!l
4240
MC/DC0%0/1
$function ||= "run"
$function
Truth table50%1/2
A
A= $function
Aresult
11
00
1937 # package => 1: fully-qualified sub names (e.g. DB::DB, a debugger
1938 # hook installed into the DB:: package regardless of its source
1939 # package) are legitimate function names, not just bare identifiers
1940 424 _assert_identifier($function, 'function', package => 1);
1941 422 ▶ $iterations ||= $DEFAULT_ITERATIONS; # default fuzz runs if not specified
Condition66%2/3
$iterations ||= $DEFAULT_ITERATIONS
l!l&&r!l&&!r
1163060
MC/DC0%0/2
$iterations ||= $DEFAULT_ITERATIONS
$iterations $DEFAULT_ITERATIONS
Truth table66%2/3
A ||= B
A= $iterationsB= $DEFAULT_ITERATIONS
ABresult
1X1
011
000
1942 422 ▶ $seed = undef if defined $seed && $seed eq ''; # treat empty as undef
Branch: 1 branch
BranchTrueFalseTotal
if defined $seed and $seed eq "" 0 422 422
Condition66%2/3
defined $seed and $seed eq ""
!ll&&!rl&&r
408140
MC/DC0%0/2
defined $seed and $seed eq ""
defined $seed $seed eq ""
Truth table66%2/3
A and B
A= defined $seedB= $seed eq ""
ABresult
0X0
100
111
1943  
1944 # --- YAML corpus support (yaml_cases is filename string) ---
1945 422 my %yaml_corpus_data;
1946 422 ▶ if (defined $yaml_cases) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $yaml_cases) 5 417 422
1947 5 ▶ croak("$yaml_cases: $!") if(!-f $yaml_cases);
Branch: 1 branch
BranchTrueFalseTotal
unless -f $yaml_cases 1 4 5
1948  
1949 4 my $yaml_data = LoadFile(Encode::decode('utf8', $yaml_cases));
1950 4 ▶ if ($yaml_data && ref($yaml_data) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($yaml_data and ref $yaml_data eq "HASH") 4 0 4
Condition33%1/3
$yaml_data and ref $yaml_data eq "HASH"
!ll&&!rl&&r
004
MC/DC0%0/2
$yaml_data and ref $yaml_data eq "HASH"
$yaml_data ref $yaml_data eq "HASH"
Truth table33%1/3
A and B
A= $yaml_dataB= ref $yaml_data eq "HASH"
ABresult
0X0
100
111
1951 # Validate that the corpus inputs are arrayrefs
1952 # e.g: "FooBar": ["foo_bar"]
1953 # Skip only invalid entries:
1954 4 for my $expected (keys %{$yaml_data}) {
1955 6 my $outputs = $yaml_data->{$expected};
1956 6 ▶ unless($outputs && (ref $outputs eq 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($outputs and ref $outputs eq "ARRAY") 2 4 6
Condition66%2/3
$outputs and ref $outputs eq "ARRAY"
!ll&&!rl&&r
024
MC/DC50%1/2
$outputs and ref $outputs eq "ARRAY"
$outputs ref $outputs eq "ARRAY"
Truth table66%2/3
A and B
A= $outputsB= ref $outputs eq "ARRAY"
ABresult
0X0
100
111
1957 2 carp("$yaml_cases: $expected does not point to an array ref, ignoring");
1958 2 next;
1959 }
1960 4 $yaml_corpus_data{$expected} = $outputs;
1961 }
1962 }
1963 }
1964  
1965 # Merge Perl %cases and YAML corpus safely
1966 # my %all_cases = (%cases, %yaml_corpus_data);
1967 421 my %all_cases = (%yaml_corpus_data, %cases);
1968 421 for my $k (keys %yaml_corpus_data) {
1969 4 ▶ if (exists $cases{$k} && ref($cases{$k}) eq 'ARRAY' && ref($yaml_corpus_data{$k}) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $cases{$k} and ref $cases{$k} eq "ARRAY" and ref $yaml_corpus_data{$k} eq "ARRAY") 1 3 4
Condition66%4/6
exists $cases{$k} and ref $cases{$k} eq "ARRAY" and ref $yaml_corpus_data{$k} eq "ARRAY"
!ll&&!rl&&r
301
exists $cases{$k} and ref $cases{$k} eq "ARRAY"
!ll&&!rl&&r
301
MC/DC33%1/3
exists $cases{$k} and ref $cases{$k} eq "ARRAY" and ref $yaml_corpus_data{$k} eq "ARRAY"
exists $cases{$k} ref $cases{$k} eq "ARRAY" ref $yaml_corpus_data{$k} eq "ARRAY"
Truth table50%2/4
A and B and C
A= exists $cases{$k}B= ref $cases{$k} eq "ARRAY"C= ref $yaml_corpus_data{$k} eq "ARRAY"
ABCresult
0XX0
10X0
1100
1111
1970 1 $all_cases{$k} = [ @{$yaml_corpus_data{$k}}, @{$cases{$k}} ];
1971 }
1972 }
1973  
1974 421 ▶ if(my $hints = delete $schema->{_yamltest_hints}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $hints = delete $schema->{"_yamltest_hints"}) 9 412 421
1975 9 ▶ if(my $boundaries = $hints->{boundary_values}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $boundaries = $hints->{"boundary_values"}) 9 0 9
1976 9 push @edge_case_array, @{$boundaries};
1977 }
1978 9 ▶ if(my $invalid = $hints->{invalid}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $invalid = $hints->{"invalid"}) 0 9 9
1979 0 carp('TODO: handle yamltest_hints->invalid');
1980 }
1981 }
1982  
1983 # If the schema says the type is numeric, normalize
1984 421 ▶ if ($schema->{type} && $schema->{type} =~ /^(integer|number|float)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema->{"type"} and $schema->{"type"} =~ /^(integer|number|float)$/u) 1 420 421
Condition66%2/3
$schema->{"type"} and $schema->{"type"} =~ /^(integer|number|float)$/u
!ll&&!rl&&r
42001
MC/DC50%1/2
$schema->{"type"} and $schema->{"type"} =~ /^(integer|number|float)$/u
$schema->{"type"} $schema->{"type"} =~ /^(integer|number|float)$/u
Truth table66%2/3
A and B
A= $schema->{"type"}B= $schema->{"type"} =~ /^(integer|number|float)$/u
ABresult
0X0
100
111
1985 1 for (@edge_case_array) {
1986 2 ▶ next unless defined $_;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 0 2 2
1987 2 ▶ $_ += 0 if Scalar::Util::looks_like_number($_);
Branch: 1 branch
BranchTrueFalseTotal
if &Scalar::Util::looks_like_number($_) 1 1 2
1988 }
1989 }
1990  
1991 # Load relationships from the schema if present and well-formed.
1992 # SchemaExtractor may set this to undef or an empty arrayref when
1993 # no relationships were detected, so guard both existence and type.
1994 421 my @relationships;
1995 421 ▶ if(exists($schema->{relationships}) && ref($schema->{relationships}) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $schema->{"relationships"} and ref $schema->{"relationships"} eq "ARRAY") 0 421 421
Condition33%1/3
exists $schema->{"relationships"} and ref $schema->{"relationships"} eq "ARRAY"
!ll&&!rl&&r
42100
MC/DC0%0/2
exists $schema->{"relationships"} and ref $schema->{"relationships"} eq "ARRAY"
exists $schema->{"relationships"} ref $schema->{"relationships"} eq "ARRAY"
Truth table33%1/3
A and B
A= exists $schema->{"relationships"}B= ref $schema->{"relationships"} eq "ARRAY"
ABresult
0X0
100
111
1996 0 @relationships = @{$schema->{relationships}};
1997 }
1998  
1999 # Serialise the relationships array from the schema into Perl source
2000 # code for embedding in the generated test file. Each relationship
2001 # type is rendered as a hashref in the @relationships array.
2002  
2003 421 my $relationships_code = '';
2004  
2005 # Walk each relationship in the order SchemaExtractor produced them
2006 421 for my $rel (@relationships) {
2007 0 ▶ my $type = $rel->{type} // '';
Condition0%0/2
$rel->{"type"} // ""
l!l
00
MC/DC0%0/1
$rel->{"type"} // ""
$rel->{"type"}
Truth table0%0/2
A
A= $rel->{"type"}
Aresult
11
00
2008  
2009 # Mutually exclusive: both params being set should cause the method to die
2010 0 ▶ if($type eq 'mutually_exclusive') {
Branch: 6 branches
BranchTrueFalseTotal
if ($type eq 'mutually_exclusive') { } 0 0 0
elsif ($type eq 'required_group') { } 0 0 0
elsif ($type eq 'conditional_requirement') { } 0 0 0
elsif ($type eq 'dependency') { } 0 0 0
elsif ($type eq 'value_constraint') { } 0 0 0
elsif ($type eq 'value_conditional') { } 0 0 0
2011 $relationships_code .= "{ type => 'mutually_exclusive', params => [" .
2012 0 join(', ', map { perl_quote($_) } @{$rel->{params}}) .
2013 "] },\n";
2014  
2015 # Required group: at least one of the params must be present
2016 } elsif($type eq 'required_group') {
2017 $relationships_code .= "{ type => 'required_group', params => [" .
2018 0 ▶ join(', ', map { perl_quote($_) } @{$rel->{params}}) .
Condition0%0/2
$rel->{"logic"} // "or"
l!l
00
MC/DC0%0/1
$rel->{"logic"} // "or"
$rel->{"logic"}
Truth table0%0/2
A
A= $rel->{"logic"}
Aresult
11
00
2019 0 "], logic => " . perl_quote($rel->{logic} // 'or') . " },\n";
2020  
2021 # Conditional requirement: if one param is set, another becomes mandatory
2022 } elsif($type eq 'conditional_requirement') {
2023 $relationships_code .= "{ type => 'conditional_requirement', if => " .
2024 perl_quote($rel->{'if'}) . ", then_required => " .
2025 0 perl_quote($rel->{then_required}) . " },\n";
2026  
2027 # Dependency: one param requires another to also be present
2028 } elsif($type eq 'dependency') {
2029 $relationships_code .= "{ type => 'dependency', param => " .
2030 perl_quote($rel->{param}) . ", requires => " .
2031 0 perl_quote($rel->{requires}) . " },\n";
2032  
2033 # Value constraint: one param being set forces another to a specific value
2034 } elsif($type eq 'value_constraint') {
2035 $relationships_code .= "{ type => 'value_constraint', if => " .
2036 perl_quote($rel->{'if'}) . ", then => " .
2037 perl_quote($rel->{then}) . ", operator => " .
2038 perl_quote($rel->{operator}) . ", value => " .
2039 0 perl_quote($rel->{value}) . " },\n";
2040  
2041 # Value conditional: one param equalling a specific value requires another param
2042 } elsif($type eq 'value_conditional') {
2043 $relationships_code .= "{ type => 'value_conditional', if => " .
2044 perl_quote($rel->{'if'}) . ", equals => " .
2045 perl_quote($rel->{equals}) . ", then_required => " .
2046 0 perl_quote($rel->{then_required}) . " },\n";
2047  
2048 # Unknown type — warn and skip rather than emitting broken code
2049 } else {
2050 0 carp "Unknown relationship type '$type', skipping";
2051 }
2052 }
2053  
2054 # Dedup the edge cases
2055 421 my %seen;
2056 @edge_case_array = grep {
2057 421 ▶ my $key = defined($_) ? (Scalar::Util::looks_like_number($_) ? "N:$_" : "S:$_") : 'U';
Branch: 2 branches
BranchTrueFalseTotal
defined $_ ? : 113 0 113
&Scalar::Util::looks_like_number($_) ? : 99 14 113
2058 113 !$seen{$key}++;
2059 } @edge_case_array;
2060  
2061 # Sort the edge cases to keep it consistent across runs
2062 @edge_case_array = sort {
2063 421 ▶ return -1 if !defined $a;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $a 0 156 156
2064 156 ▶ return 1 if !defined $b;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $b 0 156 156
2065  
2066 156 my $na = Scalar::Util::looks_like_number($a);
2067 156 my $nb = Scalar::Util::looks_like_number($b);
2068  
2069 156 ▶ return $a <=> $b if $na && $nb;
Branch: 1 branch
BranchTrueFalseTotal
if $na and $nb 138 18 156
Condition100%3/3
$na and $nb
!ll&&!rl&&r
135138
MC/DC100%2/2
$na and $nb
$na $nb
Truth table100%3/3
A and B
A= $naB= $nb
ABresult
0X0
100
111
2070 18 ▶ return -1 if $na;
Branch: 1 branch
BranchTrueFalseTotal
if $na 5 13 18
2071 13 ▶ return 1 if $nb;
Branch: 1 branch
BranchTrueFalseTotal
if $nb 2 11 13
2072 11 return $a cmp $b;
2073 } @edge_case_array;
2074  
2075 # render edge case maps for inclusion in the .t
2076 421 my $edge_cases_code = render_arrayref_map(\%edge_cases);
2077 421 my $type_edge_cases_code = render_arrayref_map(\%type_edge_cases);
2078  
2079 421 my $edge_case_array_code = '';
2080 421 ▶ if(scalar(@edge_case_array)) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @edge_case_array) 23 398 421
2081 23 $edge_case_array_code = join(', ', map { q_wrap($_) } @edge_case_array);
2082 }
2083  
2084 # Render configuration - all the values are integers for now, if that changes, wrap the $config{$key} in single quotes
2085 421 my $config_code = '';
2086 421 foreach my $key (sort keys %config) {
2087 # Skip nested structures like 'properties' - they're used during
2088 # generation but don't need to be in the generated test
2089 5585 ▶ if(ref($config{$key}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $config{$key} eq "HASH") 421 5164 5585
2090 421 next;
2091 }
2092 5164 ▶ if((!defined($config{$key})) || !$config{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $config{$key} && $config{$key}) { } 1842 3322 5164
Condition66%2/3
defined $config{$key} && $config{$key}
!ll&&!rl&&r
018423322
MC/DC50%1/2
defined $config{$key} && $config{$key}
defined $config{$key} $config{$key}
Truth table66%2/3
A && B
A= defined $config{$key}B= $config{$key}
ABresult
0X0
100
111
2093 # YAML will strip the word 'false'
2094 # e.g. in 'test_undef: false'
2095 1842 $config_code .= "'$key' => 0,\n";
2096 } else {
2097 3322 $config_code .= "'$key' => $config{$key},\n";
2098 }
2099 }
2100  
2101 # Render input/output
2102 421 my $input_code = '';
2103 421 ▶ if(((scalar keys %input) == 1) && exists($input{'type'}) && !ref($input{'type'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %input == 1 and exists $input{'type'} and not ref $input{'type'}) { } 50 371 421
Condition83%5/6
scalar keys %input == 1 and exists $input{"type"} and not ref $input{"type"}
!ll&&!rl&&r
371050
scalar keys %input == 1 and exists $input{"type"}
!ll&&!rl&&r
17319850
MC/DC66%2/3
scalar keys %input == 1 and exists $input{"type"} and not ref $input{"type"}
scalar keys %input == 1 exists $input{"type"} not ref $input{"type"}
Truth table75%3/4
A and B and not(C)
A= scalar keys %input == 1B= exists $input{"type"}C= not ref $input{"type"}
ABCresult
0XX0
10X0
1100
1111
2104 # %input = ( type => 'string' );
2105 50 foreach my $key (sort keys %input) {
2106 50 $input_code .= "'$key' => '$input{$key}',\n";
2107 }
2108 } else {
2109 # %input = ( str => { type => 'string' } );
2110 371 $input_code = render_hash(\%input);
2111 }
2112 421 ▶ if(defined(my $re = $output{'matches'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $re = $output{"matches"})) 0 421 421
2113 0 ▶ if(ref($re) ne 'Regexp') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $re ne "Regexp") 0 0 0
2114 # Use eval to compile safely — qr/$re/ would interpolate
2115 # the string first, corrupting patterns containing [ or \
2116 0 my $compiled = eval { qr/$re/ };
2117 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
2118 0 carp("Invalid matches pattern '$re': $@");
2119 } else {
2120 0 $output{'matches'} = $compiled;
2121 }
2122 }
2123 }
2124  
2125 # Compile nomatch pattern to a Regexp object so it renders
2126 # as qr{} in the generated test rather than a raw string.
2127 # Without this, patterns containing [ or other regex
2128 # metacharacters cause compilation failures in validators
2129 421 ▶ if(defined(my $re = $output{'nomatch'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $re = $output{"nomatch"})) 0 421 421
2130 0 ▶ if(ref($re) ne 'Regexp') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $re ne "Regexp") 0 0 0
2131 # Use eval to compile safely — qr/$re/ would interpolate
2132 # the string first, corrupting patterns containing [ or \
2133 0 my $compiled = eval { qr/$re/ };
2134 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
2135 0 carp("Invalid nomatch pattern '$re': $@");
2136 } else {
2137 0 $output{'nomatch'} = $compiled;
2138 }
2139 }
2140 }
2141  
2142 421 my $output_code = render_args_hash(\%output);
2143 421 ▶ my $new_code = ($new && (ref $new eq 'HASH')) ? render_args_hash($new) : '';
Branch: 1 branch
BranchTrueFalseTotal
$new && ref $new eq 'HASH' ? : 100 321 421
Condition100%3/3
$new and ref $new eq "HASH"
!ll&&!rl&&r
28833100
MC/DC100%2/2
$new and ref $new eq "HASH"
$new ref $new eq "HASH"
Truth table100%3/3
A and B
A= $newB= ref $new eq "HASH"
ABresult
0X0
100
111
2144  
2145 421 my $transforms_code;
2146 421 ▶ if(keys %transforms) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %transforms) 8 413 421
2147 8 foreach my $transform(keys %transforms) {
2148 12 my $properties = render_fallback($transforms{$transform}->{'properties'});
2149  
2150 12 ▶ if($transforms_code) {
Branch: 1 branch
BranchTrueFalseTotal
if ($transforms_code) 4 8 12
2151 4 $transforms_code .= "},\n";
2152 }
2153 $transforms_code .= "$transform => {\n" .
2154 "\t'input' => { " .
2155 render_args_hash($transforms{$transform}->{'input'}) .
2156 "\t}, 'output' => { " .
2157 12 render_args_hash($transforms{$transform}->{'output'}) .
2158 "\t}, 'properties' => $properties\n" .
2159 "\t,\n";
2160 }
2161 8 $transforms_code .= "}\n";
2162 }
2163  
2164 421 my $transform_properties_code = '';
2165 421 my $use_properties = 0;
2166  
2167 421 ▶ if (keys %transforms && ($config{properties}{enable} // 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %transforms and $config{"properties"}{"enable"} // 0) 5 416 421
Condition80%4/5
keys %transforms and $config{"properties"}{"enable"} // 0
!ll&&!rl&&r
41335
$config{"properties"}{"enable"} // 0
l!l
80
MC/DC50%1/2
keys %transforms and $config{"properties"}{"enable"} // 0
keys %transforms $config{"properties"}{"enable"}
Truth table66%2/3
A and B
A= keys %transformsB= $config{"properties"}{"enable"}
ABresult
0X0
100
111
2168 5 $use_properties = 1;
2169  
2170 # Generate property-based tests for transforms
2171 5 my $properties = _generate_transform_properties(
2172 \%transforms,
2173 $function,
2174 $module,
2175 \%input,
2176 \%config,
2177 $new
2178 );
2179  
2180 # Convert to code for template
2181 4 $transform_properties_code = _render_properties($properties);
2182 }
2183  
2184 420 ▶ if(keys %accessor) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %accessor) 29 391 420
2185 # Sanity test
2186 29 my $property = $accessor{property};
2187 29 my $type = $accessor{type};
2188  
2189 29 ▶ if(!defined($new)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $new) 0 29 29
2190 # Internal invariant — schema has a contradictory accessor+type combination;
2191 # confess gives the full call chain to aid debugging
2192 0 confess("invariant violation: $property: accessor $type can only work on an object, incorrectly tagged as $type");
2193 }
2194 29 ▶ if($type eq 'getset') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "getset") 9 20 29
2195 9 ▶ if(scalar(keys %input) != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %input != 1) 1 8 9
2196 1 confess("invariant violation: $property: getset must take one input argument, incorrectly tagged as getset");
2197 }
2198 8 ▶ if(scalar(keys %output) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %output == 0) 1 7 8
2199 1 confess("invariant violation: $property: getset must give one output, incorrectly tagged as getset");
2200 }
2201 }
2202 }
2203  
2204 # Setup / call code (always load module)
2205 418 ▶ my $setup_code = ($module) ? "BEGIN { use_ok('$module') }" : '';
Branch: 1 branch
BranchTrueFalseTotal
$module ? : 364 54 418
2206 418 my $call_code; # Code to call the function being test when used with named arguments
2207 my $position_code; # Code to call the function being test when used with position arguments
2208 418 my $has_positions = _has_positions(\%input);
2209  
2210 # Numeric values have no single string form: one and the same integer can
2211 # stringify as "5967331536404480" (an IV) or "5.96733153640448e+15" (an
2212 # NV), so a getset round trip on an integer or number parameter is compared
2213 # numerically. The routine returns the value unchanged, yet eq failed on
2214 # the harness's own input about once in forty runs.
2215 418 my $cmp_op = 'eq';
2216 418 ▶ if(scalar(keys %input) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %input == 1) 246 172 418
2217 246 my ($spec) = values %input;
2218 246 ▶ my $type = (ref($spec) eq 'HASH') ? $spec->{type} : $spec;
Branch: 1 branch
BranchTrueFalseTotal
ref $spec eq 'HASH' ? : 196 50 246
2219 246 ▶ $cmp_op = '==' if(defined($type) && !ref($type) && ($type =~ /^(?:integer|number|float)$/));
Branch: 1 branch
BranchTrueFalseTotal
if defined $type and not ref $type and $type =~ /^(?:integer|number|float)$/u 48 198 246
Condition50%3/6
defined $type and not ref $type and $type =~ /^(?:integer|number|float)$/u
!ll&&!rl&&r
019848
defined $type and not ref $type
!ll&&!rl&&r
00246
MC/DC33%1/3
defined $type and not ref $type and $type =~ /^(?:integer|number|float)$/u
defined $type not ref $type $type =~ /^(?:integer|number|float)$/u
Truth table50%2/4
A and not(B) and C
A= defined $typeB= not ref $typeC= $type =~ /^(?:integer|number|float)$/u
ABCresult
0XX0
10X0
1100
1111
2220 }
2221 418 ▶ if(defined($new) && defined($module)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $new and defined $module) { } 130 288 418
elsif (defined $module and length $module) { } 234 54 288
Condition100%3/3
defined $new and defined $module
!ll&&!rl&&r
2871130
MC/DC100%2/2
defined $new and defined $module
defined $new defined $module
Truth table100%3/3
A and B
A= defined $newB= defined $module
ABresult
0X0
100
111
2222 # keep use_ok regardless (user found earlier issue)
2223 130 ▶ if($new_code eq '') {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_code eq '') { } 95 35 130
2224 95 $new_code = "new_ok('$module')";
2225 } else {
2226 35 $new_code = "new_ok('$module' => [ $new_code ] )";
2227 }
2228 130 $setup_code .= "\nmy \$obj = $new_code;";
2229 130 ▶ if($has_positions) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_positions) { } 66 64 130
2230 66 $position_code = "\$result = (scalar(\@alist) == 1) ? \$obj->$function(\$alist[0]) : (scalar(\@alist) == 0) ? \$obj->$function() : \$obj->$function(\@alist);";
2231 66 ▶ if(defined($accessor{type})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $accessor{"type"}) 5 61 66
2232 5 ▶ if($accessor{type} eq 'getter') {
Branch: 2 branches
BranchTrueFalseTotal
if ($accessor{'type'} eq 'getter') { } 0 5 5
elsif ($accessor{'type'} eq 'getset') { } 5 0 5
2233 0 $position_code .= "my \$prev_value = \$obj->{$accessor{property}};";
2234 } elsif($accessor{type} eq 'getset') {
2235 5 $position_code .= 'if(scalar(@alist) == 1) { ';
2236 5 $position_code .= "cmp_ok(\$result, '$cmp_op', \$alist[0], 'getset function returns what was put in'); ok(\$obj->$function() $cmp_op \$result, 'test getset accessor');";
2237 5 $position_code .= '}';
2238 }
2239 5 ▶ if(($accessor{type} eq 'getset') || ($accessor{type} eq 'getter')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($accessor{"type"} eq "getset" or $accessor{"type"} eq "getter") 5 0 5
Condition33%1/3
$accessor{"type"} eq "getset" or $accessor{"type"} eq "getter"
l!l&&r!l&&!r
500
MC/DC0%0/2
$accessor{"type"} eq "getset" or $accessor{"type"} eq "getter"
$accessor{"type"} eq "getset" $accessor{"type"} eq "getter"
Truth table33%1/3
A or B
A= $accessor{"type"} eq "getset"B= $accessor{"type"} eq "getter"
ABresult
1X1
011
000
2240 # Since Perl doesn't support data encapsulation, we can test the getter returns the correct item
2241 5 $position_code .= 'if(scalar(@alist) == 1) { ';
2242 5 $position_code .= "cmp_ok(\$result, '$cmp_op', \$obj->{$accessor{property}}, 'getset function returns correct item');";
2243 5 ▶ if($accessor{type} eq 'getter') {
Branch: 1 branch
BranchTrueFalseTotal
if ($accessor{"type"} eq "getter") 0 5 5
2244 0 $position_code .= "if(defined(\$prev_value)) { cmp_ok(\$result, 'eq', \$prev_value, 'getter does not change value'); } ";
2245 }
2246 5 $position_code .= '}';
2247 }
2248 5 ▶ if($output{'_returns_self'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($output{"_returns_self"}) 0 5 5
2249 0 croak("$accessor{type} for $accessor{property} cannot return \$self");
2250 }
2251 }
2252 } else {
2253 64 $call_code = "\$result = \$obj->$function(_fuzz_args(\$input));";
2254 64 ▶ if($output{'_returns_self'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($output{'_returns_self'}) { } 0 64 64
elsif (defined $accessor{'type'} and $accessor{'type'} eq 'getset') { } 2 104 106
2255 0 $call_code .= "ok(defined(\$result)); ok(\$result eq \$obj, '$function returns self')";
2256 ▶ } elsif(defined($accessor{type}) && ($accessor{type} eq 'getset')) {
Condition100%3/3
defined $accessor{"type"} and $accessor{"type"} eq "getset"
!ll&&!rl&&r
42202
MC/DC100%2/2
defined $accessor{"type"} and $accessor{"type"} eq "getset"
defined $accessor{"type"} $accessor{"type"} eq "getset"
Truth table100%3/3
A and B
A= defined $accessor{"type"}B= $accessor{"type"} eq "getset"
ABresult
0X0
100
111
2257 2 $call_code .= "ok(\$obj->$function() $cmp_op \$result, 'test getset accessor');"
2258 }
2259 64 ▶ if(scalar(keys %input) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %input == 0) 55 9 64
2260 55 ▶ if(defined($accessor{type}) && ($accessor{type} eq 'getter')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $accessor{"type"} and $accessor{"type"} eq "getter") 20 35 55
Condition66%2/3
defined $accessor{"type"} and $accessor{"type"} eq "getter"
!ll&&!rl&&r
35020
MC/DC50%1/2
defined $accessor{"type"} and $accessor{"type"} eq "getter"
defined $accessor{"type"} $accessor{"type"} eq "getter"
Truth table66%2/3
A and B
A= defined $accessor{"type"}B= $accessor{"type"} eq "getter"
ABresult
0X0
100
111
2261 20 $call_code .= "cmp_ok(\$result, 'eq', \$obj->{$accessor{property}}, 'getter function returns correct item') if(defined(\$result));";
2262 }
2263 }
2264 }
2265 ▶ } elsif(defined($module) && length($module)) {
Condition66%2/3
defined $module and length $module
!ll&&!rl&&r
540234
MC/DC50%1/2
defined $module and length $module
defined $module length $module
Truth table66%2/3
A and B
A= defined $moduleB= length $module
ABresult
0X0
100
111
2266 # `import` is a class method: `use Module` calls Module->import(...).
2267 # Some modules (Database::Abstraction) take the class as their first
2268 # argument, so a plain Module::import() with no named arguments dies.
2269 234 ▶ if(($function eq 'new') || ($function eq 'import')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($function eq 'new' or $function eq 'import') { } 45 189 234
Condition100%3/3
$function eq "new" or $function eq "import"
l!l&&r!l&&!r
441189
MC/DC100%2/2
$function eq "new" or $function eq "import"
$function eq "new" $function eq "import"
Truth table100%3/3
A or B
A= $function eq "new"B= $function eq "import"
ABresult
1X1
011
000
2270 45 ▶ if($has_positions) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_positions) { } 0 45 45
2271 0 $position_code = "\$result = (scalar(\@alist) == 1) ? ${module}\->$function(\$alist[0]) : (scalar(\@alist) == 0) ? ${module}\->$function() : ${module}\->$function(\@alist);";
2272 } else {
2273 45 $call_code = "\$result = ${module}\->$function(_fuzz_args(\$input));";
2274 }
2275 } else {
2276 189 ▶ if($has_positions) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_positions) { } 121 68 189
2277 121 $position_code = "\$result = (scalar(\@alist) == 1) ? ${module}::$function(\$alist[0]) : (scalar(\@alist) == 0) ? ${module}::$function() : ${module}::$function(\@alist);";
2278 } else {
2279 68 $call_code = "\$result = ${module}::$function(_fuzz_args(\$input));";
2280 }
2281 }
2282 } else {
2283 54 ▶ if($has_positions) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_positions) { } 8 46 54
2284 8 $position_code = "\$result = $function(\@alist);";
2285 } else {
2286 46 $call_code = "\$result = $function(_fuzz_args(\$input));";
2287 }
2288 }
2289  
2290 # List-context capture: $result = func() in scalar context returns a count, not the list.
2291 # When the schema says output type is 'array', capture into @_r then take a ref.
2292 418 ▶ if(($output{type} // '') eq 'array') {
Branch: 1 branch
BranchTrueFalseTotal
if (($output{"type"} // "") eq "array") 9 409 418
Condition100%2/2
$output{"type"} // ""
l!l
40018
MC/DC100%1/1
$output{"type"} // ""
$output{"type"}
Truth table100%2/2
A
A= $output{"type"}
Aresult
11
00
2293 9 ▶ if(defined($call_code)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $call_code) 7 2 9
2294 7 $call_code =~ s/\A\$result = ([^;]+);/my \@_r = ($1); \$result = \\\@_r;/;
2295 }
2296 9 ▶ if(defined($position_code)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $position_code) 2 7 9
2297 2 $position_code =~ s/\A\$result = ([^;]+);/my \@_r = ($1); \$result = \\\@_r;/;
2298 }
2299 }
2300  
2301 # A getter is called for its return value, so it must not change the state
2302 # of the object it was handed. The object is deep copied before the call
2303 # and its existing state compared afterwards; values it fills in where it
2304 # was handed undef are ignored along with keys it adds, because a getter
2305 # that caches the value it worked out is doing its job, while one that
2306 # overwrites or removes state it was given is not
2307 # - the change is invisible to the caller, which still holds the object,
2308 # and the next call sees different behaviour for the same input.
2309 418 ▶ if(defined($accessor{type}) && ($accessor{type} eq 'getter')) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $accessor{"type"} and $accessor{"type"} eq "getter") 20 398 418
Condition100%3/3
defined $accessor{"type"} and $accessor{"type"} eq "getter"
!ll&&!rl&&r
391720
MC/DC100%2/2
defined $accessor{"type"} and $accessor{"type"} eq "getter"
defined $accessor{"type"} $accessor{"type"} eq "getter"
Truth table100%3/3
A and B
A= defined $accessor{"type"}B= $accessor{"type"} eq "getter"
ABresult
0X0
100
111
2310 # A getter with no declared input must be called with no arguments:
2311 # $input is the schema's own hashref, and a getter that takes
2312 # an optional second argument would store it as if it were a value.
2313 20 foreach my $code (\$call_code, \$position_code) {
2314 40 ▶ next unless(defined($$code));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$code 20 20 40
2315 20 $$code =~ s/\Q$function\E\(_fuzz_args\(\$input\)\)/$function()/g;
2316 }
2317 20 my $snapshot = 'my $getter_copy = eval { require Storable; Storable::dclone($obj) }; ';
2318 20 my $check = 'if(defined($getter_copy) && eval { scalar(keys %{$getter_copy}); 1 }) {'
2319 . ' my %getter_state = map { $_ => $getter_copy->{$_} } grep { defined($getter_copy->{$_}) } keys %{$getter_copy};'
2320 . ' is_deeply({ map { $_ => $obj->{$_} } grep { exists($obj->{$_}) } keys %getter_state }, \\%getter_state, q{getter leaves its object unmodified});'
2321 . ' }';
2322 20 foreach my $code (\$call_code, \$position_code) {
2323 40 ▶ next unless(defined($$code) && ($config{'check_accessors'} // 1));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$code and $config{"check_accessors"} // 1 21 19 40
Condition80%4/5
defined $$code and $config{"check_accessors"} // 1
!ll&&!rl&&r
20119
$config{"check_accessors"} // 1
l!l
200
MC/DC50%1/2
defined $$code and $config{"check_accessors"} // 1
defined $$code $config{"check_accessors"}
Truth table66%2/3
A and B
A= defined $$codeB= $config{"check_accessors"}
ABresult
0X0
100
111
2324 19 $$code = $snapshot . $$code . ' ' . $check;
2325 }
2326 }
2327  
2328 # A setter is called to change one property, so everything else the object
2329 # was handed must come back untouched. The object is deep copied before the
2330 # call and the rest of its state compared afterwards; the property itself is
2331 # excluded, since changing that is the point, and values it fills in where it
2332 # was handed undef are ignored along with keys it adds, so that lazy
2333 # initialisation is not reported as damage.
2334 418 ▶ if(defined($accessor{type}) && ($accessor{type} eq 'getset') && defined($accessor{property})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $accessor{"type"} and $accessor{"type"} eq "getset" and defined $accessor{"property"}) 7 411 418
Condition83%5/6
defined $accessor{"type"} and $accessor{"type"} eq "getset" and defined $accessor{"property"}
!ll&&!rl&&r
41107
defined $accessor{"type"} and $accessor{"type"} eq "getset"
!ll&&!rl&&r
391207
MC/DC66%2/3
defined $accessor{"type"} and $accessor{"type"} eq "getset" and defined $accessor{"property"}
defined $accessor{"type"} $accessor{"type"} eq "getset" defined $accessor{"property"}
Truth table75%3/4
A and B and C
A= defined $accessor{"type"}B= $accessor{"type"} eq "getset"C= defined $accessor{"property"}
ABCresult
0XX0
10X0
1100
1111
2335 7 my $property = perl_quote($accessor{property});
2336 7 my $snapshot = 'my $setter_copy = eval { require Storable; Storable::dclone($obj) }; ';
2337 7 my $check = 'if(defined($setter_copy) && eval { scalar(keys %{$setter_copy}); 1 }) {'
2338 . ' my %setter_state = map { $_ => $setter_copy->{$_} } grep { defined($setter_copy->{$_}) && ($_ ne ' . $property . ') } keys %{$setter_copy};'
2339 . ' is_deeply({ map { $_ => $obj->{$_} } grep { exists($obj->{$_}) } keys %setter_state }, \\%setter_state, q{setter changes nothing but its property});'
2340 . ' }';
2341 7 foreach my $code (\$call_code, \$position_code) {
2342 14 ▶ next unless(defined($$code) && ($config{'check_accessors'} // 1));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$code and $config{"check_accessors"} // 1 8 6 14
Condition80%4/5
defined $$code and $config{"check_accessors"} // 1
!ll&&!rl&&r
716
$config{"check_accessors"} // 1
l!l
70
MC/DC50%1/2
defined $$code and $config{"check_accessors"} // 1
defined $$code $config{"check_accessors"}
Truth table66%2/3
A and B
A= defined $$codeB= $config{"check_accessors"}
ABresult
0X0
100
111
2343 6 $$code = $snapshot . $$code . ' ' . $check;
2344 }
2345 }
2346  
2347 # Build static corpus code
2348 418 my $corpus_code = '';
2349 418 ▶ if (%all_cases) {
Branch: 1 branch
BranchTrueFalseTotal
if (%all_cases) 3 415 418
2350 3 $corpus_code = "\n# --- Static Corpus Tests ---\n" .
2351 "diag('Running " . scalar(keys %all_cases) . " corpus tests');\n";
2352  
2353 3 for my $expected (sort keys %all_cases) {
2354 6 my $inputs = $all_cases{$expected};
2355 6 ▶ next unless($inputs);
Branch: 1 branch
BranchTrueFalseTotal
unless $inputs 0 6 6
2356  
2357 6 my $expected_str = perl_quote($expected);
2358 6 ▶ my $status = ((ref($inputs) eq 'HASH') && $inputs->{'_STATUS'}) // 'OK';
Condition40%2/5
ref $inputs eq "HASH" && $inputs->{"_STATUS"} // "OK"
l!l
60
ref $inputs eq "HASH" and $inputs->{"_STATUS"}
!ll&&!rl&&r
600
MC/DC0%0/2
ref $inputs eq "HASH" && $inputs->{"_STATUS"} // "OK"
ref $inputs eq "HASH" $inputs->{"_STATUS"}
Truth table33%1/3
A and B
A= ref $inputs eq "HASH"B= $inputs->{"_STATUS"}
ABresult
111
0X0
100
2359 6 ▶ if($expected_str eq "'_STATUS:DIES'") {
Branch: 2 branches
BranchTrueFalseTotal
if ($expected_str eq q['_STATUS:DIES']) { } 0 6 6
elsif ($expected_str eq q['_STATUS:WARNS']) { } 0 6 6
2360 0 $status = 'DIES';
2361 } elsif($expected_str eq "'_STATUS:WARNS'") {
2362 0 $status = 'WARNS';
2363 }
2364  
2365 6 ▶ if(ref($inputs) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $inputs eq "HASH") 0 6 6
2366 0 $inputs = $inputs->{'input'};
2367 }
2368 6 my $input_str;
2369 6 ▶ if(ref($inputs) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $inputs eq 'ARRAY') { } 6 0 6
elsif (ref $inputs eq 'HASH') { } 0 0 0
2370 6 $input_str = join(', ', map { perl_quote($_) } @{$inputs});
2371 } elsif(ref($inputs) eq 'HASH') {
2372 0 $input_str = render_fallback($inputs);
2373  
2374 # YAML can't express Perl's undef, so a corpus value of
2375 # the sentinel string 'undef' means "this param is
2376 # undef" -- convert the quoted sentinel back to the
2377 # bareword so the generated test passes real undef
2378 0 $input_str =~ s/=> 'undef'/=> undef/gms;
2379 } else {
2380 0 $input_str = $inputs;
2381 }
2382 6 ▶ if(($input_str eq 'undef') && (!$config{'test_undef'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input_str eq "undef" and not $config{"test_undef"}) 0 6 6
Condition33%1/3
$input_str eq "undef" and not $config{"test_undef"}
!ll&&!rl&&r
600
MC/DC0%0/2
$input_str eq "undef" and not $config{"test_undef"}
$input_str eq "undef" not $config{"test_undef"}
Truth table33%1/3
A and not(B)
A= $input_str eq "undef"B= not $config{"test_undef"}
ABresult
0X0
100
111
2383 0 carp('corpus case set to undef, yet test_undef is not set in config');
2384 }
2385 6 ▶ if($new) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new) { } 0 6 6
2386 0 ▶ if($status eq 'DIES') {
Branch: 2 branches
BranchTrueFalseTotal
if ($status eq 'DIES') { } 0 0 0
elsif ($status eq 'WARNS') { } 0 0 0
2387 $corpus_code .= "dies_ok { \$obj->$function($input_str) } " .
2388 0 ▶ "'$function(" . join(', ', map { $_ // '' } @$inputs ) . ") dies';\n";
Condition0%0/2
$_ // ""
l!l
00
MC/DC0%0/1
$_ // ""
$_
Truth table0%0/2
A
A= $_
Aresult
11
00
2389 } elsif($status eq 'WARNS') {
2390 $corpus_code .= "warnings_exist { \$obj->$function($input_str) } qr/./, " .
2391 0 ▶ "'$function(" . join(', ', map { $_ // '' } @$inputs ) . ") warns';\n";
Condition0%0/2
$_ // ""
l!l
00
MC/DC0%0/1
$_ // ""
$_
Truth table0%0/2
A
A= $_
Aresult
11
00
2392 } else {
2393 my $desc = sprintf("$function(%s) returns %s",
2394 0 ▶ perl_quote(join(', ', map { $_ // '' } @$inputs )),
Condition0%0/2
$_ // ""
l!l
00
MC/DC0%0/1
$_ // ""
$_
Truth table0%0/2
A
A= $_
Aresult
11
00
2395 $expected_str
2396 );
2397 0 ▶ if(($output{'type'} // '') eq 'boolean') {
Branch: 1 branch
BranchTrueFalseTotal
if (($output{'type'} // '') eq 'boolean') { } 0 0 0
Condition0%0/2
$output{"type"} // ""
l!l
00
MC/DC0%0/1
$output{"type"} // ""
$output{"type"}
Truth table0%0/2
A
A= $output{"type"}
Aresult
11
00
2398 0 ▶ if($expected_str eq '1') {
Branch: 2 branches
BranchTrueFalseTotal
if ($expected_str eq '1') { } 0 0 0
elsif ($expected_str eq '0') { } 0 0 0
2399 0 $corpus_code .= "ok(\$obj->$function($input_str), " . q_wrap($desc) . ");\n";
2400 } elsif($expected_str eq '0') {
2401 0 $corpus_code .= "ok(!\$obj->$function($input_str), " . q_wrap($desc) . ");\n";
2402 } else {
2403 0 croak("Boolean is expected to return $expected_str");
2404 }
2405 } else {
2406 0 $corpus_code .= "is(\$obj->$function($input_str), $expected_str, " . q_wrap($desc) . ");\n";
2407 }
2408 }
2409 } else {
2410 6 ▶ if($status eq 'DIES') {
Branch: 2 branches
BranchTrueFalseTotal
if ($status eq 'DIES') { } 0 6 6
elsif ($status eq 'WARNS') { } 0 6 6
2411 0 ▶ if($module) {
Branch: 1 branch
BranchTrueFalseTotal
if ($module) { } 0 0 0
2412 0 $corpus_code .= "dies_ok { $module\::$function($input_str) } " .
2413 "'Corpus $expected dies';\n";
2414 } else {
2415 0 $corpus_code .= "dies_ok { $function($input_str) } " .
2416 "'Corpus $expected dies';\n";
2417 }
2418 } elsif($status eq 'WARNS') {
2419 0 ▶ if($module) {
Branch: 1 branch
BranchTrueFalseTotal
if ($module) { } 0 0 0
2420 0 $corpus_code .= "warnings_exist { $module\::$function($input_str) } qr/./, " .
2421 "'Corpus $expected warns';\n";
2422 } else {
2423 0 $corpus_code .= "warnings_exist { $function($input_str) } qr/./, " .
2424 "'Corpus $expected warns';\n";
2425 }
2426 } else {
2427 my $desc = sprintf("$function(%s) returns %s",
2428 6 ▶ perl_quote((ref $inputs eq 'ARRAY') ? (join(', ', map { $_ // '' } @{$inputs})) : $inputs),
Branch: 1 branch
BranchTrueFalseTotal
ref $inputs eq 'ARRAY' ? : 6 0 6
Condition50%1/2
$_ // ""
l!l
90
MC/DC0%0/1
$_ // ""
$_
Truth table50%1/2
A
A= $_
Aresult
11
00
2429 $expected_str
2430 );
2431 6 ▶ if(($output{'type'} // '') eq 'boolean') {
Branch: 1 branch
BranchTrueFalseTotal
if (($output{'type'} // '') eq 'boolean') { } 0 6 6
Condition50%1/2
$output{"type"} // ""
l!l
60
MC/DC0%0/1
$output{"type"} // ""
$output{"type"}
Truth table50%1/2
A
A= $output{"type"}
Aresult
11
00
2432 0 ▶ if($expected_str eq '1') {
Branch: 2 branches
BranchTrueFalseTotal
if ($expected_str eq '1') { } 0 0 0
elsif ($expected_str eq '0') { } 0 0 0
2433 0 $corpus_code .= "ok(\$obj->$function($input_str), " . q_wrap($desc) . ");\n";
2434 } elsif($expected_str eq '0') {
2435 0 $corpus_code .= "ok(!\$obj->$function($input_str), " . q_wrap($desc) . ");\n";
2436 } else {
2437 0 croak("Boolean is expected to return $expected_str");
2438 }
2439 } else {
2440 6 $corpus_code .= "is(\$obj->$function($input_str), $expected_str, " . q_wrap($desc) . ");\n";
2441 }
2442 }
2443 }
2444 }
2445 }
2446  
2447 # Prepare seed/iterations code fragment for the generated test
2448 # A schema can record a precondition that no generated value can meet (for
2449 # example a file the routine parses). The harness then has nothing to
2450 # assert and says so instead of failing on a call it cannot make.
2451 418 my $skip_reason = $schema->{skip};
2452  
2453 # The generated harness needs the seed both to seed Perl's RNG (which the
2454 # regex generator uses) and to name it in failure diagnostics.
2455 418 my $seed_code = "our \$seed;\n";
2456 418 ▶ if (defined $seed) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $seed) 14 404 418
2457 # ensure integer-ish
2458 14 $seed = int($seed);
2459 14 $seed_code .= "srand(\$seed = $seed);\n";
2460 }
2461  
2462 418 ▶ my $determinism_code = 'my $result2;' .
Branch: 1 branch
BranchTrueFalseTotal
defined $position_code ? : 195 223 418
2463 'eval { $result2 = do { ' . (defined($position_code) ? $position_code : $call_code) . " }; };\n" .
2464 'is_deeply($result2, $result, "deterministic result for same input");' .
2465 "\n";
2466  
2467 # Generate the test content
2468 418 my $tt = Template->new({ ENCODING => 'utf8', TRIM => 1 });
2469  
2470 # Read template from DATA handle
2471 418 my $template_package = __PACKAGE__ . '::Template';
2472 418 my $template = $template_package->get_data_section('test.tt');
2473  
2474 my $vars = {
2475 setup_code => $setup_code,
2476 edge_cases_code => $edge_cases_code,
2477 edge_case_array_code => $edge_case_array_code,
2478 type_edge_cases_code => $type_edge_cases_code,
2479 config_code => $config_code,
2480 seed_code => $seed_code,
2481 input_code => $input_code,
2482 output_code => $output_code,
2483 transforms_code => $transforms_code,
2484 corpus_code => $corpus_code,
2485 call_code => $call_code,
2486 position_code => $position_code,
2487 determinism_code => $determinism_code,
2488 documented_sources => join(' ', App::Test::Generator::Provenance::documented_sources()),
2489 type_checks_source => App::Test::Generator::Provenance::type_checks_source(),
2490 function => $function,
2491 iterations_code => int($iterations),
2492 use_properties => $use_properties,
2493 transform_properties_code => $transform_properties_code,
2494 418 ▶ property_trials => $config{properties}{trials} // $DEFAULT_PROPERTY_TRIALS,
Condition100%3/3
$config{"properties"}{"trials"} // $DEFAULT_PROPERTY_TRIALS
l!l&&r!l&&!r
4215199
MC/DC100%2/2
$config{"properties"}{"trials"} // $DEFAULT_PROPERTY_TRIALS
$config{"properties"}{"trials"} $DEFAULT_PROPERTY_TRIALS
Truth table100%3/3
A // B
A= $config{"properties"}{"trials"}B= $DEFAULT_PROPERTY_TRIALS
ABresult
1X1
011
000
2495 relationships_code => $relationships_code,
2496 module => $module,
2497 skip_reason => $skip_reason
2498 };
2499  
2500 418 my $test;
2501 418 ▶ $tt->process($template, $vars, \$test) or croak($tt->error());
Branch: 1 branch
BranchTrueFalseTotal
$tt->process($template, $vars, \$test) or croak($tt->error) 418 0 418
2502  
2503 418 ▶ if ($test_file) {
Branch: 1 branch
BranchTrueFalseTotal
if ($test_file) { } 359 59 418
2504 # autodie is disabled for this open -- under "use autodie qw(:all)"
2505 # open() never returns false on failure, it throws its own exception
2506 # instead, which would silently make the "or croak" dead code.
2507 226 ▶ no autodie qw(open);
Subroutine BEGIN: called CC=1 SCAR=0.0
2508 359 ▶ open my $fh, '>:encoding(UTF-8)', $test_file or croak "Cannot open $test_file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">:encoding(UTF-8)", $test_file or croak("Cannot open ${test_file}: $!") 359 0 359
2509 359 print $fh "$test\n";
2510 359 close $fh;
2511 359 ▶ if($module) {
Branch: 1 branch
BranchTrueFalseTotal
if ($module) { } 345 14 359
2512 345 print "Generated $test_file for $module\::$function with fuzzing + corpus support\n";
2513 } else {
2514 14 print "Generated $test_file for $function with fuzzing + corpus support\n";
2515 }
2516 } else {
2517 59 print "$test\n";
2518 }
2519  
2520 418 return 1;
2521 }
2522  
2523 # --- Helpers for rendering data structures into Perl code for the generated test ---
2524  
2525 # --------------------------------------------------
2526 # _is_perl_builtin
2527 #
2528 # Purpose: Return true if a string is the name of
2529 # a Perl core builtin function, to prevent
2530 # it being used as a module name in
2531 # use_ok() calls in generated tests.
2532 #
2533 # Entry: $name - the string to check.
2534 # Exit: Returns 1 if builtin, 0 otherwise.
2535 # --------------------------------------------------
2536 34 ▶sub _is_perl_builtin {
Subroutine _is_perl_builtin: called CC=3 SCAR=11.0
2537 34 my $name = $_[0];
2538 34 ▶ return 0 unless defined $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 2 32 34
2539  
2540 32 state %BUILTINS = map { $_ => 1 } qw(
2541 abs accept alarm atan2 bind binmode bless
2542 caller chdir chmod chomp chop chown chr chroot
2543 close closedir connect cos crypt
2544 dbmclose dbmopen defined delete die do dump
2545 each endgrent endhostent endnetent endprotoent endpwent endservent
2546 eof eval exec exists exit exp
2547 fcntl fileno flock fork format formline
2548 getc getgrent getgrgid getgrnam gethostbyaddr gethostbyname
2549 gethostent getlogin getnetbyaddr getnetbyname getnetent
2550 getpeername getpgrp getppid getpriority getprotobyname
2551 getprotobynumber getprotoent getpwent getpwnam getpwuid
2552 getservbyname getservbyport getservent getsockname getsockopt
2553 glob gmtime goto grep
2554 hex
2555 index int ioctl
2556 join
2557 keys kill
2558 last lc lcfirst length link listen local localtime log lstat
2559 map mkdir msgctl msgget msgrcv msgsnd my
2560 next no
2561 oct open opendir ord our
2562 pack pipe pop pos print printf prototype push
2563 quotemeta
2564 rand read readdir readline readlink readpipe recv redo
2565 ref rename require reset return reverse rewinddir rindex rmdir
2566 say scalar seek seekdir select semctl semget semop send
2567 setgrent sethostent setnetent setpgrp setpriority setprotoent
2568 setpwent setservent setsockopt shift shmctl shmget shmread
2569 shmwrite shutdown sin sleep socket socketpair sort splice split
2570 sprintf sqrt srand stat study sub substr symlink syscall
2571 sysopen sysread sysseek system syswrite
2572 tell telldir tie tied time times truncate
2573 uc ucfirst umask undef unlink unpack unshift untie use
2574 utime values vec wait waitpid wantarray warn write
2575 );
2576 32 ▶ return $BUILTINS{lc $name} // 0;
Condition100%2/2
$BUILTINS{lc $name} // 0
l!l
2012
MC/DC100%1/1
$BUILTINS{lc $name} // 0
$BUILTINS{lc $name}
Truth table100%2/2
A
A= $BUILTINS{lc $name}
Aresult
11
00
2577 }
2578  
2579 # --------------------------------------------------
2580 # _load_schema
2581 #
2582 # Load and parse a schema file using
2583 # Config::Abstraction, returning the
2584 # schema as a hashref.
2585 #
2586 # Entry: $schema_file - path to the schema file.
2587 # Must be defined, non-empty, and readable.
2588 #
2589 # Exit: Returns a hashref of the parsed schema
2590 # with a '_source' key added containing
2591 # the originating file path.
2592 # Croaks on any error.
2593 #
2594 # Side effects: Reads from the filesystem.
2595 #
2596 # Notes: Legacy Perl-file configs (containing
2597 # '$module' or 'our $module' keys) are
2598 # rejected with a clear error. Config::
2599 # Abstraction is used rather than require()
2600 # to avoid executing arbitrary code from
2601 # user-supplied config files.
2602 # --------------------------------------------------
2603 415 ▶sub _load_schema {
Subroutine _load_schema: called CC=8 SCAR=21.1
2604 415 my $schema_file = $_[0];
2605  
2606 # Validate the argument before touching the filesystem
2607 415 ▶ croak(__PACKAGE__, ': Usage: _load_schema($schema_file)') unless defined $schema_file;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $schema_file 2 413 415
2608  
2609 413 ▶ croak(__PACKAGE__, ': _load_schema given empty filename') unless length($schema_file);
Branch: 1 branch
BranchTrueFalseTotal
unless length $schema_file 2 411 413
2610  
2611 # Confirm the file exists and is readable before attempting
2612 # to load it — gives a clearer error than Config::Abstraction would
2613 411 ▶ croak(__PACKAGE__, ": _load_schema($schema_file): $!") unless -r $schema_file;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $schema_file 5 406 411
2614  
2615 # Load configuration via Config::Abstraction which supports
2616 # YAML, JSON, and other formats without executing arbitrary code.
2617 # no_fixate prevents automatic type coercion that could alter values
2618 406 ▶ if(my $schema = Config::Abstraction->new(
Branch: 1 branch
BranchTrueFalseTotal
if (my $schema = "Config::Abstraction"->new("config_dirs", [".", ""], "config_file", $schema_file, "no_fixate", 1)) 406 0 406
2619 config_dirs => ['.', ''],
2620 config_file => $schema_file,
2621 no_fixate => 1,
2622 )) {
2623 406 ▶ if($schema = $schema->all()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema = $schema->all) 406 0 406
2624 # Detect legacy Perl config files by the presence of
2625 # variable declaration keys — these are no longer supported
2626 406 ▶ if(exists($schema->{$LEGACY_PERL_KEY_1}) ||
Branch: 1 branch
BranchTrueFalseTotal
if (exists $schema->{$LEGACY_PERL_KEY_1} or exists $schema->{$LEGACY_PERL_KEY_2}) 1 405 406
Condition66%2/3
exists $schema->{$LEGACY_PERL_KEY_1} or exists $schema->{$LEGACY_PERL_KEY_2}
l!l&&r!l&&!r
10405
MC/DC50%1/2
exists $schema->{$LEGACY_PERL_KEY_1} or exists $schema->{$LEGACY_PERL_KEY_2}
exists $schema->{$LEGACY_PERL_KEY_1} exists $schema->{$LEGACY_PERL_KEY_2}
Truth table66%2/3
A or B
A= exists $schema->{$LEGACY_PERL_KEY_1}B= exists $schema->{$LEGACY_PERL_KEY_2}
ABresult
1X1
011
000
2627 exists($schema->{$LEGACY_PERL_KEY_2})) {
2628 1 croak("$schema_file: Loading perl files as configs is no longer supported");
2629 }
2630  
2631 # Tag the schema with its source path for error messages
2632 405 $schema->{$SOURCE_KEY} = $schema_file;
2633 405 return $schema;
2634 }
2635 }
2636  
2637 0 croak "Failed to load schema from $schema_file";
2638 }
2639  
2640 # --------------------------------------------------
2641 # _load_schema_section
2642 #
2643 # Purpose: Extract a named section from a parsed
2644 # schema hashref, validating that it is
2645 # a hashref if present.
2646 #
2647 # Entry: $schema - the full parsed schema hashref.
2648 # $section - name of the section to extract
2649 # (e.g. 'input', 'output').
2650 # $schema_file - path of the schema file,
2651 # used in error messages only.
2652 #
2653 # Exit: Returns the section hashref if present,
2654 # or an empty hashref {} if absent.
2655 # Croaks if the section exists but is not
2656 # a hashref (and not the string 'undef').
2657 #
2658 # Notes: The string 'undef' is treated as an
2659 # absent section — callers that set a
2660 # section to 'undef' in YAML get the same
2661 # result as omitting it entirely.
2662 # --------------------------------------------------
2663 1734 ▶sub _load_schema_section {
Subroutine _load_schema_section: called CC=6 SCAR=18.0
2664 1734 my ($schema, $section, $schema_file) = @_;
2665  
2666 # Section absent — return empty hash as the safe default
2667 1734 ▶ return {} unless exists $schema->{$section};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $schema->{$section} 954 780 1734
2668  
2669 # Section present and is a hashref — return it directly
2670 return $schema->{$section}
2671 780 ▶ if ref($schema->{$section}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $schema->{$section} eq "HASH" 772 8 780
2672  
2673 # Treat the YAML scalar 'undef' as equivalent to absent
2674 return {}
2675 if defined($schema->{$section}) &&
2676 8 ▶ $schema->{$section} eq 'undef';
Branch: 1 branch
BranchTrueFalseTotal
if defined $schema->{$section} and $schema->{$section} eq "undef" 3 5 8
Condition66%2/3
defined $schema->{$section} and $schema->{$section} eq "undef"
!ll&&!rl&&r
053
MC/DC50%1/2
defined $schema->{$section} and $schema->{$section} eq "undef"
defined $schema->{$section} $schema->{$section} eq "undef"
Truth table66%2/3
A and B
A= defined $schema->{$section}B= $schema->{$section} eq "undef"
ABresult
0X0
100
111
2677  
2678 # Section present but wrong type — croak with a clear message
2679 # showing what type was found so the user can fix their schema
2680 croak(
2681 "$schema_file: $section should be a hash, not ",
2682 5 ▶ ref($schema->{$section}) || $schema->{$section}
Condition66%2/3
ref $schema->{$section} || $schema->{$section}
l!l&&r!l&&!r
140
MC/DC0%0/2
ref $schema->{$section} || $schema->{$section}
ref $schema->{$section} $schema->{$section}
Truth table66%2/3
A || B
A= ref $schema->{$section}B= $schema->{$section}
ABresult
1X1
011
000
2683 );
2684 }
2685  
2686 # --------------------------------------------------
2687 # _validate_config
2688 #
2689 # Purpose: Validate the top-level schema hashref
2690 # loaded from a schema file, checking that
2691 # required fields are present and that all
2692 # input parameters, types, positions, and
2693 # transform properties are well-formed.
2694 #
2695 # Entry: $schema - the full parsed schema hashref
2696 # as returned by _load_schema().
2697 #
2698 # Exit: Returns nothing on success.
2699 # Croaks on any structural error.
2700 # Carps on non-fatal warnings (unknown
2701 # semantic types, position gaps, missing
2702 # input/output definitions).
2703 #
2704 # Side effects: May delete $schema->{input} if its
2705 # value is the string 'undef'.
2706 #
2707 # Notes: The parameter is named $schema throughout
2708 # to distinguish the top-level schema from
2709 # the nested config sub-hash. _validate_config
2710 # is called before _normalize_config so config
2711 # boolean normalisation has not yet occurred.
2712 # --------------------------------------------------
2713 445 ▶sub _validate_config {
Subroutine _validate_config: called CC=14 SCAR=26.4
2714 445 my $schema = $_[0];
2715  
2716 # At least one of module or function must be present —
2717 # without these we cannot generate any meaningful test
2718 445 ▶ if(!defined($schema->{'module'}) && !defined($schema->{'function'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $schema->{"module"} or defined $schema->{"function"}) 4 441 445
Condition100%3/3
defined $schema->{"module"} or defined $schema->{"function"}
l!l&&r!l&&!r
424174
MC/DC100%2/2
defined $schema->{"module"} or defined $schema->{"function"}
defined $schema->{"module"} defined $schema->{"function"}
Truth table100%3/3
A or B
A= defined $schema->{"module"}B= defined $schema->{"function"}
ABresult
1X1
011
000
2719 4 croak('At least one of function and module must be defined');
2720 }
2721  
2722 # Warn if neither input nor output is defined — a few
2723 # generic tests can still be generated but it is unusual
2724 441 ▶ if(!defined($schema->{'input'}) && !defined($schema->{'output'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $schema->{"input"} or defined $schema->{"output"}) 9 432 441
Condition100%3/3
defined $schema->{"input"} or defined $schema->{"output"}
l!l&&r!l&&!r
3111219
MC/DC100%2/2
defined $schema->{"input"} or defined $schema->{"output"}
defined $schema->{"input"} defined $schema->{"output"}
Truth table100%3/3
A or B
A= defined $schema->{"input"}B= defined $schema->{"output"}
ABresult
1X1
011
000
2725 9 carp('Neither input nor output is defined, only a few tests will be generated');
2726 }
2727  
2728 # Normalise input: the string 'undef' means no input defined
2729 441 ▶ if($schema->{'input'} && ref($schema->{input}) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema->{"input"} and ref $schema->{"input"} ne "HASH") 3 438 441
Condition100%3/3
$schema->{"input"} and ref $schema->{"input"} ne "HASH"
!ll&&!rl&&r
1303083
MC/DC100%2/2
$schema->{"input"} and ref $schema->{"input"} ne "HASH"
$schema->{"input"} ref $schema->{"input"} ne "HASH"
Truth table100%3/3
A and B
A= $schema->{"input"}B= ref $schema->{"input"} ne "HASH"
ABresult
0X0
100
111
2730 3 ▶ if($schema->{'input'} eq 'undef') {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema->{'input'} eq 'undef') { } 1 2 3
2731 1 delete $schema->{'input'};
2732 } else {
2733 2 croak("Invalid input specification: expected hash, got '$schema->{'input'}'");
2734 }
2735 }
2736  
2737 # Validate each input parameter if input is defined
2738 439 ▶ if($schema->{input}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema->{"input"}) 308 131 439
2739 308 _validate_input_params($schema);
2740 305 _validate_input_positions($schema);
2741 305 _validate_input_semantics($schema);
2742 }
2743  
2744 # Validate transform property definitions if present
2745 436 ▶ if(exists($schema->{transforms}) && ref($schema->{transforms}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $schema->{"transforms"} and ref $schema->{"transforms"} eq "HASH") 15 421 436
Condition66%2/3
exists $schema->{"transforms"} and ref $schema->{"transforms"} eq "HASH"
!ll&&!rl&&r
421015
MC/DC50%1/2
exists $schema->{"transforms"} and ref $schema->{"transforms"} eq "HASH"
exists $schema->{"transforms"} ref $schema->{"transforms"} eq "HASH"
Truth table66%2/3
A and B
A= exists $schema->{"transforms"}B= ref $schema->{"transforms"} eq "HASH"
ABresult
0X0
100
111
2746 15 _validate_transform_properties($schema);
2747 }
2748  
2749 # Validate any nested config sub-hash keys against known types
2750 436 ▶ if(ref($schema->{config}) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $schema->{"config"} eq "HASH") 337 99 436
2751 337 for my $k (keys %{$schema->{'config'}}) {
2752 # %VALID_CONFIG_KEYS is the authoritative set — O(1) hash lookup
2753 croak "unknown config setting '$k'"
2754 2302 ▶ unless $VALID_CONFIG_KEYS{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless $VALID_CONFIG_KEYS{$k} 2 2300 2302
2755 }
2756 }
2757 }
2758  
2759 # --------------------------------------------------
2760 # _validate_input_params
2761 #
2762 # Purpose: Validate type specifications for each
2763 # named input parameter.
2764 #
2765 # Entry: $schema - the full parsed schema hashref.
2766 # $schema->{input} must be a hashref.
2767 #
2768 # Exit: Returns nothing. Croaks on invalid type.
2769 # --------------------------------------------------
2770 # Validate a nested element specification. `schema` on an arrayref describes
2771 # every element; on a hashref it describes every value, or -- when it has no
2772 # type of its own -- maps fixed key names to element specs.
2773 9 ▶sub _validate_element_spec {
Subroutine _validate_element_spec: called CC=23 SCAR=35.0
2774 9 my ($element, $param, $allow_keys) = @_;
2775  
2776 9 ▶ return unless defined($element);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $element 0 9 9
2777 9 ▶ if(!ref($element)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $element) 0 9 9
2778 0 ▶ croak("Invalid element type '$element' for '$param'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_nested_type($element) 0 0 0
2779 unless _valid_nested_type($element);
2780 0 return;
2781 }
2782 9 ▶ croak("schema for parameter '$param' must be a hash or a type name")
Branch: 1 branch
BranchTrueFalseTotal
if ref $element ne "HASH" 0 9 9
2783 if ref($element) ne 'HASH';
2784  
2785 9 ▶ if($allow_keys && !exists($element->{type})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($allow_keys and not exists $element->{"type"}) 1 8 9
Condition100%3/3
$allow_keys and not exists $element->{"type"}
!ll&&!rl&&r
711
MC/DC100%2/2
$allow_keys and not exists $element->{"type"}
$allow_keys not exists $element->{"type"}
Truth table100%3/3
A and not(B)
A= $allow_keysB= not exists $element->{"type"}
ABresult
0X0
100
111
2786 croak("A hashref schema for '$param' with fixed keys needs at least one key")
2787 1 ▶ unless keys %{$element};
Branch: 1 branch
BranchTrueFalseTotal
unless keys %{$element;} 0 1 1
2788 1 foreach my $key (sort keys %{$element}) {
2789 2 my $value = $element->{$key};
2790 2 ▶ if(!ref($value)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $value) 1 1 2
2791 1 ▶ croak("Invalid element type '$value' for '$param.$key'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_nested_type($value) 0 1 1
2792 unless _valid_nested_type($value);
2793 1 next;
2794 }
2795 1 ▶ croak("Element schema for '$param.$key' must be a hash")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "HASH" 0 1 1
2796 unless ref($value) eq 'HASH';
2797 1 _validate_element_spec($value, "$param.$key", 0);
2798 }
2799 1 return;
2800 }
2801  
2802 croak("Missing type in the element schema for '$param'")
2803 8 ▶ unless defined($element->{type});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $element->{"type"} 0 8 8
2804 croak("Invalid element type '$element->{type}' for '$param'")
2805 8 ▶ unless !ref($element->{type}) && _valid_nested_type($element->{type});
Branch: 1 branch
BranchTrueFalseTotal
unless not ref $element->{"type"} and _valid_nested_type($element->{"type"}) 1 7 8
Condition66%2/3
not ref $element->{"type"} and _valid_nested_type($element->{"type"})
!ll&&!rl&&r
017
MC/DC50%1/2
not ref $element->{"type"} and _valid_nested_type($element->{"type"})
not ref $element->{"type"} _valid_nested_type($element->{"type"})
Truth table66%2/3
not(A) and B
A= not ref $element->{"type"}B= _valid_nested_type($element->{"type"})
ABresult
0X0
100
111
2806 croak("Object element schema for '$param' needs 'isa' or 'can'")
2807 7 ▶ if(($element->{type} eq 'object') && !defined($element->{isa}) && !defined($element->{can}));
Branch: 1 branch
BranchTrueFalseTotal
if $element->{"type"} eq "object" and not defined $element->{"isa"} and not defined $element->{"can"} 1 6 7
Condition83%5/6
$element->{"type"} eq "object" and not defined $element->{"isa"} and not defined $element->{"can"}
!ll&&!rl&&r
601
$element->{"type"} eq "object" and not defined $element->{"isa"}
!ll&&!rl&&r
511
MC/DC66%2/3
$element->{"type"} eq "object" and not defined $element->{"isa"} and not defined $element->{"can"}
$element->{"type"} eq "object" not defined $element->{"isa"} not defined $element->{"can"}
Truth table75%3/4
A and not(B) and not(C)
A= $element->{"type"} eq "object"B= not defined $element->{"isa"}C= not defined $element->{"can"}
ABCresult
0XX0
10X0
1100
1111
2808  
2809 6 ▶ if(($element->{type} eq 'arrayref') || ($element->{type} eq 'array')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($element->{'type'} eq 'arrayref' or $element->{'type'} eq 'array') { } 1 5 6
elsif ($element->{'type'} eq 'hashref') { } 0 5 5
Condition66%2/3
$element->{"type"} eq "arrayref" or $element->{"type"} eq "array"
l!l&&r!l&&!r
105
MC/DC50%1/2
$element->{"type"} eq "arrayref" or $element->{"type"} eq "array"
$element->{"type"} eq "arrayref" $element->{"type"} eq "array"
Truth table66%2/3
A or B
A= $element->{"type"} eq "arrayref"B= $element->{"type"} eq "array"
ABresult
1X1
011
000
2810 1 ▶ _validate_element_spec($element->{schema}, $param, 0) if defined($element->{schema});
Branch: 1 branch
BranchTrueFalseTotal
if defined $element->{"schema"} 1 0 1
2811 } elsif($element->{type} eq 'hashref') {
2812 0 ▶ _validate_element_spec($element->{schema}, $param, 1) if defined($element->{schema});
Branch: 1 branch
BranchTrueFalseTotal
if defined $element->{"schema"} 0 0 0
2813 }
2814 }
2815  
2816 9 ▶sub _valid_nested_type {
Subroutine _valid_nested_type: called CC=5 SCAR=19.4
2817 9 my ($type) = @_;
2818  
2819 9 ▶ return 0 unless defined($type) && !ref($type);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type and not ref $type 0 9 9
Condition33%1/3
defined $type and not ref $type
!ll&&!rl&&r
009
MC/DC0%0/2
defined $type and not ref $type
defined $type not ref $type
Truth table33%1/3
A and not(B)
A= defined $typeB= not ref $type
ABresult
0X0
100
111
2820 9 ▶ return 1 if($type eq 'array') || ($type eq 'coderef');
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "array" or $type eq "coderef" 0 9 9
Condition33%1/3
$type eq "array" or $type eq "coderef"
l!l&&r!l&&!r
009
MC/DC0%0/2
$type eq "array" or $type eq "coderef"
$type eq "array" $type eq "coderef"
Truth table33%1/3
A or B
A= $type eq "array"B= $type eq "coderef"
ABresult
1X1
011
000
2821 9 return _valid_type($type);
2822 }
2823  
2824 311 ▶sub _validate_input_params {
Subroutine _validate_input_params: called CC=13 SCAR=25.7
2825 311 my $schema = $_[0];
2826  
2827 311 for my $param (keys %{$schema->{input}}) {
2828 # Catch empty parameter names — these would produce
2829 # broken Perl variable names in the generated test
2830 405 ▶ croak 'Empty input parameter name'
Branch: 1 branch
BranchTrueFalseTotal
unless length $param 1 404 405
2831 unless length($param);
2832  
2833 404 my $spec = $schema->{input}{$param};
2834  
2835 # Validate the type field — required for all parameters
2836 404 ▶ if(ref($spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $spec) { } 351 53 404
2837 croak("Missing type for parameter '$param'")
2838 351 ▶ unless defined $spec->{type};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec->{"type"} 1 350 351
2839 # 'coderef' is a SchemaExtractor-specific type, not one of the
2840 # schema's value types: the harness satisfies it with a no-op
2841 # coderef rather than generating values for it.
2842 350 ▶ next if $spec->{type} eq 'coderef';
Branch: 1 branch
BranchTrueFalseTotal
if $spec->{"type"} eq "coderef" 5 345 350
2843 croak("Invalid type '$spec->{type}' for parameter '$param'")
2844 345 ▶ unless _valid_type($spec->{type});
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_type($spec->{"type"}) 2 343 345
2845  
2846 343 ▶ if(($spec->{type} eq 'arrayref') || ($spec->{type} eq 'array')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($spec->{'type'} eq 'arrayref' or $spec->{'type'} eq 'array') { } 13 330 343
elsif ($spec->{'type'} eq 'hashref') { } 58 272 330
Condition66%2/3
$spec->{"type"} eq "arrayref" or $spec->{"type"} eq "array"
l!l&&r!l&&!r
130330
MC/DC50%1/2
$spec->{"type"} eq "arrayref" or $spec->{"type"} eq "array"
$spec->{"type"} eq "arrayref" $spec->{"type"} eq "array"
Truth table66%2/3
A or B
A= $spec->{"type"} eq "arrayref"B= $spec->{"type"} eq "array"
ABresult
1X1
011
000
2847 13 ▶ _validate_element_spec($spec->{schema}, $param, 0) if defined($spec->{schema});
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"schema"} 5 8 13
2848 } elsif($spec->{type} eq 'hashref') {
2849 58 ▶ _validate_element_spec($spec->{schema}, $param, 1) if defined($spec->{schema});
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"schema"} 2 56 58
2850 }
2851 } else {
2852 53 ▶ croak("Invalid type '$spec' for parameter '$param'")
Branch: 1 branch
BranchTrueFalseTotal
unless _valid_type($spec) 0 53 53
2853 unless _valid_type($spec);
2854 }
2855 }
2856 }
2857  
2858 # --------------------------------------------------
2859 # _validate_input_positions
2860 #
2861 # Purpose: Validate positional argument declarations
2862 # in the input schema — positions must be
2863 # non-negative integers with no duplicates,
2864 # and either all or no parameters must have
2865 # positions.
2866 #
2867 # Entry: $schema - the full parsed schema hashref.
2868 # $schema->{input} must be a hashref.
2869 #
2870 # Exit: Returns nothing. Croaks on invalid or
2871 # duplicate positions. Carps on gaps.
2872 # --------------------------------------------------
2873 313 ▶sub _validate_input_positions {
Subroutine _validate_input_positions: called CC=12 SCAR=24.9
2874 313 my $schema = $_[0];
2875  
2876 313 my $has_positions = 0;
2877 313 my %positions;
2878  
2879 313 for my $param (keys %{$schema->{input}}) {
2880 413 my $spec = $schema->{input}{$param};
2881  
2882 # Only process params that explicitly declare a position
2883 413 ▶ next unless ref($spec) eq 'HASH' && defined($spec->{position});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" and defined $spec->{"position"} 183 230 413
Condition100%3/3
ref $spec eq "HASH" and defined $spec->{"position"}
!ll&&!rl&&r
53130230
MC/DC100%2/2
ref $spec eq "HASH" and defined $spec->{"position"}
ref $spec eq "HASH" defined $spec->{"position"}
Truth table100%3/3
A and B
A= ref $spec eq "HASH"B= defined $spec->{"position"}
ABresult
0X0
100
111
2884  
2885 230 $has_positions = 1;
2886 230 my $pos = $spec->{position};
2887  
2888 # Position must be a non-negative integer
2889 230 ▶ croak "Position for '$param' must be a non-negative integer"
Branch: 1 branch
BranchTrueFalseTotal
unless $pos =~ /^\d+$/u 1 229 230
2890 unless $pos =~ /^\d+$/;
2891  
2892 # Duplicate positions would produce ambiguous generated tests
2893 croak "Duplicate position $pos for parameters '$positions{$pos}' and '$param'"
2894 229 ▶ if exists $positions{$pos};
Branch: 1 branch
BranchTrueFalseTotal
if exists $positions{$pos} 2 227 229
2895  
2896 227 $positions{$pos} = $param;
2897 }
2898  
2899 # If any param has a position, all params must have one
2900 310 ▶ if($has_positions) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_positions) 201 109 310
2901 201 for my $param (keys %{$schema->{input}}) {
2902 226 my $spec = $schema->{input}{$param};
2903 226 ▶ unless(ref($spec) eq 'HASH' && defined($spec->{position})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $spec eq "HASH" and defined $spec->{"position"}) 2 224 226
Condition66%2/3
ref $spec eq "HASH" and defined $spec->{"position"}
!ll&&!rl&&r
02224
MC/DC50%1/2
ref $spec eq "HASH" and defined $spec->{"position"}
ref $spec eq "HASH" defined $spec->{"position"}
Truth table66%2/3
A and B
A= ref $spec eq "HASH"B= defined $spec->{"position"}
ABresult
0X0
100
111
2904 2 croak "Parameter '$param' missing position " .
2905 '(all params must have positions if any do)';
2906 }
2907 }
2908  
2909 # Check for gaps — positions must be a contiguous sequence
2910 # starting at 0, otherwise the generated test will be wrong
2911 199 my @sorted = sort { $a <=> $b } keys %positions;
2912 199 for my $i (0 .. $#sorted) {
2913 223 ▶ if($sorted[$i] != $i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sorted[$i] != $i) 1 222 223
2914 1 carp "Position sequence has gaps (positions: @sorted)";
2915 1 last;
2916 }
2917 }
2918 }
2919 }
2920  
2921 # --------------------------------------------------
2922 # _validate_input_semantics
2923 #
2924 # Purpose: Validate semantic type annotations and
2925 # enum/memberof constraints on input params.
2926 #
2927 # Entry: $schema - the full parsed schema hashref.
2928 # $schema->{input} must be a hashref.
2929 #
2930 # Exit: Returns nothing. Croaks on conflicting
2931 # or malformed enum/memberof. Carps on
2932 # unknown semantic types.
2933 # --------------------------------------------------
2934 315 ▶sub _validate_input_semantics {
Subroutine _validate_input_semantics: called CC=10 SCAR=23.0
2935 315 my $schema = $_[0];
2936  
2937 315 my $semantic_generators = _get_semantic_generators();
2938  
2939 315 for my $param (keys %{$schema->{input}}) {
2940 408 my $spec = $schema->{input}{$param};
2941 408 ▶ next unless ref($spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 54 354 408
2942  
2943 # Warn on unknown semantic types rather than croaking —
2944 # new semantic types may be added without updating this list
2945 354 ▶ if(defined($spec->{semantic})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $spec->{"semantic"}) 12 342 354
2946 12 my $semantic = $spec->{semantic};
2947 12 ▶ unless(exists $semantic_generators->{$semantic}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $semantic_generators->{$semantic}) 2 10 12
2948 carp "Unknown semantic type '$semantic' for parameter '$param'. " .
2949 'Available types: ' .
2950 2 join(', ', sort keys %{$semantic_generators});
2951 }
2952 }
2953  
2954 # enum and memberof are mutually exclusive representations
2955 # of the same concept — having both is always a schema error
2956 354 ▶ if($spec->{'enum'} && $spec->{'memberof'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"enum"} and $spec->{"memberof"}) 2 352 354
Condition100%3/3
$spec->{"enum"} and $spec->{"memberof"}
!ll&&!rl&&r
35022
MC/DC100%2/2
$spec->{"enum"} and $spec->{"memberof"}
$spec->{"enum"} $spec->{"memberof"}
Truth table100%3/3
A and B
A= $spec->{"enum"}B= $spec->{"memberof"}
ABresult
0X0
100
111
2957 2 croak "$param: has both enum and memberof";
2958 }
2959  
2960 # Both enum and memberof must be arrayrefs when present
2961 352 for my $type ('enum', 'memberof') {
2962 703 ▶ if(exists $spec->{$type}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $spec->{$type}) 17 686 703
2963 croak "$type must be an arrayref"
2964 17 ▶ unless ref($spec->{$type}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec->{$type} eq "ARRAY" 3 14 17
2965 }
2966 }
2967 }
2968 }
2969  
2970 # --------------------------------------------------
2971 # _validate_transform_properties
2972 #
2973 # Purpose: Validate the properties array in each
2974 # transform definition, checking that each
2975 # property is either a known builtin name
2976 # or a custom hashref with name and code.
2977 #
2978 # Entry: $schema - the full parsed schema hashref.
2979 # $schema->{transforms} must be a hashref.
2980 #
2981 # Exit: Returns nothing. Croaks on invalid property
2982 # definitions. Carps on unknown builtins.
2983 # --------------------------------------------------
2984 21 ▶sub _validate_transform_properties {
Subroutine _validate_transform_properties: called CC=10 SCAR=23.0
2985 21 my $schema = $_[0];
2986  
2987 21 my $builtin_props = _get_builtin_properties();
2988  
2989 21 for my $transform_name (keys %{$schema->{transforms}}) {
2990 19 my $transform = $schema->{transforms}{$transform_name};
2991  
2992 # properties is optional — skip transforms that don't define it
2993 19 ▶ next unless exists $transform->{properties};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $transform->{"properties"} 13 6 19
2994  
2995 croak "Transform '$transform_name': properties must be an array"
2996 6 ▶ unless ref($transform->{properties}) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $transform->{"properties"} eq "ARRAY" 1 5 6
2997  
2998 5 for my $prop (@{$transform->{properties}}) {
2999 5 ▶ if(!ref($prop)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not ref $prop) { } 2 3 5
elsif (ref $prop eq 'HASH') { } 2 1 3
3000 # Plain string — must be a known builtin property name
3001 2 ▶ unless(exists $builtin_props->{$prop}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $builtin_props->{$prop}) 1 1 2
3002 carp "Transform '$transform_name': unknown built-in property '$prop'. " .
3003 'Available: ' .
3004 1 join(', ', sort keys %{$builtin_props});
3005 }
3006 } elsif(ref($prop) eq 'HASH') {
3007 # Custom property — must have both name and code fields
3008 2 ▶ unless($prop->{name} && $prop->{code}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($prop->{"name"} and $prop->{"code"}) 1 1 2
Condition66%2/3
$prop->{"name"} and $prop->{"code"}
!ll&&!rl&&r
011
MC/DC50%1/2
$prop->{"name"} and $prop->{"code"}
$prop->{"name"} $prop->{"code"}
Truth table66%2/3
A and B
A= $prop->{"name"}B= $prop->{"code"}
ABresult
0X0
100
111
3009 1 croak "Transform '$transform_name': " .
3010 "custom properties must have 'name' and 'code' fields";
3011 }
3012 } else {
3013 1 croak "Transform '$transform_name': invalid property definition";
3014 }
3015 }
3016 }
3017 }
3018  
3019 # --------------------------------------------------
3020 # _normalize_config
3021 #
3022 # Purpose: Normalise boolean string values in the
3023 # config sub-hash to Perl integers (1/0),
3024 # and default absent boolean fields to 1
3025 # (enabled). The 'properties' field is a
3026 # hashref not a boolean and is handled
3027 # separately.
3028 #
3029 # Entry: $config - the config sub-hash extracted
3030 # from the schema (i.e. $schema->{config}).
3031 # May be empty.
3032 #
3033 # Exit: Returns nothing. Modifies $config in place.
3034 #
3035 # Side effects: Modifies the caller's config hashref.
3036 #
3037 # Notes: String-to-boolean conversion is delegated
3038 # to %Readonly::Values::Boolean::booleans
3039 # which handles 'yes'/'no', 'on'/'off',
3040 # 'true'/'false' etc. Fields not present in
3041 # the config hash are defaulted to 1 so
3042 # that test generation is maximally thorough
3043 # unless the schema explicitly disables a
3044 # feature.
3045 # --------------------------------------------------
3046 434 ▶sub _normalize_config {
Subroutine _normalize_config: called CC=8 SCAR=20.8
3047 434 my $config = $_[0];
3048  
3049 434 for my $field (keys %VALID_CONFIG_KEYS) {
3050 # Non-boolean fields are handled separately
3051 5642 ▶ next if $field eq $CONFIG_PROPERTIES_KEY;
Branch: 1 branch
BranchTrueFalseTotal
if $field eq $CONFIG_PROPERTIES_KEY 434 5208 5642
3052 5208 ▶ next if $field eq 'timeout'; # numeric, not boolean; absence means use generated-test default
Branch: 1 branch
BranchTrueFalseTotal
if $field eq "timeout" 434 4774 5208
3053  
3054 4774 ▶ if(exists($config->{$field}) && defined($config->{$field})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $config->{$field} and defined $config->{$field}) { } 2990 1784 4774
Condition100%3/3
exists $config->{$field} and defined $config->{$field}
!ll&&!rl&&r
178312990
MC/DC100%2/2
exists $config->{$field} and defined $config->{$field}
exists $config->{$field} defined $config->{$field}
Truth table100%3/3
A and B
A= exists $config->{$field}B= defined $config->{$field}
ABresult
0X0
100
111
3055 # Convert string boolean representations to integers
3056 # using the lookup table from Readonly::Values::Boolean
3057 2990 ▶ if(defined(my $b = $Readonly::Values::Boolean::booleans{$config->{$field}})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $b = $Readonly::Values::Boolean::booleans{$config->{$field}})) 2990 0 2990
3058 2990 $config->{$field} = $b;
3059 }
3060 } else {
3061 # Default absent boolean fields to enabled (1) so that
3062 # test generation is comprehensive unless explicitly disabled
3063 1784 $config->{$field} = 1;
3064 }
3065 }
3066  
3067 # Ensure properties is always a hashref — if absent or set to
3068 # a non-hash value, replace with a disabled default so that
3069 # downstream code can safely dereference it without checking ref()
3070 434 ▶ $config->{$CONFIG_PROPERTIES_KEY} = { enable => 0 } unless ref($config->{$CONFIG_PROPERTIES_KEY}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $config->{$CONFIG_PROPERTIES_KEY} eq "HASH" 354 80 434
3071 }
3072  
3073 # --------------------------------------------------
3074 # _valid_type
3075 #
3076 # Determine whether a string is a
3077 # recognised schema field type accepted
3078 # by the generator.
3079 #
3080 # Entry: $type - the type string to validate.
3081 # May be undef.
3082 #
3083 # Exit: Returns 1 if the type is known,
3084 # 0 if the type is unknown or undef.
3085 #
3086 # Notes: The lookup hash is declared with
3087 # 'state' so it is built only once per
3088 # process rather than on every call —
3089 # important since _valid_type is called
3090 # in a loop over all input parameters.
3091 #
3092 # 'int' and 'bool' are accepted as
3093 # aliases for 'integer' and 'boolean'
3094 # respectively, for compatibility with
3095 # schemas generated by external tools
3096 # that use the shorter forms.
3097 # --------------------------------------------------
3098 470 ▶sub _valid_type {
Subroutine _valid_type: called CC=3 SCAR=11.0
3099 470 my $type = $_[0];
3100  
3101 # Undef is never a valid type
3102 470 ▶ return 0 unless defined($type);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 3 467 470
3103  
3104 # Build the lookup table once and cache it for
3105 # the lifetime of the process via 'state'
3106 467 state %VALID = map { $_ => 1 } qw(
3107 string boolean integer number float
3108 hashref arrayref object int bool any
3109 );
3110  
3111 467 ▶ return($VALID{$type} // 0);
Condition100%2/2
$VALID{$type} // 0
l!l
44621
MC/DC100%1/1
$VALID{$type} // 0
$VALID{$type}
Truth table100%2/2
A
A= $VALID{$type}
Aresult
11
00
3112 }
3113  
3114 # --------------------------------------------------
3115 # _assert_identifier
3116 #
3117 # Purpose: Validate that a string is shaped like a
3118 # plain Perl identifier (or, with
3119 # package => 1, a "::"-separated package
3120 # name) before it is spliced into generated
3121 # test source as a bareword, package name,
3122 # method name, or variable name rather than
3123 # a quoted string literal. Schema-derived
3124 # names (module, function, transform names)
3125 # are spliced unescaped at the call sites
3126 # that use this guard, so an unvalidated
3127 # name could otherwise break out of the
3128 # generated source and inject arbitrary
3129 # Perl into a file that L<prove> will run.
3130 #
3131 # Entry: $name - the string to validate.
3132 # $what - short label for the value, used
3133 # only in the croak message.
3134 # %opts - package => 1 allows "::"
3135 # separators in $name.
3136 #
3137 # Exit: Returns $name unchanged on success.
3138 # Croaks if $name is not identifier-shaped.
3139 # --------------------------------------------------
3140 832 ▶sub _assert_identifier {
Subroutine _assert_identifier: called CC=5 SCAR=16.1
3141 832 my ($name, $what, %opts) = @_;
3142  
3143 832 ▶ croak(__PACKAGE__, ": $what is missing or empty")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 2 830 832
Condition100%3/3
defined $name and length $name
!ll&&!rl&&r
11830
MC/DC100%2/2
defined $name and length $name
defined $name length $name
Truth table100%3/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
3144 unless defined($name) && length($name);
3145  
3146 my $re = $opts{package}
3147 830 ▶ ? qr/^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
Branch: 1 branch
BranchTrueFalseTotal
$opts{'package'} ? : 799 31 830
3148 : qr/^[A-Za-z_]\w*\z/;
3149  
3150 830 ▶ croak(__PACKAGE__, ": $what '$name' is not a valid Perl identifier")
Branch: 1 branch
BranchTrueFalseTotal
unless $name =~ /$re/u 10 820 830
3151 unless $name =~ $re;
3152  
3153 820 return $name;
3154 }
3155  
3156 # --------------------------------------------------
3157 # _validate_module
3158 #
3159 # Purpose: Check whether the module named in a
3160 # schema can be found in @INC during
3161 # test generation. Optionally also
3162 # attempts to load it if the
3163 # GENERATOR_VALIDATE_LOAD environment
3164 # variable is set.
3165 #
3166 # Entry: $module - the module name to
3167 # check. If undef or
3168 # empty, returns 1
3169 # immediately (builtin
3170 # functions need no
3171 # module).
3172 # $schema_file - path to the schema
3173 # file, used in warning
3174 # messages only.
3175 #
3176 # Exit: Returns 1 if the module was found
3177 # (and loaded, if validation was
3178 # requested).
3179 # Returns 0 if the module was not
3180 # found or failed to load — this is
3181 # non-fatal; generation continues.
3182 # Returns 1 immediately for undef or
3183 # empty $module.
3184 #
3185 # Side effects: Prints to STDERR when TEST_VERBOSE
3186 # or GENERATOR_VERBOSE is set.
3187 # Carps (non-fatally) when the module
3188 # cannot be found or loaded.
3189 # May attempt to load the module into
3190 # the current process when
3191 # GENERATOR_VALIDATE_LOAD is set —
3192 # this can have side effects depending
3193 # on the module.
3194 #
3195 # Notes: Not finding a module during generation
3196 # is intentionally non-fatal — the module
3197 # may be available on the target machine
3198 # even if not on the generation machine.
3199 # Verbose output goes to STDERR via
3200 # print rather than carp since it is
3201 # informational, not a warning.
3202 # --------------------------------------------------
3203 374 ▶sub _validate_module {
Subroutine _validate_module: called CC=13 SCAR=32.9
3204 374 my ($module, $schema_file) = @_;
3205  
3206 # Builtin functions have no module to validate
3207 374 ▶ return 1 unless $module;
Branch: 1 branch
BranchTrueFalseTotal
unless $module 2 372 374
3208  
3209 # Check whether the module is findable in @INC
3210 372 my $mod_info = check_install(module => $module);
3211  
3212 372 ▶ if($schema_file && !$mod_info) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema_file and not $mod_info) 21 351 372
Condition100%3/3
$schema_file and not $mod_info
!ll&&!rl&&r
2632521
MC/DC100%2/2
$schema_file and not $mod_info
$schema_file not $mod_info
Truth table100%3/3
A and not(B)
A= $schema_fileB= not $mod_info
ABresult
0X0
100
111
3213 # Non-fatal — emit a single consolidated warning so
3214 # the caller sees one message rather than four
3215 21 carp(
3216 "Module '$module' not found in \@INC during generation.\n" .
3217 " Config file: $schema_file\n" .
3218 " This is OK if the module will be available when tests run.\n" .
3219 ' If unexpected, check your module name and installation.'
3220 );
3221 21 return 0;
3222 }
3223  
3224 # Check once and reuse — avoids evaluating two env vars twice
3225 351 ▶ my $verbose = $ENV{$ENV_TEST_VERBOSE} || $ENV{$ENV_GENERATOR_VERBOSE};
Condition33%1/3
$ENV{$ENV_TEST_VERBOSE} || $ENV{$ENV_GENERATOR_VERBOSE}
l!l&&r!l&&!r
00351
MC/DC0%0/2
$ENV{$ENV_TEST_VERBOSE} || $ENV{$ENV_GENERATOR_VERBOSE}
$ENV{$ENV_TEST_VERBOSE} $ENV{$ENV_GENERATOR_VERBOSE}
Truth table33%1/3
A || B
A= $ENV{$ENV_TEST_VERBOSE}B= $ENV{$ENV_GENERATOR_VERBOSE}
ABresult
1X1
011
000
3226  
3227 351 ▶ if($verbose) {
Branch: 1 branch
BranchTrueFalseTotal
if ($verbose) 0 351 351
3228 # check_install() returns undef when the module is not in @INC, which
3229 # is normal for a schema whose module only exists when the tests run
3230 # (and when no schema file was given, the miss is not reported
3231 # above). Never read a location from a missing result: it would be
3232 # concatenated as an undefined value.
3233 0 ▶ if($mod_info) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mod_info) { } 0 0 0
3234 carp "Found module '$module' at: " .
3235 ($mod_info->{'file'} // 'an unknown location') .
3236 0 ▶ ' (version ' . ($mod_info->{'version'} || 'unknown') . ')';
Condition0%0/4
$mod_info->{"file"} // "an unknown location"
l!l
00
$mod_info->{'version'} || 'unknown'
l!l
00
MC/DC0%0/1
$mod_info->{"file"} // "an unknown location"
$mod_info->{"file"}
MC/DC0%0/1
$mod_info->{'version'} || 'unknown'
$mod_info->{'version'}
Truth table0%0/2
A
A= $mod_info->{"file"}
Aresult
11
00
Truth table0%0/2
A
A= $mod_info->{'version'}
Aresult
11
00
3237 } else {
3238 0 carp "Module '$module' is not in \@INC during generation; " .
3239 'continuing (it may be available when the tests run)';
3240 }
3241 }
3242  
3243 # Optional load validation — disabled by default because
3244 # loading a module can have side effects (e.g. BEGIN blocks,
3245 # database connections, file I/O) that are undesirable
3246 # during generation
3247 351 ▶ if($ENV{$ENV_VALIDATE_LOAD}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{$ENV_VALIDATE_LOAD}) 1 350 351
3248 1 my $loaded = can_load(modules => { $module => undef }, verbose => 0);
3249  
3250 1 ▶ if(!$loaded) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($loaded) 0 1 1
3251 0 ▶ my $err = $Module::Load::Conditional::ERROR || 'unknown error';
Condition0%0/2
$Module::Load::Conditional::ERROR || 'unknown error'
l!l
00
MC/DC0%0/1
$Module::Load::Conditional::ERROR || 'unknown error'
$Module::Load::Conditional::ERROR
Truth table0%0/2
A
A= $Module::Load::Conditional::ERROR
Aresult
11
00
3252 0 carp(
3253 "Module '$module' found but failed to load: $err\n" .
3254 ' This might indicate a broken installation or missing dependencies.'
3255 );
3256 0 return 0;
3257 }
3258  
3259 1 ▶ if($verbose) {
Branch: 1 branch
BranchTrueFalseTotal
if ($verbose) 0 1 1
3260 0 carp "Successfully loaded module '$module'";
3261 }
3262 }
3263  
3264 351 return 1;
3265 }
3266  
3267 =head2 render_fallback
3268  
3269 Render any Perl value into a compact Perl source-code string using
3270 L<Data::Dumper>. Used as a catch-all when no more specific renderer
3271 applies.
3272  
3273 my $code = render_fallback({ key => 'value' });
3274 # returns: "{'key' => 'value'}"
3275  
3276 =head3 Arguments
3277  
3278 =over 4
3279  
3280 =item * C<$v>
3281  
3282 Any Perl value, including undef, scalars, refs, and blessed objects.
3283  
3284 =back
3285  
3286 =head3 Returns
3287  
3288 A string of Perl source code that reproduces the value when evaluated.
3289 Returns the string C<'undef'> when C<$v> is undef.
3290  
3291 =head3 Side effects
3292  
3293 Temporarily sets C<$Data::Dumper::Terse> and C<$Data::Dumper::Indent>
3294 to produce compact single-line output. Both are restored on return via
3295 C<local>.
3296  
3297 =head3 Notes
3298  
3299 The output is always a single line with no trailing newline. Suitable
3300 for embedding in generated test code where readability is secondary to
3301 correctness.
3302  
3303 =head3 API SPECIFICATION
3304  
3305 =head4 input
3306  
3307 { v => { type => 'any', optional => 1 } }
3308  
3309 =head4 output
3310  
3311 { type => 'string' }
3312  
3313 The mathematical description is in L</FORMAL SPECIFICATION>.
3314  
3315 =cut
3316  
3317 85 ▶sub render_fallback {
Subroutine render_fallback: called CC=2 SCAR=6.9
Pod documented
3318 85 my $v = $_[0];
3319  
3320 # Handle undef explicitly rather than letting Dumper produce
3321 # 'undef' without the localised settings applied
3322 85 ▶ return 'undef' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 14 71 85
3323  
3324 # Use Terse+Indent=0 to produce compact single-line output
3325 # suitable for embedding in generated test code
3326 71 local $Data::Dumper::Terse = 1;
3327 71 local $Data::Dumper::Indent = 0;
3328  
3329 71 my $s = Dumper($v);
3330  
3331 # Remove trailing newline that Dumper always appends
3332 71 chomp $s;
3333 71 return $s;
3334 }
3335  
3336 =head2 render_hash
3337  
3338 Render a two-level hashref (parameter name => spec hashref) into Perl
3339 source code suitable for embedding in a generated test file as the
3340 input specification passed to L<Params::Validate::Strict>.
3341  
3342 my $code = render_hash(\%input);
3343  
3344 =head3 Arguments
3345  
3346 =over 4
3347  
3348 =item * C<$href>
3349  
3350 A hashref whose values are themselves hashrefs containing field
3351 specifications. A scalar value that is a recognised type string (see
3352 C<_valid_type>) is expanded to C<{ type =E<gt> $value }>. Any other
3353 non-hashref value is skipped with a warning.
3354  
3355 =back
3356  
3357 =head3 Returns
3358  
3359 A string of comma-separated Perl source-code lines, one per key, of
3360 the form:
3361  
3362 'key' => { subkey => value, ... }
3363  
3364 Returns an empty string if C<$href> is undef, empty, or not a hashref.
3365  
3366 =head3 Notes
3367  
3368 The C<matches> and C<nomatch> sub-keys are treated specially - their
3369 values are compiled to C<Regexp> objects via C<eval { qr/.../ }> and
3370 then rendered using C<perl_quote> so they appear as C<qr{...}> in the
3371 generated test. This prevents unmatched bracket characters in the
3372 pattern from causing compilation failures.
3373  
3374 Other sub-keys are rendered via C<perl_quote>.
3375  
3376 =head3 API SPECIFICATION
3377  
3378 =head4 input
3379  
3380 { href => { type => 'any', optional => 1 } }
3381  
3382 =head4 output
3383  
3384 { type => 'string' }
3385  
3386 The mathematical description is in L</FORMAL SPECIFICATION>.
3387  
3388 =cut
3389  
3390 # Render a nested hashref of scalars (and further hashrefs) as Perl source.
3391 # _constraint_source is such a map: constraint name => provenance.
3392 61 ▶sub _render_nested_hash {
Subroutine _render_nested_hash: called CC=4 SCAR=13.9
3393 61 my ($href) = @_;
3394  
3395 61 my @pairs;
3396 61 foreach my $key (sort keys %{$href}) {
3397 97 my $value = $href->{$key};
3398 97 ▶ next unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 97 97
3399 97 ▶ push @pairs, perl_quote($key) . ' => ' . (ref($value) eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'HASH' ? : 2 95 97
3400 ? _render_nested_hash($value)
3401 : perl_quote($value));
3402 }
3403  
3404 61 return '{ ' . join(', ', @pairs) . ' }';
3405 }
3406  
3407 394 ▶sub render_hash {
Subroutine render_hash: called CC=21 SCAR=31.3
Pod documented
3408 394 my $href = $_[0];
3409  
3410 # Return empty string for absent or non-hash input — callers
3411 # treat '' as "no input specification" in the generated test
3412 394 ▶ return '' unless $href && ref($href) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $href and ref $href eq "HASH" 5 389 394
Condition100%3/3
$href and ref $href eq "HASH"
!ll&&!rl&&r
32389
MC/DC100%2/2
$href and ref $href eq "HASH"
$href ref $href eq "HASH"
Truth table100%3/3
A and B
A= $hrefB= ref $href eq "HASH"
ABresult
0X0
100
111
3413  
3414 389 my @lines;
3415  
3416 389 for my $k (sort keys %{$href}) {
3417 354 my $def = $href->{$k};
3418  
3419 # Handle scalar shorthand — 'arg1: string' is equivalent to
3420 # 'arg1: { type: string }' and is explicitly supported by the
3421 # validation layer in _validate_input_params
3422 354 ▶ unless(defined($def) && ref($def) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $def and ref $def eq "HASH") 8 346 354
Condition66%2/3
defined $def and ref $def eq "HASH"
!ll&&!rl&&r
08346
MC/DC50%1/2
defined $def and ref $def eq "HASH"
defined $def ref $def eq "HASH"
Truth table66%2/3
A and B
A= defined $defB= ref $def eq "HASH"
ABresult
0X0
100
111
3423 8 ▶ if(defined($def) && !ref($def) && _valid_type($def)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $def and not ref $def and _valid_type($def)) { } 4 4 8
Condition50%3/6
defined $def and not ref $def and _valid_type($def)
!ll&&!rl&&r
044
defined $def and not ref $def
!ll&&!rl&&r
008
MC/DC33%1/3
defined $def and not ref $def and _valid_type($def)
defined $def not ref $def _valid_type($def)
Truth table50%2/4
A and not(B) and C
A= defined $defB= not ref $defC= _valid_type($def)
ABCresult
0XX0
10X0
1100
1111
3424 # Expand scalar type shorthand to a full spec hashref
3425 4 $def = { type => $def };
3426 } else {
3427 4 carp "render_hash: skipping key '$k' — value is not a hashref or recognised type string";
3428 4 next;
3429 }
3430 }
3431  
3432 350 my @pairs;
3433  
3434 350 for my $subk (sort keys %{$def}) {
3435 # Skip undef sub-values — they contribute nothing to the spec
3436 1362 ▶ next unless defined $def->{$subk};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $def->{$subk} 1 1361 1362
3437  
3438 # Validate that reference types are ones we can render. A nested
3439 # hashref of scalars (such as _constraint_source) is rendered as a
3440 # nested Perl hash literal.
3441 1361 ▶ if(ref($def->{$subk})) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $def->{$subk}) 79 1282 1361
3442 79 ▶ unless((ref($def->{$subk}) eq 'ARRAY') ||
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $def->{$subk} eq "ARRAY" or ref $def->{$subk} eq "Regexp" or ref $def->{$subk} eq "HASH") 0 79 79
Condition83%5/6
ref $def->{$subk} eq "ARRAY" or ref $def->{$subk} eq "Regexp" or ref $def->{$subk} eq "HASH"
l!l&&r!l&&!r
20590
ref $def->{$subk} eq "ARRAY" or ref $def->{$subk} eq "Regexp"
l!l&&r!l&&!r
15559
MC/DC0%0/3
ref $def->{$subk} eq "ARRAY" or ref $def->{$subk} eq "Regexp" or ref $def->{$subk} eq "HASH"
ref $def->{$subk} eq "ARRAY" ref $def->{$subk} eq "Regexp" ref $def->{$subk} eq "HASH"
Truth table75%3/4
A or B or C
A= ref $def->{$subk} eq "ARRAY"B= ref $def->{$subk} eq "Regexp"C= ref $def->{$subk} eq "HASH"
ABCresult
1XX1
01X1
0011
0000
3443 (ref($def->{$subk}) eq 'Regexp') ||
3444 (ref($def->{$subk}) eq 'HASH')) {
3445 croak(
3446 __PACKAGE__,
3447 ": $subk is a nested element, not yet supported (",
3448 0 ref($def->{$subk}), ')'
3449 );
3450 }
3451 }
3452  
3453 # matches and nomatch values must be Regexp objects in the
3454 # generated test — compile raw strings safely via eval so
3455 # patterns containing [ or \ don't cause compile failures
3456 1361 ▶ if(($subk eq $KEY_MATCHES) || ($subk eq $KEY_NOMATCH)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($subk eq $KEY_MATCHES or $subk eq $KEY_NOMATCH) { } 18 1343 1361
elsif (ref $def->{$subk} eq 'HASH') { } 59 1284 1343
Condition100%3/3
$subk eq $KEY_MATCHES or $subk eq $KEY_NOMATCH
l!l&&r!l&&!r
1711343
MC/DC100%2/2
$subk eq $KEY_MATCHES or $subk eq $KEY_NOMATCH
$subk eq $KEY_MATCHES $subk eq $KEY_NOMATCH
Truth table100%3/3
A or B
A= $subk eq $KEY_MATCHESB= $subk eq $KEY_NOMATCH
ABresult
1X1
011
000
3457 my $re = ref($def->{$subk}) eq 'Regexp'
3458 ? $def->{$subk}
3459 18 ▶ : eval { qr/$def->{$subk}/ };
Branch: 1 branch
BranchTrueFalseTotal
ref $def->{$subk} eq 'Regexp' ? : 5 13 18
3460 18 ▶ if($@ || !defined($re)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not defined $re) 0 18 18
Condition33%1/3
$@ or not defined $re
l!l&&r!l&&!r
0018
MC/DC0%0/2
$@ or not defined $re
$@ not defined $re
Truth table33%1/3
A or not(B)
A= $@B= not defined $re
ABresult
1X1
011
000
3461 0 carp "render_hash: invalid $subk pattern '$def->{$subk}': $@";
3462 0 next;
3463 }
3464 18 push @pairs, "$subk => " . perl_quote($re);
3465 } elsif(ref($def->{$subk}) eq 'HASH') {
3466 59 push @pairs, "$subk => " . _render_nested_hash($def->{$subk});
3467 } else {
3468 # All other sub-keys are rendered via perl_quote which
3469 # handles scalars, arrayrefs, and Regexp objects correctly
3470 1284 push @pairs, "$subk => " . perl_quote($def->{$subk});
3471 }
3472 }
3473  
3474 # Use "\t" rather than a literal tab for clarity and grep-ability
3475 350 push @lines, "\t" . perl_quote($k) . ' => { ' . join(', ', @pairs) . ' }';
3476 }
3477  
3478 389 return join(",\n", @lines);
3479 }
3480  
3481 =head2 render_args_hash
3482  
3483 Render a flat hashref into a Perl source-code argument list of the
3484 form C<'key' => value, ...>, suitable for embedding in a function call
3485 in a generated test file.
3486  
3487 my $code = render_args_hash({ type => 'string', min => 1 });
3488 # returns: "'min' => 1, 'type' => 'string'"
3489  
3490 =head3 Arguments
3491  
3492 =over 4
3493  
3494 =item * C<$href>
3495  
3496 A flat hashref of key-value pairs. Values may be scalars, arrayrefs,
3497 or Regexp objects - all are handled by C<perl_quote>.
3498  
3499 =back
3500  
3501 =head3 Returns
3502  
3503 A comma-separated string of C<key => value> pairs sorted by key.
3504 Returns an empty string if C<$href> is undef, empty, or not a hashref.
3505  
3506 =head3 Notes
3507  
3508 Keys and values are both rendered via C<perl_quote>. In particular,
3509 C<Regexp> values are rendered as C<qr{...}> which is correct for
3510 L<Params::Validate::Strict> and L<Return::Set> schema arguments in
3511 the generated test.
3512  
3513 =head3 API SPECIFICATION
3514  
3515 =head4 input
3516  
3517 { href => { type => 'any', optional => 1 } }
3518  
3519 =head4 output
3520  
3521 { type => 'string' }
3522  
3523 The mathematical description is in L</FORMAL SPECIFICATION>.
3524  
3525 =cut
3526  
3527 570 ▶sub render_args_hash {
Subroutine render_args_hash: called CC=3 SCAR=11.0
Pod documented
3528 570 my $href = $_[0];
3529  
3530 # Return empty string for absent or non-hash input
3531 570 ▶ return '' unless $href && ref($href) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $href and ref $href eq "HASH" 12 558 570
Condition100%3/3
$href and ref $href eq "HASH"
!ll&&!rl&&r
39558
MC/DC100%2/2
$href and ref $href eq "HASH"
$href ref $href eq "HASH"
Truth table100%3/3
A and B
A= $hrefB= ref $href eq "HASH"
ABresult
0X0
100
111
3532  
3533 # Sort keys for deterministic output across runs — important for
3534 # generated test files that are committed to version control
3535 my @pairs = map {
3536 619 perl_quote($_) . ' => ' . perl_quote($href->{$_})
3537 558 } sort keys %{$href};
3538  
3539 558 return join(', ', @pairs);
3540 }
3541  
3542 =head2 render_arrayref_map
3543  
3544 Render a hashref whose values are arrayrefs into a Perl source-code
3545 fragment suitable for use as a hash literal in a generated test file.
3546  
3547 my $code = render_arrayref_map({ name => ['', 'a' x 100] });
3548  
3549 =head3 Arguments
3550  
3551 =over 4
3552  
3553 =item * C<$href>
3554  
3555 A hashref whose values are arrayrefs. Keys whose values are not
3556 arrayrefs are silently skipped.
3557  
3558 =back
3559  
3560 =head3 Returns
3561  
3562 A comma-separated string of C<'key' => [ val, ... ]> entries, one per
3563 qualifying key, sorted alphabetically. Returns the string C<'()'> if
3564 C<$href> is undef or not a hashref - this produces an empty
3565 hash assignment in the generated test rather than a syntax error.
3566 Returns an empty string if C<$href> is a hashref with no arrayref values.
3567  
3568 =head3 Notes
3569  
3570 Array element values are rendered via C<perl_quote> which handles
3571 scalars, arrayrefs, and Regexp objects. Non-arrayref values are
3572 skipped without warning - this is intentional since callers may pass
3573 mixed-value hashes and only want the arrayref entries rendered.
3574  
3575 =head3 API SPECIFICATION
3576  
3577 =head4 input
3578  
3579 { href => { type => 'any', optional => 1 } }
3580  
3581 =head4 output
3582  
3583 { type => 'string' }
3584  
3585 The mathematical description is in L</FORMAL SPECIFICATION>.
3586  
3587 =cut
3588  
3589 865 ▶sub render_arrayref_map {
Subroutine render_arrayref_map: called CC=5 SCAR=16.1
Pod documented
3590 865 my $href = $_[0];
3591  
3592 # Return '()' rather than '' so callers get a valid empty hash
3593 # literal rather than a syntax error in the generated test
3594 865 ▶ return '()' unless $href && ref($href) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $href and ref $href eq "HASH" 11 854 865
Condition100%3/3
$href and ref $href eq "HASH"
!ll&&!rl&&r
38854
MC/DC100%2/2
$href and ref $href eq "HASH"
$href ref $href eq "HASH"
Truth table100%3/3
A and B
A= $hrefB= ref $href eq "HASH"
ABresult
0X0
100
111
3595  
3596 854 my @entries;
3597  
3598 854 for my $k (sort keys %{$href}) {
3599 10 my $aref = $href->{$k};
3600  
3601 # Skip non-arrayref values — mixed hashes are allowed by callers
3602 10 ▶ next unless ref($aref) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $aref eq "ARRAY" 3 7 10
3603  
3604 # Render each array element via perl_quote so strings are
3605 # properly quoted and numbers are left unquoted
3606 7 my $vals = join(', ', map { perl_quote($_) } @{$aref});
3607  
3608 # Use "\t" rather than a literal tab for clarity
3609 7 push @entries, "\t" . perl_quote($k) . " => [ $vals ]";
3610 }
3611  
3612 854 return join(",\n", @entries);
3613 }
3614  
3615 # --------------------------------------------------
3616 # _has_positions
3617 #
3618 # Purpose: Determine whether any field in an input
3619 # spec hashref declares a positional argument
3620 # via the 'position' key.
3621 #
3622 # Entry: $input_spec - the input section of a parsed
3623 # schema, expected to be a hashref whose values
3624 # are themselves hashrefs containing field specs.
3625 # May be undef or a non-hash ref.
3626 #
3627 # Exit: Returns 1 if any field has a defined
3628 # 'position' key, 0 otherwise.
3629 #
3630 # Notes: Returns 0 immediately for undef or non-hash
3631 # input rather than throwing — callers use the
3632 # return value as a boolean and do not expect
3633 # exceptions from this function.
3634 # --------------------------------------------------
3635 447 ▶sub _has_positions {
Subroutine _has_positions: called CC=6 SCAR=17.9
3636 447 my $input_spec = $_[0];
3637  
3638 # Guard against undef or non-hash input — keys %$undef would throw
3639 447 ▶ return 0 unless defined($input_spec) && ref($input_spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input_spec and ref $input_spec eq "HASH" 4 443 447
Condition100%3/3
defined $input_spec and ref $input_spec eq "HASH"
!ll&&!rl&&r
31443
MC/DC100%2/2
defined $input_spec and ref $input_spec eq "HASH"
defined $input_spec ref $input_spec eq "HASH"
Truth table100%3/3
A and B
A= defined $input_specB= ref $input_spec eq "HASH"
ABresult
0X0
100
111
3640  
3641 443 for my $field (keys %{$input_spec}) {
3642 # Only examine fields whose spec is a hashref — scalar specs
3643 # (e.g. input: { type: string }) cannot have positions
3644 389 ▶ next unless ref($input_spec->{$field}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $input_spec->{$field} eq "HASH" 53 336 389
3645  
3646 # Return immediately on first match — no need to scan further
3647 336 ▶ return 1 if defined $input_spec->{$field}{position};
Branch: 1 branch
BranchTrueFalseTotal
if defined $input_spec->{$field}{"position"} 211 125 336
3648 }
3649  
3650 # No positional arguments found in any field
3651 232 return 0;
3652 }
3653  
3654 # --------------------------------------------------
3655 # q_wrap
3656 #
3657 # Purpose: Wrap a string in the most readable
3658 # q{} form that does not require escaping,
3659 # falling back to single-quoted form with
3660 # escaped apostrophes if no delimiter is
3661 # available.
3662 #
3663 # Entry: $s - the string to wrap. May be undef.
3664 # Exit: Returns a Perl source-code fragment that
3665 # evaluates to the original string value,
3666 # or the string 'undef' if $s is undef.
3667 #
3668 # Notes: index() returns -1 when not found and
3669 # any value >= 0 when found, including 0
3670 # for a delimiter at the start of the
3671 # string. We compare against $INDEX_NOT_FOUND
3672 # to make this boundary explicit and to
3673 # prevent off-by-one mutation survivors.
3674 # See GitHub issue #1.
3675 # --------------------------------------------------
3676 382 ▶sub q_wrap {
Subroutine q_wrap: called CC=7 SCAR=19.5
Pod undocumented
3677 382 my $s = $_[0];
3678  
3679 382 ▶ croak('q_wrap: argument must be a plain string, not a reference') if ref($s);
Branch: 1 branch
BranchTrueFalseTotal
if ref $s 0 382 382
3680  
3681 # Return empty string for undef — this function is a low-level
3682 # string quoter only. Callers that need the Perl literal 'undef'
3683 # for undefined values should use perl_quote() instead, which
3684 # handles the undef -> 'undef' semantic conversion correctly.
3685 # Returning '' here preserves the original behaviour and avoids
3686 # injecting the bare word 'undef' into contexts that expect a
3687 # quoted string value.
3688 382 ▶ return "''" unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 3 379 382
3689  
3690 # Try bracket-form q{} delimiters first — most readable
3691 379 for my $p (@Q_BRACKET_PAIRS) {
3692 396 my ($l, $r) = @{$p};
3693  
3694 # Only use this bracket pair if neither bracket
3695 # appears in the string — both must be checked
3696 396 ▶ return "q$l$s$r" unless $s =~ /\Q$l\E|\Q$r\E/;
Branch: 1 branch
BranchTrueFalseTotal
unless $s =~ /\Q$l\E|\Q$r\E/u 375 21 396
3697 }
3698  
3699 # Try single-character delimiters in preference order
3700 4 for my $d (@Q_SINGLE_DELIMITERS) {
3701 # index() returns $INDEX_NOT_FOUND (-1) when not found.
3702 # Must use != $INDEX_NOT_FOUND rather than > 0 since
3703 # the delimiter may legitimately appear at position 0
3704 26 ▶ return "q$d$s$d" if index($s, $d) == $INDEX_NOT_FOUND;
Branch: 1 branch
BranchTrueFalseTotal
if index($s, $d) == $INDEX_NOT_FOUND 2 24 26
3705 }
3706  
3707 # Last resort — single-quoted string with escaped apostrophes
3708 2 (my $esc = $s) =~ s/'/\\'/g;
3709 2 return "'$esc'";
3710 }
3711  
3712 # --------------------------------------------------
3713 # perl_sq
3714 #
3715 # Purpose: Escape a string for safe inclusion
3716 # inside a single-quoted Perl string
3717 # literal in generated test code.
3718 #
3719 # Entry: $s - the string to escape.
3720 # Exit: Returns the escaped string, or an
3721 # empty string if $s is undef.
3722 #
3723 # Notes: NUL byte replacement produces the
3724 # two-character sequence \0 which is
3725 # only correct when the result is used
3726 # inside a double-quoted string context
3727 # in the generated test.
3728 #
3729 # The \b substitution (backspace) is
3730 # intentionally omitted — in Perl regex
3731 # context \b means word boundary, not
3732 # backspace, so substituting it here
3733 # would corrupt strings containing word
3734 # boundaries.
3735 # --------------------------------------------------
3736 2697 ▶sub perl_sq {
Subroutine perl_sq: called CC=3 SCAR=11.0
Pod undocumented
3737 2697 my $s = $_[0];
3738  
3739 2697 ▶ croak('perl_sq: argument must be a plain string, not a reference') if ref($s);
Branch: 1 branch
BranchTrueFalseTotal
if ref $s 0 2697 2697
3740  
3741 # Return empty string for undef — callers that need
3742 # 'undef' literal should use perl_quote instead
3743 2697 ▶ return '' unless defined $s;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $s 2 2695 2697
3744  
3745 # Escape backslashes first so later substitutions
3746 # don't double-escape already-escaped sequences
3747 2695 $s =~ s/\\/\\\\/g;
3748  
3749 # Escape apostrophes so they don't terminate the
3750 # surrounding single-quoted string literal
3751 2695 $s =~ s/'/\\'/g;
3752  
3753 # Escape common control characters to their
3754 # printable two-character escape sequences
3755 2695 $s =~ s/\n/\\n/g;
3756 2695 $s =~ s/\r/\\r/g;
3757 2695 $s =~ s/\t/\\t/g;
3758 2695 $s =~ s/\f/\\f/g;
3759  
3760 # Replace NUL bytes with \0 — valid only in
3761 # double-quoted string context in generated code
3762 2695 $s =~ s/\0/\\0/g;
3763  
3764 2695 return $s;
3765 }
3766  
3767 =head2 perl_quote
3768  
3769 Convert any Perl value into a source-code fragment that reproduces that value
3770 when evaluated in a generated test file.
3771  
3772 =head3 Arguments
3773  
3774 =over 4
3775  
3776 =item * C<$v>
3777  
3778 Any Perl value. May be undef, a scalar, an arrayref, a Regexp, or a blessed
3779 object. All types are handled - undef becomes C<'undef'>, the strings
3780 C<'true'>/C<'false'> become the Perl boolean constants C<!!1>/C<!!0>,
3781 numbers are unquoted, other strings are single-quoted, arrayrefs recurse,
3782 Regexps become C<qr{...}>, and anything else (including hashrefs and
3783 blessed objects) falls through to C<render_fallback>.
3784  
3785 =back
3786  
3787 =head3 API SPECIFICATION
3788  
3789 =head4 input
3790  
3791 { v => { type => 'any', optional => 1 } }
3792  
3793 =head4 output
3794  
3795 { type => 'string' }
3796  
3797 The mathematical description is in L</FORMAL SPECIFICATION>.
3798  
3799 =cut
3800  
3801 3191 ▶sub perl_quote {
Subroutine perl_quote: called CC=1 SCAR=0.0
Pod documented
3802 3191 my ($v) = @_;
3803 3191 return _perl_quote($v, 0);
3804 }
3805  
3806 3366 ▶sub _perl_quote {
Subroutine _perl_quote: called CC=10 SCAR=23.0
3807 3366 my ($v, $depth) = @_;
3808 226 ▶ no warnings 'recursion'; ## no critic (TestingAndDebugging::ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
3809 3366 ▶ croak('perl_quote: structure too deeply nested (circular reference?)') if $depth > 100;
Branch: 1 branch
BranchTrueFalseTotal
if $depth > 100 1 3365 3366
3810  
3811 # Undef produces the Perl literal 'undef'
3812 3365 ▶ return 'undef' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 5 3360 3365
3813  
3814 # Convert YAML boolean string literals to Perl
3815 # boolean constants so they survive round-tripping
3816 3360 ▶ return '!!1' if $v eq 'true';
Branch: 1 branch
BranchTrueFalseTotal
if $v eq "true" 3 3357 3360
3817 3357 ▶ return '!!0' if $v eq 'false';
Branch: 1 branch
BranchTrueFalseTotal
if $v eq "false" 5 3352 3357
3818  
3819 3352 ▶ if(ref($v)) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v) 206 3146 3352
3820 # Recursively quote each element of an arrayref
3821 206 ▶ if(ref($v) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq "ARRAY") 128 78 206
3822 128 my @quoted_v = map { _perl_quote($_, $depth + 1) } @{$v};
3823 27 return '[ ' . join(', ', @quoted_v) . ' ]';
3824 }
3825  
3826 # Render Regexp objects as qr{} with modifiers
3827 78 ▶ if(ref($v) eq 'Regexp') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq "Regexp") 27 51 78
3828 27 my ($pat, $mods) = regexp_pattern($v);
3829 27 my $re = "qr{$pat}";
3830  
3831 # Append modifiers (e.g. 'i', 'x') if present
3832 27 ▶ $re .= $mods if $mods;
Branch: 1 branch
BranchTrueFalseTotal
if $mods 18 9 27
3833 27 return $re;
3834 }
3835  
3836 # Hashrefs and other reference types fall through
3837 # to render_fallback which uses Data::Dumper
3838 51 return render_fallback($v);
3839 }
3840  
3841 # Numeric values are emitted unquoted so the generated
3842 # test performs numeric rather than string comparison
3843 3146 ▶ return looks_like_number($v) ? $v : "'" . perl_sq($v) . "'";
Branch: 1 branch
BranchTrueFalseTotal
&looks_like_number($v) ? : 727 2419 3146
3844 }
3845  
3846 # --------------------------------------------------
3847 # _generate_transform_properties
3848 #
3849 # Convert a hashref of transform
3850 # specifications into an arrayref of
3851 # LectroTest property definition hashrefs,
3852 # one per transform. Each hashref contains
3853 # all the information needed by
3854 # _render_properties to emit a runnable
3855 # Test::LectroTest property block.
3856 #
3857 # Entry: $transforms - hashref of transform name
3858 # => transform spec, as
3859 # loaded from the schema.
3860 # $function - name of the function under
3861 # test.
3862 # $module - module name, or undef for
3863 # builtin functions.
3864 # $input - the top-level input spec
3865 # hashref from the schema
3866 # (used for position sorting).
3867 # $config - the normalised config
3868 # hashref, used to read
3869 # properties.trials.
3870 # $new - defined if the function is
3871 # an object method; the value
3872 # is not used here since
3873 # property tests always
3874 # construct a fresh object
3875 # via new_ok() with no args.
3876 # Presence vs absence is the
3877 # only signal used.
3878 #
3879 # Exit: Returns an arrayref of property hashrefs.
3880 # Returns an empty arrayref if no transforms
3881 # produce any testable properties.
3882 # Never returns undef.
3883 #
3884 # Notes: Transforms whose input is the string
3885 # 'undef' or whose input spec is not a
3886 # hashref are silently skipped — they
3887 # represent error-case transforms that have
3888 # no meaningful generator.
3889 #
3890 # The 'WARN' vs 'WARNS' distinction in
3891 # _STATUS: the schema convention uses
3892 # 'WARNS' throughout. This function checks
3893 # for 'WARNS' to match that convention.
3894 # --------------------------------------------------
3895 12 ▶sub _generate_transform_properties {
Subroutine _generate_transform_properties: called CC=22 SCAR=33.3
3896 12 my ($transforms, $function, $module, $input, $config, $new) = @_;
3897  
3898 12 my @properties;
3899  
3900 12 for my $transform_name (sort keys %{$transforms}) {
3901 # $transform_name is spliced by _render_properties as a Perl
3902 # *variable name* (my $$transform_name = Property {...}), not
3903 # just inside a string literal — reject anything that isn't
3904 # identifier-shaped before it reaches that point.
3905 15 _assert_identifier($transform_name, 'transform name');
3906  
3907 14 my $transform = $transforms->{$transform_name};
3908  
3909 14 my $input_spec = $transform->{input};
3910  
3911 # Guard: skip transforms with no input or with the
3912 # YAML scalar 'undef' as their input — these have no
3913 # generator and cannot produce meaningful properties
3914 14 ▶ if(!defined($input_spec) ||
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $input_spec or not ref $input_spec and $input_spec eq "undef") 2 12 14
Condition83%5/6
not defined $input_spec or not ref $input_spec and $input_spec eq "undef"
l!l&&r!l&&!r
1112
not ref $input_spec and $input_spec eq "undef"
!ll&&!rl&&r
1201
MC/DC66%2/3
not defined $input_spec or not ref $input_spec and $input_spec eq "undef"
not defined $input_spec not ref $input_spec $input_spec eq "undef"
Truth table75%3/4
not(A) or not(B) and C
A= not defined $input_specB= not ref $input_specC= $input_spec eq "undef"
ABCresult
1XX1
0111
00X0
0100
3915 (!ref($input_spec) && $input_spec eq 'undef')) {
3916 2 next;
3917 }
3918  
3919 # Guard: skip transforms whose input is not a hashref —
3920 # must come before the helper calls below so we never
3921 # pass a non-hash to _detect_transform_properties or
3922 # _process_custom_properties
3923 12 ▶ next unless ref($input_spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $input_spec eq "HASH" 1 11 12
3924  
3925 # Default output spec to empty hash so _STATUS lookups
3926 # below are always safe regardless of schema content
3927 11 ▶ my $output_spec = $transform->{output} // {};
Condition50%1/2
$transform->{"output"} // {}
l!l
110
MC/DC0%0/1
$transform->{"output"} // {}
$transform->{"output"}
Truth table50%1/2
A
A= $transform->{"output"}
Aresult
11
00
3928  
3929 # Detect automatic properties from the transform spec
3930 # (range constraints, type preservation, definedness)
3931 11 my @detected_props = _detect_transform_properties(
3932 $transform_name,
3933 $input_spec,
3934 $output_spec
3935 );
3936  
3937 # Process any custom properties defined in the schema
3938 11 my @custom_props = ();
3939 11 ▶ if(exists($transform->{properties}) &&
Branch: 1 branch
BranchTrueFalseTotal
if (exists $transform->{"properties"} and ref $transform->{"properties"} eq "ARRAY") 0 11 11
Condition33%1/3
exists $transform->{"properties"} and ref $transform->{"properties"} eq "ARRAY"
!ll&&!rl&&r
1100
MC/DC0%0/2
exists $transform->{"properties"} and ref $transform->{"properties"} eq "ARRAY"
exists $transform->{"properties"} ref $transform->{"properties"} eq "ARRAY"
Truth table33%1/3
A and B
A= exists $transform->{"properties"}B= ref $transform->{"properties"} eq "ARRAY"
ABresult
0X0
100
111
3940 ref($transform->{properties}) eq 'ARRAY') {
3941 @custom_props = _process_custom_properties(
3942 $transform->{properties},
3943 0 $function,
3944 $module,
3945 $input_spec,
3946 $output_spec,
3947 $new
3948 );
3949 }
3950  
3951 # Combine auto-detected and custom properties into one list
3952 11 my @all_props = (@detected_props, @custom_props);
3953  
3954 # Skip this transform if no properties were produced —
3955 # nothing useful to render into the generated test
3956 11 ▶ next unless @all_props;
Branch: 1 branch
BranchTrueFalseTotal
unless @all_props 0 11 11
3957  
3958 # Build the LectroTest generator specification string,
3959 # one entry per input field that has a generator
3960 11 my @generators;
3961 my @var_names;
3962  
3963 11 for my $field (sort keys %{$input_spec}) {
3964 11 my $spec = $input_spec->{$field};
3965  
3966 # Skip non-hashref field specs — scalar types
3967 # like 'string' have no generator sub-structure
3968 11 ▶ next unless ref($spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 11 11
3969  
3970 # $field is spliced unescaped into the generated
3971 # LectroTest generator spec by
3972 # _schema_to_lectrotest_generator() — reject anything
3973 # that isn't identifier-shaped first.
3974 11 _assert_identifier($field, 'input field name');
3975  
3976 11 my $gen = _schema_to_lectrotest_generator($field, $spec);
3977 11 ▶ if(defined($gen) && length($gen)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $gen and length $gen) 11 0 11
Condition33%1/3
defined $gen and length $gen
!ll&&!rl&&r
0011
MC/DC0%0/2
defined $gen and length $gen
defined $gen length $gen
Truth table33%1/3
A and B
A= defined $genB= length $gen
ABresult
0X0
100
111
3978 11 push @generators, $gen;
3979 11 push @var_names, $field;
3980 }
3981 }
3982  
3983 11 my $gen_spec = join(', ', @generators);
3984  
3985 # Build the call expression for the function under test.
3986 # Note: property tests always construct a fresh object
3987 # via new_ok() with no constructor arguments, regardless
3988 # of what $new holds in the caller — the intent here is
3989 # to test the method in isolation, not with specific
3990 # construction state.
3991 11 my $call_code;
3992 11 ▶ if($module && defined($new)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($module and defined $new) { } 1 10 11
elsif ($module and $module ne $MODULE_BUILTIN) { } 0 10 10
Condition66%2/3
$module and defined $new
!ll&&!rl&&r
1001
MC/DC50%1/2
$module and defined $new
$module defined $new
Truth table66%2/3
A and B
A= $moduleB= defined $new
ABresult
0X0
100
111
3993 # OO mode — construct a fresh object for each trial
3994 1 $call_code = "my \$obj = new_ok('$module');";
3995 1 $call_code .= "\$obj->$function";
3996 ▶ } elsif($module && $module ne $MODULE_BUILTIN) {
Condition33%1/3
$module and $module ne $MODULE_BUILTIN
!ll&&!rl&&r
1000
MC/DC0%0/2
$module and $module ne $MODULE_BUILTIN
$module $module ne $MODULE_BUILTIN
Truth table33%1/3
A and B
A= $moduleB= $module ne $MODULE_BUILTIN
ABresult
0X0
100
111
3997 # Functional mode with a named module
3998 0 $call_code = "$module\::$function";
3999 } else {
4000 # Builtin or unqualified function call
4001 10 $call_code = $function;
4002 }
4003  
4004 # Build the argument list, respecting positional order
4005 # if the input spec declares positions
4006 11 my @args;
4007 11 ▶ if(_has_positions($input_spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_has_positions($input_spec)) { } 11 0 11
4008 # Sort fields by declared position so the generated
4009 # call passes arguments in the correct order
4010 my @sorted = sort {
4011 $input_spec->{$a}{position} <=>
4012 $input_spec->{$b}{position}
4013 0 } keys %{$input_spec};
4014 11 @args = map { "\$$_" } @sorted;
4015 } else {
4016 # No positions — use alphabetical order from @var_names
4017 0 @args = map { "\$$_" } @var_names;
4018 }
4019  
4020 11 my $args_str = join(', ', @args);
4021  
4022 # Concatenate all property check expressions with &&
4023 # so the generated property block passes only when
4024 # every check holds
4025 11 my @checks = map { $_->{code} } @all_props;
4026 11 my $property_checks = join(" &&\n\t", @checks);
4027  
4028 # Determine expected behaviour from output _STATUS.
4029 # Note: the schema convention uses 'WARNS' not 'WARN'
4030 11 ▶ my $should_die = ($output_spec->{'_STATUS'} // '') eq 'DIES';
Condition100%2/2
$output_spec->{"_STATUS"} // ""
l!l
110
MC/DC100%1/1
$output_spec->{"_STATUS"} // ""
$output_spec->{"_STATUS"}
Truth table100%2/2
A
A= $output_spec->{"_STATUS"}
Aresult
11
00
4031 11 ▶ my $should_warn = ($output_spec->{'_STATUS'} // '') eq 'WARNS';
Condition100%2/2
$output_spec->{"_STATUS"} // ""
l!l
110
MC/DC100%1/1
$output_spec->{"_STATUS"} // ""
$output_spec->{"_STATUS"}
Truth table100%2/2
A
A= $output_spec->{"_STATUS"}
Aresult
11
00
4032  
4033 push @properties, {
4034 name => $transform_name,
4035 generator_spec => $gen_spec,
4036 call_code => "$call_code($args_str)",
4037 property_checks => $property_checks,
4038 should_die => $should_die,
4039 should_warn => $should_warn,
4040 11 ▶ trials => $config->{'properties'}{'trials'} // $DEFAULT_PROPERTY_TRIALS,
Condition33%1/3
$config->{"properties"}{"trials"} // $DEFAULT_PROPERTY_TRIALS
l!l&&r!l&&!r
1100
MC/DC0%0/2
$config->{"properties"}{"trials"} // $DEFAULT_PROPERTY_TRIALS
$config->{"properties"}{"trials"} $DEFAULT_PROPERTY_TRIALS
Truth table33%1/3
A // B
A= $config->{"properties"}{"trials"}B= $DEFAULT_PROPERTY_TRIALS
ABresult
1X1
011
000
4041 };
4042 }
4043  
4044 11 return \@properties;
4045 }
4046  
4047 # --------------------------------------------------
4048 # _get_semantic_generators
4049 #
4050 # Return a hashref of named semantic
4051 # generator definitions for use in
4052 # LectroTest property-based tests.
4053 # Each entry contains a 'code' key
4054 # holding a Gen {} block string and a
4055 # 'description' key for documentation
4056 # and validation messages.
4057 #
4058 # Entry: None.
4059 #
4060 # Exit: Returns a hashref keyed by semantic
4061 # type name. Each value is a hashref
4062 # with 'code' and 'description' keys.
4063 #
4064 # Notes: The returned hashref is built fresh
4065 # on every call — callers that need it
4066 # repeatedly should cache the result.
4067 # The 'code' strings are multi-line
4068 # Gen {} blocks; callers are responsible
4069 # for compressing whitespace before
4070 # embedding them in generated test files.
4071 # --------------------------------------------------
4072 320 ▶sub _get_semantic_generators {
Subroutine _get_semantic_generators: called CC=1 SCAR=0.0
4073 return {
4074 320 email => {
4075 code => q{
4076 Gen {
4077 my $len = 5 + int(rand(10));
4078 my @addr;
4079 my @tlds = qw(com org net edu gov io co uk de fr);
4080  
4081 for(my $i = 0; $i < $len; $i++) {
4082 push @addr, pack('c', (int(rand 26))+97);
4083 }
4084 push @addr, '@';
4085 $len = 5 + int(rand(10));
4086 for(my $i = 0; $i < $len; $i++) {
4087 push @addr, pack('c', (int(rand 26))+97);
4088 }
4089 push @addr, '.';
4090 $len = rand($#tlds+1);
4091 push @addr, $tlds[$len];
4092 return join('', @addr);
4093 }
4094 },
4095 description => 'Valid email addresses',
4096 }, url => {
4097 code => q{
4098 Gen {
4099 my @schemes = qw(http https);
4100 my @tlds = qw(com org net io);
4101 my $scheme = $schemes[int(rand(@schemes))];
4102 my $domain = join('', map { ('a'..'z')[int(rand(26))] } 1..(5 + int(rand(10))));
4103 my $tld = $tlds[int(rand(@tlds))];
4104 my $path = join('', map { ('a'..'z', '0'..'9', '-', '_')[int(rand(38))] } 1..int(rand(20)));
4105  
4106 return "$scheme://$domain.$tld" . ($path ? "/$path" : '');
4107 }
4108 },
4109 description => 'Valid HTTP/HTTPS URLs',
4110 }, uuid => {
4111 code => q{
4112 Gen {
4113 require UUID::Tiny;
4114 UUID::Tiny::create_uuid_as_string(UUID::Tiny::UUID_V4());
4115 }
4116 },
4117 description => 'Valid UUIDv4 identifiers',
4118 }, phone_us => {
4119 code => q{
4120 Gen {
4121 my $area = 200 + int(rand(800));
4122 my $exchange = 200 + int(rand(800));
4123 my $subscriber = int(rand(10000));
4124 sprintf('%03d-%03d-%04d', $area, $exchange, $subscriber);
4125 }
4126 },
4127 description => 'US phone numbers (XXX-XXX-XXXX format)',
4128 }, phone_e164 => {
4129 code => q{
4130 Gen {
4131 my $country = 1 + int(rand(999));
4132 my $area = 100 + int(rand(900));
4133 my $number = int(rand(10000000));
4134 sprintf('+%d%03d%07d', $country, $area, $number);
4135 }
4136 },
4137 description => 'E.164 international phone numbers',
4138 }, ipv4 => {
4139 code => q{
4140 Gen {
4141 join('.', map { int(rand(256)) } 1..4);
4142 }
4143 },
4144 description => 'IPv4 addresses',
4145 }, ipv6 => {
4146 code => q{
4147 Gen {
4148 join(':', map { sprintf('%04x', int(rand(0x10000))) } 1..8);
4149 }
4150 },
4151 description => 'IPv6 addresses',
4152 }, username => {
4153 code => q{
4154 Gen {
4155 my $len = 3 + int(rand(13));
4156 my @chars = ('a'..'z', '0'..'9', '_', '-');
4157 my $first = ('a'..'z')[int(rand(26))];
4158 $first . join('', map { $chars[int(rand(@chars))] } 1..($len-1));
4159 }
4160 },
4161 description => 'Valid usernames (alphanumeric with _ and -)',
4162 }, slug => {
4163 code => q{
4164 Gen {
4165 my @words = qw(quick brown fox jumps over lazy dog hello world test data);
4166 my $count = 1 + int(rand(4));
4167 join('-', map { $words[int(rand(@words))] } 1..$count);
4168 }
4169 },
4170 description => 'URL slugs (lowercase words separated by hyphens)',
4171 }, hex_color => {
4172 code => q{
4173 Gen {
4174 sprintf('#%06x', int(rand(0x1000000)));
4175 }
4176 },
4177 description => 'Hex color codes (#RRGGBB)',
4178 }, iso_date => {
4179 code => q{
4180 Gen {
4181 my $year = 2000 + int(rand(25));
4182 my $month = 1 + int(rand(12));
4183 my $day = 1 + int(rand(28));
4184 sprintf('%04d-%02d-%02d', $year, $month, $day);
4185 }
4186 },
4187 description => 'ISO 8601 date format (YYYY-MM-DD)',
4188 },
4189 iso_datetime => {
4190 code => q{
4191 Gen {
4192 my $year = 2000 + int(rand(25));
4193 my $month = 1 + int(rand(12));
4194 my $day = 1 + int(rand(28));
4195 my $hour = int(rand(24));
4196 my $minute = int(rand(60));
4197 my $second = int(rand(60));
4198 sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',
4199 $year, $month, $day, $hour, $minute, $second);
4200 }
4201 },
4202 description => 'ISO 8601 datetime format (YYYY-MM-DDTHH:MM:SSZ)',
4203 }, semver => {
4204 code => q{
4205 Gen {
4206 my $major = int(rand(10));
4207 my $minor = int(rand(20));
4208 my $patch = int(rand(50));
4209 "$major.$minor.$patch";
4210 }
4211 },
4212 description => 'Semantic version strings (major.minor.patch)',
4213 }, jwt => {
4214 code => q{
4215 Gen {
4216 my @chars = ('A'..'Z', 'a'..'z', '0'..'9', '-', '_');
4217 my $header = join('', map { $chars[int(rand(@chars))] } 1..20);
4218 my $payload = join('', map { $chars[int(rand(@chars))] } 1..40);
4219 my $signature = join('', map { $chars[int(rand(@chars))] } 1..30);
4220 "$header.$payload.$signature";
4221 }
4222 },
4223 description => 'JWT-like tokens (base64url format)',
4224 }, json => {
4225 code => q{
4226 Gen {
4227 my @keys = qw(id name value status count);
4228 my $key = $keys[int(rand(@keys))];
4229 my $value = 1 + int(rand(1000));
4230 qq({"$key":$value});
4231 }
4232 },
4233 description => 'Simple JSON objects',
4234 }, base64 => {
4235 code => q{
4236 Gen {
4237 my @chars = ('A'..'Z', 'a'..'z', '0'..'9', '+', '/');
4238 my $len = 12 + int(rand(20));
4239 my $str = join('', map { $chars[int(rand(@chars))] } 1..$len);
4240 $str .= '=' x (4 - ($len % 4)) if $len % 4;
4241 $str;
4242 }
4243 },
4244 description => 'Base64-encoded strings',
4245 }, md5 => {
4246 code => q{
4247 Gen {
4248 join('', map { sprintf('%x', int(rand(16))) } 1..32);
4249 }
4250 },
4251 description => 'MD5 hashes (32 hex characters)',
4252 }, sha256 => {
4253 code => q{
4254 Gen {
4255 join('', map { sprintf('%x', int(rand(16))) } 1..64);
4256 }
4257 },
4258 description => 'SHA-256 hashes (64 hex characters)',
4259 }, directory => {
4260 code => q{
4261 Gen {
4262 require File::Temp;
4263 File::Temp::tempdir(CLEANUP => 1);
4264 }
4265 },
4266 description => 'Paths to existing writable directories',
4267 }, existing_file => {
4268 code => q{
4269 Gen {
4270 require File::Temp;
4271 my ($fh, $path) = File::Temp::tempfile(SUFFIX => '.pm', UNLINK => 1);
4272 close $fh;
4273 $path;
4274 }
4275 },
4276 description => 'Paths to existing files',
4277 }, unix_timestamp => {
4278 code => q{
4279 Gen {
4280 time;
4281 }
4282 },
4283 description => 'Unix timestamps (seconds since epoch)',
4284 },
4285 };
4286 }
4287  
4288 # --------------------------------------------------
4289 # _get_builtin_properties
4290 #
4291 # Purpose: Return a hashref of named built-in
4292 # property templates that can be
4293 # referenced by name in a transform's
4294 # 'properties' list in the schema.
4295 # Each entry contains a 'description'
4296 # string, a 'code_template' coderef, and
4297 # an 'applicable_to' arrayref.
4298 #
4299 # Entry: None.
4300 #
4301 # Exit: Returns a hashref keyed by property
4302 # name. Each value is a hashref with
4303 # 'description', 'code_template', and
4304 # 'applicable_to' keys.
4305 #
4306 # Notes: 'applicable_to' lists the types for
4307 # which each property is meaningful. It
4308 # is stored for documentation purposes
4309 # and potential future filtering — it is
4310 # not currently enforced by any caller.
4311 #
4312 # Each 'code_template' coderef receives
4313 # three arguments: ($function, $call_code,
4314 # $input_vars). Most templates use only
4315 # $call_code; $function and $input_vars
4316 # are provided for templates that need
4317 # them (e.g. idempotent, length_preserved,
4318 # preserves_keys).
4319 #
4320 # 'monotonic_increasing' has been
4321 # intentionally omitted. A correct
4322 # implementation requires calling the
4323 # function twice with ordered inputs,
4324 # which the current single-call property
4325 # framework does not support. A
4326 # placeholder that unconditionally returns
4327 # true would give false confidence and has
4328 # therefore been removed.
4329 # --------------------------------------------------
4330 32 ▶sub _get_builtin_properties {
Subroutine _get_builtin_properties: called CC=1 SCAR=0.0
4331 return {
4332 idempotent => {
4333 description => 'Function is idempotent: f(f(x)) == f(x)',
4334 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4335 2 my ($function, $call_code, $input_vars) = @_;
4336  
4337 # String comparison works for all scalar types in Perl —
4338 # numeric values stringify consistently for eq
4339 2 return "do { my \$tmp = $call_code; \$result eq \$tmp }";
4340 },
4341 applicable_to => ['all'],
4342 }, non_negative => {
4343 description => 'Result is always non-negative',
4344 3 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4345 3 my ($function, $call_code, $input_vars) = @_;
4346 3 return '$result >= 0';
4347 },
4348 applicable_to => ['number', 'integer', 'float'],
4349 }, positive => {
4350 description => 'Result is always positive (> 0)',
4351 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4352 2 my ($function, $call_code, $input_vars) = @_;
4353 2 return '$result > 0';
4354 },
4355 applicable_to => ['number', 'integer', 'float'],
4356 }, non_empty => {
4357 description => 'Result is never empty',
4358 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4359 2 my ($function, $call_code, $input_vars) = @_;
4360 2 return 'length($result) > 0';
4361 },
4362 applicable_to => ['string'],
4363 },
4364  
4365 length_preserved => {
4366 description => 'Output length equals input length',
4367 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4368 2 my ($function, $call_code, $input_vars) = @_;
4369 2 my $first_var = $input_vars->[0];
4370 2 return "length(\$result) == length(\$$first_var)";
4371 },
4372 applicable_to => ['string'],
4373 },
4374  
4375 uppercase => {
4376 description => 'Result is all uppercase',
4377 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4378 2 my ($function, $call_code, $input_vars) = @_;
4379 2 return '$result eq uc($result)';
4380 },
4381 applicable_to => ['string'],
4382 },
4383  
4384 lowercase => {
4385 description => 'Result is all lowercase',
4386 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4387 2 my ($function, $call_code, $input_vars) = @_;
4388 2 return '$result eq lc($result)';
4389 },
4390 applicable_to => ['string'],
4391 },
4392  
4393 trimmed => {
4394 description => 'Result has no leading or trailing whitespace',
4395 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4396 2 my ($function, $call_code, $input_vars) = @_;
4397 2 return '$result !~ /^\s/ && $result !~ /\s$/';
4398 },
4399 applicable_to => ['string'],
4400 },
4401  
4402 sorted_ascending => {
4403 description => 'Array is sorted in ascending order',
4404 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4405 2 my ($function, $call_code, $input_vars) = @_;
4406 2 return 'do { my @arr = @$result; my $sorted = 1; ' .
4407 'for my $i (1..$#arr) { $sorted = 0 if $arr[$i] < $arr[$i-1]; } ' .
4408 '$sorted }';
4409 },
4410 applicable_to => ['arrayref'],
4411 },
4412  
4413 sorted_descending => {
4414 description => 'Array is sorted in descending order',
4415 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4416 2 my ($function, $call_code, $input_vars) = @_;
4417 2 return 'do { my @arr = @$result; my $sorted = 1; ' .
4418 'for my $i (1..$#arr) { $sorted = 0 if $arr[$i] > $arr[$i-1]; } ' .
4419 '$sorted }';
4420 },
4421 applicable_to => ['arrayref'],
4422 },
4423  
4424 unique_elements => {
4425 description => 'Array has no duplicate elements',
4426 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4427 2 my ($function, $call_code, $input_vars) = @_;
4428 2 return 'do { my @arr = @$result; my %seen; !grep { $seen{$_}++ } @arr }';
4429 },
4430 applicable_to => ['arrayref'],
4431 },
4432  
4433 preserves_keys => {
4434 description => 'Hash has same keys as input',
4435 2 ▶ code_template => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
4436 2 my ($function, $call_code, $input_vars) = @_;
4437 2 my $first_var = $input_vars->[0];
4438 2 return 'do { my @in = sort keys %{$' . $first_var . '}; ' .
4439 'my @out = sort keys %$result; ' .
4440 'join(",", @in) eq join(",", @out) }';
4441 },
4442 32 applicable_to => ['hashref'],
4443 },
4444 };
4445 }
4446  
4447 # --------------------------------------------------
4448 # _schema_to_lectrotest_generator
4449 #
4450 # Purpose: Convert a single schema field spec
4451 # hashref into a LectroTest generator
4452 # declaration string of the form
4453 # '$field <- Generator(...)'.
4454 # Used to build the ##[ ... ]## generator
4455 # block inside a Property definition.
4456 #
4457 # Entry: $field_name - the parameter name as it
4458 # will appear in the
4459 # generated test code.
4460 # $spec - hashref containing at
4461 # minimum a 'type' key.
4462 # May also contain 'min',
4463 # 'max', 'semantic', and
4464 # 'matches' keys depending
4465 # on type.
4466 #
4467 # Exit: Returns a string of the form
4468 # '$field <- Generator(...)' on success.
4469 # Returns undef if the spec is not a
4470 # hashref or if range constraints are
4471 # invalid (min >= max for numeric types).
4472 # Returns a String generator with a carp
4473 # warning for unknown types.
4474 #
4475 # Side effects: Carps on unknown semantic types,
4476 # invalid numeric ranges, and unknown
4477 # field types.
4478 #
4479 # Notes: Semantic generators are checked first
4480 # for string fields and take precedence
4481 # over the regular string generator.
4482 # The $input_spec parameter in the type-
4483 # detection helpers is reserved for future
4484 # use and is currently unused.
4485 # --------------------------------------------------
4486 55 ▶sub _schema_to_lectrotest_generator {
Subroutine _schema_to_lectrotest_generator: called CC=40 SCAR=37.2
4487 55 my ($field_name, $spec) = @_;
4488  
4489 # Guard: must be a hashref to dereference safely
4490 55 ▶ return unless defined($spec) && ref($spec) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and ref $spec eq "HASH" 3 52 55
Condition100%3/3
defined $spec and ref $spec eq "HASH"
!ll&&!rl&&r
2152
MC/DC100%2/2
defined $spec and ref $spec eq "HASH"
defined $spec ref $spec eq "HASH"
Truth table100%3/3
A and B
A= defined $specB= ref $spec eq "HASH"
ABresult
0X0
100
111
4491  
4492 # Default to string when no type is declared
4493 52 ▶ my $type = $spec->{'type'} || $DEFAULT_FIELD_TYPE;
Condition33%1/3
$spec->{'type'} || $DEFAULT_FIELD_TYPE
l!l&&r!l&&!r
5200
MC/DC0%0/2
$spec->{'type'} || $DEFAULT_FIELD_TYPE
$spec->{'type'} $DEFAULT_FIELD_TYPE
Truth table33%1/3
A || B
A= $spec->{'type'}B= $DEFAULT_FIELD_TYPE
ABresult
1X1
011
000
4494  
4495 # --------------------------------------------------
4496 # Semantic generators take precedence for string
4497 # fields — they produce realistic domain-specific
4498 # values rather than random character sequences
4499 # --------------------------------------------------
4500 52 ▶ if($type eq 'string' && defined($spec->{'semantic'})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "string" and defined $spec->{"semantic"}) 1 51 52
Condition100%3/3
$type eq "string" and defined $spec->{"semantic"}
!ll&&!rl&&r
41101
MC/DC100%2/2
$type eq "string" and defined $spec->{"semantic"}
$type eq "string" defined $spec->{"semantic"}
Truth table100%3/3
A and B
A= $type eq "string"B= defined $spec->{"semantic"}
ABresult
0X0
100
111
4501 1 my $semantic_type = $spec->{'semantic'};
4502 1 my $generators = _get_semantic_generators();
4503  
4504 1 ▶ if(exists($generators->{$semantic_type})) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $generators->{$semantic_type}) { } 1 0 1
4505 1 my $gen_code = $generators->{$semantic_type}{'code'};
4506  
4507 # Compress the multi-line generator code into a
4508 # single line for embedding in the ##[ ]## block
4509 1 $gen_code =~ s/^\s+//;
4510 1 $gen_code =~ s/\s+$//;
4511 1 $gen_code =~ s/\n\s+/ /g;
4512  
4513 1 return "$field_name <- $gen_code";
4514 } else {
4515 0 carp "Unknown semantic type '$semantic_type', " .
4516 "falling back to regular string generator";
4517 # Fall through to regular string generation below
4518 }
4519 }
4520  
4521 # --------------------------------------------------
4522 # Integer generator
4523 # --------------------------------------------------
4524 51 ▶ if($type eq 'integer') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "integer") 10 41 51
4525 10 my $min = $spec->{'min'};
4526 10 my $max = $spec->{'max'};
4527  
4528 10 ▶ if(!defined($min) && !defined($max)) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $min || defined $max) { } 4 6 10
elsif (not defined $min) { } 1 5 6
elsif (not defined $max) { } 1 4 5
Condition100%3/3
defined $min || defined $max
l!l&&r!l&&!r
514
MC/DC100%2/2
defined $min || defined $max
defined $min defined $max
Truth table100%3/3
A || B
A= defined $minB= defined $max
ABresult
1X1
011
000
4529 # Unconstrained — use LectroTest's built-in Int
4530 4 return "$field_name <- Int";
4531 } elsif(!defined($min)) {
4532 # Only max defined — generate 0 to max
4533 1 return "$field_name <- Int(sized => sub { int(rand($max + 1)) })";
4534 } elsif(!defined($max)) {
4535 # Only min defined — generate min to min + range
4536 1 return "$field_name <- Int(sized => sub { $min + int(rand($DEFAULT_GENERATOR_RANGE)) })";
4537 } else {
4538 # Both defined — generate within [min, max]
4539 4 my $range = $max - $min;
4540 4 return "$field_name <- Int(sized => sub { $min + int(rand($range + 1)) })";
4541 }
4542 }
4543  
4544 # --------------------------------------------------
4545 # Float / number generator
4546 # --------------------------------------------------
4547 41 ▶ if($type eq 'number' || $type eq 'float') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "number" or $type eq "float") 23 18 41
Condition100%3/3
$type eq "number" or $type eq "float"
l!l&&r!l&&!r
111218
MC/DC100%2/2
$type eq "number" or $type eq "float"
$type eq "number" $type eq "float"
Truth table100%3/3
A or B
A= $type eq "number"B= $type eq "float"
ABresult
1X1
011
000
4548 23 my $min = $spec->{'min'};
4549 23 my $max = $spec->{'max'};
4550  
4551 23 ▶ if(!defined($min) && !defined($max)) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $min || defined $max) { } 3 20 23
elsif (not defined $min) { } 8 12 20
elsif (not defined $max) { } 7 5 12
Condition100%3/3
defined $min || defined $max
l!l&&r!l&&!r
1283
MC/DC100%2/2
defined $min || defined $max
defined $min defined $max
Truth table100%3/3
A || B
A= defined $minB= defined $max
ABresult
1X1
011
000
4552 # Unconstrained — symmetric range around zero
4553 3 return "$field_name <- Float(sized => sub { rand($DEFAULT_GENERATOR_RANGE) - $DEFAULT_GENERATOR_RANGE / 2 })";
4554  
4555 } elsif(!defined($min)) {
4556 # Only max defined — choose range based on sign of max
4557 8 ▶ if($max == $ZERO_BOUNDARY) {
Branch: 2 branches
BranchTrueFalseTotal
if ($max == $ZERO_BOUNDARY) { } 6 2 8
elsif ($max > $ZERO_BOUNDARY) { } 1 1 2
4558 # max=0: negative numbers only
4559 6 return "$field_name <- Float(sized => sub { -rand($DEFAULT_GENERATOR_RANGE) })";
4560 } elsif($max > $ZERO_BOUNDARY) {
4561 # Positive max: generate 0 to max
4562 1 return "$field_name <- Float(sized => sub { rand($max) })";
4563 } else {
4564 # Negative max: generate from (max - range) to max
4565 1 return "$field_name <- Float(sized => sub { ($max - $DEFAULT_GENERATOR_RANGE) + rand($DEFAULT_GENERATOR_RANGE + $max) })";
4566 }
4567  
4568 } elsif(!defined($max)) {
4569 # Only min defined — choose range based on sign of min
4570 7 ▶ if($min == $ZERO_BOUNDARY) {
Branch: 2 branches
BranchTrueFalseTotal
if ($min == $ZERO_BOUNDARY) { } 5 2 7
elsif ($min > $ZERO_BOUNDARY) { } 1 1 2
4571 # min=0: positive numbers only
4572 5 return "$field_name <- Float(sized => sub { rand($DEFAULT_GENERATOR_RANGE) })";
4573 } elsif($min > $ZERO_BOUNDARY) {
4574 # Positive min: generate min to min + range
4575 1 return "$field_name <- Float(sized => sub { $min + rand($DEFAULT_GENERATOR_RANGE) })";
4576 } else {
4577 # Negative min: generate from min to min + range
4578 1 return "$field_name <- Float(sized => sub { $min + rand(-$min + $DEFAULT_GENERATOR_RANGE) })";
4579 }
4580  
4581 } else {
4582 # Both min and max defined — validate then generate
4583 5 my $range = $max - $min;
4584 5 ▶ if($range <= $ZERO_BOUNDARY) {
Branch: 1 branch
BranchTrueFalseTotal
if ($range <= $ZERO_BOUNDARY) 4 1 5
4585 4 carp "Invalid range for '$field_name': min=$min, max=$max";
4586 # Return undef rather than emitting a degenerate
4587 # generator that would silently produce wrong values
4588 4 return;
4589 }
4590 1 return "$field_name <- Float(sized => sub { $min + rand($range) })";
4591 }
4592 }
4593  
4594 # --------------------------------------------------
4595 # String generator
4596 # --------------------------------------------------
4597 18 ▶ if($type eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "string") 10 8 18
4598 10 ▶ my $min_len = $spec->{'min'} // 0;
Condition100%2/2
$spec->{"min"} // 0
l!l
28
MC/DC100%1/1
$spec->{"min"} // 0
$spec->{"min"}
Truth table100%2/2
A
A= $spec->{"min"}
Aresult
11
00
4599 10 ▶ my $max_len = $spec->{'max'} // $DEFAULT_MAX_STRING_LEN;
Condition100%3/3
$spec->{"max"} // $DEFAULT_MAX_STRING_LEN
l!l&&r!l&&!r
244
MC/DC100%2/2
$spec->{"max"} // $DEFAULT_MAX_STRING_LEN
$spec->{"max"} $DEFAULT_MAX_STRING_LEN
Truth table100%3/3
A // B
A= $spec->{"max"}B= $DEFAULT_MAX_STRING_LEN
ABresult
1X1
011
000
4600  
4601 # If a regex pattern is declared, delegate to
4602 # Data::Random::String::Matches for pattern-aware generation
4603 10 ▶ if(defined($spec->{'matches'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $spec->{"matches"}) 6 4 10
4604 6 my $pattern = $spec->{'matches'};
4605  
4606 # Compile the pattern safely rather than splicing the raw
4607 # string into qr/$pattern/ — the raw form lets a pattern
4608 # containing an unescaped '/' break out of the qr//
4609 # delimiter and inject arbitrary Perl into the generated
4610 # test. regexp_pattern() decomposes the already-compiled
4611 # Regexp object back into pattern text that is guaranteed
4612 # to be a self-contained regex body, safe to re-embed.
4613 6 ▶ my $compiled = ref($pattern) eq 'Regexp' ? $pattern : eval { qr/$pattern/ };
Branch: 1 branch
BranchTrueFalseTotal
ref $pattern eq 'Regexp' ? : 3 3 6
4614 6 ▶ if($@ || !defined($compiled)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not defined $compiled) 0 6 6
Condition33%1/3
$@ or not defined $compiled
l!l&&r!l&&!r
006
MC/DC0%0/2
$@ or not defined $compiled
$@ not defined $compiled
Truth table33%1/3
A or not(B)
A= $@B= not defined $compiled
ABresult
1X1
011
000
4615 0 carp "Invalid matches pattern '$pattern' for field '$field_name': $@";
4616 0 return "$field_name <- String(length => [$min_len, $max_len])";
4617 }
4618 6 my ($pat, $mods) = regexp_pattern($compiled);
4619 6 ▶ my $safe_re = "qr{$pat}" . ($mods // '');
Condition50%1/2
$mods // ""
l!l
60
MC/DC0%0/1
$mods // ""
$mods
Truth table50%1/2
A
A= $mods
Aresult
11
00
4620  
4621 6 ▶ if(defined($spec->{'max'})) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $spec->{'max'}) { } 1 5 6
elsif (defined $spec->{'min'}) { } 1 4 5
4622 1 return "$field_name <- Gen { Data::Random::String::Matches->create_random_string({ regex => $safe_re, length => $spec->{'max'} }) }";
4623 } elsif(defined($spec->{'min'})) {
4624 1 return "$field_name <- Gen { Data::Random::String::Matches->create_random_string({ regex => $safe_re, length => $spec->{'min'} }) }";
4625 } else {
4626 4 return "$field_name <- Gen { Data::Random::String::Matches->create_random_string({ regex => $safe_re }) }";
4627 }
4628 }
4629  
4630 4 return "$field_name <- String(length => [$min_len, $max_len])";
4631 }
4632  
4633 # --------------------------------------------------
4634 # Boolean generator
4635 # --------------------------------------------------
4636 8 ▶ if($type eq 'boolean') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "boolean") 2 6 8
4637 2 return "$field_name <- Bool";
4638 }
4639  
4640 # --------------------------------------------------
4641 # Arrayref generator
4642 # --------------------------------------------------
4643 6 ▶ if($type eq 'arrayref') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "arrayref") 2 4 6
4644 2 ▶ my $min_size = $spec->{'min'} // 0;
Condition50%1/2
$spec->{"min"} // 0
l!l
02
MC/DC0%0/1
$spec->{"min"} // 0
$spec->{"min"}
Truth table50%1/2
A
A= $spec->{"min"}
Aresult
11
00
4645 2 ▶ my $max_size = $spec->{'max'} // $DEFAULT_MAX_COLLECTION_SIZE;
Condition33%1/3
$spec->{"max"} // $DEFAULT_MAX_COLLECTION_SIZE
l!l&&r!l&&!r
002
MC/DC0%0/2
$spec->{"max"} // $DEFAULT_MAX_COLLECTION_SIZE
$spec->{"max"} $DEFAULT_MAX_COLLECTION_SIZE
Truth table33%1/3
A // B
A= $spec->{"max"}B= $DEFAULT_MAX_COLLECTION_SIZE
ABresult
1X1
011
000
4646 2 return "$field_name <- List(Int, length => [$min_size, $max_size])";
4647 }
4648  
4649 # --------------------------------------------------
4650 # Hashref generator
4651 # LectroTest has no built-in Hash generator so we
4652 # use Elements over a pre-built list of hashrefs
4653 # --------------------------------------------------
4654 4 ▶ if($type eq 'hashref') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "hashref") 3 1 4
4655 3 ▶ my $min_keys = $spec->{'min'} // 0;
Condition100%2/2
$spec->{"min"} // 0
l!l
21
MC/DC100%1/1
$spec->{"min"} // 0
$spec->{"min"}
Truth table100%2/2
A
A= $spec->{"min"}
Aresult
11
00
4656 3 ▶ my $max_keys = $spec->{'max'} // $DEFAULT_MAX_COLLECTION_SIZE;
Condition66%2/3
$spec->{"max"} // $DEFAULT_MAX_COLLECTION_SIZE
l!l&&r!l&&!r
201
MC/DC50%1/2
$spec->{"max"} // $DEFAULT_MAX_COLLECTION_SIZE
$spec->{"max"} $DEFAULT_MAX_COLLECTION_SIZE
Truth table66%2/3
A // B
A= $spec->{"max"}B= $DEFAULT_MAX_COLLECTION_SIZE
ABresult
1X1
011
000
4657 3 return "$field_name <- Elements(map { my \%h; for (1..\$_) { \$h{'key'.\$_} = \$_ }; \\\%h } $min_keys..$max_keys)";
4658 }
4659  
4660 # --------------------------------------------------
4661 # Unknown type — fall back to String with a warning
4662 # --------------------------------------------------
4663 1 carp "Unknown type '$type' for '$field_name' LectroTest generator, using String";
4664 1 return "$field_name <- String";
4665 }
4666  
4667 # --------------------------------------------------
4668 # _is_numeric_transform
4669 #
4670 # Determine whether a transform's output
4671 # spec declares a numeric type, indicating
4672 # that numeric range properties should be
4673 # generated for it.
4674 #
4675 # Entry: $input_spec - the transform's input
4676 # spec hashref. Currently
4677 # unused; reserved for
4678 # future input-type checks.
4679 # $output_spec - the transform's output
4680 # spec hashref.
4681 #
4682 # Exit: Returns 1 if the output type is one of
4683 # 'number', 'integer', or 'float'.
4684 # Returns 0 otherwise.
4685 # --------------------------------------------------
4686 39 ▶sub _is_numeric_transform {
Subroutine _is_numeric_transform: called CC=5 SCAR=16.1
4687 39 my ($input_spec, $output_spec) = @_;
4688  
4689 # $input_spec is currently unused — reserved for future
4690 # input-side type checking when detecting mixed transforms
4691 39 ▶ my $out_type = ($output_spec // {})->{'type'} // '';
Condition100%4/4
+($output_spec // {})->{"type"} // ""
l!l
345
$output_spec // {}
l!l
372
MC/DC100%1/1
+($output_spec // {})->{"type"} // ""
$output_spec
Truth table100%2/2
A
A= $output_spec
Aresult
11
00
4692  
4693 39 ▶ return($out_type eq 'number' || $out_type eq 'integer' || $out_type eq 'float');
Condition100%6/6
$out_type eq 'number' || $out_type eq 'integer' || $out_type eq 'float'
l!l&&r!l&&!r
21216
$out_type eq "number" or $out_type eq "integer"
l!l&&r!l&&!r
17418
MC/DC100%3/3
$out_type eq 'number' || $out_type eq 'integer' || $out_type eq 'float'
$out_type eq "number" $out_type eq "integer" $out_type eq 'float'
Truth table100%4/4
A or B || C
A= $out_type eq "number"B= $out_type eq "integer"C= $out_type eq 'float'
ABCresult
1XX1
01X1
0011
0000
4694 }
4695  
4696 # --------------------------------------------------
4697 # _is_string_transform
4698 #
4699 # Purpose: Determine whether a transform's output
4700 # spec declares a string type, indicating
4701 # that string length and pattern properties
4702 # should be generated for it.
4703 #
4704 # Entry: $input_spec - the transform's input
4705 # spec hashref. Currently
4706 # unused; reserved for
4707 # future input-type checks.
4708 # $output_spec - the transform's output
4709 # spec hashref.
4710 #
4711 # Exit: Returns 1 if the output type is 'string'.
4712 # Returns 0 otherwise.
4713 # --------------------------------------------------
4714 33 ▶sub _is_string_transform {
Subroutine _is_string_transform: called CC=3 SCAR=11.0
4715 33 my ($input_spec, $output_spec) = @_;
4716  
4717 # $input_spec is currently unused — reserved for future
4718 # input-side type checking when detecting mixed transforms
4719 33 ▶ my $out_type = ($output_spec // {})->{'type'} // '';
Condition100%4/4
+($output_spec // {})->{"type"} // ""
l!l
294
$output_spec // {}
l!l
321
MC/DC100%1/1
+($output_spec // {})->{"type"} // ""
$output_spec
Truth table100%2/2
A
A= $output_spec
Aresult
11
00
4720  
4721 33 return($out_type eq 'string');
4722 }
4723  
4724 # --------------------------------------------------
4725 # _same_type
4726 #
4727 # Purpose: Determine whether the dominant type of
4728 # a transform's input and output specs
4729 # match, indicating that type-preservation
4730 # properties are meaningful.
4731 #
4732 # Entry: $input_spec - the transform's input
4733 # spec hashref, or a nested
4734 # multi-field hashref.
4735 # $output_spec - the transform's output
4736 # spec hashref.
4737 #
4738 # Exit: Returns 1 if the dominant input and
4739 # output types are identical strings.
4740 # Returns 0 otherwise.
4741 #
4742 # Notes: Uses _get_dominant_type for both sides.
4743 # For multi-field input specs, dominant
4744 # type is the type of the first field
4745 # encountered — this is a simplification.
4746 # TODO: extend to handle mixed-type inputs
4747 # by checking all fields, not just the
4748 # first one found.
4749 # --------------------------------------------------
4750 33 ▶sub _same_type {
Subroutine _same_type: called CC=3 SCAR=11.0
4751 33 my ($input_spec, $output_spec) = @_;
4752  
4753 # Guard: treat missing specs as untyped — two untyped
4754 # specs both default to $DEFAULT_FIELD_TYPE and would
4755 # compare equal, which is intentionally conservative
4756 33 ▶ my $in_type = _get_dominant_type($input_spec // {});
Condition100%2/2
$input_spec // {}
l!l
312
MC/DC100%1/1
$input_spec // {}
$input_spec
Truth table100%2/2
A
A= $input_spec
Aresult
11
00
4757 33 ▶ my $out_type = _get_dominant_type($output_spec // {});
Condition100%2/2
$output_spec // {}
l!l
312
MC/DC100%1/1
$output_spec // {}
$output_spec
Truth table100%2/2
A
A= $output_spec
Aresult
11
00
4758  
4759 33 return($in_type eq $out_type);
4760 }
4761  
4762 # --------------------------------------------------
4763 # _get_dominant_type
4764 #
4765 # Purpose: Extract the most representative type
4766 # string from a spec hashref. For flat
4767 # output specs this is simply the 'type'
4768 # key. For multi-field input specs it is
4769 # the type of the first sub-field found
4770 # that declares one.
4771 #
4772 # Entry: $spec - a spec hashref. May be a flat
4773 # output spec ({ type => '...' })
4774 # or a multi-field input spec
4775 # ({ field => { type => '...' } }).
4776 # May be undef or empty.
4777 #
4778 # Exit: Returns a type string. Returns
4779 # $DEFAULT_FIELD_TYPE ('string') if no
4780 # type can be determined.
4781 # --------------------------------------------------
4782 99 ▶sub _get_dominant_type {
Subroutine _get_dominant_type: called CC=7 SCAR=19.5
4783 99 my $spec = $_[0];
4784  
4785 # Guard: return default for undef or non-hash input
4786 99 ▶ return $DEFAULT_FIELD_TYPE
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec and ref $spec eq "HASH" 2 97 99
Condition66%2/3
defined $spec and ref $spec eq "HASH"
!ll&&!rl&&r
2097
MC/DC50%1/2
defined $spec and ref $spec eq "HASH"
defined $spec ref $spec eq "HASH"
Truth table66%2/3
A and B
A= defined $specB= ref $spec eq "HASH"
ABresult
0X0
100
111
4787 unless defined($spec) && ref($spec) eq 'HASH';
4788  
4789 # Flat spec — type declared directly
4790 97 ▶ return $spec->{'type'} if defined($spec->{'type'});
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{"type"} 59 38 97
4791  
4792 # Multi-field spec — return the type of the first
4793 # sub-field that declares one
4794 38 for my $field (keys %{$spec}) {
4795 33 ▶ next unless ref($spec->{$field}) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec->{$field} eq "HASH" 2 31 33
4796 return $spec->{$field}{'type'}
4797 31 ▶ if defined($spec->{$field}{'type'});
Branch: 1 branch
BranchTrueFalseTotal
if defined $spec->{$field}{"type"} 30 1 31
4798 }
4799  
4800 # No type found anywhere — return the safe default
4801 8 return $DEFAULT_FIELD_TYPE;
4802 }
4803  
4804 # --------------------------------------------------
4805 # _render_properties
4806 #
4807 # Purpose: Render an arrayref of property definition
4808 # hashrefs (as produced by
4809 # _generate_transform_properties) into a
4810 # string of Perl source code suitable for
4811 # embedding in a generated test file.
4812 # The output uses Test::LectroTest::Compat
4813 # to run each property as a holds() check.
4814 #
4815 # Entry: $properties - arrayref of property
4816 # hashrefs, each containing: name,
4817 # generator_spec, call_code,
4818 # property_checks, should_die,
4819 # should_warn, trials.
4820 # May be undef or an empty arrayref.
4821 #
4822 # Exit: Returns a string of Perl source code.
4823 # Returns an empty string if $properties
4824 # is undef, not an arrayref, or empty.
4825 #
4826 # Notes: The generated code uses 4-space
4827 # indentation deliberately — this is the
4828 # indentation style of the generated test
4829 # file, not of this module. Tabs are used
4830 # in this module's own source; spaces are
4831 # emitted into generated output for
4832 # readability of the produced test files.
4833 # --------------------------------------------------
4834 13 ▶sub _render_properties {
Subroutine _render_properties: called CC=6 SCAR=17.9
4835 13 my $properties = $_[0];
4836  
4837 # Return empty string for absent or non-array input —
4838 # callers treat '' as no property block to emit
4839 13 ▶ return '' unless defined($properties) && ref($properties) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $properties and ref $properties eq "ARRAY" 3 10 13
Condition100%3/3
defined $properties and ref $properties eq "ARRAY"
!ll&&!rl&&r
2110
MC/DC100%2/2
defined $properties and ref $properties eq "ARRAY"
defined $properties ref $properties eq "ARRAY"
Truth table100%3/3
A and B
A= defined $propertiesB= ref $properties eq "ARRAY"
ABresult
0X0
100
111
4840 10 ▶ return '' unless @{$properties};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$properties;} 2 8 10
4841  
4842 8 my $code = "use_ok('Test::LectroTest::Compat');\n\n";
4843  
4844 8 for my $prop (@{$properties}) {
4845 # Emit a labelled Property block for each transform property
4846 12 $code .= "# Transform property: $prop->{'name'}\n";
4847 12 $code .= "my \$$prop->{'name'} = Property {\n";
4848 12 $code .= " ##[ $prop->{'generator_spec'} ]##\n";
4849 12 $code .= " \n";
4850 12 $code .= " my \$result = eval { $prop->{'call_code'} };\n";
4851  
4852 12 ▶ if($prop->{'should_die'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prop->{'should_die'}) { } 2 10 12
4853 # For transforms that expect death, pass if the
4854 # eval caught an exception
4855 2 $code .= " my \$died = defined(\$\@) && \$\@;\n";
4856 2 $code .= " \$died;\n";
4857 } else {
4858 # For normal transforms, pass only if no exception
4859 # was thrown and all property checks hold
4860 10 $code .= " my \$error = \$\@;\n";
4861 10 $code .= " \n";
4862 10 $code .= " !\$error && (\n";
4863 10 $code .= " $prop->{'property_checks'}\n";
4864 10 $code .= " );\n";
4865 }
4866  
4867 12 $code .= "}, name => '$prop->{'name'}', trials => $prop->{'trials'};\n\n";
4868 12 $code .= "holds(\$$prop->{'name'});\n";
4869 }
4870  
4871 8 return $code;
4872 }
4873  
4874 # --------------------------------------------------
4875 # _detect_transform_properties
4876 #
4877 # Purpose: Automatically derive a list of testable
4878 # LectroTest property hashrefs from a
4879 # transform's input and output specs.
4880 # Detects numeric range constraints, exact
4881 # value matches, string length constraints,
4882 # type preservation, and definedness.
4883 #
4884 # Entry: $transform_name - string name of the
4885 # transform, used for
4886 # heuristic matching
4887 # (e.g. 'positive').
4888 # $input_spec - the transform's input
4889 # hashref, or the string
4890 # 'undef'.
4891 # $output_spec - the transform's output
4892 # hashref, or undef if
4893 # absent.
4894 #
4895 # Exit: Returns a list of property hashrefs,
4896 # each containing 'name' and 'code' keys.
4897 # Returns an empty list if no properties
4898 # can be detected or if $input_spec is
4899 # undef or the string 'undef'.
4900 #
4901 # Notes: The 'positive' heuristic checks the
4902 # transform name case-insensitively against
4903 # $TRANSFORM_POSITIVE_PATTERN and adds a
4904 # non-negative constraint if matched.
4905 # This is intentionally a rough heuristic
4906 # rather than a precise semantic check.
4907 # --------------------------------------------------
4908 30 ▶sub _detect_transform_properties {
Subroutine _detect_transform_properties: called CC=25 SCAR=36.1
4909 30 my ($transform_name, $input_spec, $output_spec) = @_;
4910  
4911 30 my @properties;
4912  
4913 # Guard: skip undef input and the YAML scalar 'undef'
4914 30 ▶ return @properties unless defined($input_spec);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input_spec 2 28 30
4915 28 ▶ return @properties if(!ref($input_spec) && $input_spec eq 'undef');
Branch: 1 branch
BranchTrueFalseTotal
if not ref $input_spec and $input_spec eq "undef" 2 26 28
Condition66%2/3
not ref $input_spec and $input_spec eq "undef"
!ll&&!rl&&r
2602
MC/DC50%1/2
not ref $input_spec and $input_spec eq "undef"
not ref $input_spec $input_spec eq "undef"
Truth table66%2/3
not(A) and B
A= not ref $input_specB= $input_spec eq "undef"
ABresult
0X0
100
111
4916  
4917 # Default output spec to empty hash so all key lookups
4918 # below are safe regardless of what the schema provides
4919 26 ▶ $output_spec //= {};
Condition50%1/2
$output_spec //= {}
l!l
260
MC/DC0%0/1
$output_spec //= {}
$output_spec
Truth table50%1/2
A
A= $output_spec
Aresult
11
00
4920  
4921 # --------------------------------------------------
4922 # Property 1: Output range constraints (numeric)
4923 # --------------------------------------------------
4924 26 ▶ if(_is_numeric_transform($input_spec, $output_spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_numeric_transform($input_spec, $output_spec)) 17 9 26
4925 17 ▶ if(defined($output_spec->{'min'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output_spec->{"min"}) 13 4 17
4926 13 my $min = $output_spec->{'min'};
4927 13 push @properties, {
4928 name => 'min_constraint',
4929 code => "defined(\$result) && looks_like_number(\$result) && \$result >= $min",
4930 };
4931 }
4932  
4933 17 ▶ if(defined($output_spec->{'max'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output_spec->{"max"}) 2 15 17
4934 2 my $max = $output_spec->{'max'};
4935 2 push @properties, {
4936 name => 'max_constraint',
4937 code => "defined(\$result) && looks_like_number(\$result) && \$result <= $max",
4938 };
4939 }
4940  
4941 # Heuristic: transforms named 'positive' (case-insensitive)
4942 # imply a non-negative result constraint
4943 17 ▶ if($transform_name =~ /$TRANSFORM_POSITIVE_PATTERN/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($transform_name =~ /$TRANSFORM_POSITIVE_PATTERN/iu) 7 10 17
4944 7 push @properties, {
4945 name => 'non_negative',
4946 code => "defined(\$result) && looks_like_number(\$result) && \$result >= 0",
4947 };
4948 }
4949 }
4950  
4951 # --------------------------------------------------
4952 # Property 2: Specific value output
4953 # --------------------------------------------------
4954 26 ▶ if(defined($output_spec->{'value'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output_spec->{"value"}) 2 24 26
4955 2 my $expected = $output_spec->{'value'};
4956  
4957 # Numeric refs use == for comparison; scalars use eq
4958 # via perl_quote to produce the correct quoted literal
4959 2 ▶ push @properties, {
Branch: 1 branch
BranchTrueFalseTotal
ref $expected ? : 0 2 2
4960 name => 'exact_value',
4961 code => ref($expected)
4962 ? "\$result == $expected"
4963 : "\$result eq " . perl_quote($expected),
4964 };
4965 }
4966  
4967 # --------------------------------------------------
4968 # Property 3: String length constraints
4969 # --------------------------------------------------
4970 26 ▶ if(_is_string_transform($input_spec, $output_spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_string_transform($input_spec, $output_spec)) 6 20 26
4971 6 ▶ if(defined($output_spec->{'min'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output_spec->{"min"}) 2 4 6
4972 2 push @properties, {
4973 name => 'min_length',
4974 code => "length(\$result) >= $output_spec->{'min'}",
4975 };
4976 }
4977  
4978 6 ▶ if(defined($output_spec->{'max'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output_spec->{"max"}) 0 6 6
4979 0 push @properties, {
4980 name => 'max_length',
4981 code => "length(\$result) <= $output_spec->{'max'}",
4982 };
4983 }
4984  
4985 6 ▶ if(defined($output_spec->{'matches'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output_spec->{"matches"}) 0 6 6
4986 0 my $pattern = $output_spec->{'matches'};
4987  
4988 # See the matching comment in _schema_to_lectrotest_generator —
4989 # compile first and re-embed via regexp_pattern() rather than
4990 # splicing the raw string into qr/$pattern/, which would let
4991 # an unescaped '/' break out of the delimiter.
4992 0 ▶ my $compiled = ref($pattern) eq 'Regexp' ? $pattern : eval { qr/$pattern/ };
Branch: 1 branch
BranchTrueFalseTotal
ref $pattern eq 'Regexp' ? : 0 0 0
4993 0 ▶ if($@ || !defined($compiled)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not defined $compiled) { } 0 0 0
Condition0%0/3
$@ or not defined $compiled
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ or not defined $compiled
$@ not defined $compiled
Truth table0%0/3
A or not(B)
A= $@B= not defined $compiled
ABresult
1X1
011
000
4994 0 carp "Invalid matches pattern '$pattern' for transform '$transform_name': $@";
4995 } else {
4996 0 my ($pat, $mods) = regexp_pattern($compiled);
4997 0 ▶ my $safe_re = "qr{$pat}" . ($mods // '');
Condition0%0/2
$mods // ""
l!l
00
MC/DC0%0/1
$mods // ""
$mods
Truth table0%0/2
A
A= $mods
Aresult
11
00
4998 0 push @properties, {
4999 name => 'pattern_match',
5000 code => "\$result =~ $safe_re",
5001 };
5002 }
5003 }
5004 }
5005  
5006 # --------------------------------------------------
5007 # Property 4: Type preservation
5008 # --------------------------------------------------
5009 26 ▶ if(_same_type($input_spec, $output_spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_same_type($input_spec, $output_spec)) 24 2 26
5010 24 my $type = _get_dominant_type($output_spec);
5011  
5012 # Only emit a numeric_type check for numeric types —
5013 # string and other types have no equivalent simple check
5014 24 ▶ if($type eq 'number' || $type eq 'integer' || $type eq 'float') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "number" or $type eq "integer" or $type eq "float") 17 7 24
Condition83%5/6
$type eq "number" or $type eq "integer" or $type eq "float"
l!l&&r!l&&!r
1707
$type eq "number" or $type eq "integer"
l!l&&r!l&&!r
1527
MC/DC66%2/3
$type eq "number" or $type eq "integer" or $type eq "float"
$type eq "number" $type eq "integer" $type eq "float"
Truth table75%3/4
A or B or C
A= $type eq "number"B= $type eq "integer"C= $type eq "float"
ABCresult
1XX1
01X1
0011
0000
5015 17 push @properties, {
5016 name => 'numeric_type',
5017 code => 'looks_like_number($result)',
5018 };
5019 }
5020 }
5021  
5022 # --------------------------------------------------
5023 # Property 5: Definedness
5024 # --------------------------------------------------
5025 # Emit a defined() check for all transforms except those
5026 # whose output type is explicitly 'undef' — those are
5027 # expected to return nothing
5028 26 ▶ unless(($output_spec->{'type'} // '') eq 'undef') {
Branch: 1 branch
BranchTrueFalseTotal
unless (($output_spec->{"type"} // "") eq "undef") 24 2 26
Condition100%2/2
$output_spec->{"type"} // ""
l!l
251
MC/DC100%1/1
$output_spec->{"type"} // ""
$output_spec->{"type"}
Truth table100%2/2
A
A= $output_spec->{"type"}
Aresult
11
00
5029 24 push @properties, {
5030 name => 'defined',
5031 code => 'defined($result)',
5032 };
5033 }
5034  
5035 26 return @properties;
5036 }
5037  
5038 # --------------------------------------------------
5039 # _process_custom_properties
5040 #
5041 # Purpose: Process the 'properties' array from a
5042 # transform definition, resolving each
5043 # entry to either a named builtin property
5044 # (looked up from _get_builtin_properties)
5045 # or a custom property with inline code.
5046 #
5047 # Entry: $properties_spec - arrayref of property
5048 # definitions from the
5049 # schema. Each element
5050 # is either a string
5051 # (builtin name) or a
5052 # hashref with 'name'
5053 # and 'code' fields.
5054 # $function - name of the function
5055 # under test.
5056 # $module - module name, or undef
5057 # for builtins.
5058 # $input_spec - the transform's input
5059 # spec hashref.
5060 # $output_spec - the transform's output
5061 # spec hashref.
5062 # $new - defined if the function
5063 # is an OO method; value
5064 # is not used, only
5065 # presence is checked.
5066 #
5067 # Exit: Returns a list of property hashrefs,
5068 # each containing 'name', 'code', and
5069 # 'description' keys.
5070 # Invalid or unrecognised entries are
5071 # skipped with a carp warning.
5072 #
5073 # Side effects: Carps on unrecognised builtin names,
5074 # missing code fields, and invalid
5075 # property definition types.
5076 #
5077 # Notes: The sixth argument is $new (the OO
5078 # constructor signal), not the full schema
5079 # hashref. It is used only to determine
5080 # whether to emit OO-style call code for
5081 # builtin property templates.
5082 # --------------------------------------------------
5083 7 ▶sub _process_custom_properties {
Subroutine _process_custom_properties: called CC=15 SCAR=29.0
5084 7 my ($properties_spec, $function, $module, $input_spec, $output_spec, $new) = @_;
5085  
5086 7 my @properties;
5087 7 my $builtin_properties = _get_builtin_properties();
5088  
5089 7 for my $prop_def (@{$properties_spec}) {
5090 6 my $prop_name;
5091 my $prop_code;
5092 6 my $prop_desc;
5093  
5094 6 ▶ if(!ref($prop_def)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not ref $prop_def) { } 2 4 6
elsif (ref $prop_def eq 'HASH') { } 3 1 4
5095 # Plain string — look up as a named builtin property
5096 2 $prop_name = $prop_def;
5097  
5098 2 ▶ unless(exists($builtin_properties->{$prop_name})) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $builtin_properties->{$prop_name}) 1 1 2
5099 1 carp "Unknown built-in property '$prop_name', skipping";
5100 1 next;
5101 }
5102  
5103 1 my $builtin = $builtin_properties->{$prop_name};
5104  
5105 # Build the argument list, respecting positional order
5106 1 my @var_names = sort keys %{$input_spec};
5107 1 my @args;
5108 1 ▶ if(_has_positions($input_spec)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_has_positions($input_spec)) { } 1 0 1
5109 0 my @sorted = sort { $input_spec->{$a}{'position'} <=> $input_spec->{$b}{'position'} } @var_names;
5110 1 @args = map { "\$$_" } @sorted;
5111 } else {
5112 0 @args = map { "\$$_" } @var_names;
5113 }
5114  
5115 # Build the call expression for the builtin template.
5116 # $new here is the raw OO signal from the caller —
5117 # defined means OO mode, undef means functional
5118 1 my $call_code;
5119 1 ▶ if($module && defined($new)) {
Branch: 2 branches
BranchTrueFalseTotal
if ($module and defined $new) { } 0 1 1
elsif ($module and $module ne $MODULE_BUILTIN) { } 0 1 1
Condition33%1/3
$module and defined $new
!ll&&!rl&&r
100
MC/DC0%0/2
$module and defined $new
$module defined $new
Truth table33%1/3
A and B
A= $moduleB= defined $new
ABresult
0X0
100
111
5120 # OO mode — fresh object per trial
5121 0 $call_code = "my \$obj = new_ok('$module');";
5122 0 $call_code .= "\$obj->$function";
5123 ▶ } elsif($module && $module ne $MODULE_BUILTIN) {
Condition33%1/3
$module and $module ne $MODULE_BUILTIN
!ll&&!rl&&r
100
MC/DC0%0/2
$module and $module ne $MODULE_BUILTIN
$module $module ne $MODULE_BUILTIN
Truth table33%1/3
A and B
A= $moduleB= $module ne $MODULE_BUILTIN
ABresult
0X0
100
111
5124 # Functional mode with a named module
5125 0 $call_code = "$module\::$function";
5126 } else {
5127 # Builtin or unqualified function call
5128 1 $call_code = $function;
5129 }
5130 1 $call_code .= '(' . join(', ', @args) . ')';
5131  
5132 # Instantiate the builtin's code template with the
5133 # call expression and input variable list
5134 1 $prop_code = $builtin->{'code_template'}->($function, $call_code, \@var_names);
5135 1 $prop_desc = $builtin->{'description'};
5136  
5137 } elsif(ref($prop_def) eq 'HASH') {
5138 # Hashref — custom property with inline Perl code
5139 3 ▶ $prop_name = $prop_def->{'name'} || 'custom_property';
Condition100%2/2
$prop_def->{'name'} || 'custom_property'
l!l
21
MC/DC100%1/1
$prop_def->{'name'} || 'custom_property'
$prop_def->{'name'}
Truth table100%2/2
A
A= $prop_def->{'name'}
Aresult
11
00
5140 3 $prop_code = $prop_def->{'code'};
5141 3 ▶ $prop_desc = $prop_def->{'description'} || "Custom property: $prop_name";
Condition100%2/2
$prop_def->{'description'} || "Custom property: $prop_name"
l!l
12
MC/DC100%1/1
$prop_def->{'description'} || "Custom property: $prop_name"
$prop_def->{'description'}
Truth table100%2/2
A
A= $prop_def->{'description'}
Aresult
11
00
5142  
5143 3 ▶ unless($prop_code) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($prop_code) 1 2 3
5144 1 carp "Custom property '$prop_name' missing 'code' field, skipping";
5145 1 next;
5146 }
5147  
5148 # Sanity-check: code must contain at least a variable
5149 # reference or a word character to be meaningful
5150 2 ▶ unless($prop_code =~ /\$/ || $prop_code =~ /\w+/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($prop_code =~ /\$/u or $prop_code =~ /\w+/u) 0 2 2
Condition33%1/3
$prop_code =~ /\$/u or $prop_code =~ /\w+/u
l!l&&r!l&&!r
200
MC/DC0%0/2
$prop_code =~ /\$/u or $prop_code =~ /\w+/u
$prop_code =~ /\$/u $prop_code =~ /\w+/u
Truth table33%1/3
A or B
A= $prop_code =~ /\$/uB= $prop_code =~ /\w+/u
ABresult
1X1
011
000
5151 0 carp "Custom property '$prop_name' code looks invalid: $prop_code";
5152 0 next;
5153 }
5154  
5155 } else {
5156 # Neither string nor hashref — unrecognised definition type
5157 1 carp 'Invalid property definition: ', render_fallback($prop_def);
5158 1 next;
5159 }
5160  
5161 3 push @properties, {
5162 name => $prop_name,
5163 code => $prop_code,
5164 description => $prop_desc,
5165 };
5166 }
5167  
5168 7 return @properties;
5169 }
5170  
5171 =head1 NOTES
5172  
5173 C<seed> and C<iterations> really should be within C<config>.
5174  
5175 =head1 SEE ALSO
5176  
5177 =over 4
5178  
5179 =item * L<Test Dashboard|https://nigelhorne.github.io/App-Test-Generator/coverage/>
5180  
5181 =item * L<App::Test::Generator::Template> - Template of the file of tests created by C<App::Test::Generator>
5182  
5183 =item * L<App::Test::Generator::SchemaExtractor> - Create schemas from Perl programs
5184  
5185 =item * L<Params::Validate::Strict>: Schema Definition
5186  
5187 =item * L<Params::Get>: Input validation
5188  
5189 =item * L<Return::Set>: Output validation
5190  
5191 =item * L<Test::LectroTest>
5192  
5193 =item * L<Test::Most>
5194  
5195 =item * L<YAML::XS>
5196  
5197 =back
5198  
5199 =head1 AUTHOR
5200  
5201 Nigel Horne, C<< <njh at nigelhorne.com> >>
5202  
5203 Portions of this module's initial design and documentation were created with the
5204 assistance of AI.
5205  
5206 =head1 SUPPORT
5207  
5208 This module is provided as-is without any warranty.
5209  
5210 You can find documentation for this module with the perldoc command.
5211  
5212 perldoc App::Test::Generator
5213  
5214 You can also look for information at:
5215  
5216 =over 4
5217  
5218 =item * MetaCPAN
5219  
5220 L<https://metacpan.org/release/App-Test-Generator>
5221  
5222 =item * GitHub
5223  
5224 L<https://github.com/nigelhorne/App-Test-Generator>
5225  
5226 =item * CPANTS
5227  
5228 L<http://cpants.cpanauthors.org/dist/App-Test-Generator>
5229  
5230 =item * CPAN Testers' Matrix
5231  
5232 L<http://matrix.cpantesters.org/?dist=App-Test-Generator>
5233  
5234 =item * CPAN Testers Dependencies
5235  
5236 L<http://deps.cpantesters.org/?module=App::Test::Generator>
5237  
5238 =back
5239  
5240 =head1 FORMAL SPECIFICATION
5241  
5242 This section describes the documented routines in Z notation. It is for
5243 readers who want an exact, mathematical statement. You do not need it to use
5244 the module.
5245  
5246 How to read it: a name ending in C<?> is an input and a name ending in C<!> is
5247 an output. None of these routines keeps any state between calls, so there is
5248 no state schema. C<quote(v)> stands for the result of C<perl_quote(v)>.
5249  
5250 =head2 generate
5251  
5252 ┌─ Generate ────────────────────────────────────────
5253 │ schema_file? : STRING
5254 │ output_file? : STRING ∪ { undef }
5255 │ test : STRING
5256 │ result! : BOOLEAN
5257 ├───────────────────────────────────────────────────
5258 │ pre schema_file? names a readable schema
5259 │ the schema defines function
5260 │ every name in the schema is an identifier
5261 │ post test is a complete Perl test file for function
5262 │ output_file? ≠ undef ⇒ file output_file? holds test
5263 │ output_file? = undef ⇒ test is printed on STDOUT
5264 │ result! = 1
5265 └───────────────────────────────────────────────────
5266  
5267 no arguments ⇒ croak 'Usage: generate(...)'
5268 output_file? cannot be written ⇒ croak 'Cannot open ...'
5269  
5270 =head2 render_fallback
5271  
5272 ┌─ RenderFallback ──────────────────────────────────
5273 │ v? : VALUE
5274 │ result! : STRING
5275 ├───────────────────────────────────────────────────
5276 │ post v? = undef ⇒ result! = 'undef'
5277 │ v? ≠ undef ⇒ result! is one line of Perl source
5278 │ ∧ eval(result!) is a copy of v?
5279 └───────────────────────────────────────────────────
5280  
5281 =head2 render_hash
5282  
5283 ┌─ RenderHash ──────────────────────────────────────
5284 │ href? : VALUE
5285 │ result! : STRING
5286 │ kept : ℙ STRING
5287 ├───────────────────────────────────────────────────
5288 │ post ref(href?) ≠ 'HASH' ∨ href? = ∅ ⇒ result! = ''
5289 │ ref(href?) = 'HASH' ⇒
5290 │ kept = { k : dom href? | href?(k) is a hashref
5291 │ ∨ href?(k) is a type name }
5292 │ result! has one "'k' => { ... }" entry for each
5293 │ k in kept, in sorted order
5294 └───────────────────────────────────────────────────
5295  
5296 =head2 render_args_hash
5297  
5298 ┌─ RenderArgsHash ──────────────────────────────────
5299 │ href? : VALUE
5300 │ result! : STRING
5301 ├───────────────────────────────────────────────────
5302 │ post ref(href?) ≠ 'HASH' ∨ href? = ∅ ⇒ result! = ''
5303 │ ref(href?) = 'HASH' ⇒
5304 │ result! = join(', ', ⟨ k : sort(dom href?) •
5305 │ quote(k) . ' => ' . quote(href?(k)) ⟩)
5306 └───────────────────────────────────────────────────
5307  
5308 =head2 render_arrayref_map
5309  
5310 ┌─ RenderArrayrefMap ───────────────────────────────
5311 │ href? : VALUE
5312 │ result! : STRING
5313 │ kept : ℙ STRING
5314 ├───────────────────────────────────────────────────
5315 │ post href? is false ∨ ref(href?) ≠ 'HASH' ⇒ result! = '()'
5316 │ ref(href?) = 'HASH' ⇒
5317 │ kept = { k : dom href? | ref(href?(k)) = 'ARRAY' }
5318 │ kept = ∅ ⇒ result! = ''
5319 │ result! has one "'k' => [ ... ]" entry for each
5320 │ k in kept, in sorted order
5321 └───────────────────────────────────────────────────
5322  
5323 =head2 perl_quote
5324  
5325 ┌─ PerlQuote ───────────────────────────────────────
5326 │ v? : VALUE
5327 │ result! : STRING
5328 ├───────────────────────────────────────────────────
5329 │ pre v? is nested no more than 100 levels deep
5330 │ post v? = undef ⇒ result! = 'undef'
5331 │ v? = 'true' ⇒ result! = '!!1'
5332 │ v? = 'false' ⇒ result! = '!!0'
5333 │ v? looks like a number ⇒ result! = v?
5334 │ v? is any other string ⇒ result! = v? in single quotes,
5335 │ with ' and \ escaped
5336 │ ref(v?) = 'ARRAY' ⇒ result! = '[ ' . join(', ',
5337 │ ⟨ e : v? • quote(e) ⟩) . ' ]'
5338 │ ref(v?) = 'Regexp' ⇒ result! = 'qr{...}'
5339 │ otherwise ⇒ result! = render_fallback(v?)
5340 └───────────────────────────────────────────────────
5341  
5342 nested more than 100 levels deep ⇒ croak 'structure too deeply nested'
5343  
5344 =head1 STATE DIAGRAM
5345  
5346 C<generate> is a class method and keeps no state. One call runs from start
5347 to finish through these stages, and any stage may stop it by croaking.
5348  
5349 +-------------+
5350 | START |
5351 +-------------+
5352 |
5353 | generate(schema_file, output_file)
5354 v
5355 +-------------+ no arguments, file not readable
5356 | LOAD SCHEMA |--------------------------------------+
5357 +-------------+ |
5358 | |
5359 | schema parsed |
5360 v |
5361 +-------------+ missing function, bad name, |
5362 | VALIDATE | contradictory input spec |
5363 +-------------+--------------------------------------+
5364 | |
5365 | schema is good |
5366 v v
5367 +-------------+ +-------------+
5368 | RENDER | | CROAKED |
5369 +-------------+ +-------------+
5370 | ^
5371 | test source built |
5372 v |
5373 +-------------+ output_file cannot be opened |
5374 | WRITE |--------------------------------------+
5375 +-------------+
5376 |
5377 | file written, or source printed on STDOUT
5378 v
5379 +-------------+
5380 | DONE |
5381 +-------------+
5382  
5383 Side effects: C<generate> writes C<output_file> and prints one line saying so,
5384 or prints the test source when no output file is given. The C<render_*>
5385 routines and C<perl_quote> write no files and print nothing.
5386  
5387 =head1 LICENCE AND COPYRIGHT
5388  
5389 Copyright 2025-2026 Nigel Horne.
5390  
5391 Usage is subject to the terms of GPL2.
5392 If you use it,
5393 please let me know.
5394  
5395 =cut
5396  
5397 226 1;
↑ Summary bin/fuzz-harness-generator »