lib/App/Test/Generator.pm

Structural Coverage (Approximate)

TER1 (Statement): 88.40%
TER2 (Branch): 79.19%
TER3 (LCSAJ): 100.0% (71/71)
Approximate LCSAJ segments: 645

LCSAJ Legend

● Covered — this LCSAJ path was executed during testing.

● Not covered — this LCSAJ path was never executed. These are the paths to focus on.

Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:

        start → end → jump
        

Uncovered paths show [NOT COVERED] in the tooltip.

Mutant Testing Legend

Survived (tests missed this) Killed (tests detected this) No mutation
    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: use 5.036;
   29: 
   30: use strict;
   31: use warnings;
   32: use autodie qw(:all);
   33: 
   34: use utf8;
   35: use open qw(:std :encoding(UTF-8));
   36: 
   37: use App::Test::Generator::Provenance ();
   38: use App::Test::Generator::Template;
   39: use Carp qw(carp croak confess);
   40: use Config::Abstraction 0.36;
   41: use Data::Dumper;
   42: use Data::Section::Simple;
   43: use File::Basename qw(basename);
   44: use File::Spec;
   45: use Module::Load::Conditional qw(check_install can_load);
   46: use Params::Get;
   47: use Params::Validate::Strict 0.36;
   48: use Readonly;
   49: use Readonly::Values::Boolean;
   50: use Scalar::Util qw(looks_like_number);
   51: use re 'regexp_pattern';
   52: use Template;
   53: use YAML::XS qw(LoadFile);
   54: 
   55: use Exporter 'import';
   56: 
   57: our @EXPORT_OK = qw(generate);
   58: 
   59: our $VERSION = '0.52';
   60: 
   61: Readonly my $DEFAULT_ITERATIONS      => 30;
   62: Readonly my $DEFAULT_PROPERTY_TRIALS => 1000;
   63: 
   64: # Hash for O(1) lookup rather than a list needing grep O(n)
   65: 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: 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: 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: Readonly my $INDEX_NOT_FOUND => -1;
  101: 
  102: # --------------------------------------------------
  103: # Readonly constants for schema validation
  104: # --------------------------------------------------
  105: Readonly my $CONFIG_PROPERTIES_KEY => 'properties';
  106: Readonly my $LEGACY_PERL_KEY_1     => '$module';
  107: Readonly my $LEGACY_PERL_KEY_2     => 'our $module';
  108: Readonly my $SOURCE_KEY            => '_source';
  109: 
  110: # --------------------------------------------------
  111: # Readonly constants for render_hash key detection
  112: # --------------------------------------------------
  113: Readonly my $KEY_MATCHES => 'matches';
  114: 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: 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: 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: 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: 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: 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: 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: 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: Readonly my $ENV_TEST_VERBOSE       => 'TEST_VERBOSE';
  172: Readonly my $ENV_GENERATOR_VERBOSE  => 'GENERATOR_VERBOSE';
  173: 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.52
  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:   # See also [t/all-fuzz.t](t/all-fuzz.t), which aims to be a file you can drop in to any
  214:   # distribution and have it automatically fuzz test your CPAN module.
  215:   extract-schemas lib/App/Test/Generator/Sample/Module.pm && fuzz-harness-generator -r schemas/greet.yml
  216: 
  217:   # Fuzz a module and keep the corpus bounded: trim to the minimum subset that still covers every branch
  218:   extract-schemas --fuzz --minimize-corpus lib/My/Module.pm
  219: 
  220:   # Generate round-trip tests that run every code example in a module's POD and verify the results
  221:   pod-example-tester lib/My/Module.pm --output t/pod_examples.t
  222: 
  223:   # Generate a Benchmark::cmpthese script from a schema; each transform becomes one timed variant
  224:   benchmark-generator -i schemas/abs.yml -o benchmarks/abs.pl
  225: 
  226:   # Copy dashboard.yml and mutate.yml into a module repository's .github/workflows/ directory
  227:   deploy-workflows --target /path/to/my-module
  228: 
  229: From Perl:
  230: 
  231:   use App::Test::Generator qw(generate);
  232:   use App::Test::Generator::SchemaExtractor;
  233: 
  234:   # Generate to STDOUT
  235:   App::Test::Generator->generate("t/conf/abs.yml");
  236: 
  237:   # Generate directly to a file
  238:   App::Test::Generator->generate('t/conf/abs.yml', 't/add_fuzz.t');
  239: 
  240:   # Holy grail mode - read a Perl file, generate tests, and run them
  241:   # This is a long way away yet, but see t/schema_input.t for a proof of concept
  242:   my $extractor = App::Test::Generator::SchemaExtractor->new(
  243:     input_file => 'lib/App/Test/Generator/Template.pm',
  244:     output_dir => '/tmp',
  245:   );
  246:   my $schemas = $extractor->extract_all();
  247:   use File::Temp qw(tempfile);
  248:   foreach my $schema(keys %{$schemas}) {
  249:     my ($fh, $tempfile) = tempfile(SUFFIX => '.t', UNLINK => 1);
  250:     close $fh;
  251:     App::Test::Generator->generate(
  252:       schema => $schemas->{$schema},
  253:       output_file => $tempfile,
  254:     );
  255:     system($^X, '-Ilib', $tempfile);
  256:   }
  257: 
  258: =head1 OVERVIEW
  259: 
  260: This module takes a formal input/output specification for a routine or
  261: method and automatically generates test cases. In effect, it allows you
  262: to easily add comprehensive black-box tests in addition to the more
  263: common white-box tests that are typically written for CPAN modules and other
  264: subroutines.
  265: 
  266: The generated tests combine:
  267: 
  268: =over 4
  269: 
  270: =item * Random fuzzing based on input types
  271: 
  272: =item * Deterministic edge cases for min/max constraints
  273: 
  274: =item * Static corpus tests defined in Perl or YAML
  275: 
  276: =back
  277: 
  278: This approach strengthens your test suite by probing both expected and
  279: unexpected inputs, helping you to catch boundary errors, invalid data
  280: handling, and regressions without manually writing every case.
  281: 
  282: =head1 TOOLS
  283: 
  284: The distribution ships the following command-line tools:
  285: 
  286: =over 4
  287: 
  288: =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.
  289: 
  290: =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>.
  291: 
  292: To add a test dashboard to your CPAN module: copy these scripts into your C<.github/workflows> directory,
  293: then commit the changes to GitHub and enable the page through C<Settings-Pages-branch = gh_pages>:
  294: 
  295: =over 4
  296: 
  297: =item * L<https://github.com/nigelhorne/App-Test-Generator/blob/master/.github/workflows/dashboard.yml>
  298: 
  299: =item * L<https://github.com/nigelhorne/App-Test-Generator/blob/master/.github/workflows/mutate.yml>
  300: 
  301: =back
  302: 
  303: =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>).
  304: 
  305: =item * L<fuzz-harness-generator> - generate a C<Test::Most> fuzzing harness from a YAML schema.
  306: 
  307: =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.
  308: 
  309: =item * L<test-generator-mutate> - run mutation testing against a module's test suite.
  310: 
  311: =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.
  312: 
  313: =back
  314: 
  315: =head1 DESCRIPTION
  316: 
  317: This module implements the logic behind L<fuzz-harness-generator>.
  318: It parses configuration files (fuzz and/or corpus YAML), and
  319: produces a ready-to-run F<.t> test script to run through C<prove>.
  320: 
  321: It reads configuration files in any format,
  322: and optional YAML corpus files.
  323: All of the examples in this documentation are in C<YAML> format,
  324: other formats may not work as they aren't so heavily tested.
  325: It then generates a L<Test::Most>-based fuzzing harness combining:
  326: 
  327: =over 4
  328: 
  329: =item * Randomized fuzzing of inputs (with edge cases)
  330: 
  331: =item * Optional static corpus tests from Perl C<%cases> or YAML file (C<yaml_cases> key)
  332: 
  333: =item * Functional or OO mode (via C<$new>)
  334: 
  335: =item * Reproducible runs via C<$seed> and configurable iterations via C<$iterations>
  336: 
  337: =back
  338: 
  339: =head1 MUTATION-GUIDED TEST GENERATION
  340: 
  341: C<App::Test::Generator> includes a pipeline that automatically closes the
  342: feedback loop between mutation testing, schema extraction, and fuzz
  343: testing. The goal is that surviving mutants drive the creation of new
  344: tests that kill them on the next run, without manual intervention.
  345: 
  346: =head2 The Pipeline
  347: 
  348:     mutation survivor
  349:         |
  350:         v
  351:     SchemaExtractor extracts the schema for the enclosing sub
  352:         |
  353:         v
  354:     Schema augmented with boundary values from the mutant
  355:         |
  356:         v
  357:     Augmented schema written to t/conf/
  358:         |
  359:         v
  360:     t/fuzz.t picks up the new schema and runs fuzz tests
  361:         |
  362:         v
  363:     Mutation killed on next run
  364: 
  365: =head2 How to Use It
  366: 
  367: The pipeline is driven by three flags passed to
  368: C<bin/test-generator-index>, which is invoked automatically by
  369: C<bin/generate-test-dashboard> on each CI push.
  370: 
  371: =head3 Step 1: Generate TODO stubs for all survivors
  372: 
  373:     bin/test-generator-index --generate_mutant_tests=t
  374: 
  375: Produces C<t/mutant_YYYYMMDD_HHMMSS.t> containing:
  376: 
  377: =over 4
  378: 
  379: =item * TODO stubs for HIGH and MEDIUM difficulty survivors, with
  380: boundary value suggestions, environment variable hints, and the
  381: enclosing subroutine name for navigation context.
  382: 
  383: =item * Comment-only hints for LOW difficulty survivors.
  384: 
  385: =back
  386: 
  387: Multiple mutations on the same source line are deduplicated into one
  388: stub. One good test kills all variants on that line.
  389: 
  390: =head3 Step 2: Generate runnable schemas for NUM_BOUNDARY survivors
  391: 
  392:     bin/test-generator-index \
  393:         --generate_mutant_tests=t \
  394:         --generate_test=mutant
  395: 
  396: For each NUM_BOUNDARY survivor, calls
  397: L<App::Test::Generator::SchemaExtractor> to extract the schema for
  398: the enclosing subroutine. If the confidence level is sufficient, the
  399: schema is augmented with the boundary value from the mutant (plus one
  400: value either side) and written to C<t/conf/> as a runnable YAML file.
  401: L<t/fuzz.t> picks it up automatically on the next test run.
  402: 
  403: Falls back to a TODO stub if:
  404: 
  405: =over 4
  406: 
  407: =item * SchemaExtractor cannot parse the file
  408: 
  409: =item * The enclosing sub cannot be determined
  410: 
  411: =item * The extracted schema confidence is C<very_low> or C<none>
  412: 
  413: =back
  414: 
  415: =head3 Step 3: Augment existing schemas with survivor boundary values
  416: 
  417:     bin/test-generator-index \
  418:         --generate_mutant_tests=t \
  419:         --generate_test=mutant \
  420:         --generate_fuzz
  421: 
  422: Scans C<t/conf/> for existing YAML schema files (hand-written or
  423: previously generated) and writes augmented copies with boundary values
  424: from surviving NUM_BOUNDARY mutants merged in. The original schema is
  425: never modified. Augmented copies are written as
  426: C<t/conf/mutant_fuzz_YYYYMMDD_HHMMSS_FUNCTION.yml> and picked up
  427: automatically by C<t/fuzz.t>.
  428: 
  429: Schemas whose filename already starts with C<mutant_fuzz_> are skipped
  430: to prevent cascading augmentation. Schemas with no matching survivors
  431: are skipped, with a note if C<--verbose> is active.
  432: 
  433: =head3 Putting It All Together
  434: 
  435: The recommended invocation in C<bin/generate-test-dashboard>
  436: Step 7 runs all three stages together:
  437: 
  438:     bin/test-generator-index \
  439:         --generate_mutant_tests=t \
  440:         --generate_test=mutant \
  441:         --generate_fuzz
  442: 
  443: The GitHub Actions workflow in C<.github/workflows/dashboard.yml>
  444: then commits any new C<t/mutant_*.t> and C<t/conf/mutant_*.yml> files
  445: to the repository so they accumulate over time as the test suite
  446: improves.
  447: 
  448: =head2 Confidence Levels
  449: 
  450: L<App::Test::Generator::SchemaExtractor> assigns a confidence level
  451: to each extracted schema:
  452: 
  453: =over 4
  454: 
  455: =item * C<high> / C<medium> / C<low> - Schema is used for test generation
  456: 
  457: =item * C<very_low> / C<none> - Falls back to TODO stub
  458: 
  459: =back
  460: 
  461: Confidence is based on how much type and constraint information could
  462: be inferred from the source code and its POD documentation. Methods
  463: with explicit parameter validation (L<Params::Validate::Strict>,
  464: L<Params::Get>) or comprehensive POD will produce higher-confidence
  465: schemas.
  466: 
  467: =head2 Files Produced
  468: 
  469: =over 4
  470: 
  471: =item * C<t/mutant_YYYYMMDD_HHMMSS.t>
  472: 
  473: TODO stub file for all survivors. Committed to the repository by the
  474: GitHub Actions workflow.
  475: 
  476: =item * C<t/conf/mutant_MODNAME_FUNCTION_YYYYMMDD_HHMMSS.yml>
  477: 
  478: Runnable YAML schema for a NUM_BOUNDARY survivor where SchemaExtractor
  479: confidence was sufficient. Picked up by C<t/fuzz.t>.
  480: 
  481: =item * C<t/conf/mutant_fuzz_YYYYMMDD_HHMMSS_FUNCTION.yml>
  482: 
  483: Augmented copy of an existing schema with survivor boundary values
  484: merged in. Picked up by C<t/fuzz.t>.
  485: 
  486: =back
  487: 
  488: =head2 See Also
  489: 
  490: =over 4
  491: 
  492: =item * L<App::Test::Generator::SchemaExtractor> - Schema extraction
  493: from Perl source code
  494: 
  495: =item * L<bin/test-generator-index> - Dashboard generator and
  496: pipeline driver
  497: 
  498: =item * L<bin/generate-test-dashboard> - Full pipeline runner
  499: 
  500: =back
  501: 
  502: =head1 CONFIGURATION
  503: 
  504: The configuration file,
  505: for each set of tests to be produced,
  506: is a file containing a schema that can be read by L<Config::Abstraction>.
  507: 
  508: =head2 SCHEMA
  509: 
  510: The schema is split into several sections.
  511: 
  512: =head3 C<%input> - input params with keys => type/optional specs
  513: 
  514: When using named parameters
  515: 
  516:   input:
  517:     name:
  518:       type: string
  519:       optional: false
  520:     age:
  521:       type: integer
  522:       optional: true
  523: 
  524: Supported basic types used by the fuzzer: C<string>, C<integer>, C<float>, C<number>, C<boolean>, C<arrayref>, C<hashref>.
  525: See also L<Params::Validate::Strict>.
  526: You can add more custom types using properties.
  527: 
  528: A nested C<schema> describes the elements of an C<arrayref> or the values of a
  529: C<hashref>.  Element schemas are full specs, so they carry their own
  530: constraints and can nest again:
  531: 
  532:   input:
  533:     words:
  534:       type: arrayref
  535:       min: 1
  536:       max: 3
  537:       schema:
  538:         type: string
  539:         min: 3
  540:         max: 10
  541:     scores:
  542:       type: hashref
  543:       schema:
  544:         type: integer
  545:         min: 0
  546:         max: 100
  547:     record:
  548:       type: hashref
  549:       schema:
  550:         name:
  551:           type: string
  552:           min: 2
  553:           max: 20
  554:         age: integer
  555:     grid:
  556:       type: arrayref
  557:       schema:
  558:         type: arrayref
  559:         min: 1
  560:         max: 2
  561:         schema:
  562:           type: integer
  563:           min: 0
  564:           max: 9
  565:     things:
  566:       type: arrayref
  567:       schema:
  568:         type: object
  569:         isa: My::Thing      # needs a no-argument constructor
  570:         # or: can: label   # mocked with Class::Simple
  571: 
  572: A hashref C<schema> without a C<type> is a map of fixed key names to element
  573: schemas, so generated valid data uses those keys instead of random filler.
  574: Generated element values satisfy the element's own constraints.
  575: 
  576: For routines with one unnamed parameter
  577: 
  578:   input:
  579:     type: string
  580: 
  581: For routines with more than one named parameter, use the C<position> keyword.
  582: 
  583:   module: Math::Simple::MinMax
  584:   fuction: max
  585: 
  586:   input:
  587:     left:
  588:       type: number
  589:       position: 0
  590:     right:
  591:       type: number
  592:       position: 1
  593: 
  594:   output:
  595:     type: number
  596: 
  597: A routine can take positional arguments followed by named options, as
  598: C<< sub publish { my ($message, %opts) = @_ } >> does.  Give the leading
  599: arguments their positions and mark every trailing option C<named: 1>:
  600: 
  601:   input:
  602:     message:
  603:       type: string
  604:       position: 0
  605:     priority:
  606:       type: integer
  607:       optional: 1
  608:       named: 1
  609: 
  610:   # publish($message, priority => $priority)
  611: 
  612: A parameter in a schema that declares positions must say which it is: a
  613: missing position on a parameter without C<named: 1> is an error, not a
  614: second call shape.
  615: 
  616: A numeric parameter can document a range whose top end this harness cannot
  617: afford to reach: a count of hashing rounds costs time in proportion to the
  618: value, so one call at the documented maximum can take minutes.  C<sample_max>
  619: limits the valid data that is generated while C<max> stays the documented
  620: bound, so a value above C<max> is still probed (and refused cheaply):
  621: 
  622:   input:
  623:     rounds:
  624:       type: integer
  625:       named: 1
  626:       optional: 1
  627:       min: 10_000
  628:       max: 100_000_000
  629:       sample_max: 200_000
  630: 
  631: The keyword C<undef> is used to indicate that the C<function> takes no arguments.
  632: 
  633: =head3 C<%output> - output param types for L<Return::Set> checking
  634: 
  635:   output:
  636:     type: string
  637: 
  638: If the output hash contains the key _STATUS, and if that key is set to DIES,
  639: the routine should die with the given arguments; otherwise, it should live.
  640: If it's set to WARNS,
  641: the routine should warn with the given arguments.
  642: The output can be set to the string 'undef' if the routine should return the undefined value:
  643: 
  644:   ---
  645:   module: Scalar::Util
  646:   function: blessed
  647: 
  648:   input:
  649:     type: string
  650: 
  651:   output: undef
  652: 
  653: The keyword C<undef> is used to indicate that the C<function> returns nothing.
  654: 
  655: For methods that return a list (rather than a reference), use C<type: array>.
  656: The generated test captures the result in list context and validates it as an
  657: arrayref, which requires L<Test::Returns> 0.03 or later:
  658: 
  659:   output:
  660:     type: array
  661: 
  662: =head3 C<%config> - optional hash of configuration.
  663: 
  664: The current supported variables are
  665: 
  666: =over 4
  667: 
  668: =item * C<close_stdin>
  669: 
  670: Tests should not attempt to read from STDIN (default: 1).
  671: This is ignored on Windows, when never closes STDIN.
  672: 
  673: =item * C<test_nuls>, inject NUL bytes into strings (default: 1)
  674: 
  675: With this test enabled, the function is expected to die when a NUL byte is passed in.
  676: 
  677: =item * C<test_undef>, test with undefined value (default: 1)
  678: 
  679: =item * C<test_empty>, test with empty strings (default: 1)
  680: 
  681: =item * C<test_non_ascii>, test with strings that contain non ascii characters (default: 1)
  682: 
  683: =item * C<timeout>, ensure tests don't hang (default: 10)
  684: 
  685: =item * C<regex_timeout>, seconds allowed for generating one string that
  686: matches a regex pattern (default: 5)
  687: 
  688: A pattern the generator cannot satisfy, or one that makes it search for too
  689: long, falls back to a fixed matching value; when none exists the pattern's
  690: cases are skipped and reported once instead of failing the run.  Matching
  691: strings are generated from the seeded RNG, so a schema's C<seed> makes them
  692: reproducible.
  693: 
  694: Setting this to 0 disables timeout testing.
  695: 
  696: =item * C<check_files>, assert the routine leaves no files in the working
  697:  directory (default: 1)
  698: 
  699: Every call is checked for files it created.  They are removed afterwards
  700: whatever the setting, so a routine that writes a file cannot break the cases
  701: that follow it; set this to 0 for a routine whose purpose is to write one.
  702: C<extract-schemas> sets it to 0 when the routine's POD documents creating or
  703: writing a file in its SIDE EFFECTS section.
  704: 
  705: =item * C<check_fds>, assert the routine leaks no file descriptors
  706:  (default: 1)
  707: 
  708: Only checked where F</proc/self/fd> exists.  Set this to 0 for a routine that
  709: returns a filehandle to its caller, which still holds a descriptor.
  710: 
  711: The first descriptor a call opens on a given file (or its first socket or
  712: pipe) is taken as a resource held on purpose, such as a log file an object
  713: opens on first use, and is not reported.  A later call that opens the same
  714: target again is.
  715: 
  716: =item * C<check_accessors>, assert an accessor leaves the object it was called
  717:  on alone (default: 1)
  718: 
  719: The object is deep copied before each call and the state it was handed
  720: compared afterwards.  A getter that overwrites or deletes that state fails
  721: "getter leaves its object unmodified"; a getset that changes anything but the
  722: property it is named for fails "setter changes nothing but its property".
  723: Values the call fills in where it was handed undef, and keys it adds, are
  724: ignored, so a getter that memoises what it computed is not reported.  Set this
  725: to 0 for an accessor whose purpose is to change state, such as an iterator's
  726: C<next()>; a getter that declares no input is called with no arguments either
  727: way.
  728: 
  729: =item * C<dedup>, fuzzing can create duplicate tests, go some way to remove duplicates (default: 1)
  730: 
  731: =item * C<properties>, enable L<Test::LectroTest> Property tests (default: 0)
  732: 
  733: *item * C<test_security>, send some security string based tests (default: 0)
  734: 
  735: =back
  736: 
  737: All values default to C<true>.
  738: 
  739: =head3 C<%accessor> - this is an accessor routine
  740: 
  741:   accessor:
  742:     property: ua
  743:     type: getset
  744: 
  745: Has two mandatory elements:
  746: 
  747: =over 4
  748: 
  749: =item * C<property>
  750: 
  751: The name of the property in the object that the routine controls.
  752: 
  753: =item * C<type>
  754: 
  755: One of C<getter>, C<setter>, C<getset>.
  756: 
  757: =back
  758: 
  759: =head3 C<%transforms> - list of transformations from input sets to output sets
  760: 
  761: Transforms allow you to define how input data should be transformed into output data.
  762: This is useful for testing functions that convert between formats, normalize data,
  763: or apply business logic transformations on a set of data to different set of data.
  764: It takes a list of subsets of the input and output definitions,
  765: and verifies that data from each input subset is correctly transformed into data from the matching output subset.
  766: 
  767: A transform whose input names at least one field that the top-level input does not
  768: introduces its own call shape: its test cases are built from those fields rather
  769: than the top-level ones.  This lets one schema cover two calls, such as an
  770: arrayref argument and a list of scalar arguments.  A transform whose input only
  771: names fields that are already at the top level adjusts the top-level input and
  772: keeps the usual behaviour.
  773: 
  774: =head4 Transform Validation Rules
  775: 
  776: For each transform:
  777: 
  778: =over 4
  779: 
  780: =item 1. Generate test cases using the transform's input schema
  781: 
  782: =item 2. Call the function with those inputs
  783: 
  784: =item 3. Validate the output matches the transform's output schema
  785: 
  786: =item 4. If output has a specific 'value', check exact match
  787: 
  788: =item 5. If output has constraints (min/max), validate within bounds
  789: 
  790: =back
  791: 
  792: =head4 Example 1
  793: 
  794:   ---
  795:   module: builtin
  796:   function: abs
  797: 
  798:   config:
  799:     test_undef: no
  800:     test_empty: no
  801:     test_nuls: no
  802:     test_non_ascii: no
  803: 
  804:   input:
  805:     number:
  806:       type: number
  807:       position: 0
  808: 
  809:   output:
  810:     type: number
  811:     min: 0
  812: 
  813:   transforms:
  814:     positive:
  815:       input:
  816:         number:
  817:           type: number
  818:           position: 0
  819:           min: 0
  820:       output:
  821:         type: number
  822:         min: 0
  823:     negative:
  824:       input:
  825:         number:
  826:           type: number
  827:           position: 0
  828:           max: 0
  829:       output:
  830:         type: number
  831:         min: 0
  832:     error:
  833:       input:
  834:         undef
  835:       output:
  836:         _STATUS: DIES
  837: 
  838: If the output hash contains the key _STATUS, and if that key is set to DIES,
  839: the routine should die with the given arguments; otherwise, it should live.
  840: If it's set to WARNS, the routine should warn with the given arguments.
  841: 
  842: The keyword C<undef> is used to indicate that the C<function> returns nothing.
  843: 
  844: =head4 Example 2
  845: 
  846:   ---
  847:   module: Math::Utils
  848:   function: normalize_number
  849: 
  850:   input:
  851:     value:
  852:       type: number
  853:       position: 0
  854: 
  855:   output:
  856:     type: number
  857: 
  858:   transforms:
  859:     positive_stays_positive:
  860:       input:
  861:         value:
  862:           type: number
  863:           min: 0
  864:           max: 1000
  865:       output:
  866:         type: number
  867:         min: 0
  868:         max: 1
  869: 
  870:     negative_becomes_zero:
  871:       input:
  872:         value:
  873:           type: number
  874:           max: 0
  875:       output:
  876:         type: number
  877:         value: 0
  878: 
  879:     preserves_zero:
  880:       input:
  881:         value:
  882:           type: number
  883:           value: 0
  884:       output:
  885:         type: number
  886:         value: 0
  887: 
  888: =head3 C<$module>
  889: 
  890: The name of the module (optional).
  891: 
  892: Using the reserved word C<builtin> means you're testing a Perl builtin function.
  893: 
  894: If omitted, the generator will guess from the config filename:
  895: C<My-Widget.conf> -> C<My::Widget>.
  896: 
  897: =head3 C<$function>
  898: 
  899: The function/method to test.
  900: 
  901: This defaults to C<run>.
  902: 
  903: =head3 C<%new>
  904: 
  905: An optional hashref of args to pass to the module's constructor.
  906: 
  907:   new:
  908:     api_key: ABC123
  909:     verbose: true
  910: 
  911: To ensure C<new()> is called with no arguments, you still need to define new, thus:
  912: 
  913:   module: MyModule
  914:   function: my_function
  915: 
  916:   new:
  917: 
  918: =head3 C<$invocant>
  919: 
  920: The word C<class> when the routine is a class method: the harness calls
  921: C<Module-E<gt>routine(...)> instead of C<Module::routine(...)>.  With C<new>
  922: set the routine is called on the object C<new> builds, and without an
  923: C<invocant> it is called as a plain function.
  924: 
  925:   invocant: class
  926: 
  927: =head3 C<%cases>
  928: 
  929: An optional Perl static corpus, when the output is a simple string (expected => [ args... ]).
  930: 
  931: Maps the expected output string to the input and _STATUS
  932: 
  933:   cases:
  934:     ok:
  935:       input: ping
  936:       _STATUS: OK
  937:     error:
  938:       input: ""
  939:       _STATUS: DIES
  940: 
  941: =head3 C<$yaml_cases>
  942: 
  943: An optional path to a YAML file with the same shape as C<%cases>.
  944: 
  945: =head3 C<$seed>
  946: 
  947: An optional integer.
  948: When provided, the generated C<t/fuzz.t> will call C<srand($seed)> so fuzz runs are reproducible.
  949: 
  950: =head3 C<$iterations>
  951: 
  952: An optional integer controlling how many fuzz iterations to perform (default 30).
  953: 
  954: =head3 C<%edge_cases>
  955: 
  956: An optional hash mapping of extra values to inject.
  957: 
  958: 	# Two named parameters
  959: 	edge_cases:
  960: 		name: [ '', 'a' x 1024, \"\x{263A}" ]
  961: 		age: [ -1, 0, 99999999 ]
  962: 
  963: 	# Takes a string input
  964: 	edge_cases: [ 'foo', 'bar' ]
  965: 
  966: Values can be strings or numbers; strings will be properly quoted.
  967: Note that this only works with routines that take named parameters.
  968: 
  969: =head3 C<%type_edge_cases>
  970: 
  971: An optional hash mapping types to arrayrefs of extra values to try for any field of that type:
  972: 
  973: 	type_edge_cases:
  974: 		string: [ '', ' ', "\t", "\n", "\0", 'long' x 1024, chr(0x1F600) ]
  975: 		number: [ 0, 1.0, -1.0, 1e308, -1e308, 1e-308, -1e-308, 'NaN', 'Infinity' ]
  976: 		integer: [ 0, 1, -1, 2**31-1, -(2**31), 2**63-1, -(2**63) ]
  977: 
  978: =head3 C<%edge_case_array>
  979: 
  980: Specify edge case values for routines that accept a single unnamed parameter.
  981: This is specifically designed for simple functions that take one argument without a parameter name.
  982: These edge cases supplement the normal random string generation, ensuring specific problematic values are always tested.
  983: 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.
  984: 
  985:   ---
  986:   module: Text::Processor
  987:   function: sanitize
  988: 
  989:   input:
  990:     type: string
  991:     min: 1
  992:     max: 1000
  993: 
  994:   edge_case_array:
  995:     - "<script>alert('xss')</script>"
  996:     - "'; DROP TABLE users; --"
  997:     - "\0null\0byte"
  998:     - "emoji\U0001F60Atest"
  999:     - ""
 1000:     - " "
 1001: 
 1002:   seed: 42
 1003:   iterations: 30
 1004: 
 1005: =head3 Semantic Data Generators
 1006: 
 1007: For property-based testing with L<Test::LectroTest>,
 1008: you can use semantic generators to create realistic test data.
 1009: 
 1010: C<unix_timestamp> is currently fully supported,
 1011: other fuzz testing support for C<semantic> entries is being developed.
 1012: 
 1013:   input:
 1014:     email:
 1015:       type: string
 1016:       semantic: email
 1017: 
 1018:     user_id:
 1019:       type: string
 1020:       semantic: uuid
 1021: 
 1022:     phone:
 1023:       type: string
 1024:       semantic: phone_us
 1025: 
 1026: =head4 Available Semantic Types
 1027: 
 1028: =over 4
 1029: 
 1030: =item * C<email> - Valid email addresses (user@domain.tld)
 1031: 
 1032: =item * C<url> - HTTP/HTTPS URLs
 1033: 
 1034: =item * C<uuid> - UUIDv4 identifiers
 1035: 
 1036: =item * C<phone_us> - US phone numbers (XXX-XXX-XXXX)
 1037: 
 1038: =item * C<phone_e164> - International E.164 format (+XXXXXXXXXXXX)
 1039: 
 1040: =item * C<ipv4> - IPv4 addresses (0.0.0.0 - 255.255.255.255)
 1041: 
 1042: =item * C<ipv6> - IPv6 addresses
 1043: 
 1044: =item * C<username> - Alphanumeric usernames with _ and -
 1045: 
 1046: =item * C<slug> - URL slugs (lowercase-with-hyphens)
 1047: 
 1048: =item * C<hex_color> - Hex color codes (#RRGGBB)
 1049: 
 1050: =item * C<iso_date> - ISO 8601 dates (YYYY-MM-DD)
 1051: 
 1052: =item * C<iso_datetime> - ISO 8601 datetimes (YYYY-MM-DDTHH:MM:SSZ)
 1053: 
 1054: =item * C<semver> - Semantic version strings (major.minor.patch)
 1055: 
 1056: =item * C<jwt> - JWT-like tokens (base64url format)
 1057: 
 1058: =item * C<json> - Simple JSON objects
 1059: 
 1060: =item * C<base64> - Base64-encoded strings
 1061: 
 1062: =item * C<md5> - MD5 hashes (32 hex chars)
 1063: 
 1064: =item * C<sha256> - SHA-256 hashes (64 hex chars)
 1065: 
 1066: =item * C<bytes> - Byte strings (arbitrary octets, not text)
 1067: 
 1068: The property test draws octets rather than characters.  A byte string holds
 1069: data, not a document, so no text-oriented case applies to it;
 1070: L<App::Test::Generator::SchemaExtractor> sets this for a parameter that is a
 1071: file's contents (`$bytes`, `blob`, "raw bytes").
 1072: 
 1073: =item * C<directory> - The path of an existing, writable directory
 1074: 
 1075: The harness creates a temporary directory and passes its path, because no
 1076: pattern can describe "a directory that exists".
 1077: No empty-string case is generated for such a parameter, since routines
 1078: commonly read an empty path as "not given".
 1079: L<App::Test::Generator::SchemaExtractor> sets this for a parameter that the
 1080: routine tests with C<-d>.
 1081: 
 1082: =item * C<existing_file> - The path of an existing file
 1083: 
 1084: The harness creates a temporary file and passes its path, because no pattern
 1085: can describe "a file that exists".  L<App::Test::Generator::SchemaExtractor>
 1086: sets this for a parameter that the routine tests with C<-e> or C<-f> but does
 1087: not read.
 1088: 
 1089: =item * C<unix_timestamp>
 1090: 
 1091: =back
 1092: 
 1093: =head2 EDGE CASE GENERATION
 1094: 
 1095: In addition to purely random fuzz cases, the harness generates
 1096: deterministic edge cases for parameters that declare C<min>, C<max> or C<len> in their schema definitions.
 1097: 
 1098: For each constraint, three edge cases are added:
 1099: 
 1100: =over 4
 1101: 
 1102: =item * Just inside the allowable range
 1103: 
 1104: This case should succeed, since it lies strictly within the bounds.
 1105: 
 1106: =item * Exactly on the boundary
 1107: 
 1108: This case should succeed, since it meets the constraint exactly.
 1109: 
 1110: =item * Just outside the boundary
 1111: 
 1112: This case is annotated with C<_STATUS = 'DIES'> in the corpus and
 1113: should cause the harness to fail validation or croak.
 1114: 
 1115: A constraint that came only from L<extract-schemas> reading POD (marked
 1116: with C<_source: pod> for prose or C<_source: input_spec> for a formal spec)
 1117: is a claim about valid input, not a check the routine has been seen to make.
 1118: The constraint still sizes the valid data that is generated.  It also gets
 1119: explicit out-of-bound probes: a probe that dies is accepted as enforcement
 1120: of the documented limit, while one that survives is recorded as a
 1121: documentation contradiction.  Provenance is tracked per constraint in
 1122: C<_constraint_source>, so a documented minimum does not make a maximum that
 1123: the code enforces tolerant on the same field.  This applies to array and hash sizes, string
 1124: lengths and numeric ranges, to constraints parsed from POD prose
 1125: (C<3-50>, C<at least 5>), and to C<memberof> lists and C<matches> patterns.
 1126: Every documented constraint gets an outside value as an advisory probe; in
 1127: the normal advisory mode a probe that survives is reported as a routine
 1128: accepting a value its POD says is invalid, without failing the run.  A
 1129: constraint written by hand in a schema is still required to die outside
 1130: it.  Because tolerance reduces what the
 1131: harness proves, every tolerated bound is reported with C<diag>, so a
 1132: passing run never hides the concession.  Without this, a routine whose POD
 1133: says C<min =E<gt> 1> but which accepts an empty list failed every harness
 1134: run.
 1135: 
 1136: Fuzzing can still reveal a contradiction in either direction: a routine may
 1137: reject a value inside a documented constraint, or accept one outside it.  The
 1138: harness records those observations and reports them together at the end of
 1139: the run.  Advisory mode tolerates them, so POD-derived documentation cannot
 1140: fail a routine that merely documents differently; pass C<--strict-documented>
 1141: to C<fuzz-harness-generator> to make each recorded contradiction a failing
 1142: test.  The strict choice is embedded in the generated harness, so a later
 1143: C<prove> run behaves the same way.
 1144: 
 1145: =back
 1146: 
 1147: Supported constraint types:
 1148: 
 1149: =over 4
 1150: 
 1151: =item * C<number>, C<integer>, C<float>
 1152: 
 1153: Uses numeric values one below, equal to, and one above the boundary.
 1154: 
 1155: =item * C<string>
 1156: 
 1157: Uses strings of lengths one below, equal to, and one above the boundary.
 1158: 
 1159: =item * C<arrayref>
 1160: 
 1161: Uses references to arrays of with the number of elements one below, equal to, and one above the boundary.
 1162: 
 1163: =item * C<hashref>
 1164: 
 1165: Uses hashes with key counts one below, equal to, and one above the
 1166: boundary (C<min> = minimum number of keys, C<max> = maximum number
 1167: of keys).
 1168: 
 1169: =item * C<memberof> - arrayref of allowed values for a parameter
 1170: 
 1171: This example is for a routine called C<input()> that takes two arguments: C<status> and C<level>.
 1172: C<status> is a string that must have the value C<ok>, C<error> or C<pending>.
 1173: The C<level> argument is an integer that must be one of C<1>, C<5> or C<111>.
 1174: 
 1175:   ---
 1176:   input:
 1177:     status:
 1178:       type: string
 1179:       memberof:
 1180:         - ok
 1181:         - error
 1182:         - pending
 1183:     level:
 1184:       type: integer
 1185:       memberof:
 1186:         - 1
 1187:         - 5
 1188:         - 111
 1189: 
 1190: The generator will automatically create test cases for each allowed value (inside the member list),
 1191: and at least one value outside the list (which should die or C<croak>, C<_STATUS = 'DIES'>).
 1192: This works for strings, integers, and numbers.
 1193: 
 1194: =item * C<enum> - synonym of C<memberof>
 1195: 
 1196: =item * C<boolean> - automatic boundary tests for boolean fields
 1197: 
 1198:   input:
 1199:     flag:
 1200:       type: boolean
 1201: 
 1202: 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'>.
 1203: 
 1204: =back
 1205: 
 1206: These edge cases are inserted automatically, in addition to the random
 1207: fuzzing inputs, so each run will reliably probe boundary conditions
 1208: without relying solely on randomness.
 1209: 
 1210: =head1 EXAMPLES
 1211: 
 1212: See the files in C<t/conf> for examples.
 1213: 
 1214: =head2 Adding Scheduled fuzz Testing with GitHub Actions to Your Code
 1215: 
 1216: To automatically create and run tests on a regular basis on GitHub Actions,
 1217: you need to create a configuration file for each method and subroutine that you're testing,
 1218: and a GitHub Actions configuration file.
 1219: 
 1220: This example takes you through testing the online_render method of L<HTML::Genealogy::Map>.
 1221: 
 1222: =head3 t/conf/online_render.yml
 1223: 
 1224:   ---
 1225: 
 1226:   module: HTML::Genealogy::Map
 1227:   function: onload_render
 1228: 
 1229:   input:
 1230:     gedcom:
 1231:       type: object
 1232:       can: individuals
 1233:     geocoder:
 1234:       type: object
 1235:       can: geocode
 1236:     debug:
 1237:       type: boolean
 1238:       optional: true
 1239:     google_key:
 1240:       type: string
 1241:       optional: true
 1242:       min: 39
 1243:       max: 39
 1244:       matches: "^AIza[0-9A-Za-z_-]{35}$"
 1245: 
 1246:   config:
 1247:     test_undef: 0
 1248: 
 1249: =head3 .github/actions/fuzz.t
 1250: 
 1251:   ---
 1252:   name: Fuzz Testing
 1253: 
 1254:   permissions:
 1255:     contents: read
 1256: 
 1257:   on:
 1258:     push:
 1259:       branches: [main, master]
 1260:     pull_request:
 1261:       branches: [main, master]
 1262:     schedule:
 1263:       - cron: '29 5 14 * *'
 1264: 
 1265:   jobs:
 1266:     generate-fuzz-tests:
 1267:       strategy:
 1268:         fail-fast: false
 1269:         matrix:
 1270:           os:
 1271:             - macos-latest
 1272:             - ubuntu-latest
 1273:             - windows-latest
 1274:           perl: ['5.42', '5.40', '5.38', '5.36', '5.34', '5.32', '5.30', '5.28', '5.22']
 1275: 
 1276:       runs-on: ${{ matrix.os }}
 1277:       name: Fuzz testing with perl ${{ matrix.perl }} on ${{ matrix.os }}
 1278: 
 1279:       steps:
 1280:         - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
 1281: 
 1282:         - name: Set up Perl
 1283:           uses: shogo82148/actions-setup-perl@8b574cdc2dffdae49f803204a4f2b716a2fa1db7 # v1.44.2
 1284:           with:
 1285:             perl-version: ${{ matrix.perl }}
 1286: 
 1287:         - name: Install App::Test::Generator this module's dependencies
 1288:           run: |
 1289:             cpanm App::Test::Generator
 1290:             cpanm --installdeps .
 1291: 
 1292:         - name: Make Module
 1293:           run: |
 1294:             perl Makefile.PL
 1295:             make
 1296:           env:
 1297:             AUTOMATED_TESTING: 1
 1298:             NONINTERACTIVE_TESTING: 1
 1299: 
 1300:         - name: Generate fuzz tests
 1301:           run: |
 1302:             mkdir t/fuzz
 1303:             find t/conf -name '*.yml' | while read config; do
 1304:               test_name=$(basename "$config" .conf)
 1305:               fuzz-harness-generator "$config" > "t/fuzz/${test_name}_fuzz.t"
 1306:             done
 1307: 
 1308:         - name: Run generated fuzz tests
 1309:           run: |
 1310:             prove -lr t/fuzz/
 1311:           env:
 1312:             AUTOMATED_TESTING: 1
 1313:             NONINTERACTIVE_TESTING: 1
 1314: 
 1315: =head2 Fuzz Testing your CPAN Module
 1316: 
 1317: Running fuzz tests when you run C<make test> in your CPAN module.
 1318: 
 1319: Create a directory <t/conf> which contains the schemas.
 1320: 
 1321: Then create this file as <t/fuzz.t>:
 1322: 
 1323:   #!/usr/bin/env perl
 1324: 
 1325:   use strict;
 1326:   use warnings;
 1327: 
 1328:   use FindBin qw($Bin);
 1329:   use IPC::Run3;
 1330:   use IPC::System::Simple qw(system);
 1331:   use Test::Needs 'App::Test::Generator';
 1332:   use Test::Most;
 1333: 
 1334:   my $dirname = "$Bin/conf";
 1335: 
 1336:   if((-d $dirname) && opendir(my $dh, $dirname)) {
 1337: 	while (my $filename = readdir($dh)) {
 1338: 		# Skip '.' and '..' entries and vi temporary files
 1339: 		next if ($filename eq '.' || $filename eq '..') || ($filename =~ /\.swp$/);
 1340: 
 1341: 		my $filepath = "$dirname/$filename";
 1342: 
 1343: 		if(-f $filepath) {	# Check if it's a regular file
 1344: 			my ($stdout, $stderr);
 1345: 			run3 ['fuzz-harness-generator', '-r', $filepath], undef, \$stdout, \$stderr;
 1346: 
 1347: 			ok($? == 0, 'Generated test script exits successfully');
 1348: 
 1349: 			if($? == 0) {
 1350: 				ok($stdout =~ /^Result: PASS/ms);
 1351: 				if($stdout =~ /Files=1, Tests=(\d+)/ms) {
 1352: 					diag("$1 tests run");
 1353: 				}
 1354: 			} else {
 1355: 				diag("$filepath: STDOUT:\n$stdout");
 1356: 				diag($stderr) if(length($stderr));
 1357: 				diag("$filepath Failed");
 1358: 				last;
 1359: 			}
 1360: 			diag($stderr) if(length($stderr));
 1361: 		}
 1362: 	}
 1363: 	closedir($dh);
 1364:   }
 1365: 
 1366:   done_testing();
 1367: 
 1368: =head2 Property-Based Testing with Transforms
 1369: 
 1370: The generator can create property-based tests using L<Test::LectroTest> when the
 1371: C<properties> configuration option is enabled.
 1372: This provides more comprehensive
 1373: testing by automatically generating thousands of test cases and verifying that
 1374: mathematical properties hold across all inputs.
 1375: 
 1376: =head3 Basic Property-Based Transform Example
 1377: 
 1378: Here's a complete example testing the C<abs> builtin function:
 1379: 
 1380: B<t/conf/abs.yml>:
 1381: 
 1382:   ---
 1383:   module: builtin
 1384:   function: abs
 1385: 
 1386:   config:
 1387:     test_undef: no
 1388:     test_empty: no
 1389:     test_nuls: no
 1390:     properties:
 1391:       enable: true
 1392:       trials: 1000
 1393: 
 1394:   input:
 1395:     number:
 1396:       type: number
 1397:       position: 0
 1398: 
 1399:   output:
 1400:     type: number
 1401:     min: 0
 1402: 
 1403:   transforms:
 1404:     positive:
 1405:       input:
 1406:         number:
 1407:           type: number
 1408:           min: 0
 1409:       output:
 1410:         type: number
 1411:         min: 0
 1412: 
 1413:     negative:
 1414:       input:
 1415:         number:
 1416:           type: number
 1417:           max: 0
 1418:       output:
 1419:         type: number
 1420:         min: 0
 1421: 
 1422: This configuration:
 1423: 
 1424: =over 4
 1425: 
 1426: =item * Enables property-based testing with 1000 trials per property
 1427: 
 1428: =item * Defines two transforms: one for positive numbers, one for negative
 1429: 
 1430: =item * Automatically generates properties that verify C<abs()> always returns non-negative numbers
 1431: 
 1432: =back
 1433: 
 1434: Generate the test:
 1435: 
 1436:   fuzz-harness-generator t/conf/abs.yml > t/abs_property.t
 1437: 
 1438: The generated test will include:
 1439: 
 1440: =over 4
 1441: 
 1442: =item * Traditional edge-case tests for boundary conditions
 1443: 
 1444: =item * Random fuzzing with 30 iterations (or as configured)
 1445: 
 1446: =item * Property-based tests that verify the transforms with 1000 trials each
 1447: 
 1448: =back
 1449: 
 1450: =head3 What Properties Are Tested?
 1451: 
 1452: The generator automatically detects and tests these properties based on your transform specifications:
 1453: 
 1454: =over 4
 1455: 
 1456: =item * B<Range constraints> - If output has C<min> or C<max>, verifies results stay within bounds
 1457: 
 1458: =item * B<Type preservation> - Ensures numeric inputs produce numeric outputs
 1459: 
 1460: =item * B<Definedness> - Verifies the function doesn't return C<undef> unexpectedly
 1461: 
 1462: =item * B<Specific values> - If output specifies a C<value>, checks exact equality
 1463: 
 1464: =back
 1465: 
 1466: For the C<abs> example above, the generated properties verify:
 1467: 
 1468:   # For the "positive" transform:
 1469:   - Given a positive number, abs() returns >= 0
 1470:   - The result is a valid number
 1471:   - The result is defined
 1472: 
 1473:   # For the "negative" transform:
 1474:   - Given a negative number, abs() returns >= 0
 1475:   - The result is a valid number
 1476:   - The result is defined
 1477: 
 1478: =head3 Advanced Example: String Normalization
 1479: 
 1480: Here's a more complex example testing a string normalization function:
 1481: 
 1482: B<t/conf/normalize.yml>:
 1483: 
 1484:   ---
 1485:   module: Text::Processor
 1486:   function: normalize_whitespace
 1487: 
 1488:   config:
 1489:     properties:
 1490:       enable: true
 1491:       trials: 500
 1492: 
 1493:   input:
 1494:     text:
 1495:       type: string
 1496:       min: 0
 1497:       max: 1000
 1498:       position: 0
 1499: 
 1500:   output:
 1501:     type: string
 1502:     min: 0
 1503:     max: 1000
 1504: 
 1505:   transforms:
 1506:     empty_preserved:
 1507:       input:
 1508:         text:
 1509:           type: string
 1510:           value: ""
 1511:       output:
 1512:         type: string
 1513:         value: ""
 1514: 
 1515:     single_space:
 1516:       input:
 1517:         text:
 1518:           type: string
 1519:           min: 1
 1520:           matches: '^\S+(\s+\S+)*$'
 1521:       output:
 1522:         type: string
 1523:         matches: '^\S+( \S+)*$'
 1524: 
 1525:     length_bounded:
 1526:       input:
 1527:         text:
 1528:           type: string
 1529:           min: 1
 1530:           max: 100
 1531:       output:
 1532:         type: string
 1533:         min: 1
 1534:         max: 100
 1535: 
 1536: This tests that the normalization function:
 1537: 
 1538: =over 4
 1539: 
 1540: =item * Preserves empty strings (C<empty_preserved> transform)
 1541: 
 1542: =item * Collapses multiple spaces into single spaces (C<single_space> transform)
 1543: 
 1544: =item * Maintains length constraints (C<length_bounded> transform)
 1545: 
 1546: =back
 1547: 
 1548: =head3 Interpreting Property Test Results
 1549: 
 1550: When property-based tests run, you'll see output like:
 1551: 
 1552:   ok 123 - negative property holds (1000 trials)
 1553:   ok 124 - positive property holds (1000 trials)
 1554: 
 1555: If a property fails, Test::LectroTest will attempt to find the minimal failing
 1556: case and display it:
 1557: 
 1558:   not ok 123 - positive property holds (47 trials)
 1559:   # Property failed
 1560:   # Reason: counterexample found
 1561: 
 1562: This helps you quickly identify edge cases that your function doesn't handle correctly.
 1563: 
 1564: =head3 Configuration Options for Property-Based Testing
 1565: 
 1566: In the C<config> section:
 1567: 
 1568:   config:
 1569:     properties:
 1570:       enable: true     # Enable property-based testing (default: false)
 1571:       trials: 1000     # Number of test cases per property (default: 1000)
 1572: 
 1573: You can also disable traditional fuzzing and only use property-based tests:
 1574: 
 1575:   config:
 1576:     properties:
 1577:       enable: true
 1578:       trials: 5000
 1579: 
 1580:   iterations: 0  # Disable random fuzzing, use only property tests
 1581: 
 1582: =head3 When to Use Property-Based Testing
 1583: 
 1584: Property-based testing with transforms is particularly useful for:
 1585: 
 1586: =over 4
 1587: 
 1588: =item * Mathematical functions (C<abs>, C<sqrt>, C<min>, C<max>, etc.)
 1589: 
 1590: =item * Data transformations (encoding, normalization, sanitization)
 1591: 
 1592: =item * Parsers and formatters
 1593: 
 1594: =item * Functions with clear input-output relationships
 1595: 
 1596: =item * Code that should satisfy mathematical properties (commutativity, associativity, idempotence)
 1597: 
 1598: =back
 1599: 
 1600: =head3 Requirements
 1601: 
 1602: Property-based testing requires both L<Test::LectroTest> and
 1603: L<Test::LectroTest::Compat> to be installed:
 1604: 
 1605:   cpanm Test::LectroTest Test::LectroTest::Compat
 1606: 
 1607: L<Test::LectroTest::Compat> provides the C<use_ok> bridge between
 1608: L<Test::LectroTest> and L<Test::Most>; it is used in every generated
 1609: property-based test file.  Both are declared in the distribution's
 1610: C<TEST_REQUIRES> so they are installed automatically during C<make test>.
 1611: 
 1612: If not installed, the generated tests will automatically skip the property-based
 1613: portion with a message.
 1614: 
 1615: =head3 Testing Email Validation
 1616: 
 1617:   ---
 1618:   module: Email::Valid
 1619:   function: rfc822
 1620: 
 1621:   config:
 1622:     properties:
 1623:       enable: true
 1624:       trials: 200
 1625:     close_stdin: true
 1626:     test_undef: no
 1627:     test_empty: no
 1628:     test_nuls: no
 1629: 
 1630:   input:
 1631:     email:
 1632:       type: string
 1633:       semantic: email
 1634:       position: 0
 1635: 
 1636:   output:
 1637:     type: boolean
 1638: 
 1639:   transforms:
 1640:     valid_emails:
 1641:       input:
 1642:         email:
 1643:           type: string
 1644:           semantic: email
 1645:       output:
 1646:         type: boolean
 1647: 
 1648: This generates 200 realistic email addresses for testing, rather than random strings.
 1649: 
 1650: =head3 Combining Semantic with Regex
 1651: 
 1652: You can combine semantic generators with regex validation:
 1653: 
 1654:   input:
 1655:     corporate_email:
 1656:       type: string
 1657:       semantic: email
 1658:       matches: '@company\.com$'
 1659: 
 1660: The semantic generator creates realistic emails, and the regex ensures they match your domain.
 1661: 
 1662: =head3 Custom Properties for Transforms
 1663: 
 1664: You can define additional properties that should hold for your transforms beyond
 1665: the automatically detected ones.
 1666: 
 1667: =head4 Using Built-in Properties
 1668: 
 1669:   transforms:

Mutants (Total: 1, Killed: 1, Survived: 0)

1670: positive: 1671: input: 1672: number: 1673: type: number 1674: min: 0 1675: output: 1676: type: number 1677: min: 0 1678: properties: 1679: - idempotent # f(f(x)) == f(x) 1680: - non_negative # result >= 0 1681: - positive # result > 0

Mutants (Total: 1, Killed: 1, Survived: 0)

1682: 1683: Available built-in properties: 1684: 1685: =over 4 1686: 1687: =item * C<idempotent> - Function is idempotent: f(f(x)) == f(x) 1688: 1689: =item * C<non_negative> - Result is always >= 0 1690: 1691: =item * C<positive> - Result is always > 0 1692: 1693: =item * C<non_empty> - String result is never empty

Mutants (Total: 1, Killed: 1, Survived: 0)

1694: 1695: =item * C<length_preserved> - Output length equals input length 1696: 1697: =item * C<uppercase> - Result is all uppercase 1698: 1699: =item * C<lowercase> - Result is all lowercase 1700: 1701: =item * C<trimmed> - No leading/trailing whitespace 1702:

Mutants (Total: 1, Killed: 1, Survived: 0)

1703: =item * C<sorted_ascending> - Array is sorted ascending 1704: 1705: =item * C<sorted_descending> - Array is sorted descending 1706: 1707: =item * C<unique_elements> - Array has no duplicates 1708: 1709: =item * C<preserves_keys> - Hash has same keys as input

Mutants (Total: 1, Killed: 1, Survived: 0)

1710: 1711: =back 1712: 1713: =head4 Custom Property Code 1714: 1715: Custom properties allows the definition additional invariants and relationships that should hold for their transforms, 1716: beyond what's auto-detected. 1717: For example: 1718: 1719: =over 4 1720: 1721: =item * Idempotence: f(f(x)) == f(x) 1722: 1723: =item * Commutativity: f(x, y) == f(y, x) 1724: 1725: =item * Associativity: f(f(x, y), z) == f(x, f(y, z)) 1726: 1727: =item * Inverse relationships: decode(encode(x)) == x 1728:

Mutants (Total: 1, Killed: 1, Survived: 0)

1729: =item * Domain-specific invariants: Custom business logic 1730: 1731: =back 1732: 1733: Define your own properties with custom Perl code: 1734: 1735: transforms: 1736: normalize: 1737: input: 1738: text: 1739: type: string 1740: output: 1741: type: string 1742: properties: 1743: - name: single_spaces

Mutants (Total: 1, Killed: 1, Survived: 0)

1744: description: "No multiple consecutive spaces"

Mutants (Total: 1, Killed: 1, Survived: 0)

1745: code: $result !~ / / 1746: 1747: - name: no_leading_space 1748: description: "No space at start" 1749: code: $result !~ /^\s/

Mutants (Total: 1, Killed: 1, Survived: 0)

1750: 1751: - name: reversible 1752: description: "Can be reversed back" 1753: code: length($result) == length($text) 1754: 1755: The code has access to: 1756: 1757: =over 4

Mutants (Total: 1, Killed: 1, Survived: 0)

1758: 1759: =item * C<$result> - The function's return value 1760: 1761: =item * Input variables - All input parameters (e.g., C<$text>, C<$number>) 1762: 1763: =item * The function itself - Can call it again for idempotence checks 1764: 1765: =back 1766: 1767: =head4 Combining Auto-detected and Custom Properties 1768: 1769: The generator automatically detects properties from your output spec, and adds 1770: your custom properties: 1771: 1772: transforms: 1773: sanitize: 1774: input: 1775: html: 1776: type: string 1777: output:

Mutants (Total: 1, Killed: 1, Survived: 0)

1778: type: string 1779: min: 0 # Auto-detects: defined, min_length >= 0 1780: max: 10000 1781: properties: # Additional custom checks:

Mutants (Total: 1, Killed: 1, Survived: 0)

1782: - name: no_scripts 1783: code: $result !~ /<script/i 1784: - name: no_iframes 1785: code: $result !~ /<iframe/i 1786: 1787: =head2 GENERATED OUTPUT

Mutants (Total: 1, Killed: 1, Survived: 0)

1788: 1789: The generated test: 1790: 1791: =over 4 1792: 1793: =item * Seeds RND (if configured) for reproducible fuzz runs 1794: 1795: =item * Uses edge cases (per-field and per-type) with configurable probability 1796: 1797: =item * Runs C<$iterations> fuzz cases plus appended edge-case runs 1798: 1799: =item * Validates inputs with Params::Get / Params::Validate::Strict 1800:

Mutants (Total: 1, Killed: 1, Survived: 0)

1801: =item * Asserts that a wrong-typed argument dies, where the type is enforced 1802: 1803: Passing a reference where a string is declared is only expected to die for a 1804: parameter whose input spec sets C<_source: validator>. 1805: L<App::Test::Generator::SchemaExtractor> sets that source when the routine

Mutants (Total: 1, Killed: 1, Survived: 0)

1806: checks its arguments with a validator such as L<Params::Validate::Strict>.

Mutants (Total: 1, Killed: 1, Survived: 0)

1807: A type taken from POD, or inferred from the code, documents intent but does not 1808: promise rejection, so no such case is generated for it. 1809: Add the source by hand to a schema whose routine does check its argument types.

Mutants (Total: 1, Killed: 0, Survived: 1)
1810: 1811: =item * Validates outputs with L<Return::Set> 1812: 1813: =item * Runs static C<is(... )> corpus tests from Perl and/or YAML corpus 1814: 1815: =item * Runs L<Test::LectroTest> tests

Mutants (Total: 1, Killed: 1, Survived: 0)

1816: 1817: =back 1818: 1819: =cut 1820: 1821: =head1 METHODS 1822: 1823: =head2 generate 1824: 1825: Takes a schema file and produces a test file (or STDOUT). 1826:

Mutants (Total: 1, Killed: 1, Survived: 0)

1827: # Modern named API 1828: App::Test::Generator->generate( 1829: schema_file => 'schemas/foo.yml', 1830: output_file => 'test/foo.t', 1831: ); 1832: 1833: # Feed surviving mutants into the generated harness 1834: App::Test::Generator->generate( 1835: schema_file => 'schemas/foo.yml', 1836: mutation_results => 'mutation.json', 1837: output_file => 'test/foo.t', 1838: ); 1839: 1840: # Legacy positional API 1841: App::Test::Generator->generate($schema_file, $test_file);

Mutants (Total: 1, Killed: 0, Survived: 1)
1842: 1843: =head3 API SPECIFICATION 1844: 1845: =head4 Input 1846: 1847: { 1848: schema_file => { type => 'string', optional => 0 }, 1849: input_file => { type => 'string', optional => 1 }, 1850: output_file => { type => 'string', optional => 1, max => 255 }, 1851: strict_documented => { type => 'boolean', optional => 1 }, 1852: mutation_results => { type => 'string', optional => 1 }, 1853: } 1854: 1855: C<mutation_results> is the JSON report written by 1856: C<test-generator-mutate --json>. Surviving numeric-boundary mutants are 1857: converted into C<min> or C<max> constraints on the matching input field, so 1858: the harness generates data either side of the boundary the survivor exposed. 1859: Existing constraints are never replaced. See 1860: L<App::Test::Generator::Mutation::Feedback>. 1861: 1862: =head4 Output 1863: 1864: { type => 'boolean' } 1865: 1866: Always 1. The test source itself is written to C<output_file>, or printed 1867: on STDOUT when no output file is given; it is not returned. 1868: 1869: The mathematical description is in L</FORMAL SPECIFICATION>. 1870: 1871: =cut 1872: 1873: sub generate 1874: { ●1875 → 1888 → 1937 1875: croak 'Usage: generate(schema_file [, outfile])' if(scalar(@_) == 0); 1876: 1877: # Accept both class-method call (App::Test::Generator->generate(...)) 1878: # and plain-function call with a hashref (generate({...})). 1879: # In the method form the first arg is the class name (a plain string); 1880: # in the function form with a hashref the first arg IS the hashref. 1881: my $class = (ref($_[0]) ne 'HASH') ? shift : undef; 1882: my ($schema_file, $test_file, $schema); 1883: # Globals loaded from the user's conf (all optional except function maybe) 1884: my ($module, $function, $new, $yaml_cases, $invocant); 1885: my ($seed, $iterations); 1886: my $strict_documented = 0; 1887: 1888: if((ref($_[0]) eq 'HASH') || defined($_[2])) { 1889: # Modern API 1890: my $params = Params::Validate::Strict::validate_strict({ 1891: args => Params::Get::get_params(undef, \@_), 1892: schema => { 1893: input_file => { type => 'string', optional => 1 }, 1894: schema_file => { type => 'string', optional => 1 },
Mutants (Total: 2, Killed: 0, Survived: 2)
1895: output_file => { type => 'string', optional => 1 },
Mutants (Total: 2, Killed: 0, Survived: 2)
1896: schema => { type => 'hashref', optional => 1 }, 1897: quiet => { type => 'boolean', optional => 1 }, # Not yet used 1898: strict_documented => { type => 'boolean', optional => 1 }, 1899: mutation_results => { type => 'string', optional => 1 }, 1900: }

Mutants (Total: 2, Killed: 2, Survived: 0)

1901: });

Mutants (Total: 2, Killed: 0, Survived: 2)
1902: $strict_documented = $params->{'strict_documented'} ? 1 : 0;

Mutants (Total: 2, Killed: 2, Survived: 0)

1903: if($params->{'schema_file'}) {

Mutants (Total: 2, Killed: 2, Survived: 0)

1904: $schema_file = $params->{'schema_file'}; 1905: } elsif($params->{'input_file'}) { 1906: $schema_file = $params->{'input_file'}; 1907: } elsif($params->{'schema'}) { 1908: $schema = $params->{'schema'}; 1909: } else { 1910: croak(__PACKAGE__, ': Usage: generate(input_file|schema [, output_file]'); 1911: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1912: if(defined($schema_file)) { 1913: $schema = _load_schema($schema_file); 1914: } 1915: if($params->{'mutation_results'}) { 1916: # Surviving mutants add constraints the schema is missing, so 1917: # the harness exercises the boundary that survived the suite. 1918: require App::Test::Generator::Mutation::Feedback; 1919: my $feedback = App::Test::Generator::Mutation::Feedback->new( 1920: mutation_results => $params->{'mutation_results'},

Mutants (Total: 1, Killed: 1, Survived: 0)

1921: (defined($schema->{module}) ? (module => $schema->{module}) : ()), 1922: ); 1923: $feedback->apply_to_schema($schema);

Mutants (Total: 1, Killed: 1, Survived: 0)

1924: } 1925: $test_file = $params->{'output_file'}; 1926: } else { 1927: # Legacy API 1928: ($schema_file, $test_file) = @_; 1929: if(defined($schema_file)) { 1930: $schema = _load_schema($schema_file); 1931: } else { 1932: croak 'Usage: generate(schema_file [, outfile])'; 1933: } 1934: }

Mutants (Total: 2, Killed: 1, Survived: 1)
1935: 1936: # Parse the schema file and load into our structures ●1937 → 1948 → 1951 1937: my %input = %{_load_schema_section($schema, 'input', $schema_file)}; 1938: my %output = %{_load_schema_section($schema, 'output', $schema_file)}; 1939: my %transforms = %{_load_schema_section($schema, 'transforms', $schema_file)}; 1940: my %accessor = %{_load_schema_section($schema, 'accessor', $schema_file)}; 1941: 1942: my %cases = %{$schema->{cases}} if(exists($schema->{cases})); 1943: my %edge_cases = %{$schema->{edge_cases}} if(exists($schema->{edge_cases}));

Mutants (Total: 1, Killed: 1, Survived: 0)

1944: my %type_edge_cases = %{$schema->{type_edge_cases}} if(exists($schema->{type_edge_cases}));

Mutants (Total: 1, Killed: 0, Survived: 1)
1945: 1946: $module = $schema->{module} if(exists($schema->{module}) && length($schema->{module})); 1947: $function = $schema->{function} if(exists($schema->{function})); 1948: if(exists($schema->{new})) {
Mutants (Total: 1, Killed: 0, Survived: 1)
1949: $new = defined($schema->{'new'}) ? $schema->{new} : '_UNDEF'; 1950: } ●1951 → 1965 → 1979 1951: $invocant = $schema->{invocant} if(exists($schema->{invocant}) && defined($schema->{invocant})); 1952: $yaml_cases = $schema->{yaml_cases} if(exists($schema->{yaml_cases})); 1953: $seed = $schema->{seed} if(exists($schema->{seed})); 1954: $iterations = $schema->{iterations} if(exists($schema->{iterations})); 1955: 1956: my @edge_case_array = @{$schema->{edge_case_array}} if(exists($schema->{edge_case_array})); 1957: _validate_config($schema); 1958: 1959: my %config = %{$schema->{config}} if(exists($schema->{config})); 1960:

Mutants (Total: 1, Killed: 1, Survived: 0)

1961: _normalize_config(\%config);

Mutants (Total: 1, Killed: 0, Survived: 1)
1962: $config{'strict_documented'} = $strict_documented; 1963: 1964: # Guess module name from config file if not set 1965: if(!$module) {
Mutants (Total: 1, Killed: 0, Survived: 1)
1966: if($schema_file) { 1967: ($module = basename($schema_file)) =~ s/\.(conf|pl|pm|yml|yaml)$//; 1968: $module =~ s/-/::/g; 1969: # Guard against Perl builtin function names being mistaken 1970: # for module names — builtins have no module to load 1971: if(_is_perl_builtin($module)) { 1972: undef $module; 1973: } 1974: } 1975: } elsif($module eq $MODULE_BUILTIN) { 1976: undef $module; 1977: }

Mutants (Total: 1, Killed: 1, Survived: 0)

1978: ●1979 → 1979 → 1986 1979: if($module && length($module) && ($module ne 'builtin')) { 1980: _validate_module($module, $schema_file); 1981: }

Mutants (Total: 1, Killed: 0, Survived: 1)
1982: 1983: # $module/$function are spliced unescaped into generated test 1984: # source below (use_ok, new_ok, ->$function, $module::$function) 1985: # — reject anything that isn't identifier-shaped before that happens. ●1986 → 1999 → 2020 1986: _assert_identifier($module, 'module', package => 1) if defined($module) && length($module); 1987: 1988: # sensible defaults 1989: $function ||= 'run'; 1990: # package => 1: fully-qualified sub names (e.g. DB::DB, a debugger 1991: # hook installed into the DB:: package regardless of its source 1992: # package) are legitimate function names, not just bare identifiers 1993: _assert_identifier($function, 'function', package => 1); 1994: $iterations ||= $DEFAULT_ITERATIONS; # default fuzz runs if not specified 1995: $seed = undef if defined $seed && $seed eq ''; # treat empty as undef 1996: 1997: # --- YAML corpus support (yaml_cases is filename string) --- 1998: my %yaml_corpus_data;

Mutants (Total: 1, Killed: 1, Survived: 0)

1999: if (defined $yaml_cases) { 2000: croak("$yaml_cases: $!") if(!-f $yaml_cases); 2001: 2002: my $yaml_data = LoadFile(Encode::decode('utf8', $yaml_cases)); 2003: if ($yaml_data && ref($yaml_data) eq 'HASH') { 2004: # Validate that the corpus inputs are arrayrefs 2005: # e.g: "FooBar": ["foo_bar"] 2006: # Skip only invalid entries: 2007: for my $expected (keys %{$yaml_data}) { 2008: my $outputs = $yaml_data->{$expected}; 2009: unless($outputs && (ref $outputs eq 'ARRAY')) { 2010: carp("$yaml_cases: $expected does not point to an array ref, ignoring"); 2011: next; 2012: } 2013: $yaml_corpus_data{$expected} = $outputs; 2014: } 2015: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2016: } 2017: 2018: # Merge Perl %cases and YAML corpus safely 2019: # my %all_cases = (%cases, %yaml_corpus_data); ●2020 → 2021 → 2027 2020: my %all_cases = (%yaml_corpus_data, %cases);

Mutants (Total: 1, Killed: 1, Survived: 0)

2021: for my $k (keys %yaml_corpus_data) { 2022: if (exists $cases{$k} && ref($cases{$k}) eq 'ARRAY' && ref($yaml_corpus_data{$k}) eq 'ARRAY') { 2023: $all_cases{$k} = [ @{$yaml_corpus_data{$k}}, @{$cases{$k}} ]; 2024: } 2025: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2026:

Mutants (Total: 2, Killed: 2, Survived: 0)

●2027 → 2027 → 2037 2027: if(my $hints = delete $schema->{_yamltest_hints}) { 2028: if(my $boundaries = $hints->{boundary_values}) { 2029: push @edge_case_array, @{$boundaries};

Mutants (Total: 2, Killed: 2, Survived: 0)

2030: } 2031: if(my $invalid = $hints->{invalid}) { 2032: carp('TODO: handle yamltest_hints->invalid'); 2033: } 2034: } 2035: 2036: # If the schema says the type is numeric, normalize ●2037 → 2037 → 2047 2037: if ($schema->{type} && $schema->{type} =~ /^(integer|number|float)$/) { 2038: for (@edge_case_array) { 2039: next unless defined $_; 2040: $_ += 0 if Scalar::Util::looks_like_number($_); 2041: } 2042: } 2043: 2044: # Load relationships from the schema if present and well-formed. 2045: # SchemaExtractor may set this to undef or an empty arrayref when 2046: # no relationships were detected, so guard both existence and type. ●2047 → 2048 → 2056 2047: my @relationships;

Mutants (Total: 2, Killed: 2, Survived: 0)

2048: if(exists($schema->{relationships}) && ref($schema->{relationships}) eq 'ARRAY') { 2049: @relationships = @{$schema->{relationships}}; 2050: } 2051: 2052: # Serialise the relationships array from the schema into Perl source

Mutants (Total: 1, Killed: 1, Survived: 0)

2053: # code for embedding in the generated test file. Each relationship 2054: # type is rendered as a hashref in the @relationships array.

Mutants (Total: 1, Killed: 1, Survived: 0)

2055: ●2056 → 2059 → 2108 2056: my $relationships_code = ''; 2057: 2058: # Walk each relationship in the order SchemaExtractor produced them 2059: for my $rel (@relationships) { 2060: my $type = $rel->{type} // '';

Mutants (Total: 1, Killed: 1, Survived: 0)

2061: 2062: # Mutually exclusive: both params being set should cause the method to die

Mutants (Total: 1, Killed: 1, Survived: 0)

2063: if($type eq 'mutually_exclusive') {

Mutants (Total: 1, Killed: 1, Survived: 0)

2064: $relationships_code .= "{ type => 'mutually_exclusive', params => [" . 2065: join(', ', map { perl_quote($_) } @{$rel->{params}}) . 2066: "] },\n"; 2067: 2068: # Required group: at least one of the params must be present 2069: } elsif($type eq 'required_group') { 2070: $relationships_code .= "{ type => 'required_group', params => [" .

Mutants (Total: 1, Killed: 0, Survived: 1)
2071: join(', ', map { perl_quote($_) } @{$rel->{params}}) . 2072: "], logic => " . perl_quote($rel->{logic} // 'or') . " },\n"; 2073: 2074: # Conditional requirement: if one param is set, another becomes mandatory

Mutants (Total: 1, Killed: 1, Survived: 0)

2075: } elsif($type eq 'conditional_requirement') { 2076: $relationships_code .= "{ type => 'conditional_requirement', if => " . 2077: perl_quote($rel->{'if'}) . ", then_required => " . 2078: perl_quote($rel->{then_required}) . " },\n"; 2079:

Mutants (Total: 1, Killed: 1, Survived: 0)

2080: # Dependency: one param requires another to also be present 2081: } elsif($type eq 'dependency') { 2082: $relationships_code .= "{ type => 'dependency', param => " . 2083: perl_quote($rel->{param}) . ", requires => " . 2084: perl_quote($rel->{requires}) . " },\n"; 2085:

Mutants (Total: 1, Killed: 1, Survived: 0)

2086: # Value constraint: one param being set forces another to a specific value 2087: } elsif($type eq 'value_constraint') { 2088: $relationships_code .= "{ type => 'value_constraint', if => " . 2089: perl_quote($rel->{'if'}) . ", then => " . 2090: perl_quote($rel->{then}) . ", operator => " .

Mutants (Total: 2, Killed: 2, Survived: 0)

2091: perl_quote($rel->{operator}) . ", value => " .

Mutants (Total: 1, Killed: 1, Survived: 0)

2092: perl_quote($rel->{value}) . " },\n"; 2093: 2094: # Value conditional: one param equalling a specific value requires another param 2095: } elsif($type eq 'value_conditional') { 2096: $relationships_code .= "{ type => 'value_conditional', if => " . 2097: perl_quote($rel->{'if'}) . ", equals => " .

Mutants (Total: 1, Killed: 0, Survived: 1)
2098: perl_quote($rel->{equals}) . ", then_required => " .
Mutants (Total: 1, Killed: 0, Survived: 1)
2099: perl_quote($rel->{then_required}) . " },\n"; 2100: 2101: # Unknown type — warn and skip rather than emitting broken code 2102: } else { 2103: carp "Unknown relationship type '$type', skipping"; 2104: }
Mutants (Total: 1, Killed: 0, Survived: 1)
2105: } 2106: 2107: # Dedup the edge cases ●2108 → 2133 → 2138 2108: my %seen; 2109: @edge_case_array = grep { 2110: my $key = defined($_) ? (Scalar::Util::looks_like_number($_) ? "N:$_" : "S:$_") : 'U'; 2111: !$seen{$key}++;
Mutants (Total: 1, Killed: 0, Survived: 1)
2112: } @edge_case_array; 2113: 2114: # Sort the edge cases to keep it consistent across runs 2115: @edge_case_array = sort { 2116: return -1 if !defined $a; 2117: return 1 if !defined $b; 2118: 2119: my $na = Scalar::Util::looks_like_number($a); 2120: my $nb = Scalar::Util::looks_like_number($b);

Mutants (Total: 1, Killed: 1, Survived: 0)

2121:

Mutants (Total: 1, Killed: 1, Survived: 0)

2122: return $a <=> $b if $na && $nb; 2123: return -1 if $na; 2124: return 1 if $nb;

Mutants (Total: 1, Killed: 0, Survived: 1)
2125: return $a cmp $b; 2126: } @edge_case_array; 2127: 2128: # render edge case maps for inclusion in the .t 2129: my $edge_cases_code = render_arrayref_map(\%edge_cases); 2130: my $type_edge_cases_code = render_arrayref_map(\%type_edge_cases); 2131: 2132: my $edge_case_array_code = ''; 2133: if(scalar(@edge_case_array)) { 2134: $edge_case_array_code = join(', ', map { q_wrap($_) } @edge_case_array); 2135: } 2136: 2137: # Render configuration - all the values are integers for now, if that changes, wrap the $config{$key} in single quotes

Mutants (Total: 1, Killed: 1, Survived: 0)

●2138 → 2139 → 2155 2138: my $config_code = ''; 2139: foreach my $key (sort keys %config) { 2140: # Skip nested structures like 'properties' - they're used during 2141: # generation but don't need to be in the generated test 2142: if(ref($config{$key}) eq 'HASH') { 2143: next; 2144: } 2145: if((!defined($config{$key})) || !$config{$key}) { 2146: # YAML will strip the word 'false' 2147: # e.g. in 'test_undef: false' 2148: $config_code .= "'$key' => 0,\n"; 2149: } else { 2150: $config_code .= "'$key' => $config{$key},\n"; 2151: } 2152: } 2153: 2154: # Render input/output ●2155 → 2156 → 2165 2155: my $input_code = ''; 2156: if(((scalar keys %input) == 1) && exists($input{'type'}) && !ref($input{'type'})) { 2157: # %input = ( type => 'string' ); 2158: foreach my $key (sort keys %input) { 2159: $input_code .= "'$key' => '$input{$key}',\n"; 2160: } 2161: } else { 2162: # %input = ( str => { type => 'string' } );

Mutants (Total: 1, Killed: 1, Survived: 0)

2163: $input_code = render_hash(\%input); 2164: } ●2165 → 2165 → 2182 2165: if(defined(my $re = $output{'matches'})) { 2166: if(ref($re) ne 'Regexp') { 2167: # Use eval to compile safely — qr/$re/ would interpolate 2168: # the string first, corrupting patterns containing [ or \ 2169: my $compiled = eval { qr/$re/ }; 2170: if($@) { 2171: carp("Invalid matches pattern '$re': $@"); 2172: } else { 2173: $output{'matches'} = $compiled; 2174: } 2175: } 2176: } 2177:

Mutants (Total: 1, Killed: 1, Survived: 0)

2178: # Compile nomatch pattern to a Regexp object so it renders 2179: # as qr{} in the generated test rather than a raw string. 2180: # Without this, patterns containing [ or other regex 2181: # metacharacters cause compilation failures in validators ●2182 → 2182 → 2195 2182: if(defined(my $re = $output{'nomatch'})) { 2183: if(ref($re) ne 'Regexp') { 2184: # Use eval to compile safely — qr/$re/ would interpolate 2185: # the string first, corrupting patterns containing [ or \ 2186: my $compiled = eval { qr/$re/ }; 2187: if($@) {

Mutants (Total: 1, Killed: 0, Survived: 1)
2188: carp("Invalid nomatch pattern '$re': $@"); 2189: } else { 2190: $output{'nomatch'} = $compiled; 2191: } 2192: } 2193: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2194: ●2195 → 2199 → 2217 2195: my $output_code = render_args_hash(\%output); 2196: my $new_code = ($new && (ref $new eq 'HASH')) ? render_args_hash($new) : ''; 2197:

Mutants (Total: 1, Killed: 0, Survived: 1)
2198: my $transforms_code; 2199: if(keys %transforms) { 2200: foreach my $transform(keys %transforms) { 2201: my $properties = render_fallback($transforms{$transform}->{'properties'}); 2202: 2203: if($transforms_code) { 2204: $transforms_code .= "},\n"; 2205: } 2206: $transforms_code .= "$transform => {\n" . 2207: "\t'input' => { " . 2208: render_args_hash($transforms{$transform}->{'input'}) . 2209: "\t}, 'output' => { " . 2210: render_args_hash($transforms{$transform}->{'output'}) .
Mutants (Total: 1, Killed: 0, Survived: 1)
2211: "\t}, 'properties' => $properties\n" . 2212: "\t,\n"; 2213: }
Mutants (Total: 1, Killed: 0, Survived: 1)
2214: $transforms_code .= "}\n";
Mutants (Total: 1, Killed: 0, Survived: 1)
2215: } 2216: ●2217 → 2220 → 2237 2217: my $transform_properties_code = ''; 2218: my $use_properties = 0; 2219: 2220: if (keys %transforms && ($config{properties}{enable} // 0)) { 2221: $use_properties = 1; 2222: 2223: # Generate property-based tests for transforms 2224: my $properties = _generate_transform_properties( 2225: \%transforms,
Mutants (Total: 1, Killed: 0, Survived: 1)
2226: $function,
Mutants (Total: 1, Killed: 0, Survived: 1)
2227: $module, 2228: \%input, 2229: \%config, 2230: $new 2231: ); 2232: 2233: # Convert to code for template 2234: $transform_properties_code = _render_properties($properties); 2235: } 2236: ●2237 → 2237 → 2258 2237: if(keys %accessor) { 2238: # Sanity test
Mutants (Total: 1, Killed: 0, Survived: 1)
2239: my $property = $accessor{property};
Mutants (Total: 1, Killed: 0, Survived: 1)
2240: my $type = $accessor{type}; 2241: 2242: if(!defined($new)) { 2243: # Internal invariant — schema has a contradictory accessor+type combination; 2244: # confess gives the full call chain to aid debugging 2245: confess("invariant violation: $property: accessor $type can only work on an object, incorrectly tagged as $type"); 2246: } 2247: if($type eq 'getset') {
Mutants (Total: 1, Killed: 0, Survived: 1)
2248: if(scalar(keys %input) != 1) { 2249: confess("invariant violation: $property: getset must take one input argument, incorrectly tagged as getset"); 2250: } 2251: if(scalar(keys %output) == 0) { 2252: confess("invariant violation: $property: getset must give one output, incorrectly tagged as getset"); 2253: } 2254: } 2255: } 2256: 2257: # Setup / call code (always load module) ●2258 → 2269 → 2274 2258: my $setup_code = ($module) ? "BEGIN { use_ok('$module') }" : ''; 2259: my $call_code; # Code to call the function being test when used with named arguments

Mutants (Total: 1, Killed: 1, Survived: 0)

2260: my $position_code; # Code to call the function being test when used with position arguments

Mutants (Total: 1, Killed: 0, Survived: 1)
2261: my $has_positions = _has_positions(\%input); 2262: 2263: # Numeric values have no single string form: one and the same integer can 2264: # stringify as "5967331536404480" (an IV) or "5.96733153640448e+15" (an 2265: # NV), so a getset round trip on an integer or number parameter is compared 2266: # numerically. The routine returns the value unchanged, yet eq failed on 2267: # the harness's own input about once in forty runs. 2268: my $cmp_op = 'eq'; 2269: if(scalar(keys %input) == 1) { 2270: my ($spec) = values %input; 2271: my $type = (ref($spec) eq 'HASH') ? $spec->{type} : $spec; 2272: $cmp_op = '==' if(defined($type) && !ref($type) && ($type =~ /^(?:integer|number|float)$/)); 2273: } ●2274 → 2274 → 2347 2274: if(defined($new) && defined($module)) { 2275: # keep use_ok regardless (user found earlier issue) 2276: if($new_code eq '') { 2277: $new_code = "new_ok('$module')";

Mutants (Total: 1, Killed: 1, Survived: 0)

2278: } else { 2279: $new_code = "new_ok('$module' => [ $new_code ] )"; 2280: } 2281: $setup_code .= "\nmy \$obj = $new_code;"; 2282: if($has_positions) { 2283: $position_code = "\$result = (scalar(\@alist) == 1) ? \$obj->$function(\$alist[0]) : (scalar(\@alist) == 0) ? \$obj->$function() : \$obj->$function(\@alist);"; 2284: if(defined($accessor{type})) { 2285: if($accessor{type} eq 'getter') { 2286: $position_code .= "my \$prev_value = \$obj->{$accessor{property}};"; 2287: } elsif($accessor{type} eq 'getset') { 2288: $position_code .= 'if(scalar(@alist) == 1) { '; 2289: $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');"; 2290: $position_code .= '}'; 2291: } 2292: if(($accessor{type} eq 'getset') || ($accessor{type} eq 'getter')) { 2293: # Since Perl doesn't support data encapsulation, we can test the getter returns the correct item 2294: $position_code .= 'if(scalar(@alist) == 1) { '; 2295: $position_code .= "cmp_ok(\$result, '$cmp_op', \$obj->{$accessor{property}}, 'getset function returns correct item');"; 2296: if($accessor{type} eq 'getter') { 2297: $position_code .= "if(defined(\$prev_value)) { cmp_ok(\$result, 'eq', \$prev_value, 'getter does not change value'); } "; 2298: } 2299: $position_code .= '}'; 2300: } 2301: if($output{'_returns_self'}) { 2302: croak("$accessor{type} for $accessor{property} cannot return \$self"); 2303: } 2304: } 2305: } else { 2306: $call_code = "\$result = \$obj->$function(_fuzz_args(\$input));"; 2307: if($output{'_returns_self'}) { 2308: $call_code .= "ok(defined(\$result)); ok(\$result eq \$obj, '$function returns self')"; 2309: } elsif(defined($accessor{type}) && ($accessor{type} eq 'getset')) { 2310: $call_code .= "ok(\$obj->$function() $cmp_op \$result, 'test getset accessor');" 2311: } 2312: if(scalar(keys %input) == 0) { 2313: if(defined($accessor{type}) && ($accessor{type} eq 'getter')) { 2314: $call_code .= "cmp_ok(\$result, 'eq', \$obj->{$accessor{property}}, 'getter function returns correct item') if(defined(\$result));"; 2315: } 2316: } 2317: } 2318: } elsif(defined($module) && length($module)) { 2319: # `import` is a class method: `use Module` calls Module->import(...). 2320: # Some modules (Database::Abstraction) take the class as their first 2321: # argument, so a plain Module::import() with no named arguments dies.

Mutants (Total: 1, Killed: 1, Survived: 0)

2322: # A documented $class invocant (or new/import) is called on the class 2323: # itself; without one the routine is a plain function of the module. 2324: if(($function eq 'new') || ($function eq 'import') || (defined($invocant) && ($invocant eq 'class') && !defined($new))) { 2325: if($has_positions) { 2326: $position_code = "\$result = (scalar(\@alist) == 1) ? ${module}\->$function(\$alist[0]) : (scalar(\@alist) == 0) ? ${module}\->$function() : ${module}\->$function(\@alist);"; 2327: } else { 2328: $call_code = "\$result = ${module}\->$function(_fuzz_args(\$input));"; 2329: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2330: } else { 2331: if($has_positions) { 2332: $position_code = "\$result = (scalar(\@alist) == 1) ? ${module}::$function(\$alist[0]) : (scalar(\@alist) == 0) ? ${module}::$function() : ${module}::$function(\@alist);"; 2333: } else { 2334: $call_code = "\$result = ${module}::$function(_fuzz_args(\$input));"; 2335: } 2336: } 2337: } else { 2338: if($has_positions) { 2339: $position_code = "\$result = $function(\@alist);"; 2340: } else { 2341: $call_code = "\$result = $function(_fuzz_args(\$input));"; 2342: } 2343: } 2344: 2345: # List-context capture: $result = func() in scalar context returns a count, not the list. 2346: # When the schema says output type is 'array', capture into @_r then take a ref. ●2347 → 2347 → 2364 2347: if(($output{type} // '') eq 'array') { 2348: if(defined($call_code)) { 2349: $call_code =~ s/\A\$result = ([^;]+);/my \@_r = ($1); \$result = \\\@_r;/; 2350: } 2351: if(defined($position_code)) { 2352: $position_code =~ s/\A\$result = ([^;]+);/my \@_r = ($1); \$result = \\\@_r;/; 2353: } 2354: }

Mutants (Total: 2, Killed: 2, Survived: 0)

2355: 2356: # A getter is called for its return value, so it must not change the state 2357: # of the object it was handed. The object is deep copied before the call 2358: # and its existing state compared afterwards; values it fills in where it 2359: # was handed undef are ignored along with keys it adds, because a getter 2360: # that caches the value it worked out is doing its job, while one that 2361: # overwrites or removes state it was given is not 2362: # - the change is invisible to the caller, which still holds the object, 2363: # and the next call sees different behaviour for the same input. ●2364 → 2364 → 2389 2364: if(defined($accessor{type}) && ($accessor{type} eq 'getter')) { 2365: # A getter with no declared input must be called with no arguments: 2366: # $input is the schema's own hashref, and a getter that takes 2367: # an optional second argument would store it as if it were a value. 2368: foreach my $code (\$call_code, \$position_code) { 2369: next unless(defined($$code)); 2370: $$code =~ s/\Q$function\E\(_fuzz_args\(\$input\)\)/$function()/g; 2371: } 2372: my $snapshot = 'my $getter_copy = eval { require Storable; Storable::dclone($obj) }; '; 2373: my $check = 'if(defined($getter_copy) && eval { scalar(keys %{$getter_copy}); 1 }) {' 2374: . ' my %getter_state = map { $_ => $getter_copy->{$_} } grep { defined($getter_copy->{$_}) } keys %{$getter_copy};' 2375: . ' is_deeply({ map { $_ => $obj->{$_} } grep { exists($obj->{$_}) } keys %getter_state }, \\%getter_state, q{getter leaves its object unmodified});' 2376: . ' }'; 2377: foreach my $code (\$call_code, \$position_code) { 2378: next unless(defined($$code) && ($config{'check_accessors'} // 1)); 2379: $$code = $snapshot . $$code . ' ' . $check; 2380: } 2381: } 2382: 2383: # A setter is called to change one property, so everything else the object 2384: # was handed must come back untouched. The object is deep copied before the 2385: # call and the rest of its state compared afterwards; the property itself is 2386: # excluded, since changing that is the point, and values it fills in where it 2387: # was handed undef are ignored along with keys it adds, so that lazy 2388: # initialisation is not reported as damage. ●2389 → 2389 → 2403 2389: if(defined($accessor{type}) && ($accessor{type} eq 'getset') && defined($accessor{property})) { 2390: my $property = perl_quote($accessor{property}); 2391: my $snapshot = 'my $setter_copy = eval { require Storable; Storable::dclone($obj) }; '; 2392: my $check = 'if(defined($setter_copy) && eval { scalar(keys %{$setter_copy}); 1 }) {'

Mutants (Total: 2, Killed: 2, Survived: 0)

2393: . ' my %setter_state = map { $_ => $setter_copy->{$_} } grep { defined($setter_copy->{$_}) && ($_ ne ' . $property . ') } keys %{$setter_copy};' 2394: . ' is_deeply({ map { $_ => $obj->{$_} } grep { exists($obj->{$_}) } keys %setter_state }, \\%setter_state, q{setter changes nothing but its property});' 2395: . ' }'; 2396: foreach my $code (\$call_code, \$position_code) { 2397: next unless(defined($$code) && ($config{'check_accessors'} // 1)); 2398: $$code = $snapshot . $$code . ' ' . $check; 2399: } 2400: } 2401: 2402: # Build static corpus code ●2403 → 2404 → 2506 2403: my $corpus_code = ''; 2404: if (%all_cases) { 2405: $corpus_code = "\n# --- Static Corpus Tests ---\n" . 2406: "diag('Running " . scalar(keys %all_cases) . " corpus tests');\n"; 2407: 2408: for my $expected (sort keys %all_cases) { 2409: my $inputs = $all_cases{$expected}; 2410: next unless($inputs); 2411: 2412: my $expected_str = perl_quote($expected); 2413: my $status = ((ref($inputs) eq 'HASH') && $inputs->{'_STATUS'}) // 'OK'; 2414: if($expected_str eq "'_STATUS:DIES'") { 2415: $status = 'DIES'; 2416: } elsif($expected_str eq "'_STATUS:WARNS'") { 2417: $status = 'WARNS'; 2418: } 2419: 2420: if(ref($inputs) eq 'HASH') { 2421: $inputs = $inputs->{'input'}; 2422: } 2423: my $input_str; 2424: if(ref($inputs) eq 'ARRAY') { 2425: $input_str = join(', ', map { perl_quote($_) } @{$inputs}); 2426: } elsif(ref($inputs) eq 'HASH') { 2427: $input_str = render_fallback($inputs); 2428: 2429: # YAML can't express Perl's undef, so a corpus value of 2430: # the sentinel string 'undef' means "this param is 2431: # undef" -- convert the quoted sentinel back to the 2432: # bareword so the generated test passes real undef 2433: $input_str =~ s/=> 'undef'/=> undef/gms; 2434: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

2435: $input_str = $inputs; 2436: } 2437: if(($input_str eq 'undef') && (!$config{'test_undef'})) { 2438: carp('corpus case set to undef, yet test_undef is not set in config'); 2439: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2440: if($new) { 2441: if($status eq 'DIES') { 2442: $corpus_code .= "dies_ok { \$obj->$function($input_str) } " .

Mutants (Total: 1, Killed: 1, Survived: 0)

2443: "'$function(" . join(', ', map { $_ // '' } @$inputs ) . ") dies';\n"; 2444: } elsif($status eq 'WARNS') { 2445: $corpus_code .= "warnings_exist { \$obj->$function($input_str) } qr/./, " . 2446: "'$function(" . join(', ', map { $_ // '' } @$inputs ) . ") warns';\n"; 2447: } else { 2448: my $desc = sprintf("$function(%s) returns %s", 2449: perl_quote(join(', ', map { $_ // '' } @$inputs )),

Mutants (Total: 2, Killed: 2, Survived: 0)

2450: $expected_str 2451: ); 2452: if(($output{'type'} // '') eq 'boolean') { 2453: if($expected_str eq '1') { 2454: $corpus_code .= "ok(\$obj->$function($input_str), " . q_wrap($desc) . ");\n"; 2455: } elsif($expected_str eq '0') { 2456: $corpus_code .= "ok(!\$obj->$function($input_str), " . q_wrap($desc) . ");\n"; 2457: } else { 2458: croak("Boolean is expected to return $expected_str"); 2459: } 2460: } else { 2461: $corpus_code .= "is(\$obj->$function($input_str), $expected_str, " . q_wrap($desc) . ");\n"; 2462: } 2463: } 2464: } else { 2465: if($status eq 'DIES') { 2466: if($module) { 2467: $corpus_code .= "dies_ok { $module\::$function($input_str) } " . 2468: "'Corpus $expected dies';\n"; 2469: } else { 2470: $corpus_code .= "dies_ok { $function($input_str) } " . 2471: "'Corpus $expected dies';\n"; 2472: } 2473: } elsif($status eq 'WARNS') { 2474: if($module) { 2475: $corpus_code .= "warnings_exist { $module\::$function($input_str) } qr/./, " . 2476: "'Corpus $expected warns';\n"; 2477: } else { 2478: $corpus_code .= "warnings_exist { $function($input_str) } qr/./, " . 2479: "'Corpus $expected warns';\n"; 2480: } 2481: } else { 2482: my $desc = sprintf("$function(%s) returns %s", 2483: perl_quote((ref $inputs eq 'ARRAY') ? (join(', ', map { $_ // '' } @{$inputs})) : $inputs), 2484: $expected_str 2485: ); 2486: if(($output{'type'} // '') eq 'boolean') {

Mutants (Total: 2, Killed: 2, Survived: 0)

2487: if($expected_str eq '1') { 2488: $corpus_code .= "ok(\$obj->$function($input_str), " . q_wrap($desc) . ");\n"; 2489: } elsif($expected_str eq '0') { 2490: $corpus_code .= "ok(!\$obj->$function($input_str), " . q_wrap($desc) . ");\n"; 2491: } else { 2492: croak("Boolean is expected to return $expected_str"); 2493: } 2494: } else { 2495: $corpus_code .= "is(\$obj->$function($input_str), $expected_str, " . q_wrap($desc) . ");\n"; 2496: } 2497: } 2498: } 2499: } 2500: } 2501: 2502: # Prepare seed/iterations code fragment for the generated test 2503: # A schema can record a precondition that no generated value can meet (for 2504: # example a file the routine parses). The harness then has nothing to 2505: # assert and says so instead of failing on a call it cannot make. ●2506 → 2511 → 2517 2506: my $skip_reason = $schema->{skip}; 2507: 2508: # The generated harness needs the seed both to seed Perl's RNG (which the 2509: # regex generator uses) and to name it in failure diagnostics. 2510: my $seed_code = "our \$seed;\n"; 2511: if (defined $seed) { 2512: # ensure integer-ish 2513: $seed = int($seed); 2514: $seed_code .= "srand(\$seed = $seed);\n"; 2515: } 2516: ●2517 → 2558 → 2575 2517: my $determinism_code = 'my $result2;' . 2518: 'eval { $result2 = do { ' . (defined($position_code) ? $position_code : $call_code) . " }; };\n" . 2519: 'is_deeply($result2, $result, "deterministic result for same input");' . 2520: "\n"; 2521: 2522: # Generate the test content 2523: my $tt = Template->new({ ENCODING => 'utf8', TRIM => 1 }); 2524: 2525: # Read template from DATA handle 2526: my $template_package = __PACKAGE__ . '::Template'; 2527: my $template = $template_package->get_data_section('test.tt'); 2528: 2529: my $vars = { 2530: setup_code => $setup_code, 2531: edge_cases_code => $edge_cases_code, 2532: edge_case_array_code => $edge_case_array_code, 2533: type_edge_cases_code => $type_edge_cases_code, 2534: config_code => $config_code,

Mutants (Total: 1, Killed: 1, Survived: 0)

2535: seed_code => $seed_code, 2536: input_code => $input_code, 2537: output_code => $output_code, 2538: transforms_code => $transforms_code, 2539: corpus_code => $corpus_code, 2540: call_code => $call_code,

Mutants (Total: 1, Killed: 1, Survived: 0)

2541: position_code => $position_code, 2542: determinism_code => $determinism_code, 2543: documented_sources => join(' ', App::Test::Generator::Provenance::documented_sources()), 2544: type_checks_source => App::Test::Generator::Provenance::type_checks_source(), 2545: function => $function,

Mutants (Total: 1, Killed: 1, Survived: 0)

2546: iterations_code => int($iterations),

Mutants (Total: 1, Killed: 1, Survived: 0)

2547: use_properties => $use_properties, 2548: transform_properties_code => $transform_properties_code, 2549: property_trials => $config{properties}{trials} // $DEFAULT_PROPERTY_TRIALS, 2550: relationships_code => $relationships_code, 2551: module => $module, 2552: skip_reason => $skip_reason 2553: }; 2554:

Mutants (Total: 1, Killed: 1, Survived: 0)

2555: my $test; 2556: $tt->process($template, $vars, \$test) or croak($tt->error()); 2557: 2558: if ($test_file) { 2559: # autodie is disabled for this open -- under "use autodie qw(:all)" 2560: # open() never returns false on failure, it throws its own exception 2561: # instead, which would silently make the "or croak" dead code.

Mutants (Total: 1, Killed: 1, Survived: 0)

2562: no autodie qw(open); 2563: open my $fh, '>:encoding(UTF-8)', $test_file or croak "Cannot open $test_file: $!"; 2564: print $fh "$test\n"; 2565: close $fh; 2566: if($module) {

Mutants (Total: 1, Killed: 1, Survived: 0)

2567: print "Generated $test_file for $module\::$function with fuzzing + corpus support\n"; 2568: } else { 2569: print "Generated $test_file for $function with fuzzing + corpus support\n"; 2570: } 2571: } else { 2572: print "$test\n"; 2573: } 2574: 2575: return 1; 2576: } 2577: 2578: # --- Helpers for rendering data structures into Perl code for the generated test --- 2579: 2580: # -------------------------------------------------- 2581: # _is_perl_builtin 2582: # 2583: # Purpose: Return true if a string is the name of 2584: # a Perl core builtin function, to prevent 2585: # it being used as a module name in 2586: # use_ok() calls in generated tests. 2587: # 2588: # Entry: $name - the string to check. 2589: # Exit: Returns 1 if builtin, 0 otherwise. 2590: # -------------------------------------------------- 2591: sub _is_perl_builtin { 2592: my $name = $_[0]; 2593: return 0 unless defined $name; 2594: 2595: state %BUILTINS = map { $_ => 1 } qw( 2596: abs accept alarm atan2 bind binmode bless 2597: caller chdir chmod chomp chop chown chr chroot 2598: close closedir connect cos crypt

Mutants (Total: 1, Killed: 1, Survived: 0)

2599: dbmclose dbmopen defined delete die do dump 2600: each endgrent endhostent endnetent endprotoent endpwent endservent 2601: eof eval exec exists exit exp 2602: fcntl fileno flock fork format formline 2603: getc getgrent getgrgid getgrnam gethostbyaddr gethostbyname 2604: gethostent getlogin getnetbyaddr getnetbyname getnetent 2605: getpeername getpgrp getppid getpriority getprotobyname 2606: getprotobynumber getprotoent getpwent getpwnam getpwuid 2607: getservbyname getservbyport getservent getsockname getsockopt 2608: glob gmtime goto grep 2609: hex 2610: index int ioctl 2611: join 2612: keys kill 2613: last lc lcfirst length link listen local localtime log lstat 2614: map mkdir msgctl msgget msgrcv msgsnd my 2615: next no 2616: oct open opendir ord our 2617: pack pipe pop pos print printf prototype push 2618: quotemeta 2619: rand read readdir readline readlink readpipe recv redo 2620: ref rename require reset return reverse rewinddir rindex rmdir 2621: say scalar seek seekdir select semctl semget semop send 2622: setgrent sethostent setnetent setpgrp setpriority setprotoent 2623: setpwent setservent setsockopt shift shmctl shmget shmread 2624: shmwrite shutdown sin sleep socket socketpair sort splice split 2625: sprintf sqrt srand stat study sub substr symlink syscall 2626: sysopen sysread sysseek system syswrite 2627: tell telldir tie tied time times truncate 2628: uc ucfirst umask undef unlink unpack unshift untie use 2629: utime values vec wait waitpid wantarray warn write 2630: ); 2631: return $BUILTINS{lc $name} // 0; 2632: } 2633: 2634: # -------------------------------------------------- 2635: # _load_schema 2636: # 2637: # Load and parse a schema file using 2638: # Config::Abstraction, returning the 2639: # schema as a hashref. 2640: # 2641: # Entry: $schema_file - path to the schema file. 2642: # Must be defined, non-empty, and readable. 2643: # 2644: # Exit: Returns a hashref of the parsed schema 2645: # with a '_source' key added containing 2646: # the originating file path. 2647: # Croaks on any error. 2648: # 2649: # Side effects: Reads from the filesystem. 2650: # 2651: # Notes: Legacy Perl-file configs (containing 2652: # '$module' or 'our $module' keys) are 2653: # rejected with a clear error. Config:: 2654: # Abstraction is used rather than require()

Mutants (Total: 1, Killed: 1, Survived: 0)

2655: # to avoid executing arbitrary code from 2656: # user-supplied config files. 2657: # --------------------------------------------------

Mutants (Total: 1, Killed: 1, Survived: 0)

2658: sub _load_schema { ●2659 → 2673 → 2692 2659: my $schema_file = $_[0]; 2660: 2661: # Validate the argument before touching the filesystem 2662: croak(__PACKAGE__, ': Usage: _load_schema($schema_file)') unless defined $schema_file; 2663: 2664: croak(__PACKAGE__, ': _load_schema given empty filename') unless length($schema_file); 2665: 2666: # Confirm the file exists and is readable before attempting 2667: # to load it — gives a clearer error than Config::Abstraction would

Mutants (Total: 2, Killed: 2, Survived: 0)

2668: croak(__PACKAGE__, ": _load_schema($schema_file): $!") unless -r $schema_file; 2669: 2670: # Load configuration via Config::Abstraction which supports 2671: # YAML, JSON, and other formats without executing arbitrary code. 2672: # no_fixate prevents automatic type coercion that could alter values 2673: if(my $schema = Config::Abstraction->new( 2674: config_dirs => ['.', ''], 2675: config_file => $schema_file, 2676: no_fixate => 1, 2677: )) { 2678: if($schema = $schema->all()) { 2679: # Detect legacy Perl config files by the presence of 2680: # variable declaration keys — these are no longer supported 2681: if(exists($schema->{$LEGACY_PERL_KEY_1}) || 2682: exists($schema->{$LEGACY_PERL_KEY_2})) { 2683: croak("$schema_file: Loading perl files as configs is no longer supported"); 2684: } 2685: 2686: # Tag the schema with its source path for error messages 2687: $schema->{$SOURCE_KEY} = $schema_file; 2688: return $schema; 2689: } 2690: } 2691: 2692: croak "Failed to load schema from $schema_file"; 2693: } 2694: 2695: # -------------------------------------------------- 2696: # _load_schema_section 2697: # 2698: # Purpose: Extract a named section from a parsed 2699: # schema hashref, validating that it is

Mutants (Total: 1, Killed: 1, Survived: 0)

2700: # a hashref if present. 2701: #

Mutants (Total: 1, Killed: 1, Survived: 0)

2702: # Entry: $schema - the full parsed schema hashref. 2703: # $section - name of the section to extract 2704: # (e.g. 'input', 'output'). 2705: # $schema_file - path of the schema file, 2706: # used in error messages only. 2707: # 2708: # Exit: Returns the section hashref if present, 2709: # or an empty hashref {} if absent. 2710: # Croaks if the section exists but is not

Mutants (Total: 1, Killed: 1, Survived: 0)

2711: # a hashref (and not the string 'undef'). 2712: # 2713: # Notes: The string 'undef' is treated as an 2714: # absent section — callers that set a 2715: # section to 'undef' in YAML get the same 2716: # result as omitting it entirely.

Mutants (Total: 1, Killed: 1, Survived: 0)

2717: # -------------------------------------------------- 2718: sub _load_schema_section { 2719: my ($schema, $section, $schema_file) = @_; 2720: 2721: # Section absent — return empty hash as the safe default 2722: return {} unless exists $schema->{$section}; 2723: 2724: # Section present and is a hashref — return it directly 2725: return $schema->{$section} 2726: if ref($schema->{$section}) eq 'HASH'; 2727: 2728: # Treat the YAML scalar 'undef' as equivalent to absent 2729: return {} 2730: if defined($schema->{$section}) && 2731: $schema->{$section} eq 'undef'; 2732: 2733: # Section present but wrong type — croak with a clear message 2734: # showing what type was found so the user can fix their schema 2735: croak( 2736: "$schema_file: $section should be a hash, not ", 2737: ref($schema->{$section}) || $schema->{$section} 2738: ); 2739: } 2740: 2741: # -------------------------------------------------- 2742: # _validate_config 2743: # 2744: # Purpose: Validate the top-level schema hashref 2745: # loaded from a schema file, checking that 2746: # required fields are present and that all 2747: # input parameters, types, positions, and 2748: # transform properties are well-formed. 2749: # 2750: # Entry: $schema - the full parsed schema hashref 2751: # as returned by _load_schema(). 2752: # 2753: # Exit: Returns nothing on success.

Mutants (Total: 1, Killed: 1, Survived: 0)

2754: # Croaks on any structural error. 2755: # Carps on non-fatal warnings (unknown

Mutants (Total: 1, Killed: 1, Survived: 0)

2756: # semantic types, position gaps, missing 2757: # input/output definitions). 2758: # 2759: # Side effects: May delete $schema->{input} if its 2760: # value is the string 'undef'. 2761: # 2762: # Notes: The parameter is named $schema throughout

Mutants (Total: 1, Killed: 1, Survived: 0)

2763: # to distinguish the top-level schema from 2764: # the nested config sub-hash. _validate_config 2765: # is called before _normalize_config so config 2766: # boolean normalisation has not yet occurred. 2767: # -------------------------------------------------- 2768: sub _validate_config { ●2769 → 2773 → 2779 2769: my $schema = $_[0]; 2770: 2771: # At least one of module or function must be present — 2772: # without these we cannot generate any meaningful test 2773: if(!defined($schema->{'module'}) && !defined($schema->{'function'})) { 2774: croak('At least one of function and module must be defined'); 2775: } 2776: 2777: # Warn if neither input nor output is defined — a few 2778: # generic tests can still be generated but it is unusual ●2779 → 2779 → 2784 2779: if(!defined($schema->{'input'}) && !defined($schema->{'output'})) { 2780: carp('Neither input nor output is defined, only a few tests will be generated'); 2781: } 2782: 2783: # Normalise input: the string 'undef' means no input defined ●2784 → 2784 → 2793 2784: if($schema->{'input'} && ref($schema->{input}) ne 'HASH') { 2785: if($schema->{'input'} eq 'undef') { 2786: delete $schema->{'input'}; 2787: } else { 2788: croak("Invalid input specification: expected hash, got '$schema->{'input'}'"); 2789: } 2790: } 2791: 2792: # Validate each input parameter if input is defined ●2793 → 2793 → 2800 2793: if($schema->{input}) { 2794: _validate_input_params($schema); 2795: _validate_input_positions($schema); 2796: _validate_input_semantics($schema); 2797: } 2798: 2799: # Validate transform property definitions if present ●2800 → 2800 → 2805 2800: if(exists($schema->{transforms}) && ref($schema->{transforms}) eq 'HASH') { 2801: _validate_transform_properties($schema); 2802: } 2803: 2804: # Validate any nested config sub-hash keys against known types ●2805 → 2805 → 0 2805: if(ref($schema->{config}) eq 'HASH') { 2806: for my $k (keys %{$schema->{'config'}}) { 2807: # %VALID_CONFIG_KEYS is the authoritative set — O(1) hash lookup 2808: croak "unknown config setting '$k'"

Mutants (Total: 1, Killed: 1, Survived: 0)

2809: unless $VALID_CONFIG_KEYS{$k}; 2810: } 2811: }

Mutants (Total: 1, Killed: 1, Survived: 0)

2812: } 2813: 2814: # -------------------------------------------------- 2815: # _validate_input_params 2816: # 2817: # Purpose: Validate type specifications for each 2818: # named input parameter. 2819: # 2820: # Entry: $schema - the full parsed schema hashref. 2821: # $schema->{input} must be a hashref. 2822: # 2823: # Exit: Returns nothing. Croaks on invalid type. 2824: # -------------------------------------------------- 2825: # Validate a nested element specification. `schema` on an arrayref describes 2826: # every element; on a hashref it describes every value, or -- when it has no 2827: # type of its own -- maps fixed key names to element specs. 2828: sub _validate_element_spec { ●2829 → 2832 → 2837 2829: my ($element, $param, $allow_keys) = @_; 2830: 2831: return unless defined($element); 2832: if(!ref($element)) { 2833: croak("Invalid element type '$element' for '$param'") 2834: unless _valid_nested_type($element); 2835: return; 2836: } ●2837 → 2840 → 2857 2837: croak("schema for parameter '$param' must be a hash or a type name") 2838: if ref($element) ne 'HASH'; 2839: 2840: if($allow_keys && !exists($element->{type})) { 2841: croak("A hashref schema for '$param' with fixed keys needs at least one key") 2842: unless keys %{$element}; 2843: foreach my $key (sort keys %{$element}) { 2844: my $value = $element->{$key}; 2845: if(!ref($value)) { 2846: croak("Invalid element type '$value' for '$param.$key'") 2847: unless _valid_nested_type($value); 2848: next; 2849: } 2850: croak("Element schema for '$param.$key' must be a hash") 2851: unless ref($value) eq 'HASH'; 2852: _validate_element_spec($value, "$param.$key", 0); 2853: } 2854: return; 2855: } 2856:

Mutants (Total: 2, Killed: 2, Survived: 0)

●2857 → 2864 → 0 2857: croak("Missing type in the element schema for '$param'") 2858: unless defined($element->{type}); 2859: croak("Invalid element type '$element->{type}' for '$param'") 2860: unless !ref($element->{type}) && _valid_nested_type($element->{type}); 2861: croak("Object element schema for '$param' needs 'isa' or 'can'") 2862: if(($element->{type} eq 'object') && !defined($element->{isa}) && !defined($element->{can})); 2863: 2864: if(($element->{type} eq 'arrayref') || ($element->{type} eq 'array')) { 2865: # An array's elements can be hashes with fixed keys, just as a 2866: # hashref's values can: a type-less schema maps key names to specs. 2867: _validate_element_spec($element->{schema}, $param, 1) if defined($element->{schema}); 2868: } elsif($element->{type} eq 'hashref') { 2869: _validate_element_spec($element->{schema}, $param, 1) if defined($element->{schema}); 2870: } 2871: } 2872: 2873: sub _valid_nested_type { 2874: my ($type) = @_; 2875: 2876: return 0 unless defined($type) && !ref($type); 2877: return 1 if($type eq 'array') || ($type eq 'coderef'); 2878: return _valid_type($type); 2879: } 2880: 2881: sub _validate_input_params { ●2882 → 2884 → 0 2882: my $schema = $_[0]; 2883: 2884: for my $param (keys %{$schema->{input}}) { 2885: # Catch empty parameter names — these would produce 2886: # broken Perl variable names in the generated test 2887: croak 'Empty input parameter name' 2888: unless length($param); 2889: 2890: my $spec = $schema->{input}{$param}; 2891: 2892: # A sampling ceiling is not a second maximum: it must sit inside 2893: # the documented range, or generated data would not be valid. 2894: if(ref($spec) eq 'HASH' && defined($spec->{sample_max})) { 2895: croak("sample_max for parameter '$param' must be a non-negative number") 2896: unless !ref($spec->{sample_max}) && ($spec->{sample_max} =~ /\A\d+(?:\.\d+)?\z/); 2897: croak("sample_max for parameter '$param' is above max") 2898: if defined($spec->{max}) && ($spec->{sample_max} > $spec->{max}); 2899: croak("sample_max for parameter '$param' is below min") 2900: if defined($spec->{min}) && ($spec->{sample_max} < $spec->{min}); 2901: } 2902: 2903: # Validate the type field — required for all parameters 2904: if(ref($spec)) { 2905: croak("Missing type for parameter '$param'") 2906: unless defined $spec->{type}; 2907: # 'coderef' is a SchemaExtractor-specific type, not one of the

Mutants (Total: 2, Killed: 2, Survived: 0)

2908: # schema's value types: the harness satisfies it with a no-op 2909: # coderef rather than generating values for it. 2910: next if $spec->{type} eq 'coderef'; 2911: croak("Invalid type '$spec->{type}' for parameter '$param'") 2912: unless _valid_type($spec->{type}); 2913: 2914: if(($spec->{type} eq 'arrayref') || ($spec->{type} eq 'array')) { 2915: _validate_element_spec($spec->{schema}, $param, 1) if defined($spec->{schema}); 2916: } elsif($spec->{type} eq 'hashref') { 2917: _validate_element_spec($spec->{schema}, $param, 1) if defined($spec->{schema}); 2918: } 2919: } else { 2920: croak("Invalid type '$spec' for parameter '$param'") 2921: unless _valid_type($spec); 2922: } 2923: } 2924: } 2925: 2926: # -------------------------------------------------- 2927: # _validate_input_positions 2928: # 2929: # Purpose: Validate positional argument declarations 2930: # in the input schema — positions must be 2931: # non-negative integers with no duplicates, 2932: # and either all or no parameters must have 2933: # positions. 2934: # 2935: # Entry: $schema - the full parsed schema hashref. 2936: # $schema->{input} must be a hashref. 2937: # 2938: # Exit: Returns nothing. Croaks on invalid or 2939: # duplicate positions. Carps on gaps. 2940: # -------------------------------------------------- 2941: sub _validate_input_positions { ●2942 → 2947 → 2971 2942: my $schema = $_[0]; 2943: 2944: my $has_positions = 0; 2945: my %positions; 2946: 2947: for my $param (keys %{$schema->{input}}) { 2948: my $spec = $schema->{input}{$param}; 2949: 2950: # Only process params that explicitly declare a position 2951: next unless ref($spec) eq 'HASH' && defined($spec->{position}); 2952: 2953: $has_positions = 1; 2954: my $pos = $spec->{position}; 2955: 2956: # Position must be a non-negative integer 2957: croak "Position for '$param' must be a non-negative integer" 2958: unless $pos =~ /^\d+$/; 2959: 2960: # Duplicate positions would produce ambiguous generated tests 2961: croak "Duplicate position $pos for parameters '$positions{$pos}' and '$param'"

Mutants (Total: 2, Killed: 2, Survived: 0)

2962: if exists $positions{$pos}; 2963: 2964: $positions{$pos} = $param; 2965: } 2966:

Mutants (Total: 1, Killed: 1, Survived: 0)

2967: # If any param has a position, the rest are named options passed after 2968: # the positional arguments (sub f { my ($x, %opts) = @_ }), and each must 2969: # say so: an omission is otherwise a forgotten position, which would be 2970: # called by name and test nothing. ●2971 → 2971 → 0 2971: if($has_positions) { 2972: for my $param (keys %{$schema->{input}}) { 2973: my $spec = $schema->{input}{$param}; 2974: next if(ref($spec) eq 'HASH' && defined($spec->{position})); 2975: croak "Parameter '$param' missing position " .

Mutants (Total: 2, Killed: 2, Survived: 0)

2976: '(give it one, or named: 1 for a trailing named option)' 2977: unless(ref($spec) eq 'HASH' && $spec->{named}); 2978: } 2979: 2980: # Check for gaps — positions must be a contiguous sequence 2981: # starting at 0, otherwise the generated test will be wrong

Mutants (Total: 1, Killed: 1, Survived: 0)

2982: my @sorted = sort { $a <=> $b } keys %positions; 2983: for my $i (0 .. $#sorted) { 2984: if($sorted[$i] != $i) { 2985: carp "Position sequence has gaps (positions: @sorted)"; 2986: last; 2987: } 2988: } 2989: } 2990: }

Mutants (Total: 1, Killed: 0, Survived: 1)
2991: 2992: # -------------------------------------------------- 2993: # _validate_input_semantics

Mutants (Total: 1, Killed: 1, Survived: 0)

2994: # 2995: # Purpose: Validate semantic type annotations and 2996: # enum/memberof constraints on input params. 2997: # 2998: # Entry: $schema - the full parsed schema hashref. 2999: # $schema->{input} must be a hashref.

Mutants (Total: 2, Killed: 0, Survived: 2)
3000: # 3001: # Exit: Returns nothing. Croaks on conflicting 3002: # or malformed enum/memberof. Carps on
Mutants (Total: 1, Killed: 0, Survived: 1)
3003: # unknown semantic types. 3004: # -------------------------------------------------- 3005: sub _validate_input_semantics { ●3006 → 3010 → 0 3006: my $schema = $_[0]; 3007:

Mutants (Total: 2, Killed: 2, Survived: 0)

3008: my $semantic_generators = _get_semantic_generators(); 3009: 3010: for my $param (keys %{$schema->{input}}) { 3011: my $spec = $schema->{input}{$param}; 3012: next unless ref($spec) eq 'HASH'; 3013: 3014: # Warn on unknown semantic types rather than croaking — 3015: # new semantic types may be added without updating this list 3016: if(defined($spec->{semantic})) { 3017: my $semantic = $spec->{semantic}; 3018: unless(exists $semantic_generators->{$semantic}) { 3019: carp "Unknown semantic type '$semantic' for parameter '$param'. " . 3020: 'Available types: ' . 3021: join(', ', sort keys %{$semantic_generators}); 3022: } 3023: } 3024: 3025: # enum and memberof are mutually exclusive representations 3026: # of the same concept — having both is always a schema error 3027: if($spec->{'enum'} && $spec->{'memberof'}) { 3028: croak "$param: has both enum and memberof"; 3029: } 3030: 3031: # Both enum and memberof must be arrayrefs when present 3032: for my $type ('enum', 'memberof') { 3033: if(exists $spec->{$type}) { 3034: croak "$type must be an arrayref" 3035: unless ref($spec->{$type}) eq 'ARRAY'; 3036: } 3037: } 3038: } 3039: } 3040: 3041: # -------------------------------------------------- 3042: # _validate_transform_properties 3043: # 3044: # Purpose: Validate the properties array in each 3045: # transform definition, checking that each 3046: # property is either a known builtin name 3047: # or a custom hashref with name and code. 3048: # 3049: # Entry: $schema - the full parsed schema hashref. 3050: # $schema->{transforms} must be a hashref. 3051: # 3052: # Exit: Returns nothing. Croaks on invalid property 3053: # definitions. Carps on unknown builtins. 3054: # -------------------------------------------------- 3055: sub _validate_transform_properties { ●3056 → 3060 → 0 3056: my $schema = $_[0]; 3057: 3058: my $builtin_props = _get_builtin_properties(); 3059: 3060: for my $transform_name (keys %{$schema->{transforms}}) { 3061: my $transform = $schema->{transforms}{$transform_name}; 3062: 3063: # properties is optional — skip transforms that don't define it

Mutants (Total: 2, Killed: 2, Survived: 0)

3064: next unless exists $transform->{properties}; 3065: 3066: croak "Transform '$transform_name': properties must be an array" 3067: unless ref($transform->{properties}) eq 'ARRAY'; 3068: 3069: for my $prop (@{$transform->{properties}}) { 3070: if(!ref($prop)) { 3071: # Plain string — must be a known builtin property name 3072: unless(exists $builtin_props->{$prop}) { 3073: carp "Transform '$transform_name': unknown built-in property '$prop'. " . 3074: 'Available: ' .

Mutants (Total: 2, Killed: 2, Survived: 0)

3075: join(', ', sort keys %{$builtin_props}); 3076: } 3077: } elsif(ref($prop) eq 'HASH') { 3078: # Custom property — must have both name and code fields 3079: unless($prop->{name} && $prop->{code}) { 3080: croak "Transform '$transform_name': " . 3081: "custom properties must have 'name' and 'code' fields"; 3082: } 3083: } else { 3084: croak "Transform '$transform_name': invalid property definition"; 3085: } 3086: } 3087: } 3088: } 3089: 3090: # -------------------------------------------------- 3091: # _normalize_config 3092: # 3093: # Purpose: Normalise boolean string values in the 3094: # config sub-hash to Perl integers (1/0), 3095: # and default absent boolean fields to 1 3096: # (enabled). The 'properties' field is a 3097: # hashref not a boolean and is handled 3098: # separately. 3099: # 3100: # Entry: $config - the config sub-hash extracted 3101: # from the schema (i.e. $schema->{config}). 3102: # May be empty. 3103: # 3104: # Exit: Returns nothing. Modifies $config in place. 3105: # 3106: # Side effects: Modifies the caller's config hashref. 3107: # 3108: # Notes: String-to-boolean conversion is delegated 3109: # to %Readonly::Values::Boolean::booleans 3110: # which handles 'yes'/'no', 'on'/'off', 3111: # 'true'/'false' etc. Fields not present in 3112: # the config hash are defaulted to 1 so 3113: # that test generation is maximally thorough 3114: # unless the schema explicitly disables a 3115: # feature. 3116: # -------------------------------------------------- 3117: sub _normalize_config { ●3118 → 3120 → 3141 3118: my $config = $_[0]; 3119: 3120: for my $field (keys %VALID_CONFIG_KEYS) { 3121: # Non-boolean fields are handled separately 3122: next if $field eq $CONFIG_PROPERTIES_KEY; 3123: next if $field eq 'timeout'; # numeric, not boolean; absence means use generated-test default 3124: 3125: if(exists($config->{$field}) && defined($config->{$field})) { 3126: # Convert string boolean representations to integers 3127: # using the lookup table from Readonly::Values::Boolean 3128: if(defined(my $b = $Readonly::Values::Boolean::booleans{$config->{$field}})) { 3129: $config->{$field} = $b; 3130: } 3131: } else { 3132: # Default absent boolean fields to enabled (1) so that 3133: # test generation is comprehensive unless explicitly disabled 3134: $config->{$field} = 1;

Mutants (Total: 2, Killed: 2, Survived: 0)

3135: } 3136: } 3137: 3138: # Ensure properties is always a hashref — if absent or set to 3139: # a non-hash value, replace with a disabled default so that 3140: # downstream code can safely dereference it without checking ref() 3141: $config->{$CONFIG_PROPERTIES_KEY} = { enable => 0 } unless ref($config->{$CONFIG_PROPERTIES_KEY}) eq 'HASH'; 3142: } 3143: 3144: # --------------------------------------------------

Mutants (Total: 1, Killed: 1, Survived: 0)

3145: # _valid_type

Mutants (Total: 1, Killed: 1, Survived: 0)

3146: # 3147: # Determine whether a string is a 3148: # recognised schema field type accepted 3149: # by the generator. 3150: # 3151: # Entry: $type - the type string to validate. 3152: # May be undef. 3153: # 3154: # Exit: Returns 1 if the type is known, 3155: # 0 if the type is unknown or undef. 3156: # 3157: # Notes: The lookup hash is declared with 3158: # 'state' so it is built only once per 3159: # process rather than on every call — 3160: # important since _valid_type is called 3161: # in a loop over all input parameters. 3162: #

Mutants (Total: 1, Killed: 1, Survived: 0)

3163: # 'int' and 'bool' are accepted as

Mutants (Total: 1, Killed: 0, Survived: 1)
3164: # aliases for 'integer' and 'boolean' 3165: # respectively, for compatibility with 3166: # schemas generated by external tools 3167: # that use the shorter forms. 3168: # -------------------------------------------------- 3169: sub _valid_type { 3170: my $type = $_[0]; 3171: 3172: # Undef is never a valid type 3173: return 0 unless defined($type); 3174: 3175: # Build the lookup table once and cache it for 3176: # the lifetime of the process via 'state'

Mutants (Total: 1, Killed: 1, Survived: 0)

3177: state %VALID = map { $_ => 1 } qw( 3178: string boolean integer number float 3179: hashref arrayref object int bool any 3180: );

Mutants (Total: 1, Killed: 1, Survived: 0)

3181: 3182: return($VALID{$type} // 0); 3183: } 3184: 3185: # -------------------------------------------------- 3186: # _assert_identifier 3187: # 3188: # Purpose: Validate that a string is shaped like a 3189: # plain Perl identifier (or, with 3190: # package => 1, a "::"-separated package 3191: # name) before it is spliced into generated 3192: # test source as a bareword, package name, 3193: # method name, or variable name rather than 3194: # a quoted string literal. Schema-derived 3195: # names (module, function, transform names) 3196: # are spliced unescaped at the call sites

Mutants (Total: 2, Killed: 2, Survived: 0)

3197: # that use this guard, so an unvalidated 3198: # name could otherwise break out of the 3199: # generated source and inject arbitrary 3200: # Perl into a file that L<prove> will run. 3201: # 3202: # Entry: $name - the string to validate. 3203: # $what - short label for the value, used 3204: # only in the croak message. 3205: # %opts - package => 1 allows "::" 3206: # separators in $name. 3207: # 3208: # Exit: Returns $name unchanged on success. 3209: # Croaks if $name is not identifier-shaped. 3210: # -------------------------------------------------- 3211: sub _assert_identifier { 3212: my ($name, $what, %opts) = @_; 3213: 3214: croak(__PACKAGE__, ": $what is missing or empty") 3215: unless defined($name) && length($name); 3216: 3217: my $re = $opts{package} 3218: ? qr/^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/ 3219: : qr/^[A-Za-z_]\w*\z/; 3220: 3221: croak(__PACKAGE__, ": $what '$name' is not a valid Perl identifier") 3222: unless $name =~ $re; 3223: 3224: return $name; 3225: } 3226: 3227: # -------------------------------------------------- 3228: # _validate_module 3229: # 3230: # Purpose: Check whether the module named in a 3231: # schema can be found in @INC during 3232: # test generation. Optionally also 3233: # attempts to load it if the 3234: # GENERATOR_VALIDATE_LOAD environment 3235: # variable is set. 3236: # 3237: # Entry: $module - the module name to 3238: # check. If undef or 3239: # empty, returns 1 3240: # immediately (builtin 3241: # functions need no 3242: # module). 3243: # $schema_file - path to the schema 3244: # file, used in warning 3245: # messages only. 3246: # 3247: # Exit: Returns 1 if the module was found

Mutants (Total: 2, Killed: 2, Survived: 0)

3248: # (and loaded, if validation was 3249: # requested). 3250: # Returns 0 if the module was not 3251: # found or failed to load — this is 3252: # non-fatal; generation continues. 3253: # Returns 1 immediately for undef or 3254: # empty $module. 3255: #

Mutants (Total: 2, Killed: 2, Survived: 0)

3256: # Side effects: Prints to STDERR when TEST_VERBOSE 3257: # or GENERATOR_VERBOSE is set. 3258: # Carps (non-fatally) when the module 3259: # cannot be found or loaded. 3260: # May attempt to load the module into 3261: # the current process when 3262: # GENERATOR_VALIDATE_LOAD is set — 3263: # this can have side effects depending 3264: # on the module. 3265: # 3266: # Notes: Not finding a module during generation 3267: # is intentionally non-fatal — the module 3268: # may be available on the target machine 3269: # even if not on the generation machine. 3270: # Verbose output goes to STDERR via 3271: # print rather than carp since it is 3272: # informational, not a warning. 3273: # -------------------------------------------------- 3274: sub _validate_module { ●3275 → 3283 → 3296 3275: my ($module, $schema_file) = @_; 3276: 3277: # Builtin functions have no module to validate 3278: return 1 unless $module; 3279: 3280: # Check whether the module is findable in @INC 3281: my $mod_info = check_install(module => $module); 3282: 3283: if($schema_file && !$mod_info) { 3284: # Non-fatal — emit a single consolidated warning so 3285: # the caller sees one message rather than four 3286: carp( 3287: "Module '$module' not found in \@INC during generation.\n" . 3288: " Config file: $schema_file\n" . 3289: " This is OK if the module will be available when tests run.\n" . 3290: ' If unexpected, check your module name and installation.' 3291: ); 3292: return 0; 3293: } 3294: 3295: # Check once and reuse — avoids evaluating two env vars twice ●3296 → 3298 → 3318 3296: my $verbose = $ENV{$ENV_TEST_VERBOSE} || $ENV{$ENV_GENERATOR_VERBOSE}; 3297: 3298: if($verbose) { 3299: # check_install() returns undef when the module is not in @INC, which 3300: # is normal for a schema whose module only exists when the tests run 3301: # (and when no schema file was given, the miss is not reported 3302: # above). Never read a location from a missing result: it would be 3303: # concatenated as an undefined value. 3304: if($mod_info) { 3305: carp "Found module '$module' at: " . 3306: ($mod_info->{'file'} // 'an unknown location') . 3307: ' (version ' . ($mod_info->{'version'} || 'unknown') . ')';

Mutants (Total: 2, Killed: 2, Survived: 0)

3308: } else { 3309: carp "Module '$module' is not in \@INC during generation; " . 3310: 'continuing (it may be available when the tests run)'; 3311: } 3312: } 3313: 3314: # Optional load validation — disabled by default because 3315: # loading a module can have side effects (e.g. BEGIN blocks, 3316: # database connections, file I/O) that are undesirable 3317: # during generation ●3318 → 3318 → 3335 3318: if($ENV{$ENV_VALIDATE_LOAD}) { 3319: my $loaded = can_load(modules => { $module => undef }, verbose => 0); 3320: 3321: if(!$loaded) { 3322: my $err = $Module::Load::Conditional::ERROR || 'unknown error'; 3323: carp( 3324: "Module '$module' found but failed to load: $err\n" . 3325: ' This might indicate a broken installation or missing dependencies.'

Mutants (Total: 2, Killed: 2, Survived: 0)

3326: ); 3327: return 0; 3328: } 3329: 3330: if($verbose) { 3331: carp "Successfully loaded module '$module'"; 3332: } 3333: } 3334: 3335: return 1; 3336: } 3337: 3338: =head2 render_fallback 3339: 3340: Render any Perl value into a compact Perl source-code string using 3341: L<Data::Dumper>. Used as a catch-all when no more specific renderer 3342: applies. 3343: 3344: my $code = render_fallback({ key => 'value' }); 3345: # returns: "{'key' => 'value'}" 3346: 3347: =head3 Arguments 3348: 3349: =over 4 3350: 3351: =item * C<$v> 3352:

Mutants (Total: 2, Killed: 2, Survived: 0)

3353: Any Perl value, including undef, scalars, refs, and blessed objects. 3354: 3355: =back 3356: 3357: =head3 Returns 3358: 3359: A string of Perl source code that reproduces the value when evaluated. 3360: Returns the string C<'undef'> when C<$v> is undef.

Mutants (Total: 2, Killed: 2, Survived: 0)

3361: 3362: =head3 Side effects 3363: 3364: Temporarily sets C<$Data::Dumper::Terse> and C<$Data::Dumper::Indent>

Mutants (Total: 2, Killed: 2, Survived: 0)

3365: to produce compact single-line output. Both are restored on return via 3366: C<local>. 3367: 3368: =head3 Notes 3369: 3370: The output is always a single line with no trailing newline. Suitable 3371: for embedding in generated test code where readability is secondary to 3372: correctness. 3373: 3374: =head3 API SPECIFICATION 3375: 3376: =head4 input 3377: 3378: { v => { type => 'any', optional => 1 } } 3379: 3380: =head4 output 3381: 3382: { type => 'string' } 3383: 3384: The mathematical description is in L</FORMAL SPECIFICATION>. 3385: 3386: =cut 3387: 3388: sub render_fallback { 3389: my $v = $_[0]; 3390: 3391: # Handle undef explicitly rather than letting Dumper produce 3392: # 'undef' without the localised settings applied 3393: return 'undef' unless defined $v; 3394: 3395: # Use Terse+Indent=0 to produce compact single-line output 3396: # suitable for embedding in generated test code 3397: local $Data::Dumper::Terse = 1; 3398: local $Data::Dumper::Indent = 0; 3399: 3400: my $s = Dumper($v); 3401:

Mutants (Total: 2, Killed: 2, Survived: 0)

3402: # Remove trailing newline that Dumper always appends 3403: chomp $s; 3404: return $s; 3405: } 3406: 3407: =head2 render_hash 3408: 3409: Render a two-level hashref (parameter name => spec hashref) into Perl

Mutants (Total: 2, Killed: 2, Survived: 0)

3410: source code suitable for embedding in a generated test file as the 3411: input specification passed to L<Params::Validate::Strict>. 3412: 3413: my $code = render_hash(\%input); 3414: 3415: =head3 Arguments 3416: 3417: =over 4

Mutants (Total: 3, Killed: 3, Survived: 0)

3418: 3419: =item * C<$href> 3420: 3421: A hashref whose values are themselves hashrefs containing field 3422: specifications. A scalar value that is a recognised type string (see

Mutants (Total: 2, Killed: 2, Survived: 0)

3423: C<_valid_type>) is expanded to C<{ type =E<gt> $value }>. Any other 3424: non-hashref value is skipped with a warning. 3425: 3426: =back 3427: 3428: =head3 Returns 3429: 3430: A string of comma-separated Perl source-code lines, one per key, of 3431: the form: 3432: 3433: 'key' => { subkey => value, ... } 3434: 3435: Returns an empty string if C<$href> is undef, empty, or not a hashref. 3436: 3437: =head3 Notes 3438: 3439: The C<matches> and C<nomatch> sub-keys are treated specially - their 3440: values are compiled to C<Regexp> objects via C<eval { qr/.../ }> and 3441: then rendered using C<perl_quote> so they appear as C<qr{...}> in the 3442: generated test. This prevents unmatched bracket characters in the 3443: pattern from causing compilation failures. 3444: 3445: Other sub-keys are rendered via C<perl_quote>. 3446: 3447: =head3 API SPECIFICATION 3448: 3449: =head4 input 3450: 3451: { href => { type => 'any', optional => 1 } } 3452: 3453: =head4 output 3454: 3455: { type => 'string' } 3456:

Mutants (Total: 2, Killed: 2, Survived: 0)

3457: The mathematical description is in L</FORMAL SPECIFICATION>. 3458: 3459: =cut 3460: 3461: # Render a nested hashref of scalars (and further hashrefs) as Perl source. 3462: # _constraint_source is such a map: constraint name => provenance. 3463: sub _render_nested_hash { ●3464 → 3467 → 3475 3464: my ($href) = @_; 3465: 3466: my @pairs; 3467: foreach my $key (sort keys %{$href}) { 3468: my $value = $href->{$key}; 3469: next unless defined $value; 3470: push @pairs, perl_quote($key) . ' => ' . (ref($value) eq 'HASH' 3471: ? _render_nested_hash($value) 3472: : perl_quote($value)); 3473: } 3474: 3475: return '{ ' . join(', ', @pairs) . ' }'; 3476: } 3477:

Mutants (Total: 2, Killed: 2, Survived: 0)

3478: sub render_hash { ●3479 → 3487 → 3549 3479: my $href = $_[0]; 3480: 3481: # Return empty string for absent or non-hash input — callers 3482: # treat '' as "no input specification" in the generated test 3483: return '' unless $href && ref($href) eq 'HASH'; 3484: 3485: my @lines; 3486: 3487: for my $k (sort keys %{$href}) { 3488: my $def = $href->{$k}; 3489: 3490: # Handle scalar shorthand — 'arg1: string' is equivalent to 3491: # 'arg1: { type: string }' and is explicitly supported by the 3492: # validation layer in _validate_input_params 3493: unless(defined($def) && ref($def) eq 'HASH') { 3494: if(defined($def) && !ref($def) && _valid_type($def)) { 3495: # Expand scalar type shorthand to a full spec hashref 3496: $def = { type => $def }; 3497: } else { 3498: carp "render_hash: skipping key '$k' — value is not a hashref or recognised type string"; 3499: next; 3500: } 3501: } 3502: 3503: my @pairs; 3504: 3505: for my $subk (sort keys %{$def}) { 3506: # Skip undef sub-values — they contribute nothing to the spec 3507: next unless defined $def->{$subk}; 3508: 3509: # Validate that reference types are ones we can render. A nested 3510: # hashref of scalars (such as _constraint_source) is rendered as a 3511: # nested Perl hash literal. 3512: if(ref($def->{$subk})) { 3513: unless((ref($def->{$subk}) eq 'ARRAY') || 3514: (ref($def->{$subk}) eq 'Regexp') ||

Mutants (Total: 2, Killed: 2, Survived: 0)

3515: (ref($def->{$subk}) eq 'HASH')) { 3516: croak( 3517: __PACKAGE__, 3518: ": $subk is a nested element, not yet supported (", 3519: ref($def->{$subk}), ')' 3520: );

Mutants (Total: 3, Killed: 3, Survived: 0)

3521: } 3522: } 3523:

Mutants (Total: 2, Killed: 2, Survived: 0)

3524: # matches and nomatch values must be Regexp objects in the 3525: # generated test — compile raw strings safely via eval so 3526: # patterns containing [ or \ don't cause compile failures 3527: if(($subk eq $KEY_MATCHES) || ($subk eq $KEY_NOMATCH)) {

Mutants (Total: 2, Killed: 2, Survived: 0)

3528: my $re = ref($def->{$subk}) eq 'Regexp'

Mutants (Total: 2, Killed: 2, Survived: 0)

3529: ? $def->{$subk} 3530: : eval { qr/$def->{$subk}/ };

Mutants (Total: 1, Killed: 1, Survived: 0)

3531: if($@ || !defined($re)) { 3532: carp "render_hash: invalid $subk pattern '$def->{$subk}': $@";

Mutants (Total: 1, Killed: 1, Survived: 0)

3533: next; 3534: }

Mutants (Total: 2, Killed: 2, Survived: 0)

3535: push @pairs, "$subk => " . perl_quote($re); 3536: } elsif(ref($def->{$subk}) eq 'HASH') { 3537: push @pairs, "$subk => " . _render_nested_hash($def->{$subk}); 3538: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

3539: # All other sub-keys are rendered via perl_quote which 3540: # handles scalars, arrayrefs, and Regexp objects correctly 3541: push @pairs, "$subk => " . perl_quote($def->{$subk}); 3542: } 3543: } 3544:

Mutants (Total: 2, Killed: 2, Survived: 0)

3545: # Use "\t" rather than a literal tab for clarity and grep-ability 3546: push @lines, "\t" . perl_quote($k) . ' => { ' . join(', ', @pairs) . ' }'; 3547: } 3548: 3549: return join(",\n", @lines);

Mutants (Total: 2, Killed: 2, Survived: 0)

3550: } 3551: 3552: =head2 render_args_hash 3553: 3554: Render a flat hashref into a Perl source-code argument list of the

Mutants (Total: 2, Killed: 2, Survived: 0)

3555: form C<'key' => value, ...>, suitable for embedding in a function call 3556: in a generated test file. 3557: 3558: my $code = render_args_hash({ type => 'string', min => 1 }); 3559: # returns: "'min' => 1, 'type' => 'string'" 3560: 3561: =head3 Arguments 3562: 3563: =over 4 3564: 3565: =item * C<$href> 3566: 3567: A flat hashref of key-value pairs. Values may be scalars, arrayrefs, 3568: or Regexp objects - all are handled by C<perl_quote>. 3569: 3570: =back 3571: 3572: =head3 Returns 3573: 3574: A comma-separated string of C<key => value> pairs sorted by key. 3575: Returns an empty string if C<$href> is undef, empty, or not a hashref. 3576: 3577: =head3 Notes 3578: 3579: Keys and values are both rendered via C<perl_quote>. In particular, 3580: C<Regexp> values are rendered as C<qr{...}> which is correct for 3581: L<Params::Validate::Strict> and L<Return::Set> schema arguments in 3582: the generated test. 3583: 3584: =head3 API SPECIFICATION 3585: 3586: =head4 input 3587: 3588: { href => { type => 'any', optional => 1 } } 3589: 3590: =head4 output 3591: 3592: { type => 'string' } 3593: 3594: The mathematical description is in L</FORMAL SPECIFICATION>. 3595: 3596: =cut 3597: 3598: # -------------------------------------------------- 3599: # _render_arg_value 3600: # 3601: # Purpose: Render one constructor argument. A marked path is replaced by a 3602: # temporary file or directory the generated test makes at run time, 3603: # so a constructor documented to take a directory can be called as 3604: # its POD says instead of being left unbuilt. 3605: # 3606: # Entry: $value - the schema value for the argument. 3607: # 3608: # Exit: Perl source for the argument. 3609: # -------------------------------------------------- 3610: sub _render_arg_value 3611: { ●3612 → 3614 → 3622 3612: my ($value) = @_; 3613: 3614: if(ref($value) eq 'HASH' && ($value->{'_path'} // '') =~ /^(?:file|directory)$/) { 3615: return '(do { require File::Temp; File::Temp::tempdir(CLEANUP => 1) })' 3616: if $value->{'_path'} eq 'directory'; 3617: return '(do { require File::Temp; my ($_fh, $_path) = File::Temp::tempfile(UNLINK => 1); close $_fh; $_path })'; 3618: } 3619: 3620: # Render element by element: an element may be an object stand-in, which 3621: # perl_quote() would emit as the marker hashref rather than build. ●3622 → 3622 → 3626 3622: if(ref($value) eq 'ARRAY') { 3623: return '[ ' . join(', ', map { _render_arg_value($_) } @{$value}) . ' ]'; 3624: } 3625:

Mutants (Total: 1, Killed: 1, Survived: 0)

●3626 → 3626 → 3630 3626: if(ref($value) eq 'HASH' && ref($value->{'_stub'}) eq 'HASH') { 3627: return '_build_stub_object(' . _render_stub_spec($value->{'_stub'}) . ')'; 3628: } 3629: 3630: return perl_quote($value); 3631: } 3632: 3633: # A stub description as Perl source, keys sorted so the generated file is 3634: # deterministic. Values are scalars, arrayrefs or hashrefs of them. 3635: sub _render_stub_spec 3636: { 3637: my ($spec) = @_; 3638: 3639: my @methods = map { 3640: perl_quote($_) . ' => ' . perl_quote($spec->{methods}{$_}) 3641: } sort keys %{ $spec->{methods} // {} }; 3642: 3643: return '{ isa => ' . perl_quote($spec->{isa}) 3644: . ', methods => { ' . join(', ', @methods) . ' } }'; 3645: } 3646: 3647: sub render_args_hash { 3648: my $href = $_[0]; 3649: 3650: # Return empty string for absent or non-hash input

Mutants (Total: 1, Killed: 0, Survived: 1)
3651: return '' unless $href && ref($href) eq 'HASH'; 3652: 3653: # Sort keys for deterministic output across runs — important for 3654: # generated test files that are committed to version control 3655: my @pairs = map { 3656: perl_quote($_) . ' => ' . _render_arg_value($href->{$_}) 3657: } sort keys %{$href}; 3658: 3659: return join(', ', @pairs); 3660: } 3661: 3662: =head2 render_arrayref_map 3663: 3664: Render a hashref whose values are arrayrefs into a Perl source-code 3665: fragment suitable for use as a hash literal in a generated test file. 3666: 3667: my $code = render_arrayref_map({ name => ['', 'a' x 100] }); 3668: 3669: =head3 Arguments 3670: 3671: =over 4 3672: 3673: =item * C<$href> 3674: 3675: A hashref whose values are arrayrefs. Keys whose values are not 3676: arrayrefs are silently skipped. 3677: 3678: =back 3679: 3680: =head3 Returns 3681: 3682: A comma-separated string of C<'key' => [ val, ... ]> entries, one per 3683: qualifying key, sorted alphabetically. Returns the string C<'()'> if 3684: C<$href> is undef or not a hashref - this produces an empty 3685: hash assignment in the generated test rather than a syntax error. 3686: Returns an empty string if C<$href> is a hashref with no arrayref values. 3687: 3688: =head3 Notes
Mutants (Total: 1, Killed: 0, Survived: 1)
3689: 3690: Array element values are rendered via C<perl_quote> which handles 3691: scalars, arrayrefs, and Regexp objects. Non-arrayref values are 3692: skipped without warning - this is intentional since callers may pass 3693: mixed-value hashes and only want the arrayref entries rendered. 3694: 3695: =head3 API SPECIFICATION 3696: 3697: =head4 input 3698: 3699: { href => { type => 'any', optional => 1 } } 3700: 3701: =head4 output 3702: 3703: { type => 'string' }

Mutants (Total: 1, Killed: 1, Survived: 0)

3704: 3705: The mathematical description is in L</FORMAL SPECIFICATION>. 3706: 3707: =cut 3708: 3709: sub render_arrayref_map { ●3710 → 3718 → 3732 3710: my $href = $_[0]; 3711: 3712: # Return '()' rather than '' so callers get a valid empty hash 3713: # literal rather than a syntax error in the generated test 3714: return '()' unless $href && ref($href) eq 'HASH'; 3715: 3716: my @entries; 3717: 3718: for my $k (sort keys %{$href}) {

Mutants (Total: 1, Killed: 0, Survived: 1)
3719: my $aref = $href->{$k}; 3720: 3721: # Skip non-arrayref values — mixed hashes are allowed by callers 3722: next unless ref($aref) eq 'ARRAY'; 3723: 3724: # Render each array element via perl_quote so strings are 3725: # properly quoted and numbers are left unquoted 3726: my $vals = join(', ', map { perl_quote($_) } @{$aref}); 3727: 3728: # Use "\t" rather than a literal tab for clarity 3729: push @entries, "\t" . perl_quote($k) . " => [ $vals ]"; 3730: } 3731: 3732: return join(",\n", @entries); 3733: } 3734: 3735: # -------------------------------------------------- 3736: # _has_positions 3737: # 3738: # Purpose: Determine whether any field in an input 3739: # spec hashref declares a positional argument 3740: # via the 'position' key. 3741: # 3742: # Entry: $input_spec - the input section of a parsed 3743: # schema, expected to be a hashref whose values 3744: # are themselves hashrefs containing field specs. 3745: # May be undef or a non-hash ref. 3746: # 3747: # Exit: Returns 1 if any field has a defined 3748: # 'position' key, 0 otherwise. 3749: # 3750: # Notes: Returns 0 immediately for undef or non-hash 3751: # input rather than throwing — callers use the 3752: # return value as a boolean and do not expect 3753: # exceptions from this function. 3754: # -------------------------------------------------- 3755: sub _has_positions {

Mutants (Total: 2, Killed: 2, Survived: 0)

●3756 → 3761 → 3771 3756: my $input_spec = $_[0]; 3757: 3758: # Guard against undef or non-hash input — keys %$undef would throw 3759: return 0 unless defined($input_spec) && ref($input_spec) eq 'HASH'; 3760: 3761: for my $field (keys %{$input_spec}) { 3762: # Only examine fields whose spec is a hashref — scalar specs 3763: # (e.g. input: { type: string }) cannot have positions 3764: next unless ref($input_spec->{$field}) eq 'HASH'; 3765: 3766: # Return immediately on first match — no need to scan further 3767: return 1 if defined $input_spec->{$field}{position}; 3768: } 3769: 3770: # No positional arguments found in any field 3771: return 0; 3772: } 3773: 3774: # -------------------------------------------------- 3775: # q_wrap 3776: # 3777: # Purpose: Wrap a string in the most readable 3778: # q{} form that does not require escaping, 3779: # falling back to single-quoted form with 3780: # escaped apostrophes if no delimiter is 3781: # available. 3782: # 3783: # Entry: $s - the string to wrap. May be undef. 3784: # Exit: Returns a Perl source-code fragment that 3785: # evaluates to the original string value, 3786: # or the string 'undef' if $s is undef. 3787: # 3788: # Notes: index() returns -1 when not found and 3789: # any value >= 0 when found, including 0 3790: # for a delimiter at the start of the 3791: # string. We compare against $INDEX_NOT_FOUND 3792: # to make this boundary explicit and to 3793: # prevent off-by-one mutation survivors. 3794: # See GitHub issue #1. 3795: # -------------------------------------------------- 3796: sub q_wrap { ●3797 → 3811 → 3820 3797: my $s = $_[0]; 3798: 3799: croak('q_wrap: argument must be a plain string, not a reference') if ref($s); 3800: 3801: # Return empty string for undef — this function is a low-level 3802: # string quoter only. Callers that need the Perl literal 'undef' 3803: # for undefined values should use perl_quote() instead, which 3804: # handles the undef -> 'undef' semantic conversion correctly. 3805: # Returning '' here preserves the original behaviour and avoids 3806: # injecting the bare word 'undef' into contexts that expect a 3807: # quoted string value. 3808: return "''" unless defined $s; 3809: 3810: # Try bracket-form q{} delimiters first — most readable 3811: for my $p (@Q_BRACKET_PAIRS) { 3812: my ($l, $r) = @{$p}; 3813: 3814: # Only use this bracket pair if neither bracket 3815: # appears in the string — both must be checked 3816: return "q$l$s$r" unless $s =~ /\Q$l\E|\Q$r\E/; 3817: } 3818: 3819: # Try single-character delimiters in preference order ●3820 → 3820 → 3825 3820: for my $d (@Q_SINGLE_DELIMITERS) { 3821: # index() returns $INDEX_NOT_FOUND (-1) when not found. 3822: # Must use != $INDEX_NOT_FOUND rather than > 0 since 3823: # the delimiter may legitimately appear at position 0 3824: return "q$d$s$d" if index($s, $d) == $INDEX_NOT_FOUND; 3825: } 3826: 3827: # Last resort — single-quoted string with escaped apostrophes 3828: (my $esc = $s) =~ s/'/\\'/g; 3829: return "'$esc'"; 3830: } 3831: 3832: # -------------------------------------------------- 3833: # perl_sq 3834: # 3835: # Purpose: Escape a string for safe inclusion 3836: # inside a single-quoted Perl string 3837: # literal in generated test code. 3838: # 3839: # Entry: $s - the string to escape. 3840: # Exit: Returns the escaped string, or an 3841: # empty string if $s is undef. 3842: # 3843: # Notes: NUL byte replacement produces the 3844: # two-character sequence \0 which is 3845: # only correct when the result is used 3846: # inside a double-quoted string context 3847: # in the generated test. 3848: # 3849: # The \b substitution (backspace) is 3850: # intentionally omitted — in Perl regex 3851: # context \b means word boundary, not 3852: # backspace, so substituting it here 3853: # would corrupt strings containing word 3854: # boundaries. 3855: # -------------------------------------------------- 3856: sub perl_sq { 3857: my $s = $_[0]; 3858: 3859: croak('perl_sq: argument must be a plain string, not a reference') if ref($s); 3860: 3861: # Return empty string for undef — callers that need 3862: # 'undef' literal should use perl_quote instead 3863: return '' unless defined $s; 3864: 3865: # Escape backslashes first so later substitutions 3866: # don't double-escape already-escaped sequences 3867: $s =~ s/\\/\\\\/g; 3868: 3869: # Escape apostrophes so they don't terminate the 3870: # surrounding single-quoted string literal 3871: $s =~ s/'/\\'/g; 3872: 3873: # Escape common control characters to their 3874: # printable two-character escape sequences 3875: $s =~ s/\n/\\n/g; 3876: $s =~ s/\r/\\r/g; 3877: $s =~ s/\t/\\t/g; 3878: $s =~ s/\f/\\f/g; 3879: 3880: # Replace NUL bytes with \0 — valid only in 3881: # double-quoted string context in generated code 3882: $s =~ s/\0/\\0/g; 3883: 3884: return $s; 3885: } 3886: 3887: =head2 perl_quote 3888: 3889: Convert any Perl value into a source-code fragment that reproduces that value 3890: when evaluated in a generated test file. 3891: 3892: =head3 Arguments 3893: 3894: =over 4 3895: 3896: =item * C<$v> 3897: 3898: Any Perl value. May be undef, a scalar, an arrayref, a Regexp, or a blessed 3899: object. All types are handled - undef becomes C<'undef'>, the strings 3900: C<'true'>/C<'false'> become the Perl boolean constants C<!!1>/C<!!0>, 3901: numbers are unquoted, other strings are single-quoted, arrayrefs recurse, 3902: Regexps become C<qr{...}>, and anything else (including hashrefs and 3903: blessed objects) falls through to C<render_fallback>. 3904: 3905: =back 3906: 3907: =head3 API SPECIFICATION 3908: 3909: =head4 input 3910: 3911: { v => { type => 'any', optional => 1 } } 3912: 3913: =head4 output 3914: 3915: { type => 'string' } 3916: 3917: The mathematical description is in L</FORMAL SPECIFICATION>. 3918: 3919: =cut 3920: 3921: sub perl_quote { 3922: my ($v) = @_; 3923: return _perl_quote($v, 0); 3924: } 3925: 3926: sub _perl_quote { ●3927 → 3939 → 3963 3927: my ($v, $depth) = @_; 3928: no warnings 'recursion'; ## no critic (TestingAndDebugging::ProhibitNoWarnings) 3929: croak('perl_quote: structure too deeply nested (circular reference?)') if $depth > 100; 3930: 3931: # Undef produces the Perl literal 'undef' 3932: return 'undef' unless defined $v; 3933: 3934: # Convert YAML boolean string literals to Perl 3935: # boolean constants so they survive round-tripping 3936: return '!!1' if $v eq 'true'; 3937: return '!!0' if $v eq 'false'; 3938: 3939: if(ref($v)) { 3940: # Recursively quote each element of an arrayref 3941: if(ref($v) eq 'ARRAY') { 3942: my @quoted_v = map { _perl_quote($_, $depth + 1) } @{$v}; 3943: return '[ ' . join(', ', @quoted_v) . ' ]'; 3944: } 3945: 3946: # Render Regexp objects as qr{} with modifiers 3947: if(ref($v) eq 'Regexp') { 3948: my ($pat, $mods) = regexp_pattern($v); 3949: my $re = "qr{$pat}"; 3950: 3951: # Append modifiers (e.g. 'i', 'x') if present 3952: $re .= $mods if $mods; 3953: return $re; 3954: } 3955: 3956: # Hashrefs and other reference types fall through 3957: # to render_fallback which uses Data::Dumper 3958: return render_fallback($v); 3959: } 3960: 3961: # Numeric values are emitted unquoted so the generated 3962: # test performs numeric rather than string comparison 3963: return looks_like_number($v) ? $v : "'" . perl_sq($v) . "'"; 3964: } 3965: 3966: # -------------------------------------------------- 3967: # _generate_transform_properties 3968: # 3969: # Convert a hashref of transform 3970: # specifications into an arrayref of 3971: # LectroTest property definition hashrefs, 3972: # one per transform. Each hashref contains 3973: # all the information needed by 3974: # _render_properties to emit a runnable 3975: # Test::LectroTest property block. 3976: # 3977: # Entry: $transforms - hashref of transform name 3978: # => transform spec, as 3979: # loaded from the schema. 3980: # $function - name of the function under 3981: # test. 3982: # $module - module name, or undef for 3983: # builtin functions. 3984: # $input - the top-level input spec 3985: # hashref from the schema 3986: # (used for position sorting). 3987: # $config - the normalised config 3988: # hashref, used to read 3989: # properties.trials. 3990: # $new - defined if the function is 3991: # an object method; the value 3992: # is not used here since 3993: # property tests always 3994: # construct a fresh object 3995: # via new_ok() with no args. 3996: # Presence vs absence is the 3997: # only signal used. 3998: # 3999: # Exit: Returns an arrayref of property hashrefs. 4000: # Returns an empty arrayref if no transforms 4001: # produce any testable properties. 4002: # Never returns undef. 4003: # 4004: # Notes: Transforms whose input is the string 4005: # 'undef' or whose input spec is not a 4006: # hashref are silently skipped — they 4007: # represent error-case transforms that have 4008: # no meaningful generator. 4009: # 4010: # The 'WARN' vs 'WARNS' distinction in 4011: # _STATUS: the schema convention uses 4012: # 'WARNS' throughout. This function checks 4013: # for 'WARNS' to match that convention. 4014: # -------------------------------------------------- 4015: sub _generate_transform_properties { ●4016 → 4020 → 4166 4016: my ($transforms, $function, $module, $input, $config, $new) = @_; 4017: 4018: my @properties; 4019: 4020: for my $transform_name (sort keys %{$transforms}) { 4021: # $transform_name is spliced by _render_properties as a Perl 4022: # *variable name* (my $$transform_name = Property {...}), not 4023: # just inside a string literal — reject anything that isn't 4024: # identifier-shaped before it reaches that point. 4025: _assert_identifier($transform_name, 'transform name'); 4026: 4027: my $transform = $transforms->{$transform_name}; 4028: 4029: my $input_spec = $transform->{input}; 4030: 4031: # Guard: skip transforms with no input or with the 4032: # YAML scalar 'undef' as their input — these have no 4033: # generator and cannot produce meaningful properties 4034: if(!defined($input_spec) || 4035: (!ref($input_spec) && $input_spec eq 'undef')) { 4036: next; 4037: } 4038: 4039: # Guard: skip transforms whose input is not a hashref — 4040: # must come before the helper calls below so we never

Mutants (Total: 2, Killed: 2, Survived: 0)

4041: # pass a non-hash to _detect_transform_properties or 4042: # _process_custom_properties 4043: next unless ref($input_spec) eq 'HASH'; 4044: 4045: # Default output spec to empty hash so _STATUS lookups 4046: # below are always safe regardless of schema content 4047: my $output_spec = $transform->{output} // {};

Mutants (Total: 2, Killed: 2, Survived: 0)

4048: 4049: # Detect automatic properties from the transform spec 4050: # (range constraints, type preservation, definedness) 4051: my @detected_props = _detect_transform_properties( 4052: $transform_name, 4053: $input_spec, 4054: $output_spec

Mutants (Total: 2, Killed: 2, Survived: 0)

4055: ); 4056: 4057: # Process any custom properties defined in the schema 4058: my @custom_props = (); 4059: if(exists($transform->{properties}) && 4060: ref($transform->{properties}) eq 'ARRAY') { 4061: @custom_props = _process_custom_properties(

Mutants (Total: 2, Killed: 2, Survived: 0)

4062: $transform->{properties}, 4063: $function, 4064: $module, 4065: $input_spec, 4066: $output_spec, 4067: $new 4068: ); 4069: } 4070: 4071: # Combine auto-detected and custom properties into one list

Mutants (Total: 2, Killed: 2, Survived: 0)

4072: my @all_props = (@detected_props, @custom_props); 4073: 4074: # Skip this transform if no properties were produced — 4075: # nothing useful to render into the generated test 4076: next unless @all_props; 4077: 4078: # Build the LectroTest generator specification string, 4079: # one entry per input field that has a generator 4080: my @generators;

Mutants (Total: 2, Killed: 2, Survived: 0)

4081: my @var_names; 4082: 4083: for my $field (sort keys %{$input_spec}) { 4084: my $spec = $input_spec->{$field}; 4085: 4086: # Skip non-hashref field specs — scalar types 4087: # like 'string' have no generator sub-structure 4088: next unless ref($spec) eq 'HASH'; 4089:

Mutants (Total: 2, Killed: 2, Survived: 0)

4090: # $field is spliced unescaped into the generated 4091: # LectroTest generator spec by 4092: # _schema_to_lectrotest_generator() — reject anything 4093: # that isn't identifier-shaped first. 4094: _assert_identifier($field, 'input field name'); 4095: 4096: my $gen = _schema_to_lectrotest_generator($field, $spec); 4097: if(defined($gen) && length($gen)) { 4098: push @generators, $gen;

Mutants (Total: 2, Killed: 2, Survived: 0)

4099: push @var_names, $field; 4100: } 4101: } 4102: 4103: my $gen_spec = join(', ', @generators); 4104: 4105: # Build the call expression for the function under test. 4106: # Note: property tests always construct a fresh object 4107: # via new_ok() with no constructor arguments, regardless

Mutants (Total: 2, Killed: 2, Survived: 0)

4108: # of what $new holds in the caller — the intent here is 4109: # to test the method in isolation, not with specific 4110: # construction state. 4111: my $call_code; 4112: if($module && defined($new)) { 4113: # OO mode — construct a fresh object for each trial 4114: $call_code = "my \$obj = new_ok('$module');"; 4115: $call_code .= "\$obj->$function"; 4116: } elsif($module && $module ne $MODULE_BUILTIN) { 4117: # Functional mode with a named module 4118: $call_code = "$module\::$function";

Mutants (Total: 2, Killed: 2, Survived: 0)

4119: } else { 4120: # Builtin or unqualified function call 4121: $call_code = $function; 4122: } 4123: 4124: # Build the argument list, respecting positional order 4125: # if the input spec declares positions 4126: my @args; 4127: if(_has_positions($input_spec)) { 4128: # Sort fields by declared position so the generated 4129: # call passes arguments in the correct order, then pass

Mutants (Total: 2, Killed: 2, Survived: 0)

4130: # the named options as name/value pairs after them 4131: my @sorted = sort { 4132: $input_spec->{$a}{position} <=> 4133: $input_spec->{$b}{position} 4134: } grep { defined $input_spec->{$_}{position} } keys %{$input_spec}; 4135: my @named = grep { !defined $input_spec->{$_}{position} } @var_names; 4136: @args = (map { "\$$_" } @sorted, map { "'$_' => \$$_" } @named); 4137: } else { 4138: # No positions — use alphabetical order from @var_names 4139: @args = map { "\$$_" } @var_names;

Mutants (Total: 2, Killed: 2, Survived: 0)

4140: } 4141: 4142: my $args_str = join(', ', @args); 4143: 4144: # Concatenate all property check expressions with && 4145: # so the generated property block passes only when 4146: # every check holds 4147: my @checks = map { $_->{code} } @all_props; 4148: my $property_checks = join(" &&\n\t", @checks); 4149: 4150: # Determine expected behaviour from output _STATUS. 4151: # Note: the schema convention uses 'WARNS' not 'WARN' 4152: my $should_die = ($output_spec->{'_STATUS'} // '') eq 'DIES'; 4153: my $should_warn = ($output_spec->{'_STATUS'} // '') eq 'WARNS'; 4154: 4155: push @properties, { 4156: name => $transform_name, 4157: generator_spec => $gen_spec, 4158: call_code => "$call_code($args_str)", 4159: property_checks => $property_checks, 4160: should_die => $should_die, 4161: should_warn => $should_warn, 4162: trials => $config->{'properties'}{'trials'} // $DEFAULT_PROPERTY_TRIALS, 4163: }; 4164: } 4165: 4166: return \@properties; 4167: } 4168: 4169: # -------------------------------------------------- 4170: # _get_semantic_generators 4171: # 4172: # Return a hashref of named semantic 4173: # generator definitions for use in 4174: # LectroTest property-based tests. 4175: # Each entry contains a 'code' key 4176: # holding a Gen {} block string and a 4177: # 'description' key for documentation 4178: # and validation messages. 4179: # 4180: # Entry: None. 4181: # 4182: # Exit: Returns a hashref keyed by semantic 4183: # type name. Each value is a hashref 4184: # with 'code' and 'description' keys. 4185: # 4186: # Notes: The returned hashref is built fresh 4187: # on every call — callers that need it 4188: # repeatedly should cache the result. 4189: # The 'code' strings are multi-line 4190: # Gen {} blocks; callers are responsible 4191: # for compressing whitespace before 4192: # embedding them in generated test files. 4193: # -------------------------------------------------- 4194: sub _get_semantic_generators { 4195: return { 4196: email => { 4197: code => q{ 4198: Gen { 4199: my $len = 5 + int(rand(10)); 4200: my @addr; 4201: my @tlds = qw(com org net edu gov io co uk de fr);

Mutants (Total: 1, Killed: 1, Survived: 0)

4202: 4203: for(my $i = 0; $i < $len; $i++) { 4204: push @addr, pack('c', (int(rand 26))+97); 4205: }

Mutants (Total: 1, Killed: 1, Survived: 0)

4206: push @addr, '@'; 4207: $len = 5 + int(rand(10)); 4208: for(my $i = 0; $i < $len; $i++) { 4209: push @addr, pack('c', (int(rand 26))+97); 4210: } 4211: push @addr, '.'; 4212: $len = rand($#tlds+1); 4213: push @addr, $tlds[$len]; 4214: return join('', @addr);

Mutants (Total: 2, Killed: 2, Survived: 0)

4215: } 4216: }, 4217: description => 'Valid email addresses', 4218: }, url => { 4219: code => q{ 4220: Gen { 4221: my @schemes = qw(http https); 4222: my @tlds = qw(com org net io); 4223: my $scheme = $schemes[int(rand(@schemes))]; 4224: my $domain = join('', map { ('a'..'z')[int(rand(26))] } 1..(5 + int(rand(10)))); 4225: my $tld = $tlds[int(rand(@tlds))];

Mutants (Total: 1, Killed: 1, Survived: 0)

4226: my $path = join('', map { ('a'..'z', '0'..'9', '-', '_')[int(rand(38))] } 1..int(rand(20))); 4227: 4228: return "$scheme://$domain.$tld" . ($path ? "/$path" : ''); 4229: }

Mutants (Total: 1, Killed: 1, Survived: 0)

4230: }, 4231: description => 'Valid HTTP/HTTPS URLs',

Mutants (Total: 2, Killed: 2, Survived: 0)

4232: }, uuid => { 4233: code => q{ 4234: Gen {

Mutants (Total: 2, Killed: 2, Survived: 0)

4235: require UUID::Tiny; 4236: UUID::Tiny::create_uuid_as_string(UUID::Tiny::UUID_V4()); 4237: }

Mutants (Total: 2, Killed: 2, Survived: 0)

4238: }, 4239: description => 'Valid UUIDv4 identifiers', 4240: }, phone_us => { 4241: code => q{

Mutants (Total: 2, Killed: 2, Survived: 0)

4242: Gen { 4243: my $area = 200 + int(rand(800)); 4244: my $exchange = 200 + int(rand(800)); 4245: my $subscriber = int(rand(10000)); 4246: sprintf('%03d-%03d-%04d', $area, $exchange, $subscriber); 4247: } 4248: },

Mutants (Total: 1, Killed: 1, Survived: 0)

4249: description => 'US phone numbers (XXX-XXX-XXXX format)', 4250: }, phone_e164 => { 4251: code => q{ 4252: Gen {

Mutants (Total: 1, Killed: 1, Survived: 0)

4253: my $country = 1 + int(rand(999)); 4254: my $area = 100 + int(rand(900));

Mutants (Total: 2, Killed: 2, Survived: 0)

4255: my $number = int(rand(10000000)); 4256: sprintf('+%d%03d%07d', $country, $area, $number); 4257: } 4258: },

Mutants (Total: 2, Killed: 2, Survived: 0)

4259: description => 'E.164 international phone numbers', 4260: }, ipv4 => {

Mutants (Total: 2, Killed: 2, Survived: 0)

4261: code => q{

Mutants (Total: 3, Killed: 3, Survived: 0)

4262: Gen { 4263: join('.', map { int(rand(256)) } 1..4);

Mutants (Total: 2, Killed: 2, Survived: 0)

4264: } 4265: }, 4266: description => 'IPv4 addresses',

Mutants (Total: 2, Killed: 2, Survived: 0)

4267: }, ipv6 => { 4268: code => q{ 4269: Gen { 4270: join(':', map { sprintf('%04x', int(rand(0x10000))) } 1..8); 4271: }

Mutants (Total: 2, Killed: 2, Survived: 0)

4272: }, 4273: description => 'IPv6 addresses',

Mutants (Total: 2, Killed: 2, Survived: 0)

4274: }, username => {

Mutants (Total: 3, Killed: 0, Survived: 3)
4275: code => q{ 4276: Gen {

Mutants (Total: 2, Killed: 2, Survived: 0)

4277: my $len = 3 + int(rand(13)); 4278: my @chars = ('a'..'z', '0'..'9', '_', '-'); 4279: my $first = ('a'..'z')[int(rand(26))];

Mutants (Total: 2, Killed: 2, Survived: 0)

4280: $first . join('', map { $chars[int(rand(@chars))] } 1..($len-1)); 4281: } 4282: }, 4283: description => 'Valid usernames (alphanumeric with _ and -)', 4284: }, slug => { 4285: code => q{

Mutants (Total: 4, Killed: 4, Survived: 0)

4286: Gen { 4287: my @words = qw(quick brown fox jumps over lazy dog hello world test data); 4288: my $count = 1 + int(rand(4)); 4289: join('-', map { $words[int(rand(@words))] } 1..$count); 4290: } 4291: },

Mutants (Total: 2, Killed: 2, Survived: 0)

4292: description => 'URL slugs (lowercase words separated by hyphens)', 4293: }, hex_color => { 4294: code => q{ 4295: Gen { 4296: sprintf('#%06x', int(rand(0x1000000))); 4297: } 4298: },

Mutants (Total: 1, Killed: 1, Survived: 0)

4299: description => 'Hex color codes (#RRGGBB)', 4300: }, iso_date => { 4301: code => q{ 4302: Gen { 4303: my $year = 2000 + int(rand(25)); 4304: my $month = 1 + int(rand(12));

Mutants (Total: 1, Killed: 1, Survived: 0)

4305: my $day = 1 + int(rand(28)); 4306: sprintf('%04d-%02d-%02d', $year, $month, $day); 4307: } 4308: }, 4309: description => 'ISO 8601 date format (YYYY-MM-DD)', 4310: }, 4311: iso_datetime => { 4312: code => q{ 4313: Gen { 4314: my $year = 2000 + int(rand(25)); 4315: my $month = 1 + int(rand(12));

Mutants (Total: 1, Killed: 1, Survived: 0)

4316: my $day = 1 + int(rand(28)); 4317: my $hour = int(rand(24));

Mutants (Total: 2, Killed: 0, Survived: 2)
4318: my $minute = int(rand(60)); 4319: my $second = int(rand(60)); 4320: sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ', 4321: $year, $month, $day, $hour, $minute, $second); 4322: }

Mutants (Total: 1, Killed: 1, Survived: 0)

4323: },

Mutants (Total: 2, Killed: 2, Survived: 0)

4324: description => 'ISO 8601 datetime format (YYYY-MM-DDTHH:MM:SSZ)', 4325: }, semver => {

Mutants (Total: 2, Killed: 2, Survived: 0)

4326: code => q{ 4327: Gen {

Mutants (Total: 2, Killed: 2, Survived: 0)

4328: my $major = int(rand(10)); 4329: my $minor = int(rand(20)); 4330: my $patch = int(rand(50)); 4331: "$major.$minor.$patch";

Mutants (Total: 2, Killed: 2, Survived: 0)

4332: } 4333: }, 4334: description => 'Semantic version strings (major.minor.patch)', 4335: }, jwt => { 4336: code => q{ 4337: Gen {

Mutants (Total: 1, Killed: 1, Survived: 0)

4338: my @chars = ('A'..'Z', 'a'..'z', '0'..'9', '-', '_');

Mutants (Total: 2, Killed: 2, Survived: 0)

4339: my $header = join('', map { $chars[int(rand(@chars))] } 1..20); 4340: my $payload = join('', map { $chars[int(rand(@chars))] } 1..40); 4341: my $signature = join('', map { $chars[int(rand(@chars))] } 1..30); 4342: "$header.$payload.$signature"; 4343: } 4344: },

Mutants (Total: 1, Killed: 1, Survived: 0)

4345: description => 'JWT-like tokens (base64url format)', 4346: }, json => { 4347: code => q{

Mutants (Total: 2, Killed: 2, Survived: 0)

4348: Gen { 4349: my @keys = qw(id name value status count); 4350: my $key = $keys[int(rand(@keys))]; 4351: my $value = 1 + int(rand(1000)); 4352: qq({"$key":$value}); 4353: } 4354: }, 4355: description => 'Simple JSON objects',

Mutants (Total: 1, Killed: 1, Survived: 0)

4356: }, base64 => { 4357: code => q{ 4358: Gen {

Mutants (Total: 2, Killed: 2, Survived: 0)

4359: my @chars = ('A'..'Z', 'a'..'z', '0'..'9', '+', '/'); 4360: my $len = 12 + int(rand(20)); 4361: my $str = join('', map { $chars[int(rand(@chars))] } 1..$len); 4362: $str .= '=' x (4 - ($len % 4)) if $len % 4; 4363: $str; 4364: } 4365: },

Mutants (Total: 2, Killed: 2, Survived: 0)

4366: description => 'Base64-encoded strings', 4367: }, md5 => { 4368: code => q{ 4369: Gen { 4370: join('', map { sprintf('%x', int(rand(16))) } 1..32); 4371: } 4372: }, 4373: description => 'MD5 hashes (32 hex characters)', 4374: }, sha256 => { 4375: code => q{ 4376: Gen { 4377: join('', map { sprintf('%x', int(rand(16))) } 1..64); 4378: } 4379: }, 4380: description => 'SHA-256 hashes (64 hex characters)', 4381: }, bytes => { 4382: code => q{ 4383: Gen { 4384: my $len = 1 + int(rand(32)); 4385: join('', map { pack('C', int(rand(256))) } 1..$len); 4386: } 4387: }, 4388: description => 'Byte strings (arbitrary octets, not text)', 4389: }, directory => { 4390: code => q{ 4391: Gen { 4392: require File::Temp; 4393: File::Temp::tempdir(CLEANUP => 1); 4394: } 4395: }, 4396: description => 'Paths to existing writable directories', 4397: }, existing_file => { 4398: code => q{ 4399: Gen { 4400: require File::Temp; 4401: my ($fh, $path) = File::Temp::tempfile(SUFFIX => '.pm', UNLINK => 1); 4402: close $fh; 4403: $path; 4404: } 4405: }, 4406: description => 'Paths to existing files', 4407: }, unix_timestamp => { 4408: code => q{ 4409: Gen { 4410: time; 4411: } 4412: }, 4413: description => 'Unix timestamps (seconds since epoch)', 4414: }, 4415: }; 4416: } 4417: 4418: # -------------------------------------------------- 4419: # _get_builtin_properties 4420: # 4421: # Purpose: Return a hashref of named built-in 4422: # property templates that can be 4423: # referenced by name in a transform's 4424: # 'properties' list in the schema. 4425: # Each entry contains a 'description' 4426: # string, a 'code_template' coderef, and 4427: # an 'applicable_to' arrayref. 4428: # 4429: # Entry: None. 4430: # 4431: # Exit: Returns a hashref keyed by property 4432: # name. Each value is a hashref with 4433: # 'description', 'code_template', and 4434: # 'applicable_to' keys. 4435: # 4436: # Notes: 'applicable_to' lists the types for 4437: # which each property is meaningful. It 4438: # is stored for documentation purposes 4439: # and potential future filtering — it is 4440: # not currently enforced by any caller. 4441: # 4442: # Each 'code_template' coderef receives 4443: # three arguments: ($function, $call_code, 4444: # $input_vars). Most templates use only 4445: # $call_code; $function and $input_vars 4446: # are provided for templates that need 4447: # them (e.g. idempotent, length_preserved, 4448: # preserves_keys). 4449: # 4450: # 'monotonic_increasing' has been 4451: # intentionally omitted. A correct 4452: # implementation requires calling the 4453: # function twice with ordered inputs, 4454: # which the current single-call property 4455: # framework does not support. A 4456: # placeholder that unconditionally returns 4457: # true would give false confidence and has 4458: # therefore been removed. 4459: # -------------------------------------------------- 4460: sub _get_builtin_properties { 4461: return { 4462: idempotent => { 4463: description => 'Function is idempotent: f(f(x)) == f(x)', 4464: code_template => sub { 4465: my ($function, $call_code, $input_vars) = @_; 4466: 4467: # String comparison works for all scalar types in Perl — 4468: # numeric values stringify consistently for eq 4469: return "do { my \$tmp = $call_code; \$result eq \$tmp }"; 4470: }, 4471: applicable_to => ['all'], 4472: }, non_negative => { 4473: description => 'Result is always non-negative', 4474: code_template => sub { 4475: my ($function, $call_code, $input_vars) = @_; 4476: return '$result >= 0'; 4477: }, 4478: applicable_to => ['number', 'integer', 'float'], 4479: }, positive => { 4480: description => 'Result is always positive (> 0)', 4481: code_template => sub { 4482: my ($function, $call_code, $input_vars) = @_; 4483: return '$result > 0'; 4484: }, 4485: applicable_to => ['number', 'integer', 'float'], 4486: }, non_empty => { 4487: description => 'Result is never empty',

Mutants (Total: 2, Killed: 2, Survived: 0)

4488: code_template => sub { 4489: my ($function, $call_code, $input_vars) = @_; 4490: return 'length($result) > 0'; 4491: },

Mutants (Total: 2, Killed: 2, Survived: 0)

4492: applicable_to => ['string'], 4493: }, 4494: 4495: length_preserved => { 4496: description => 'Output length equals input length', 4497: code_template => sub {

Mutants (Total: 2, Killed: 2, Survived: 0)

4498: my ($function, $call_code, $input_vars) = @_; 4499: my $first_var = $input_vars->[0]; 4500: return "length(\$result) == length(\$$first_var)"; 4501: }, 4502: applicable_to => ['string'],

Mutants (Total: 2, Killed: 2, Survived: 0)

4503: }, 4504: 4505: uppercase => { 4506: description => 'Result is all uppercase', 4507: code_template => sub { 4508: my ($function, $call_code, $input_vars) = @_; 4509: return '$result eq uc($result)'; 4510: }, 4511: applicable_to => ['string'], 4512: }, 4513: 4514: lowercase => { 4515: description => 'Result is all lowercase', 4516: code_template => sub { 4517: my ($function, $call_code, $input_vars) = @_; 4518: return '$result eq lc($result)'; 4519: }, 4520: applicable_to => ['string'], 4521: }, 4522: 4523: trimmed => { 4524: description => 'Result has no leading or trailing whitespace', 4525: code_template => sub { 4526: my ($function, $call_code, $input_vars) = @_; 4527: return '$result !~ /^\s/ && $result !~ /\s$/'; 4528: }, 4529: applicable_to => ['string'], 4530: }, 4531: 4532: sorted_ascending => { 4533: description => 'Array is sorted in ascending order', 4534: code_template => sub { 4535: my ($function, $call_code, $input_vars) = @_; 4536: return 'do { my @arr = @$result; my $sorted = 1; ' . 4537: 'for my $i (1..$#arr) { $sorted = 0 if $arr[$i] < $arr[$i-1]; } ' . 4538: '$sorted }'; 4539: }, 4540: applicable_to => ['arrayref'],

Mutants (Total: 2, Killed: 2, Survived: 0)

4541: },

Mutants (Total: 2, Killed: 2, Survived: 0)

4542: 4543: sorted_descending => { 4544: description => 'Array is sorted in descending order', 4545: code_template => sub { 4546: my ($function, $call_code, $input_vars) = @_; 4547: return 'do { my @arr = @$result; my $sorted = 1; ' . 4548: 'for my $i (1..$#arr) { $sorted = 0 if $arr[$i] > $arr[$i-1]; } ' . 4549: '$sorted }'; 4550: }, 4551: applicable_to => ['arrayref'], 4552: }, 4553:

Mutants (Total: 1, Killed: 1, Survived: 0)

4554: unique_elements => { 4555: description => 'Array has no duplicate elements', 4556: code_template => sub { 4557: my ($function, $call_code, $input_vars) = @_; 4558: return 'do { my @arr = @$result; my %seen; !grep { $seen{$_}++ } @arr }'; 4559: }, 4560: applicable_to => ['arrayref'], 4561: }, 4562: 4563: preserves_keys => { 4564: description => 'Hash has same keys as input', 4565: code_template => sub { 4566: my ($function, $call_code, $input_vars) = @_; 4567: my $first_var = $input_vars->[0]; 4568: return 'do { my @in = sort keys %{$' . $first_var . '}; ' . 4569: 'my @out = sort keys %$result; ' . 4570: 'join(",", @in) eq join(",", @out) }'; 4571: }, 4572: applicable_to => ['hashref'],

Mutants (Total: 2, Killed: 2, Survived: 0)

4573: }, 4574: }; 4575: } 4576: 4577: # -------------------------------------------------- 4578: # _schema_to_lectrotest_generator 4579: # 4580: # Purpose: Convert a single schema field spec 4581: # hashref into a LectroTest generator 4582: # declaration string of the form 4583: # '$field <- Generator(...)'. 4584: # Used to build the ##[ ... ]## generator 4585: # block inside a Property definition. 4586: # 4587: # Entry: $field_name - the parameter name as it 4588: # will appear in the 4589: # generated test code. 4590: # $spec - hashref containing at 4591: # minimum a 'type' key. 4592: # May also contain 'min', 4593: # 'max', 'semantic', and 4594: # 'matches' keys depending 4595: # on type. 4596: # 4597: # Exit: Returns a string of the form 4598: # '$field <- Generator(...)' on success. 4599: # Returns undef if the spec is not a 4600: # hashref or if range constraints are 4601: # invalid (min >= max for numeric types). 4602: # Returns a String generator with a carp 4603: # warning for unknown types. 4604: # 4605: # Side effects: Carps on unknown semantic types, 4606: # invalid numeric ranges, and unknown 4607: # field types. 4608: # 4609: # Notes: Semantic generators are checked first 4610: # for string fields and take precedence 4611: # over the regular string generator. 4612: # The $input_spec parameter in the type- 4613: # detection helpers is reserved for future 4614: # use and is currently unused. 4615: # --------------------------------------------------

Mutants (Total: 2, Killed: 2, Survived: 0)

4616: sub _schema_to_lectrotest_generator {

Mutants (Total: 2, Killed: 2, Survived: 0)

●4617 → 4630 → 4654 4617: my ($field_name, $spec) = @_; 4618: 4619: # Guard: must be a hashref to dereference safely 4620: return unless defined($spec) && ref($spec) eq 'HASH'; 4621: 4622: # Default to string when no type is declared 4623: my $type = $spec->{'type'} || $DEFAULT_FIELD_TYPE; 4624: 4625: # --------------------------------------------------

Mutants (Total: 1, Killed: 1, Survived: 0)

4626: # Semantic generators take precedence for string

Mutants (Total: 1, Killed: 1, Survived: 0)

4627: # fields — they produce realistic domain-specific 4628: # values rather than random character sequences 4629: # -------------------------------------------------- 4630: if($type eq 'string' && defined($spec->{'semantic'})) { 4631: my $semantic_type = $spec->{'semantic'}; 4632: my $generators = _get_semantic_generators(); 4633: 4634: if(exists($generators->{$semantic_type})) {

Mutants (Total: 1, Killed: 1, Survived: 0)

4635: my $gen_code = $generators->{$semantic_type}{'code'}; 4636: 4637: # Compress the multi-line generator code into a 4638: # single line for embedding in the ##[ ]## block 4639: $gen_code =~ s/^\s+//; 4640: $gen_code =~ s/\s+$//; 4641: $gen_code =~ s/\n\s+/ /g; 4642: 4643: return "$field_name <- $gen_code"; 4644: } else {

Mutants (Total: 1, Killed: 1, Survived: 0)

4645: carp "Unknown semantic type '$semantic_type', " . 4646: "falling back to regular string generator"; 4647: # Fall through to regular string generation below 4648: } 4649: } 4650: 4651: # -------------------------------------------------- 4652: # Integer generator 4653: # -------------------------------------------------- ●4654 → 4654 → 4677 4654: if($type eq 'integer') { 4655: my $min = $spec->{'min'};

Mutants (Total: 1, Killed: 1, Survived: 0)

4656: my $max = $spec->{'max'}; 4657: 4658: if(!defined($min) && !defined($max)) { 4659: # Unconstrained — use LectroTest's built-in Int 4660: return "$field_name <- Int"; 4661: } elsif(!defined($min)) { 4662: # Only max defined — generate 0 to max 4663: return "$field_name <- Int(sized => sub { int(rand($max + 1)) })"; 4664: } elsif(!defined($max)) { 4665: # Only min defined — generate min to min + range 4666: return "$field_name <- Int(sized => sub { $min + int(rand($DEFAULT_GENERATOR_RANGE)) })"; 4667: } else { 4668: # Both defined — generate within [min, max] 4669: my $range = $max - $min; 4670: return "$field_name <- Int(sized => sub { $min + int(rand($range + 1)) })"; 4671: }

Mutants (Total: 1, Killed: 1, Survived: 0)

4672: }

Mutants (Total: 1, Killed: 1, Survived: 0)

4673: 4674: # -------------------------------------------------- 4675: # Float / number generator 4676: # -------------------------------------------------- ●4677 → 4677 → 4727 4677: if($type eq 'number' || $type eq 'float') { 4678: my $min = $spec->{'min'}; 4679: my $max = $spec->{'max'};

Mutants (Total: 1, Killed: 0, Survived: 1)
4680: 4681: if(!defined($min) && !defined($max)) { 4682: # Unconstrained — symmetric range around zero 4683: return "$field_name <- Float(sized => sub { rand($DEFAULT_GENERATOR_RANGE) - $DEFAULT_GENERATOR_RANGE / 2 })"; 4684: 4685: } elsif(!defined($min)) { 4686: # Only max defined — choose range based on sign of max
Mutants (Total: 1, Killed: 0, Survived: 1)
4687: if($max == $ZERO_BOUNDARY) { 4688: # max=0: negative numbers only 4689: return "$field_name <- Float(sized => sub { -rand($DEFAULT_GENERATOR_RANGE) })"; 4690: } elsif($max > $ZERO_BOUNDARY) { 4691: # Positive max: generate 0 to max 4692: return "$field_name <- Float(sized => sub { rand($max) })"; 4693: } else { 4694: # Negative max: generate from (max - range) to max
Mutants (Total: 1, Killed: 0, Survived: 1)
4695: return "$field_name <- Float(sized => sub { ($max - $DEFAULT_GENERATOR_RANGE) + rand($DEFAULT_GENERATOR_RANGE + $max) })"; 4696: } 4697: 4698: } elsif(!defined($max)) { 4699: # Only min defined — choose range based on sign of min 4700: if($min == $ZERO_BOUNDARY) { 4701: # min=0: positive numbers only 4702: return "$field_name <- Float(sized => sub { rand($DEFAULT_GENERATOR_RANGE) })"; 4703: } elsif($min > $ZERO_BOUNDARY) { 4704: # Positive min: generate min to min + range 4705: return "$field_name <- Float(sized => sub { $min + rand($DEFAULT_GENERATOR_RANGE) })"; 4706: } else { 4707: # Negative min: generate from min to min + range 4708: return "$field_name <- Float(sized => sub { $min + rand(-$min + $DEFAULT_GENERATOR_RANGE) })"; 4709: } 4710:

Mutants (Total: 1, Killed: 1, Survived: 0)

4711: } else { 4712: # Both min and max defined — validate then generate 4713: my $range = $max - $min; 4714: if($range <= $ZERO_BOUNDARY) { 4715: carp "Invalid range for '$field_name': min=$min, max=$max";

Mutants (Total: 1, Killed: 1, Survived: 0)

4716: # Return undef rather than emitting a degenerate 4717: # generator that would silently produce wrong values 4718: return; 4719: } 4720: return "$field_name <- Float(sized => sub { $min + rand($range) })"; 4721: } 4722: } 4723: 4724: # -------------------------------------------------- 4725: # String generator 4726: # -------------------------------------------------- ●4727 → 4727 → 4766 4727: if($type eq 'string') { 4728: my $min_len = $spec->{'min'} // 0; 4729: my $max_len = $spec->{'max'} // $DEFAULT_MAX_STRING_LEN;

Mutants (Total: 1, Killed: 1, Survived: 0)

4730: 4731: # If a regex pattern is declared, delegate to 4732: # Data::Random::String::Matches for pattern-aware generation 4733: if(defined($spec->{'matches'})) { 4734: my $pattern = $spec->{'matches'}; 4735: 4736: # Compile the pattern safely rather than splicing the raw

Mutants (Total: 2, Killed: 2, Survived: 0)

4737: # string into qr/$pattern/ — the raw form lets a pattern 4738: # containing an unescaped '/' break out of the qr// 4739: # delimiter and inject arbitrary Perl into the generated 4740: # test. regexp_pattern() decomposes the already-compiled 4741: # Regexp object back into pattern text that is guaranteed 4742: # to be a self-contained regex body, safe to re-embed. 4743: my $compiled = ref($pattern) eq 'Regexp' ? $pattern : eval { qr/$pattern/ }; 4744: if($@ || !defined($compiled)) { 4745: carp "Invalid matches pattern '$pattern' for field '$field_name': $@"; 4746: return "$field_name <- String(length => [$min_len, $max_len])"; 4747: } 4748: my ($pat, $mods) = regexp_pattern($compiled); 4749: my $safe_re = "qr{$pat}" . ($mods // ''); 4750: 4751: if(defined($spec->{'max'})) { 4752: return "$field_name <- Gen { Data::Random::String::Matches->create_random_string({ regex => $safe_re, length => $spec->{'max'} }) }"; 4753: } elsif(defined($spec->{'min'})) { 4754: return "$field_name <- Gen { Data::Random::String::Matches->create_random_string({ regex => $safe_re, length => $spec->{'min'} }) }"; 4755: } else { 4756: return "$field_name <- Gen { Data::Random::String::Matches->create_random_string({ regex => $safe_re }) }"; 4757: } 4758: } 4759: 4760: return "$field_name <- String(length => [$min_len, $max_len])"; 4761: } 4762: 4763: # -------------------------------------------------- 4764: # Boolean generator 4765: # -------------------------------------------------- ●4766 → 4766 → 4773 4766: if($type eq 'boolean') { 4767: return "$field_name <- Bool"; 4768: } 4769: 4770: # -------------------------------------------------- 4771: # Arrayref generator 4772: # -------------------------------------------------- ●4773 → 4773 → 4784 4773: if($type eq 'arrayref') { 4774: my $min_size = $spec->{'min'} // 0; 4775: my $max_size = $spec->{'max'} // $DEFAULT_MAX_COLLECTION_SIZE; 4776: return "$field_name <- List(Int, length => [$min_size, $max_size])"; 4777: } 4778: 4779: # -------------------------------------------------- 4780: # Hashref generator 4781: # LectroTest has no built-in Hash generator so we 4782: # use Elements over a pre-built list of hashrefs 4783: # -------------------------------------------------- ●4784 → 4784 → 4793 4784: if($type eq 'hashref') { 4785: my $min_keys = $spec->{'min'} // 0; 4786: my $max_keys = $spec->{'max'} // $DEFAULT_MAX_COLLECTION_SIZE; 4787: return "$field_name <- Elements(map { my \%h; for (1..\$_) { \$h{'key'.\$_} = \$_ }; \\\%h } $min_keys..$max_keys)"; 4788: } 4789: 4790: # -------------------------------------------------- 4791: # Unknown type — fall back to String with a warning 4792: # -------------------------------------------------- 4793: carp "Unknown type '$type' for '$field_name' LectroTest generator, using String"; 4794: return "$field_name <- String"; 4795: }

Mutants (Total: 1, Killed: 1, Survived: 0)

4796: 4797: # -------------------------------------------------- 4798: # _is_numeric_transform 4799: #

Mutants (Total: 1, Killed: 1, Survived: 0)

4800: # Determine whether a transform's output 4801: # spec declares a numeric type, indicating 4802: # that numeric range properties should be 4803: # generated for it. 4804: # 4805: # Entry: $input_spec - the transform's input 4806: # spec hashref. Currently 4807: # unused; reserved for 4808: # future input-type checks. 4809: # $output_spec - the transform's output

Mutants (Total: 1, Killed: 0, Survived: 1)
4810: # spec hashref. 4811: # 4812: # Exit: Returns 1 if the output type is one of 4813: # 'number', 'integer', or 'float'. 4814: # Returns 0 otherwise. 4815: # -------------------------------------------------- 4816: sub _is_numeric_transform { 4817: my ($input_spec, $output_spec) = @_; 4818: 4819: # $input_spec is currently unused — reserved for future 4820: # input-side type checking when detecting mixed transforms
Mutants (Total: 1, Killed: 0, Survived: 1)
4821: my $out_type = ($output_spec // {})->{'type'} // ''; 4822: 4823: return($out_type eq 'number' || $out_type eq 'integer' || $out_type eq 'float'); 4824: } 4825: 4826: # -------------------------------------------------- 4827: # _is_string_transform 4828: # 4829: # Purpose: Determine whether a transform's output 4830: # spec declares a string type, indicating 4831: # that string length and pattern properties 4832: # should be generated for it. 4833: # 4834: # Entry: $input_spec - the transform's input 4835: # spec hashref. Currently 4836: # unused; reserved for 4837: # future input-type checks. 4838: # $output_spec - the transform's output 4839: # spec hashref. 4840: # 4841: # Exit: Returns 1 if the output type is 'string'. 4842: # Returns 0 otherwise. 4843: # -------------------------------------------------- 4844: sub _is_string_transform {

Mutants (Total: 1, Killed: 1, Survived: 0)

4845: my ($input_spec, $output_spec) = @_; 4846: 4847: # $input_spec is currently unused — reserved for future 4848: # input-side type checking when detecting mixed transforms 4849: my $out_type = ($output_spec // {})->{'type'} // ''; 4850: 4851: return($out_type eq 'string');

Mutants (Total: 1, Killed: 1, Survived: 0)

4852: } 4853: 4854: # -------------------------------------------------- 4855: # _same_type 4856: # 4857: # Purpose: Determine whether the dominant type of 4858: # a transform's input and output specs 4859: # match, indicating that type-preservation 4860: # properties are meaningful. 4861: # 4862: # Entry: $input_spec - the transform's input 4863: # spec hashref, or a nested 4864: # multi-field hashref. 4865: # $output_spec - the transform's output 4866: # spec hashref. 4867: # 4868: # Exit: Returns 1 if the dominant input and 4869: # output types are identical strings.

Mutants (Total: 2, Killed: 2, Survived: 0)

4870: # Returns 0 otherwise. 4871: # 4872: # Notes: Uses _get_dominant_type for both sides. 4873: # For multi-field input specs, dominant 4874: # type is the type of the first field 4875: # encountered — this is a simplification. 4876: # TODO: extend to handle mixed-type inputs 4877: # by checking all fields, not just the 4878: # first one found. 4879: # -------------------------------------------------- 4880: sub _same_type { 4881: my ($input_spec, $output_spec) = @_; 4882: 4883: # Guard: treat missing specs as untyped — two untyped 4884: # specs both default to $DEFAULT_FIELD_TYPE and would 4885: # compare equal, which is intentionally conservative 4886: my $in_type = _get_dominant_type($input_spec // {}); 4887: my $out_type = _get_dominant_type($output_spec // {}); 4888: 4889: return($in_type eq $out_type); 4890: } 4891: 4892: # -------------------------------------------------- 4893: # _get_dominant_type 4894: # 4895: # Purpose: Extract the most representative type 4896: # string from a spec hashref. For flat 4897: # output specs this is simply the 'type' 4898: # key. For multi-field input specs it is 4899: # the type of the first sub-field found 4900: # that declares one. 4901: # 4902: # Entry: $spec - a spec hashref. May be a flat 4903: # output spec ({ type => '...' }) 4904: # or a multi-field input spec 4905: # ({ field => { type => '...' } }). 4906: # May be undef or empty. 4907: # 4908: # Exit: Returns a type string. Returns 4909: # $DEFAULT_FIELD_TYPE ('string') if no 4910: # type can be determined. 4911: # -------------------------------------------------- 4912: sub _get_dominant_type { ●4913 → 4924 → 4931 4913: my $spec = $_[0]; 4914: 4915: # Guard: return default for undef or non-hash input 4916: return $DEFAULT_FIELD_TYPE 4917: unless defined($spec) && ref($spec) eq 'HASH'; 4918: 4919: # Flat spec — type declared directly 4920: return $spec->{'type'} if defined($spec->{'type'}); 4921: 4922: # Multi-field spec — return the type of the first 4923: # sub-field that declares one 4924: for my $field (keys %{$spec}) { 4925: next unless ref($spec->{$field}) eq 'HASH'; 4926: return $spec->{$field}{'type'} 4927: if defined($spec->{$field}{'type'}); 4928: } 4929: 4930: # No type found anywhere — return the safe default 4931: return $DEFAULT_FIELD_TYPE; 4932: } 4933: 4934: # -------------------------------------------------- 4935: # _render_properties 4936: # 4937: # Purpose: Render an arrayref of property definition 4938: # hashrefs (as produced by 4939: # _generate_transform_properties) into a 4940: # string of Perl source code suitable for 4941: # embedding in a generated test file. 4942: # The output uses Test::LectroTest::Compat 4943: # to run each property as a holds() check. 4944: # 4945: # Entry: $properties - arrayref of property 4946: # hashrefs, each containing: name, 4947: # generator_spec, call_code, 4948: # property_checks, should_die, 4949: # should_warn, trials. 4950: # May be undef or an empty arrayref. 4951: # 4952: # Exit: Returns a string of Perl source code. 4953: # Returns an empty string if $properties 4954: # is undef, not an arrayref, or empty. 4955: # 4956: # Notes: The generated code uses 4-space 4957: # indentation deliberately — this is the 4958: # indentation style of the generated test 4959: # file, not of this module. Tabs are used 4960: # in this module's own source; spaces are 4961: # emitted into generated output for 4962: # readability of the produced test files. 4963: # -------------------------------------------------- 4964: sub _render_properties { ●4965 → 4974 → 5001 4965: my $properties = $_[0]; 4966: 4967: # Return empty string for absent or non-array input — 4968: # callers treat '' as no property block to emit 4969: return '' unless defined($properties) && ref($properties) eq 'ARRAY'; 4970: return '' unless @{$properties}; 4971: 4972: my $code = "use_ok('Test::LectroTest::Compat');\n\n"; 4973: 4974: for my $prop (@{$properties}) { 4975: # Emit a labelled Property block for each transform property 4976: $code .= "# Transform property: $prop->{'name'}\n"; 4977: $code .= "my \$$prop->{'name'} = Property {\n"; 4978: $code .= " ##[ $prop->{'generator_spec'} ]##\n"; 4979: $code .= " \n"; 4980: $code .= " my \$result = eval { $prop->{'call_code'} };\n"; 4981: 4982: if($prop->{'should_die'}) { 4983: # For transforms that expect death, pass if the 4984: # eval caught an exception 4985: $code .= " my \$died = defined(\$\@) && \$\@;\n"; 4986: $code .= " \$died;\n"; 4987: } else { 4988: # For normal transforms, pass only if no exception 4989: # was thrown and all property checks hold 4990: $code .= " my \$error = \$\@;\n"; 4991: $code .= " \n"; 4992: $code .= " !\$error && (\n"; 4993: $code .= " $prop->{'property_checks'}\n"; 4994: $code .= " );\n"; 4995: } 4996: 4997: $code .= "}, name => '$prop->{'name'}', trials => $prop->{'trials'};\n\n"; 4998: $code .= "holds(\$$prop->{'name'});\n"; 4999: } 5000: 5001: return $code; 5002: } 5003: 5004: # -------------------------------------------------- 5005: # _detect_transform_properties 5006: # 5007: # Purpose: Automatically derive a list of testable 5008: # LectroTest property hashrefs from a 5009: # transform's input and output specs. 5010: # Detects numeric range constraints, exact 5011: # value matches, string length constraints, 5012: # type preservation, and definedness. 5013: # 5014: # Entry: $transform_name - string name of the 5015: # transform, used for 5016: # heuristic matching 5017: # (e.g. 'positive'). 5018: # $input_spec - the transform's input 5019: # hashref, or the string 5020: # 'undef'. 5021: # $output_spec - the transform's output 5022: # hashref, or undef if 5023: # absent. 5024: # 5025: # Exit: Returns a list of property hashrefs, 5026: # each containing 'name' and 'code' keys. 5027: # Returns an empty list if no properties 5028: # can be detected or if $input_spec is 5029: # undef or the string 'undef'. 5030: # 5031: # Notes: The 'positive' heuristic checks the 5032: # transform name case-insensitively against 5033: # $TRANSFORM_POSITIVE_PATTERN and adds a 5034: # non-negative constraint if matched. 5035: # This is intentionally a rough heuristic 5036: # rather than a precise semantic check. 5037: # -------------------------------------------------- 5038: sub _detect_transform_properties { ●5039 → 5054 → 5084 5039: my ($transform_name, $input_spec, $output_spec) = @_; 5040: 5041: my @properties; 5042: 5043: # Guard: skip undef input and the YAML scalar 'undef' 5044: return @properties unless defined($input_spec); 5045: return @properties if(!ref($input_spec) && $input_spec eq 'undef'); 5046: 5047: # Default output spec to empty hash so all key lookups 5048: # below are safe regardless of what the schema provides 5049: $output_spec //= {}; 5050: 5051: # -------------------------------------------------- 5052: # Property 1: Output range constraints (numeric) 5053: # -------------------------------------------------- 5054: if(_is_numeric_transform($input_spec, $output_spec)) { 5055: if(defined($output_spec->{'min'})) { 5056: my $min = $output_spec->{'min'}; 5057: push @properties, { 5058: name => 'min_constraint', 5059: code => "defined(\$result) && looks_like_number(\$result) && \$result >= $min", 5060: }; 5061: } 5062: 5063: if(defined($output_spec->{'max'})) { 5064: my $max = $output_spec->{'max'}; 5065: push @properties, { 5066: name => 'max_constraint', 5067: code => "defined(\$result) && looks_like_number(\$result) && \$result <= $max", 5068: }; 5069: } 5070: 5071: # Heuristic: transforms named 'positive' (case-insensitive) 5072: # imply a non-negative result constraint 5073: if($transform_name =~ /$TRANSFORM_POSITIVE_PATTERN/i) { 5074: push @properties, { 5075: name => 'non_negative', 5076: code => "defined(\$result) && looks_like_number(\$result) && \$result >= 0", 5077: }; 5078: } 5079: } 5080: 5081: # -------------------------------------------------- 5082: # Property 2: Specific value output 5083: # -------------------------------------------------- ●5084 → 5084 → 5100 5084: if(defined($output_spec->{'value'})) { 5085: my $expected = $output_spec->{'value'}; 5086: 5087: # Numeric refs use == for comparison; scalars use eq 5088: # via perl_quote to produce the correct quoted literal 5089: push @properties, { 5090: name => 'exact_value', 5091: code => ref($expected) 5092: ? "\$result == $expected" 5093: : "\$result eq " . perl_quote($expected), 5094: }; 5095: } 5096: 5097: # -------------------------------------------------- 5098: # Property 3: String length constraints 5099: # -------------------------------------------------- ●5100 → 5100 → 5139 5100: if(_is_string_transform($input_spec, $output_spec)) { 5101: if(defined($output_spec->{'min'})) { 5102: push @properties, { 5103: name => 'min_length', 5104: code => "length(\$result) >= $output_spec->{'min'}", 5105: }; 5106: } 5107: 5108: if(defined($output_spec->{'max'})) { 5109: push @properties, { 5110: name => 'max_length', 5111: code => "length(\$result) <= $output_spec->{'max'}", 5112: }; 5113: } 5114: 5115: if(defined($output_spec->{'matches'})) { 5116: my $pattern = $output_spec->{'matches'}; 5117: 5118: # See the matching comment in _schema_to_lectrotest_generator — 5119: # compile first and re-embed via regexp_pattern() rather than 5120: # splicing the raw string into qr/$pattern/, which would let 5121: # an unescaped '/' break out of the delimiter. 5122: my $compiled = ref($pattern) eq 'Regexp' ? $pattern : eval { qr/$pattern/ }; 5123: if($@ || !defined($compiled)) { 5124: carp "Invalid matches pattern '$pattern' for transform '$transform_name': $@"; 5125: } else { 5126: my ($pat, $mods) = regexp_pattern($compiled); 5127: my $safe_re = "qr{$pat}" . ($mods // ''); 5128: push @properties, { 5129: name => 'pattern_match', 5130: code => "\$result =~ $safe_re", 5131: }; 5132: } 5133: } 5134: } 5135: 5136: # -------------------------------------------------- 5137: # Property 4: Type preservation 5138: # -------------------------------------------------- ●5139 → 5139 → 5158 5139: if(_same_type($input_spec, $output_spec)) { 5140: my $type = _get_dominant_type($output_spec); 5141: 5142: # Only emit a numeric_type check for numeric types — 5143: # string and other types have no equivalent simple check 5144: if($type eq 'number' || $type eq 'integer' || $type eq 'float') { 5145: push @properties, { 5146: name => 'numeric_type', 5147: code => 'looks_like_number($result)', 5148: }; 5149: } 5150: } 5151: 5152: # -------------------------------------------------- 5153: # Property 5: Definedness 5154: # -------------------------------------------------- 5155: # Emit a defined() check for all transforms except those 5156: # whose output type is explicitly 'undef' — those are 5157: # expected to return nothing ●5158 → 5158 → 5165 5158: unless(($output_spec->{'type'} // '') eq 'undef') { 5159: push @properties, { 5160: name => 'defined', 5161: code => 'defined($result)', 5162: }; 5163: } 5164: 5165: return @properties; 5166: } 5167: 5168: # -------------------------------------------------- 5169: # _process_custom_properties 5170: # 5171: # Purpose: Process the 'properties' array from a 5172: # transform definition, resolving each 5173: # entry to either a named builtin property 5174: # (looked up from _get_builtin_properties) 5175: # or a custom property with inline code. 5176: # 5177: # Entry: $properties_spec - arrayref of property 5178: # definitions from the 5179: # schema. Each element 5180: # is either a string 5181: # (builtin name) or a 5182: # hashref with 'name' 5183: # and 'code' fields. 5184: # $function - name of the function 5185: # under test. 5186: # $module - module name, or undef 5187: # for builtins. 5188: # $input_spec - the transform's input 5189: # spec hashref. 5190: # $output_spec - the transform's output 5191: # spec hashref. 5192: # $new - defined if the function 5193: # is an OO method; value 5194: # is not used, only 5195: # presence is checked. 5196: # 5197: # Exit: Returns a list of property hashrefs, 5198: # each containing 'name', 'code', and 5199: # 'description' keys. 5200: # Invalid or unrecognised entries are 5201: # skipped with a carp warning. 5202: # 5203: # Side effects: Carps on unrecognised builtin names, 5204: # missing code fields, and invalid 5205: # property definition types. 5206: # 5207: # Notes: The sixth argument is $new (the OO 5208: # constructor signal), not the full schema 5209: # hashref. It is used only to determine 5210: # whether to emit OO-style call code for 5211: # builtin property templates. 5212: # -------------------------------------------------- 5213: sub _process_custom_properties { ●5214 → 5219 → 5300 5214: my ($properties_spec, $function, $module, $input_spec, $output_spec, $new) = @_; 5215: 5216: my @properties; 5217: my $builtin_properties = _get_builtin_properties(); 5218: 5219: for my $prop_def (@{$properties_spec}) { 5220: my $prop_name; 5221: my $prop_code; 5222: my $prop_desc; 5223: 5224: if(!ref($prop_def)) { 5225: # Plain string — look up as a named builtin property 5226: $prop_name = $prop_def; 5227: 5228: unless(exists($builtin_properties->{$prop_name})) { 5229: carp "Unknown built-in property '$prop_name', skipping"; 5230: next; 5231: } 5232: 5233: my $builtin = $builtin_properties->{$prop_name}; 5234: 5235: # Build the argument list, respecting positional order 5236: my @var_names = sort keys %{$input_spec}; 5237: my @args; 5238: if(_has_positions($input_spec)) { 5239: my @sorted = sort { $input_spec->{$a}{'position'} <=> $input_spec->{$b}{'position'} } 5240: grep { defined $input_spec->{$_}{'position'} } @var_names; 5241: my @named = grep { !defined $input_spec->{$_}{'position'} } @var_names; 5242: @args = (map { "\$$_" } @sorted, map { "'$_' => \$$_" } @named); 5243: } else { 5244: @args = map { "\$$_" } @var_names; 5245: } 5246: 5247: # Build the call expression for the builtin template. 5248: # $new here is the raw OO signal from the caller — 5249: # defined means OO mode, undef means functional 5250: my $call_code; 5251: if($module && defined($new)) { 5252: # OO mode — fresh object per trial 5253: $call_code = "my \$obj = new_ok('$module');"; 5254: $call_code .= "\$obj->$function"; 5255: } elsif($module && $module ne $MODULE_BUILTIN) { 5256: # Functional mode with a named module 5257: $call_code = "$module\::$function"; 5258: } else { 5259: # Builtin or unqualified function call 5260: $call_code = $function; 5261: } 5262: $call_code .= '(' . join(', ', @args) . ')'; 5263: 5264: # Instantiate the builtin's code template with the 5265: # call expression and input variable list 5266: $prop_code = $builtin->{'code_template'}->($function, $call_code, \@var_names); 5267: $prop_desc = $builtin->{'description'}; 5268: 5269: } elsif(ref($prop_def) eq 'HASH') { 5270: # Hashref — custom property with inline Perl code 5271: $prop_name = $prop_def->{'name'} || 'custom_property'; 5272: $prop_code = $prop_def->{'code'}; 5273: $prop_desc = $prop_def->{'description'} || "Custom property: $prop_name"; 5274: 5275: unless($prop_code) { 5276: carp "Custom property '$prop_name' missing 'code' field, skipping"; 5277: next; 5278: } 5279: 5280: # Sanity-check: code must contain at least a variable 5281: # reference or a word character to be meaningful 5282: unless($prop_code =~ /\$/ || $prop_code =~ /\w+/) { 5283: carp "Custom property '$prop_name' code looks invalid: $prop_code"; 5284: next; 5285: } 5286: 5287: } else { 5288: # Neither string nor hashref — unrecognised definition type 5289: carp 'Invalid property definition: ', render_fallback($prop_def); 5290: next; 5291: } 5292: 5293: push @properties, { 5294: name => $prop_name, 5295: code => $prop_code, 5296: description => $prop_desc, 5297: }; 5298: } 5299: 5300: return @properties; 5301: } 5302: 5303: =head1 NOTES 5304: 5305: C<seed> and C<iterations> really should be within C<config>. 5306: 5307: =head1 SEE ALSO 5308: 5309: =over 4 5310: 5311: =item * L<Test Dashboard|https://nigelhorne.github.io/App-Test-Generator/coverage/> 5312: 5313: =item * L<App::Test::Generator::Template> - Template of the file of tests created by C<App::Test::Generator> 5314: 5315: =item * L<App::Test::Generator::SchemaExtractor> - Create schemas from Perl programs 5316: 5317: =item * L<Params::Validate::Strict>: Schema Definition 5318: 5319: =item * L<Params::Get>: Input validation 5320: 5321: =item * L<Return::Set>: Output validation 5322: 5323: =item * L<Test::LectroTest> 5324: 5325: =item * L<Test::Most> 5326: 5327: =item * L<YAML::XS> 5328: 5329: =back 5330: 5331: =head1 AUTHOR 5332: 5333: Nigel Horne, C<< <njh at nigelhorne.com> >> 5334: 5335: Portions of this module's initial design and documentation were created with the 5336: assistance of AI. 5337: 5338: =head1 SUPPORT 5339: 5340: This module is provided as-is without any warranty. 5341: 5342: You can find documentation for this module with the perldoc command. 5343: 5344: perldoc App::Test::Generator 5345: 5346: You can also look for information at: 5347: 5348: =over 4 5349: 5350: =item * MetaCPAN 5351: 5352: L<https://metacpan.org/release/App-Test-Generator> 5353: 5354: =item * GitHub 5355: 5356: L<https://github.com/nigelhorne/App-Test-Generator> 5357: 5358: =item * CPANTS 5359: 5360: L<http://cpants.cpanauthors.org/dist/App-Test-Generator> 5361: 5362: =item * CPAN Testers' Matrix 5363: 5364: L<http://matrix.cpantesters.org/?dist=App-Test-Generator> 5365: 5366: =item * CPAN Testers Dependencies 5367: 5368: L<http://deps.cpantesters.org/?module=App::Test::Generator> 5369: 5370: =back 5371: 5372: =head1 FORMAL SPECIFICATION 5373: 5374: This section describes the documented routines in Z notation. It is for 5375: readers who want an exact, mathematical statement. You do not need it to use 5376: the module. 5377: 5378: How to read it: a name ending in C<?> is an input and a name ending in C<!> is 5379: an output. None of these routines keeps any state between calls, so there is 5380: no state schema. C<quote(v)> stands for the result of C<perl_quote(v)>. 5381: 5382: =head2 generate 5383: 5384: ┌─ Generate ──────────────────────────────────────── 5385: │ schema_file? : STRING 5386: │ output_file? : STRING ∪ { undef } 5387: │ test : STRING 5388: │ result! : BOOLEAN 5389: ├─────────────────────────────────────────────────── 5390: │ pre schema_file? names a readable schema 5391: │ the schema defines function 5392: │ every name in the schema is an identifier 5393: │ post test is a complete Perl test file for function 5394: │ output_file? ≠ undef ⇒ file output_file? holds test 5395: │ output_file? = undef ⇒ test is printed on STDOUT 5396: │ result! = 1 5397: └─────────────────────────────────────────────────── 5398: 5399: no arguments ⇒ croak 'Usage: generate(...)' 5400: output_file? cannot be written ⇒ croak 'Cannot open ...' 5401: 5402: =head2 render_fallback 5403: 5404: ┌─ RenderFallback ────────────────────────────────── 5405: │ v? : VALUE 5406: │ result! : STRING 5407: ├─────────────────────────────────────────────────── 5408: │ post v? = undef ⇒ result! = 'undef' 5409: │ v? ≠ undef ⇒ result! is one line of Perl source 5410: │ ∧ eval(result!) is a copy of v? 5411: └─────────────────────────────────────────────────── 5412: 5413: =head2 render_hash 5414: 5415: ┌─ RenderHash ────────────────────────────────────── 5416: │ href? : VALUE 5417: │ result! : STRING 5418: │ kept : â„™ STRING 5419: ├─────────────────────────────────────────────────── 5420: │ post ref(href?) ≠ 'HASH' ∨ href? = ∅ ⇒ result! = '' 5421: │ ref(href?) = 'HASH' ⇒ 5422: │ kept = { k : dom href? | href?(k) is a hashref 5423: │ ∨ href?(k) is a type name } 5424: │ result! has one "'k' => { ... }" entry for each 5425: │ k in kept, in sorted order 5426: └─────────────────────────────────────────────────── 5427: 5428: =head2 render_args_hash 5429: 5430: ┌─ RenderArgsHash ────────────────────────────────── 5431: │ href? : VALUE 5432: │ result! : STRING 5433: ├─────────────────────────────────────────────────── 5434: │ post ref(href?) ≠ 'HASH' ∨ href? = ∅ ⇒ result! = '' 5435: │ ref(href?) = 'HASH' ⇒ 5436: │ result! = join(', ', ⟨ k : sort(dom href?) • 5437: │ quote(k) . ' => ' . quote(href?(k)) ⟩) 5438: └─────────────────────────────────────────────────── 5439: 5440: =head2 render_arrayref_map 5441: 5442: ┌─ RenderArrayrefMap ─────────────────────────────── 5443: │ href? : VALUE 5444: │ result! : STRING 5445: │ kept : â„™ STRING 5446: ├─────────────────────────────────────────────────── 5447: │ post href? is false ∨ ref(href?) ≠ 'HASH' ⇒ result! = '()' 5448: │ ref(href?) = 'HASH' ⇒ 5449: │ kept = { k : dom href? | ref(href?(k)) = 'ARRAY' } 5450: │ kept = ∅ ⇒ result! = '' 5451: │ result! has one "'k' => [ ... ]" entry for each 5452: │ k in kept, in sorted order 5453: └─────────────────────────────────────────────────── 5454: 5455: =head2 perl_quote 5456: 5457: ┌─ PerlQuote ─────────────────────────────────────── 5458: │ v? : VALUE 5459: │ result! : STRING 5460: ├─────────────────────────────────────────────────── 5461: │ pre v? is nested no more than 100 levels deep 5462: │ post v? = undef ⇒ result! = 'undef' 5463: │ v? = 'true' ⇒ result! = '!!1' 5464: │ v? = 'false' ⇒ result! = '!!0' 5465: │ v? looks like a number ⇒ result! = v? 5466: │ v? is any other string ⇒ result! = v? in single quotes, 5467: │ with ' and \ escaped 5468: │ ref(v?) = 'ARRAY' ⇒ result! = '[ ' . join(', ', 5469: │ ⟨ e : v? • quote(e) ⟩) . ' ]' 5470: │ ref(v?) = 'Regexp' ⇒ result! = 'qr{...}' 5471: │ otherwise ⇒ result! = render_fallback(v?) 5472: └─────────────────────────────────────────────────── 5473: 5474: nested more than 100 levels deep ⇒ croak 'structure too deeply nested' 5475: 5476: =head1 STATE DIAGRAM 5477: 5478: C<generate> is a class method and keeps no state. One call runs from start 5479: to finish through these stages, and any stage may stop it by croaking. 5480: 5481: +-------------+ 5482: | START | 5483: +-------------+ 5484: | 5485: | generate(schema_file, output_file) 5486: v 5487: +-------------+ no arguments, file not readable 5488: | LOAD SCHEMA |--------------------------------------+ 5489: +-------------+ | 5490: | | 5491: | schema parsed | 5492: v | 5493: +-------------+ missing function, bad name, | 5494: | VALIDATE | contradictory input spec | 5495: +-------------+--------------------------------------+ 5496: | | 5497: | schema is good | 5498: v v 5499: +-------------+ +-------------+ 5500: | RENDER | | CROAKED | 5501: +-------------+ +-------------+ 5502: | ^ 5503: | test source built | 5504: v | 5505: +-------------+ output_file cannot be opened | 5506: | WRITE |--------------------------------------+ 5507: +-------------+ 5508: | 5509: | file written, or source printed on STDOUT 5510: v 5511: +-------------+ 5512: | DONE | 5513: +-------------+ 5514: 5515: Side effects: C<generate> writes C<output_file> and prints one line saying so, 5516: or prints the test source when no output file is given. The C<render_*> 5517: routines and C<perl_quote> write no files and print nothing. 5518: 5519: =head1 LICENCE AND COPYRIGHT 5520: 5521: Copyright 2025-2026 Nigel Horne. 5522: 5523: Usage is subject to the terms of GPL2. 5524: If you use it, 5525: please let me know. 5526: 5527: =cut 5528: 5529: 1;