File Coverage

File:blib/lib/App/Test/Generator.pm
Coverage:82.0%

linestmtbrancondsubtimecode
1package 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
83
83
1543570
587
use 5.036;
29
30
83
83
83
110
48
537
use strict;
31
83
83
83
112
51
1338
use warnings;
32
83
83
83
3671
106397
128
use autodie qw(:all);
33
34
83
83
83
231933
6211
121
use utf8;
35
83
83
83
11250
31409
154
use open qw(:std :encoding(UTF-8));
36
37
83
83
83
438641
71
526
use App::Test::Generator::Provenance ();
38
83
83
83
24125
77
864
use App::Test::Generator::Template;
39
83
83
83
114
58
1599
use Carp qw(carp croak confess);
40
83
83
83
26453
1883152
972
use Config::Abstraction 0.36;
41
83
83
83
13096
131682
1756
use Data::Dumper;
42
83
83
83
143
51
1039
use Data::Section::Simple;
43
83
83
83
110
45
1316
use File::Basename qw(basename);
44
83
83
83
102
48
621
use File::Spec;
45
83
83
83
14477
497335
1878
use Module::Load::Conditional qw(check_install can_load);
46
83
83
83
141
56
983
use Params::Get;
47
83
83
83
96
536
695
use Params::Validate::Strict 0.36;
48
83
83
83
104
45
856
use Readonly;
49
83
83
83
90
48
3011
use Readonly::Values::Boolean;
50
83
83
83
116
54
1008
use Scalar::Util qw(looks_like_number);
51
83
83
83
99
56
4232
use re 'regexp_pattern';
52
83
83
83
14877
462126
910
use Template;
53
83
83
83
10236
71050
1643
use YAML::XS qw(LoadFile);
54
55
83
83
83
139
53
154088
use Exporter 'import';
56
57our @EXPORT_OK = qw(generate);
58
59our $VERSION = '0.52';
60
61Readonly my $DEFAULT_ITERATIONS      => 30;
62Readonly my $DEFAULT_PROPERTY_TRIALS => 1000;
63
64# Hash for O(1) lookup rather than a list needing grep O(n)
65Readonly 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# --------------------------------------------------
76Readonly 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# --------------------------------------------------
90Readonly 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# --------------------------------------------------
100Readonly my $INDEX_NOT_FOUND => -1;
101
102# --------------------------------------------------
103# Readonly constants for schema validation
104# --------------------------------------------------
105Readonly my $CONFIG_PROPERTIES_KEY => 'properties';
106Readonly my $LEGACY_PERL_KEY_1     => '$module';
107Readonly my $LEGACY_PERL_KEY_2     => 'our $module';
108Readonly my $SOURCE_KEY            => '_source';
109
110# --------------------------------------------------
111# Readonly constants for render_hash key detection
112# --------------------------------------------------
113Readonly my $KEY_MATCHES => 'matches';
114Readonly my $KEY_NOMATCH => 'nomatch';
115
116# --------------------------------------------------
117# Reserved module name indicating a Perl builtin
118# function rather than a CPAN or user module
119# --------------------------------------------------
120Readonly 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# --------------------------------------------------
127Readonly 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# --------------------------------------------------
134Readonly 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# --------------------------------------------------
142Readonly 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# --------------------------------------------------
149Readonly 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# --------------------------------------------------
155Readonly 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# --------------------------------------------------
163Readonly 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# --------------------------------------------------
171Readonly my $ENV_TEST_VERBOSE       => 'TEST_VERBOSE';
172Readonly my $ENV_GENERATOR_VERBOSE  => 'GENERATOR_VERBOSE';
173Readonly my $ENV_VALIDATE_LOAD      => 'GENERATOR_VALIDATE_LOAD';
174
175=encoding utf8
176
177 - 1819
=head1 NAME

App::Test::Generator - Fuzz Testing, Mutation Testing, LCSAJ Metrics and Test Dashboard for Perl modules

=head1 VERSION

Version 0.52

=head1 SYNOPSIS

C<App::Test::Generator> is a suite to help the testing of CPAN modules.
It consists of 6 subsystems:

=over 4

=item * Fuzz Tester

=item * Mutation Testing

=item * LCSAJ Metrics

=item * Test Dashboard

=item * Benchmark Generation

=item * Workflow Deployment

=back

From the command line:

  # Takes the formal definition of a routine, creates tests against that routine, and runs the test
  fuzz-harness-generator -r t/conf/abs.yml

  # Attempt to create a formal definition from a routine package, then run tests against that formal definition
  # This is the Holy Grail of test generation, a set of tests is automatically created directly from the source code,
  # See also [t/all-fuzz.t](t/all-fuzz.t), which aims to be a file you can drop in to any
  # distribution and have it automatically fuzz test your CPAN module.
  extract-schemas lib/App/Test/Generator/Sample/Module.pm && fuzz-harness-generator -r schemas/greet.yml

  # Fuzz a module and keep the corpus bounded: trim to the minimum subset that still covers every branch
  extract-schemas --fuzz --minimize-corpus lib/My/Module.pm

  # Generate round-trip tests that run every code example in a module's POD and verify the results
  pod-example-tester lib/My/Module.pm --output t/pod_examples.t

  # Generate a Benchmark::cmpthese script from a schema; each transform becomes one timed variant
  benchmark-generator -i schemas/abs.yml -o benchmarks/abs.pl

  # Copy dashboard.yml and mutate.yml into a module repository's .github/workflows/ directory
  deploy-workflows --target /path/to/my-module

From Perl:

  use App::Test::Generator qw(generate);
  use App::Test::Generator::SchemaExtractor;

  # Generate to STDOUT
  App::Test::Generator->generate("t/conf/abs.yml");

  # Generate directly to a file
  App::Test::Generator->generate('t/conf/abs.yml', 't/add_fuzz.t');

  # Holy grail mode - read a Perl file, generate tests, and run them
  # This is a long way away yet, but see t/schema_input.t for a proof of concept
  my $extractor = App::Test::Generator::SchemaExtractor->new(
    input_file => 'lib/App/Test/Generator/Template.pm',
    output_dir => '/tmp',
  );
  my $schemas = $extractor->extract_all();
  use File::Temp qw(tempfile);
  foreach my $schema(keys %{$schemas}) {
    my ($fh, $tempfile) = tempfile(SUFFIX => '.t', UNLINK => 1);
    close $fh;
    App::Test::Generator->generate(
      schema => $schemas->{$schema},
      output_file => $tempfile,
    );
    system($^X, '-Ilib', $tempfile);
  }

=head1 OVERVIEW

This module takes a formal input/output specification for a routine or
method and automatically generates test cases. In effect, it allows you
to easily add comprehensive black-box tests in addition to the more
common white-box tests that are typically written for CPAN modules and other
subroutines.

The generated tests combine:

=over 4

=item * Random fuzzing based on input types

=item * Deterministic edge cases for min/max constraints

=item * Static corpus tests defined in Perl or YAML

=back

This approach strengthens your test suite by probing both expected and
unexpected inputs, helping you to catch boundary errors, invalid data
handling, and regressions without manually writing every case.

=head1 TOOLS

The distribution ships the following command-line tools:

=over 4

=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.

=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>.

To add a test dashboard to your CPAN module: copy these scripts into your C<.github/workflows> directory,
then commit the changes to GitHub and enable the page through C<Settings-Pages-branch = gh_pages>:

=over 4

=item * L<https://github.com/nigelhorne/App-Test-Generator/blob/master/.github/workflows/dashboard.yml>

=item * L<https://github.com/nigelhorne/App-Test-Generator/blob/master/.github/workflows/mutate.yml>

=back

=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>).

=item * L<fuzz-harness-generator> - generate a C<Test::Most> fuzzing harness from a YAML schema.

=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.

=item * L<test-generator-mutate> - run mutation testing against a module's test suite.

=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.

=back

=head1 DESCRIPTION

This module implements the logic behind L<fuzz-harness-generator>.
It parses configuration files (fuzz and/or corpus YAML), and
produces a ready-to-run F<.t> test script to run through C<prove>.

It reads configuration files in any format,
and optional YAML corpus files.
All of the examples in this documentation are in C<YAML> format,
other formats may not work as they aren't so heavily tested.
It then generates a L<Test::Most>-based fuzzing harness combining:

=over 4

=item * Randomized fuzzing of inputs (with edge cases)

=item * Optional static corpus tests from Perl C<%cases> or YAML file (C<yaml_cases> key)

=item * Functional or OO mode (via C<$new>)

=item * Reproducible runs via C<$seed> and configurable iterations via C<$iterations>

=back

=head1 MUTATION-GUIDED TEST GENERATION

C<App::Test::Generator> includes a pipeline that automatically closes the
feedback loop between mutation testing, schema extraction, and fuzz
testing. The goal is that surviving mutants drive the creation of new
tests that kill them on the next run, without manual intervention.

=head2 The Pipeline

    mutation survivor
        |
        v
    SchemaExtractor extracts the schema for the enclosing sub
        |
        v
    Schema augmented with boundary values from the mutant
        |
        v
    Augmented schema written to t/conf/
        |
        v
    t/fuzz.t picks up the new schema and runs fuzz tests
        |
        v
    Mutation killed on next run

=head2 How to Use It

The pipeline is driven by three flags passed to
C<bin/test-generator-index>, which is invoked automatically by
C<bin/generate-test-dashboard> on each CI push.

=head3 Step 1: Generate TODO stubs for all survivors

    bin/test-generator-index --generate_mutant_tests=t

Produces C<t/mutant_YYYYMMDD_HHMMSS.t> containing:

=over 4

=item * TODO stubs for HIGH and MEDIUM difficulty survivors, with
boundary value suggestions, environment variable hints, and the
enclosing subroutine name for navigation context.

=item * Comment-only hints for LOW difficulty survivors.

=back

Multiple mutations on the same source line are deduplicated into one
stub. One good test kills all variants on that line.

=head3 Step 2: Generate runnable schemas for NUM_BOUNDARY survivors

    bin/test-generator-index \
        --generate_mutant_tests=t \
        --generate_test=mutant

For each NUM_BOUNDARY survivor, calls
L<App::Test::Generator::SchemaExtractor> to extract the schema for
the enclosing subroutine. If the confidence level is sufficient, the
schema is augmented with the boundary value from the mutant (plus one
value either side) and written to C<t/conf/> as a runnable YAML file.
L<t/fuzz.t> picks it up automatically on the next test run.

Falls back to a TODO stub if:

=over 4

=item * SchemaExtractor cannot parse the file

=item * The enclosing sub cannot be determined

=item * The extracted schema confidence is C<very_low> or C<none>

=back

=head3 Step 3: Augment existing schemas with survivor boundary values

    bin/test-generator-index \
        --generate_mutant_tests=t \
        --generate_test=mutant \
        --generate_fuzz

Scans C<t/conf/> for existing YAML schema files (hand-written or
previously generated) and writes augmented copies with boundary values
from surviving NUM_BOUNDARY mutants merged in. The original schema is
never modified. Augmented copies are written as
C<t/conf/mutant_fuzz_YYYYMMDD_HHMMSS_FUNCTION.yml> and picked up
automatically by C<t/fuzz.t>.

Schemas whose filename already starts with C<mutant_fuzz_> are skipped
to prevent cascading augmentation. Schemas with no matching survivors
are skipped, with a note if C<--verbose> is active.

=head3 Putting It All Together

The recommended invocation in C<bin/generate-test-dashboard>
Step 7 runs all three stages together:

    bin/test-generator-index \
        --generate_mutant_tests=t \
        --generate_test=mutant \
        --generate_fuzz

The GitHub Actions workflow in C<.github/workflows/dashboard.yml>
then commits any new C<t/mutant_*.t> and C<t/conf/mutant_*.yml> files
to the repository so they accumulate over time as the test suite
improves.

=head2 Confidence Levels

L<App::Test::Generator::SchemaExtractor> assigns a confidence level
to each extracted schema:

=over 4

=item * C<high> / C<medium> / C<low> - Schema is used for test generation

=item * C<very_low> / C<none> - Falls back to TODO stub

=back

Confidence is based on how much type and constraint information could
be inferred from the source code and its POD documentation. Methods
with explicit parameter validation (L<Params::Validate::Strict>,
L<Params::Get>) or comprehensive POD will produce higher-confidence
schemas.

=head2 Files Produced

=over 4

=item * C<t/mutant_YYYYMMDD_HHMMSS.t>

TODO stub file for all survivors. Committed to the repository by the
GitHub Actions workflow.

=item * C<t/conf/mutant_MODNAME_FUNCTION_YYYYMMDD_HHMMSS.yml>

Runnable YAML schema for a NUM_BOUNDARY survivor where SchemaExtractor
confidence was sufficient. Picked up by C<t/fuzz.t>.

=item * C<t/conf/mutant_fuzz_YYYYMMDD_HHMMSS_FUNCTION.yml>

Augmented copy of an existing schema with survivor boundary values
merged in. Picked up by C<t/fuzz.t>.

=back

=head2 See Also

=over 4

=item * L<App::Test::Generator::SchemaExtractor> - Schema extraction
from Perl source code

=item * L<bin/test-generator-index> - Dashboard generator and
pipeline driver

=item * L<bin/generate-test-dashboard> - Full pipeline runner

=back

=head1 CONFIGURATION

The configuration file,
for each set of tests to be produced,
is a file containing a schema that can be read by L<Config::Abstraction>.

=head2 SCHEMA

The schema is split into several sections.

=head3 C<%input> - input params with keys => type/optional specs

When using named parameters

  input:
    name:
      type: string
      optional: false
    age:
      type: integer
      optional: true

Supported basic types used by the fuzzer: C<string>, C<integer>, C<float>, C<number>, C<boolean>, C<arrayref>, C<hashref>.
See also L<Params::Validate::Strict>.
You can add more custom types using properties.

A nested C<schema> describes the elements of an C<arrayref> or the values of a
C<hashref>.  Element schemas are full specs, so they carry their own
constraints and can nest again:

  input:
    words:
      type: arrayref
      min: 1
      max: 3
      schema:
        type: string
        min: 3
        max: 10
    scores:
      type: hashref
      schema:
        type: integer
        min: 0
        max: 100
    record:
      type: hashref
      schema:
        name:
          type: string
          min: 2
          max: 20
        age: integer
    grid:
      type: arrayref
      schema:
        type: arrayref
        min: 1
        max: 2
        schema:
          type: integer
          min: 0
          max: 9
    things:
      type: arrayref
      schema:
        type: object
        isa: My::Thing      # needs a no-argument constructor
        # or: can: label   # mocked with Class::Simple

A hashref C<schema> without a C<type> is a map of fixed key names to element
schemas, so generated valid data uses those keys instead of random filler.
Generated element values satisfy the element's own constraints.

For routines with one unnamed parameter

  input:
    type: string

For routines with more than one named parameter, use the C<position> keyword.

  module: Math::Simple::MinMax
  fuction: max

  input:
    left:
      type: number
      position: 0
    right:
      type: number
      position: 1

  output:
    type: number

A routine can take positional arguments followed by named options, as
C<< sub publish { my ($message, %opts) = @_ } >> does.  Give the leading
arguments their positions and mark every trailing option C<named: 1>:

  input:
    message:
      type: string
      position: 0
    priority:
      type: integer
      optional: 1
      named: 1

  # publish($message, priority => $priority)

A parameter in a schema that declares positions must say which it is: a
missing position on a parameter without C<named: 1> is an error, not a
second call shape.

A numeric parameter can document a range whose top end this harness cannot
afford to reach: a count of hashing rounds costs time in proportion to the
value, so one call at the documented maximum can take minutes.  C<sample_max>
limits the valid data that is generated while C<max> stays the documented
bound, so a value above C<max> is still probed (and refused cheaply):

  input:
    rounds:
      type: integer
      named: 1
      optional: 1
      min: 10_000
      max: 100_000_000
      sample_max: 200_000

The keyword C<undef> is used to indicate that the C<function> takes no arguments.

=head3 C<%output> - output param types for L<Return::Set> checking

  output:
    type: string

If the output hash contains the key _STATUS, and if that key is set to DIES,
the routine should die with the given arguments; otherwise, it should live.
If it's set to WARNS,
the routine should warn with the given arguments.
The output can be set to the string 'undef' if the routine should return the undefined value:

  ---
  module: Scalar::Util
  function: blessed

  input:
    type: string

  output: undef

The keyword C<undef> is used to indicate that the C<function> returns nothing.

For methods that return a list (rather than a reference), use C<type: array>.
The generated test captures the result in list context and validates it as an
arrayref, which requires L<Test::Returns> 0.03 or later:

  output:
    type: array

=head3 C<%config> - optional hash of configuration.

The current supported variables are

=over 4

=item * C<close_stdin>

Tests should not attempt to read from STDIN (default: 1).
This is ignored on Windows, when never closes STDIN.

=item * C<test_nuls>, inject NUL bytes into strings (default: 1)

With this test enabled, the function is expected to die when a NUL byte is passed in.

=item * C<test_undef>, test with undefined value (default: 1)

=item * C<test_empty>, test with empty strings (default: 1)

=item * C<test_non_ascii>, test with strings that contain non ascii characters (default: 1)

=item * C<timeout>, ensure tests don't hang (default: 10)

=item * C<regex_timeout>, seconds allowed for generating one string that
matches a regex pattern (default: 5)

A pattern the generator cannot satisfy, or one that makes it search for too
long, falls back to a fixed matching value; when none exists the pattern's
cases are skipped and reported once instead of failing the run.  Matching
strings are generated from the seeded RNG, so a schema's C<seed> makes them
reproducible.

Setting this to 0 disables timeout testing.

=item * C<check_files>, assert the routine leaves no files in the working
 directory (default: 1)

Every call is checked for files it created.  They are removed afterwards
whatever the setting, so a routine that writes a file cannot break the cases
that follow it; set this to 0 for a routine whose purpose is to write one.
C<extract-schemas> sets it to 0 when the routine's POD documents creating or
writing a file in its SIDE EFFECTS section.

=item * C<check_fds>, assert the routine leaks no file descriptors
 (default: 1)

Only checked where F</proc/self/fd> exists.  Set this to 0 for a routine that
returns a filehandle to its caller, which still holds a descriptor.

The first descriptor a call opens on a given file (or its first socket or
pipe) is taken as a resource held on purpose, such as a log file an object
opens on first use, and is not reported.  A later call that opens the same
target again is.

=item * C<check_accessors>, assert an accessor leaves the object it was called
 on alone (default: 1)

The object is deep copied before each call and the state it was handed
compared afterwards.  A getter that overwrites or deletes that state fails
"getter leaves its object unmodified"; a getset that changes anything but the
property it is named for fails "setter changes nothing but its property".
Values the call fills in where it was handed undef, and keys it adds, are
ignored, so a getter that memoises what it computed is not reported.  Set this
to 0 for an accessor whose purpose is to change state, such as an iterator's
C<next()>; a getter that declares no input is called with no arguments either
way.

=item * C<dedup>, fuzzing can create duplicate tests, go some way to remove duplicates (default: 1)

=item * C<properties>, enable L<Test::LectroTest> Property tests (default: 0)

*item * C<test_security>, send some security string based tests (default: 0)

=back

All values default to C<true>.

=head3 C<%accessor> - this is an accessor routine

  accessor:
    property: ua
    type: getset

Has two mandatory elements:

=over 4

=item * C<property>

The name of the property in the object that the routine controls.

=item * C<type>

One of C<getter>, C<setter>, C<getset>.

=back

=head3 C<%transforms> - list of transformations from input sets to output sets

Transforms allow you to define how input data should be transformed into output data.
This is useful for testing functions that convert between formats, normalize data,
or apply business logic transformations on a set of data to different set of data.
It takes a list of subsets of the input and output definitions,
and verifies that data from each input subset is correctly transformed into data from the matching output subset.

A transform whose input names at least one field that the top-level input does not
introduces its own call shape: its test cases are built from those fields rather
than the top-level ones.  This lets one schema cover two calls, such as an
arrayref argument and a list of scalar arguments.  A transform whose input only
names fields that are already at the top level adjusts the top-level input and
keeps the usual behaviour.

=head4 Transform Validation Rules

For each transform:

=over 4

=item 1. Generate test cases using the transform's input schema

=item 2. Call the function with those inputs

=item 3. Validate the output matches the transform's output schema

=item 4. If output has a specific 'value', check exact match

=item 5. If output has constraints (min/max), validate within bounds

=back

=head4 Example 1

  ---
  module: builtin
  function: abs

  config:
    test_undef: no
    test_empty: no
    test_nuls: no
    test_non_ascii: no

  input:
    number:
      type: number
      position: 0

  output:
    type: number
    min: 0

  transforms:
    positive:
      input:
        number:
          type: number
          position: 0
          min: 0
      output:
        type: number
        min: 0
    negative:
      input:
        number:
          type: number
          position: 0
          max: 0
      output:
        type: number
        min: 0
    error:
      input:
        undef
      output:
        _STATUS: DIES

If the output hash contains the key _STATUS, and if that key is set to DIES,
the routine should die with the given arguments; otherwise, it should live.
If it's set to WARNS, the routine should warn with the given arguments.

The keyword C<undef> is used to indicate that the C<function> returns nothing.

=head4 Example 2

  ---
  module: Math::Utils
  function: normalize_number

  input:
    value:
      type: number
      position: 0

  output:
    type: number

  transforms:
    positive_stays_positive:
      input:
        value:
          type: number
          min: 0
          max: 1000
      output:
        type: number
        min: 0
        max: 1

    negative_becomes_zero:
      input:
        value:
          type: number
          max: 0
      output:
        type: number
        value: 0

    preserves_zero:
      input:
        value:
          type: number
          value: 0
      output:
        type: number
        value: 0

=head3 C<$module>

The name of the module (optional).

Using the reserved word C<builtin> means you're testing a Perl builtin function.

If omitted, the generator will guess from the config filename:
C<My-Widget.conf> -> C<My::Widget>.

=head3 C<$function>

The function/method to test.

This defaults to C<run>.

=head3 C<%new>

An optional hashref of args to pass to the module's constructor.

  new:
    api_key: ABC123
    verbose: true

To ensure C<new()> is called with no arguments, you still need to define new, thus:

  module: MyModule
  function: my_function

  new:

=head3 C<$invocant>

The word C<class> when the routine is a class method: the harness calls
C<Module-E<gt>routine(...)> instead of C<Module::routine(...)>.  With C<new>
set the routine is called on the object C<new> builds, and without an
C<invocant> it is called as a plain function.

  invocant: class

=head3 C<%cases>

An optional Perl static corpus, when the output is a simple string (expected => [ args... ]).

Maps the expected output string to the input and _STATUS

  cases:
    ok:
      input: ping
      _STATUS: OK
    error:
      input: ""
      _STATUS: DIES

=head3 C<$yaml_cases>

An optional path to a YAML file with the same shape as C<%cases>.

=head3 C<$seed>

An optional integer.
When provided, the generated C<t/fuzz.t> will call C<srand($seed)> so fuzz runs are reproducible.

=head3 C<$iterations>

An optional integer controlling how many fuzz iterations to perform (default 30).

=head3 C<%edge_cases>

An optional hash mapping of extra values to inject.

        # Two named parameters
        edge_cases:
                name: [ '', 'a' x 1024, \"\x{263A}" ]
                age: [ -1, 0, 99999999 ]

        # Takes a string input
        edge_cases: [ 'foo', 'bar' ]

Values can be strings or numbers; strings will be properly quoted.
Note that this only works with routines that take named parameters.

=head3 C<%type_edge_cases>

An optional hash mapping types to arrayrefs of extra values to try for any field of that type:

        type_edge_cases:
                string: [ '', ' ', "\t", "\n", "\0", 'long' x 1024, chr(0x1F600) ]
                number: [ 0, 1.0, -1.0, 1e308, -1e308, 1e-308, -1e-308, 'NaN', 'Infinity' ]
                integer: [ 0, 1, -1, 2**31-1, -(2**31), 2**63-1, -(2**63) ]

=head3 C<%edge_case_array>

Specify edge case values for routines that accept a single unnamed parameter.
This is specifically designed for simple functions that take one argument without a parameter name.
These edge cases supplement the normal random string generation, ensuring specific problematic values are always tested.
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.

  ---
  module: Text::Processor
  function: sanitize

  input:
    type: string
    min: 1
    max: 1000

  edge_case_array:
    - "<script>alert('xss')</script>"
    - "'; DROP TABLE users; --"
    - "\0null\0byte"
    - "emoji\U0001F60Atest"
    - ""
    - " "

  seed: 42
  iterations: 30

=head3 Semantic Data Generators

For property-based testing with L<Test::LectroTest>,
you can use semantic generators to create realistic test data.

C<unix_timestamp> is currently fully supported,
other fuzz testing support for C<semantic> entries is being developed.

  input:
    email:
      type: string
      semantic: email

    user_id:
      type: string
      semantic: uuid

    phone:
      type: string
      semantic: phone_us

=head4 Available Semantic Types

=over 4

=item * C<email> - Valid email addresses (user@domain.tld)

=item * C<url> - HTTP/HTTPS URLs

=item * C<uuid> - UUIDv4 identifiers

=item * C<phone_us> - US phone numbers (XXX-XXX-XXXX)

=item * C<phone_e164> - International E.164 format (+XXXXXXXXXXXX)

=item * C<ipv4> - IPv4 addresses (0.0.0.0 - 255.255.255.255)

=item * C<ipv6> - IPv6 addresses

=item * C<username> - Alphanumeric usernames with _ and -

=item * C<slug> - URL slugs (lowercase-with-hyphens)

=item * C<hex_color> - Hex color codes (#RRGGBB)

=item * C<iso_date> - ISO 8601 dates (YYYY-MM-DD)

=item * C<iso_datetime> - ISO 8601 datetimes (YYYY-MM-DDTHH:MM:SSZ)

=item * C<semver> - Semantic version strings (major.minor.patch)

=item * C<jwt> - JWT-like tokens (base64url format)

=item * C<json> - Simple JSON objects

=item * C<base64> - Base64-encoded strings

=item * C<md5> - MD5 hashes (32 hex chars)

=item * C<sha256> - SHA-256 hashes (64 hex chars)

=item * C<bytes> - Byte strings (arbitrary octets, not text)

The property test draws octets rather than characters.  A byte string holds
data, not a document, so no text-oriented case applies to it;
L<App::Test::Generator::SchemaExtractor> sets this for a parameter that is a
file's contents (`$bytes`, `blob`, "raw bytes").

=item * C<directory> - The path of an existing, writable directory

The harness creates a temporary directory and passes its path, because no
pattern can describe "a directory that exists".
No empty-string case is generated for such a parameter, since routines
commonly read an empty path as "not given".
L<App::Test::Generator::SchemaExtractor> sets this for a parameter that the
routine tests with C<-d>.

=item * C<existing_file> - The path of an existing file

The harness creates a temporary file and passes its path, because no pattern
can describe "a file that exists".  L<App::Test::Generator::SchemaExtractor>
sets this for a parameter that the routine tests with C<-e> or C<-f> but does
not read.

=item * C<unix_timestamp>

=back

=head2 EDGE CASE GENERATION

In addition to purely random fuzz cases, the harness generates
deterministic edge cases for parameters that declare C<min>, C<max> or C<len> in their schema definitions.

For each constraint, three edge cases are added:

=over 4

=item * Just inside the allowable range

This case should succeed, since it lies strictly within the bounds.

=item * Exactly on the boundary

This case should succeed, since it meets the constraint exactly.

=item * Just outside the boundary

This case is annotated with C<_STATUS = 'DIES'> in the corpus and
should cause the harness to fail validation or croak.

A constraint that came only from L<extract-schemas> reading POD (marked
with C<_source: pod> for prose or C<_source: input_spec> for a formal spec)
is a claim about valid input, not a check the routine has been seen to make.
The constraint still sizes the valid data that is generated.  It also gets
explicit out-of-bound probes: a probe that dies is accepted as enforcement
of the documented limit, while one that survives is recorded as a
documentation contradiction.  Provenance is tracked per constraint in
C<_constraint_source>, so a documented minimum does not make a maximum that
the code enforces tolerant on the same field.  This applies to array and hash sizes, string
lengths and numeric ranges, to constraints parsed from POD prose
(C<3-50>, C<at least 5>), and to C<memberof> lists and C<matches> patterns.
Every documented constraint gets an outside value as an advisory probe; in
the normal advisory mode a probe that survives is reported as a routine
accepting a value its POD says is invalid, without failing the run.  A
constraint written by hand in a schema is still required to die outside
it.  Because tolerance reduces what the
harness proves, every tolerated bound is reported with C<diag>, so a
passing run never hides the concession.  Without this, a routine whose POD
says C<min =E<gt> 1> but which accepts an empty list failed every harness
run.

Fuzzing can still reveal a contradiction in either direction: a routine may
reject a value inside a documented constraint, or accept one outside it.  The
harness records those observations and reports them together at the end of
the run.  Advisory mode tolerates them, so POD-derived documentation cannot
fail a routine that merely documents differently; pass C<--strict-documented>
to C<fuzz-harness-generator> to make each recorded contradiction a failing
test.  The strict choice is embedded in the generated harness, so a later
C<prove> run behaves the same way.

=back

Supported constraint types:

=over 4

=item * C<number>, C<integer>, C<float>

Uses numeric values one below, equal to, and one above the boundary.

=item * C<string>

Uses strings of lengths one below, equal to, and one above the boundary.

=item * C<arrayref>

Uses references to arrays of with the number of elements one below, equal to, and one above the boundary.

=item * C<hashref>

Uses hashes with key counts one below, equal to, and one above the
boundary (C<min> = minimum number of keys, C<max> = maximum number
of keys).

=item * C<memberof> - arrayref of allowed values for a parameter

This example is for a routine called C<input()> that takes two arguments: C<status> and C<level>.
C<status> is a string that must have the value C<ok>, C<error> or C<pending>.
The C<level> argument is an integer that must be one of C<1>, C<5> or C<111>.

  ---
  input:
    status:
      type: string
      memberof:
        - ok
        - error
        - pending
    level:
      type: integer
      memberof:
        - 1
        - 5
        - 111

The generator will automatically create test cases for each allowed value (inside the member list),
and at least one value outside the list (which should die or C<croak>, C<_STATUS = 'DIES'>).
This works for strings, integers, and numbers.

=item * C<enum> - synonym of C<memberof>

=item * C<boolean> - automatic boundary tests for boolean fields

  input:
    flag:
      type: boolean

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'>.

=back

These edge cases are inserted automatically, in addition to the random
fuzzing inputs, so each run will reliably probe boundary conditions
without relying solely on randomness.

=head1 EXAMPLES

See the files in C<t/conf> for examples.

=head2 Adding Scheduled fuzz Testing with GitHub Actions to Your Code

To automatically create and run tests on a regular basis on GitHub Actions,
you need to create a configuration file for each method and subroutine that you're testing,
and a GitHub Actions configuration file.

This example takes you through testing the online_render method of L<HTML::Genealogy::Map>.

=head3 t/conf/online_render.yml

  ---

  module: HTML::Genealogy::Map
  function: onload_render

  input:
    gedcom:
      type: object
      can: individuals
    geocoder:
      type: object
      can: geocode
    debug:
      type: boolean
      optional: true
    google_key:
      type: string
      optional: true
      min: 39
      max: 39
      matches: "^AIza[0-9A-Za-z_-]{35}$"

  config:
    test_undef: 0

=head3 .github/actions/fuzz.t

  ---
  name: Fuzz Testing

  permissions:
    contents: read

  on:
    push:
      branches: [main, master]
    pull_request:
      branches: [main, master]
    schedule:
      - cron: '29 5 14 * *'

  jobs:
    generate-fuzz-tests:
      strategy:
        fail-fast: false
        matrix:
          os:
            - macos-latest
            - ubuntu-latest
            - windows-latest
          perl: ['5.42', '5.40', '5.38', '5.36', '5.34', '5.32', '5.30', '5.28', '5.22']

      runs-on: ${{ matrix.os }}
      name: Fuzz testing with perl ${{ matrix.perl }} on ${{ matrix.os }}

      steps:
        - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7

        - name: Set up Perl
          uses: shogo82148/actions-setup-perl@8b574cdc2dffdae49f803204a4f2b716a2fa1db7 # v1.44.2
          with:
            perl-version: ${{ matrix.perl }}

        - name: Install App::Test::Generator this module's dependencies
          run: |
            cpanm App::Test::Generator
            cpanm --installdeps .

        - name: Make Module
          run: |
            perl Makefile.PL
            make
          env:
            AUTOMATED_TESTING: 1
            NONINTERACTIVE_TESTING: 1

        - name: Generate fuzz tests
          run: |
            mkdir t/fuzz
            find t/conf -name '*.yml' | while read config; do
              test_name=$(basename "$config" .conf)
              fuzz-harness-generator "$config" > "t/fuzz/${test_name}_fuzz.t"
            done

        - name: Run generated fuzz tests
          run: |
            prove -lr t/fuzz/
          env:
            AUTOMATED_TESTING: 1
            NONINTERACTIVE_TESTING: 1

=head2 Fuzz Testing your CPAN Module

Running fuzz tests when you run C<make test> in your CPAN module.

Create a directory <t/conf> which contains the schemas.

Then create this file as <t/fuzz.t>:

  #!/usr/bin/env perl

  use strict;
  use warnings;

  use FindBin qw($Bin);
  use IPC::Run3;
  use IPC::System::Simple qw(system);
  use Test::Needs 'App::Test::Generator';
  use Test::Most;

  my $dirname = "$Bin/conf";

  if((-d $dirname) && opendir(my $dh, $dirname)) {
        while (my $filename = readdir($dh)) {
                # Skip '.' and '..' entries and vi temporary files
                next if ($filename eq '.' || $filename eq '..') || ($filename =~ /\.swp$/);

                my $filepath = "$dirname/$filename";

                if(-f $filepath) {      # Check if it's a regular file
                        my ($stdout, $stderr);
                        run3 ['fuzz-harness-generator', '-r', $filepath], undef, \$stdout, \$stderr;

                        ok($? == 0, 'Generated test script exits successfully');

                        if($? == 0) {
                                ok($stdout =~ /^Result: PASS/ms);
                                if($stdout =~ /Files=1, Tests=(\d+)/ms) {
                                        diag("$1 tests run");
                                }
                        } else {
                                diag("$filepath: STDOUT:\n$stdout");
                                diag($stderr) if(length($stderr));
                                diag("$filepath Failed");
                                last;
                        }
                        diag($stderr) if(length($stderr));
                }
        }
        closedir($dh);
  }

  done_testing();

=head2 Property-Based Testing with Transforms

The generator can create property-based tests using L<Test::LectroTest> when the
C<properties> configuration option is enabled.
This provides more comprehensive
testing by automatically generating thousands of test cases and verifying that
mathematical properties hold across all inputs.

=head3 Basic Property-Based Transform Example

Here's a complete example testing the C<abs> builtin function:

B<t/conf/abs.yml>:

  ---
  module: builtin
  function: abs

  config:
    test_undef: no
    test_empty: no
    test_nuls: no
    properties:
      enable: true
      trials: 1000

  input:
    number:
      type: number
      position: 0

  output:
    type: number
    min: 0

  transforms:
    positive:
      input:
        number:
          type: number
          min: 0
      output:
        type: number
        min: 0

    negative:
      input:
        number:
          type: number
          max: 0
      output:
        type: number
        min: 0

This configuration:

=over 4

=item * Enables property-based testing with 1000 trials per property

=item * Defines two transforms: one for positive numbers, one for negative

=item * Automatically generates properties that verify C<abs()> always returns non-negative numbers

=back

Generate the test:

  fuzz-harness-generator t/conf/abs.yml > t/abs_property.t

The generated test will include:

=over 4

=item * Traditional edge-case tests for boundary conditions

=item * Random fuzzing with 30 iterations (or as configured)

=item * Property-based tests that verify the transforms with 1000 trials each

=back

=head3 What Properties Are Tested?

The generator automatically detects and tests these properties based on your transform specifications:

=over 4

=item * B<Range constraints> - If output has C<min> or C<max>, verifies results stay within bounds

=item * B<Type preservation> - Ensures numeric inputs produce numeric outputs

=item * B<Definedness> - Verifies the function doesn't return C<undef> unexpectedly

=item * B<Specific values> - If output specifies a C<value>, checks exact equality

=back

For the C<abs> example above, the generated properties verify:

  # For the "positive" transform:
  - Given a positive number, abs() returns >= 0
  - The result is a valid number
  - The result is defined

  # For the "negative" transform:
  - Given a negative number, abs() returns >= 0
  - The result is a valid number
  - The result is defined

=head3 Advanced Example: String Normalization

Here's a more complex example testing a string normalization function:

B<t/conf/normalize.yml>:

  ---
  module: Text::Processor
  function: normalize_whitespace

  config:
    properties:
      enable: true
      trials: 500

  input:
    text:
      type: string
      min: 0
      max: 1000
      position: 0

  output:
    type: string
    min: 0
    max: 1000

  transforms:
    empty_preserved:
      input:
        text:
          type: string
          value: ""
      output:
        type: string
        value: ""

    single_space:
      input:
        text:
          type: string
          min: 1
          matches: '^\S+(\s+\S+)*$'
      output:
        type: string
        matches: '^\S+( \S+)*$'

    length_bounded:
      input:
        text:
          type: string
          min: 1
          max: 100
      output:
        type: string
        min: 1
        max: 100

This tests that the normalization function:

=over 4

=item * Preserves empty strings (C<empty_preserved> transform)

=item * Collapses multiple spaces into single spaces (C<single_space> transform)

=item * Maintains length constraints (C<length_bounded> transform)

=back

=head3 Interpreting Property Test Results

When property-based tests run, you'll see output like:

  ok 123 - negative property holds (1000 trials)
  ok 124 - positive property holds (1000 trials)

If a property fails, Test::LectroTest will attempt to find the minimal failing
case and display it:

  not ok 123 - positive property holds (47 trials)
  # Property failed
  # Reason: counterexample found

This helps you quickly identify edge cases that your function doesn't handle correctly.

=head3 Configuration Options for Property-Based Testing

In the C<config> section:

  config:
    properties:
      enable: true     # Enable property-based testing (default: false)
      trials: 1000     # Number of test cases per property (default: 1000)

You can also disable traditional fuzzing and only use property-based tests:

  config:
    properties:
      enable: true
      trials: 5000

  iterations: 0  # Disable random fuzzing, use only property tests

=head3 When to Use Property-Based Testing

Property-based testing with transforms is particularly useful for:

=over 4

=item * Mathematical functions (C<abs>, C<sqrt>, C<min>, C<max>, etc.)

=item * Data transformations (encoding, normalization, sanitization)

=item * Parsers and formatters

=item * Functions with clear input-output relationships

=item * Code that should satisfy mathematical properties (commutativity, associativity, idempotence)

=back

=head3 Requirements

Property-based testing requires both L<Test::LectroTest> and
L<Test::LectroTest::Compat> to be installed:

  cpanm Test::LectroTest Test::LectroTest::Compat

L<Test::LectroTest::Compat> provides the C<use_ok> bridge between
L<Test::LectroTest> and L<Test::Most>; it is used in every generated
property-based test file.  Both are declared in the distribution's
C<TEST_REQUIRES> so they are installed automatically during C<make test>.

If not installed, the generated tests will automatically skip the property-based
portion with a message.

=head3 Testing Email Validation

  ---
  module: Email::Valid
  function: rfc822

  config:
    properties:
      enable: true
      trials: 200
    close_stdin: true
    test_undef: no
    test_empty: no
    test_nuls: no

  input:
    email:
      type: string
      semantic: email
      position: 0

  output:
    type: boolean

  transforms:
    valid_emails:
      input:
        email:
          type: string
          semantic: email
      output:
        type: boolean

This generates 200 realistic email addresses for testing, rather than random strings.

=head3 Combining Semantic with Regex

You can combine semantic generators with regex validation:

  input:
    corporate_email:
      type: string
      semantic: email
      matches: '@company\.com$'

The semantic generator creates realistic emails, and the regex ensures they match your domain.

=head3 Custom Properties for Transforms

You can define additional properties that should hold for your transforms beyond
the automatically detected ones.

=head4 Using Built-in Properties

  transforms:
    positive:
      input:
        number:
          type: number
          min: 0
      output:
        type: number
        min: 0
      properties:
        - idempotent       # f(f(x)) == f(x)
        - non_negative     # result >= 0
        - positive         # result > 0

Available built-in properties:

=over 4

=item * C<idempotent> - Function is idempotent: f(f(x)) == f(x)

=item * C<non_negative> - Result is always >= 0

=item * C<positive> - Result is always > 0

=item * C<non_empty> - String result is never empty

=item * C<length_preserved> - Output length equals input length

=item * C<uppercase> - Result is all uppercase

=item * C<lowercase> - Result is all lowercase

=item * C<trimmed> - No leading/trailing whitespace

=item * C<sorted_ascending> - Array is sorted ascending

=item * C<sorted_descending> - Array is sorted descending

=item * C<unique_elements> - Array has no duplicates

=item * C<preserves_keys> - Hash has same keys as input

=back

=head4 Custom Property Code

Custom properties allows the definition additional invariants and relationships that should hold for their transforms,
beyond what's auto-detected.
For example:

=over 4

=item * Idempotence: f(f(x)) == f(x)

=item * Commutativity: f(x, y) == f(y, x)

=item * Associativity: f(f(x, y), z) == f(x, f(y, z))

=item * Inverse relationships: decode(encode(x)) == x

=item * Domain-specific invariants: Custom business logic

=back

Define your own properties with custom Perl code:

  transforms:
    normalize:
      input:
        text:
          type: string
      output:
        type: string
      properties:
        - name: single_spaces
          description: "No multiple consecutive spaces"
          code: $result !~ /  /

        - name: no_leading_space
          description: "No space at start"
          code: $result !~ /^\s/

        - name: reversible
          description: "Can be reversed back"
          code: length($result) == length($text)

The code has access to:

=over 4

=item * C<$result> - The function's return value

=item * Input variables - All input parameters (e.g., C<$text>, C<$number>)

=item * The function itself - Can call it again for idempotence checks

=back

=head4 Combining Auto-detected and Custom Properties

The generator automatically detects properties from your output spec, and adds
your custom properties:

  transforms:
    sanitize:
      input:
        html:
          type: string
      output:
        type: string
        min: 0              # Auto-detects: defined, min_length >= 0
        max: 10000
      properties:           # Additional custom checks:
        - name: no_scripts
          code: $result !~ /<script/i
        - name: no_iframes
          code: $result !~ /<iframe/i

=head2 GENERATED OUTPUT

The generated test:

=over 4

=item * Seeds RND (if configured) for reproducible fuzz runs

=item * Uses edge cases (per-field and per-type) with configurable probability

=item * Runs C<$iterations> fuzz cases plus appended edge-case runs

=item * Validates inputs with Params::Get / Params::Validate::Strict

=item * Asserts that a wrong-typed argument dies, where the type is enforced

Passing a reference where a string is declared is only expected to die for a
parameter whose input spec sets C<_source: validator>.
L<App::Test::Generator::SchemaExtractor> sets that source when the routine
checks its arguments with a validator such as L<Params::Validate::Strict>.
A type taken from POD, or inferred from the code, documents intent but does not
promise rejection, so no such case is generated for it.
Add the source by hand to a schema whose routine does check its argument types.

=item * Validates outputs with L<Return::Set>

=item * Runs static C<is(... )> corpus tests from Perl and/or YAML corpus

=item * Runs L<Test::LectroTest> tests

=back

=cut
1820
1821 - 1871
=head1 METHODS

=head2 generate

Takes a schema file and produces a test file (or STDOUT).

  # Modern named API
  App::Test::Generator->generate(
      schema_file => 'schemas/foo.yml',
      output_file => 'test/foo.t',
  );

  # Feed surviving mutants into the generated harness
  App::Test::Generator->generate(
      schema_file      => 'schemas/foo.yml',
      mutation_results => 'mutation.json',
      output_file      => 'test/foo.t',
  );

  # Legacy positional API
  App::Test::Generator->generate($schema_file, $test_file);

=head3 API SPECIFICATION

=head4 Input

    {
        schema_file => { type => 'string', optional => 0 },
        input_file  => { type => 'string', optional => 1 },
        output_file => { type => 'string', optional => 1, max => 255 },
        strict_documented => { type => 'boolean', optional => 1 },
        mutation_results => { type => 'string', optional => 1 },
    }

C<mutation_results> is the JSON report written by
C<test-generator-mutate --json>.  Surviving numeric-boundary mutants are
converted into C<min> or C<max> constraints on the matching input field, so
the harness generates data either side of the boundary the survivor exposed.
Existing constraints are never replaced.  See
L<App::Test::Generator::Mutation::Feedback>.

=head4 Output

    { type => 'boolean' }

Always 1.  The test source itself is written to C<output_file>, or printed
on STDOUT when no output file is given; it is not returned.

The mathematical description is in L</FORMAL SPECIFICATION>.

=cut
1872
1873sub generate
1874{
1875
205
175443486
        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
205
428
        my $class = (ref($_[0]) ne 'HASH') ? shift : undef;
1882
205
483
        my ($schema_file, $test_file, $schema);
1883        # Globals loaded from the user's conf (all optional except function maybe)
1884
205
0
        my ($module, $function, $new, $yaml_cases, $invocant);
1885
205
0
        my ($seed, $iterations);
1886
205
237
        my $strict_documented = 0;
1887
1888
205
674
        if((ref($_[0]) eq 'HASH') || defined($_[2])) {
1889                # Modern API
1890
87
346
                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 },
1895                                output_file => { type => 'string', optional => 1 },
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                        }
1901                });
1902
87
21415
                $strict_documented = $params->{'strict_documented'} ? 1 : 0;
1903
87
247
                if($params->{'schema_file'}) {
1904
5
15
                        $schema_file = $params->{'schema_file'};
1905                } elsif($params->{'input_file'}) {
1906
53
59
                        $schema_file = $params->{'input_file'};
1907                } elsif($params->{'schema'}) {
1908
29
43
                        $schema = $params->{'schema'};
1909                } else {
1910
0
0
                        croak(__PACKAGE__, ': Usage: generate(input_file|schema [, output_file]');
1911                }
1912
87
146
                if(defined($schema_file)) {
1913
58
92
                        $schema = _load_schema($schema_file);
1914                }
1915
87
649
                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
1
3
                        require App::Test::Generator::Mutation::Feedback;
1919                        my $feedback = App::Test::Generator::Mutation::Feedback->new(
1920                                mutation_results => $params->{'mutation_results'},
1921
1
5
                                (defined($schema->{module}) ? (module => $schema->{module}) : ()),
1922                        );
1923
1
1
                        $feedback->apply_to_schema($schema);
1924                }
1925
87
131
                $test_file = $params->{'output_file'};
1926        } else {
1927                # Legacy API
1928
118
153
                ($schema_file, $test_file) = @_;
1929
118
160
                if(defined($schema_file)) {
1930
113
311
                        $schema = _load_schema($schema_file);
1931                } else {
1932
5
42
                        croak 'Usage: generate(schema_file [, outfile])';
1933                }
1934        }
1935
1936        # Parse the schema file and load into our structures
1937
197
197
1115
407
        my %input = %{_load_schema_section($schema, 'input', $schema_file)};
1938
196
196
201
201
        my %output = %{_load_schema_section($schema, 'output', $schema_file)};
1939
195
195
163
209
        my %transforms = %{_load_schema_section($schema, 'transforms', $schema_file)};
1940
194
194
194
181
        my %accessor = %{_load_schema_section($schema, 'accessor', $schema_file)};
1941
1942
194
2
344
3
        my %cases = %{$schema->{cases}} if(exists($schema->{cases}));
1943
194
0
277
0
        my %edge_cases = %{$schema->{edge_cases}} if(exists($schema->{edge_cases}));
1944
194
1
255
1
        my %type_edge_cases = %{$schema->{type_edge_cases}} if(exists($schema->{type_edge_cases}));
1945
1946
194
582
        $module = $schema->{module} if(exists($schema->{module}) && length($schema->{module}));
1947
194
338
        $function = $schema->{function} if(exists($schema->{function}));
1948
194
266
        if(exists($schema->{new})) {
1949
32
69
                $new = defined($schema->{'new'}) ? $schema->{new} : '_UNDEF';
1950        }
1951
194
326
        $invocant = $schema->{invocant} if(exists($schema->{invocant}) && defined($schema->{invocant}));
1952
194
284
        $yaml_cases = $schema->{yaml_cases} if(exists($schema->{yaml_cases}));
1953
194
300
        $seed = $schema->{seed} if(exists($schema->{seed}));
1954
194
267
        $iterations = $schema->{iterations} if(exists($schema->{iterations}));
1955
1956
194
3
267
4
        my @edge_case_array = @{$schema->{edge_case_array}} if(exists($schema->{edge_case_array}));
1957
194
370
        _validate_config($schema);
1958
1959
189
101
568
351
        my %config = %{$schema->{config}} if(exists($schema->{config}));
1960
1961
189
422
        _normalize_config(\%config);
1962
189
828
        $config{'strict_documented'} = $strict_documented;
1963
1964        # Guess module name from config file if not set
1965
189
386
        if(!$module) {
1966
5
8
                if($schema_file) {
1967
4
54
                        ($module = basename($schema_file)) =~ s/\.(conf|pl|pm|yml|yaml)$//;
1968
4
4
                        $module =~ s/-/::/g;
1969                        # Guard against Perl builtin function names being mistaken
1970                        # for module names — builtins have no module to load
1971
4
4
                        if(_is_perl_builtin($module)) {
1972
1
1
                                undef $module;
1973                        }
1974                }
1975        } elsif($module eq $MODULE_BUILTIN) {
1976
54
105
                undef $module;
1977        }
1978
1979
189
880
        if($module && length($module) && ($module ne 'builtin')) {
1980
133
278
                _validate_module($module, $schema_file);
1981        }
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
189
493
        _assert_identifier($module, 'module', package => 1) if defined($module) && length($module);
1987
1988        # sensible defaults
1989
188
246
        $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
188
285
        _assert_identifier($function, 'function', package => 1);
1994
186
471
        $iterations ||= $DEFAULT_ITERATIONS;             # default fuzz runs if not specified
1995
186
617
        $seed = undef if defined $seed && $seed eq '';  # treat empty as undef
1996
1997        # --- YAML corpus support (yaml_cases is filename string) ---
1998
186
149
        my %yaml_corpus_data;
1999
186
233
        if (defined $yaml_cases) {
2000
5
52
                croak("$yaml_cases: $!") if(!-f $yaml_cases);
2001
2002
4
13
                my $yaml_data = LoadFile(Encode::decode('utf8', $yaml_cases));
2003
4
203
                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
4
4
1
8
                        for my $expected (keys %{$yaml_data}) {
2008
6
3
                                my $outputs = $yaml_data->{$expected};
2009
6
11
                                unless($outputs && (ref $outputs eq 'ARRAY')) {
2010
2
11
                                        carp("$yaml_cases: $expected does not point to an array ref, ignoring");
2011
2
163
                                        next;
2012                                }
2013
4
5
                                $yaml_corpus_data{$expected} = $outputs;
2014                        }
2015                }
2016        }
2017
2018        # Merge Perl %cases and YAML corpus safely
2019        # my %all_cases = (%cases, %yaml_corpus_data);
2020
185
231
        my %all_cases = (%yaml_corpus_data, %cases);
2021
185
260
        for my $k (keys %yaml_corpus_data) {
2022
4
9
                if (exists $cases{$k} && ref($cases{$k}) eq 'ARRAY' && ref($yaml_corpus_data{$k}) eq 'ARRAY') {
2023
1
1
1
0
1
2
                        $all_cases{$k} = [ @{$yaml_corpus_data{$k}}, @{$cases{$k}} ];
2024                }
2025        }
2026
2027
185
295
        if(my $hints = delete $schema->{_yamltest_hints}) {
2028
8
14
                if(my $boundaries = $hints->{boundary_values}) {
2029
8
8
6
14
                        push @edge_case_array, @{$boundaries};
2030                }
2031
8
11
                if(my $invalid = $hints->{invalid}) {
2032
0
0
                        carp('TODO: handle yamltest_hints->invalid');
2033                }
2034        }
2035
2036        # If the schema says the type is numeric, normalize
2037
185
337
        if ($schema->{type} && $schema->{type} =~ /^(integer|number|float)$/) {
2038
1
1
                for (@edge_case_array) {
2039
2
2
                        next unless defined $_;
2040
2
5
                        $_ += 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
185
141
        my @relationships;
2048
185
363
        if(exists($schema->{relationships}) && ref($schema->{relationships}) eq 'ARRAY') {
2049
0
0
0
0
                @relationships = @{$schema->{relationships}};
2050        }
2051
2052        # Serialise the relationships array from the schema into Perl source
2053        # code for embedding in the generated test file. Each relationship
2054        # type is rendered as a hashref in the @relationships array.
2055
2056
185
172
        my $relationships_code = '';
2057
2058        # Walk each relationship in the order SchemaExtractor produced them
2059
185
225
        for my $rel (@relationships) {
2060
0
0
                my $type = $rel->{type} // '';
2061
2062                # Mutually exclusive: both params being set should cause the method to die
2063
0
0
                if($type eq 'mutually_exclusive') {
2064                        $relationships_code .= "{ type => 'mutually_exclusive', params => [" .
2065
0
0
0
0
0
0
                                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 => [" .
2071
0
0
0
0
                                join(', ', map { perl_quote($_) } @{$rel->{params}}) .
2072
0
0
                                "], logic => " . perl_quote($rel->{logic} // 'or') . " },\n";
2073
2074                # Conditional requirement: if one param is set, another becomes mandatory
2075                } elsif($type eq 'conditional_requirement') {
2076                        $relationships_code .= "{ type => 'conditional_requirement', if => " .
2077                                perl_quote($rel->{'if'}) . ", then_required => " .
2078
0
0
                                perl_quote($rel->{then_required}) . " },\n";
2079
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
0
0
                                perl_quote($rel->{requires}) . " },\n";
2085
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 => " .
2091                                perl_quote($rel->{operator}) . ", value => " .
2092
0
0
                                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 => " .
2098                                perl_quote($rel->{equals}) . ", then_required => " .
2099
0
0
                                perl_quote($rel->{then_required}) . " },\n";
2100
2101                # Unknown type — warn and skip rather than emitting broken code
2102                } else {
2103
0
0
                        carp "Unknown relationship type '$type', skipping";
2104                }
2105        }
2106
2107        # Dedup the edge cases
2108
185
127
        my %seen;
2109        @edge_case_array = grep {
2110
185
103
242
138
                my $key = defined($_) ? (Scalar::Util::looks_like_number($_) ? "N:$_" : "S:$_") : 'U';
2111
103
174
                !$seen{$key}++;
2112        } @edge_case_array;
2113
2114        # Sort the edge cases to keep it consistent across runs
2115        @edge_case_array = sort {
2116
185
140
255
90
                return -1 if !defined $a;
2117
140
111
                return 1 if !defined $b;
2118
2119
140
91
                my $na = Scalar::Util::looks_like_number($a);
2120
140
98
                my $nb = Scalar::Util::looks_like_number($b);
2121
2122
140
212
                return $a <=> $b if $na && $nb;
2123
18
18
                return -1 if $na;
2124
13
13
                return 1 if $nb;
2125
11
12
                return $a cmp $b;
2126        } @edge_case_array;
2127
2128        # render edge case maps for inclusion in the .t
2129
185
382
        my $edge_cases_code = render_arrayref_map(\%edge_cases);
2130
185
220
        my $type_edge_cases_code = render_arrayref_map(\%type_edge_cases);
2131
2132
185
201
        my $edge_case_array_code = '';
2133
185
263
        if(scalar(@edge_case_array)) {
2134
21
93
28
74
                $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
2138
185
197
        my $config_code = '';
2139
185
648
        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
2405
1514
                if(ref($config{$key}) eq 'HASH') {
2143
185
131
                        next;
2144                }
2145
2220
1886
                if((!defined($config{$key})) || !$config{$key}) {
2146                        # YAML will strip the word 'false'
2147                        # e.g. in 'test_undef: false'
2148
541
375
                        $config_code .= "'$key' => 0,\n";
2149                } else {
2150
1679
1076
                        $config_code .= "'$key' => $config{$key},\n";
2151                }
2152        }
2153
2154        # Render input/output
2155
185
214
        my $input_code = '';
2156
185
507
        if(((scalar keys %input) == 1) && exists($input{'type'}) && !ref($input{'type'})) {
2157                # %input = ( type => 'string' );
2158
50
51
                foreach my $key (sort keys %input) {
2159
50
49
                        $input_code .= "'$key' => '$input{$key}',\n";
2160                }
2161        } else {
2162                # %input = ( str => { type => 'string' } );
2163
135
255
                $input_code = render_hash(\%input);
2164        }
2165
185
270
        if(defined(my $re = $output{'matches'})) {
2166
0
0
                if(ref($re) ne 'Regexp') {
2167                        # Use eval to compile safely — qr/$re/ would interpolate
2168                        # the string first, corrupting patterns containing [ or \
2169
0
0
0
0
                        my $compiled = eval { qr/$re/ };
2170
0
0
                        if($@) {
2171
0
0
                                carp("Invalid matches pattern '$re': $@");
2172                        } else {
2173
0
0
                                $output{'matches'} = $compiled;
2174                        }
2175                }
2176        }
2177
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
185
236
        if(defined(my $re = $output{'nomatch'})) {
2183
0
0
                if(ref($re) ne 'Regexp') {
2184                        # Use eval to compile safely — qr/$re/ would interpolate
2185                        # the string first, corrupting patterns containing [ or \
2186
0
0
0
0
                        my $compiled = eval { qr/$re/ };
2187
0
0
                        if($@) {
2188
0
0
                                carp("Invalid nomatch pattern '$re': $@");
2189                        } else {
2190
0
0
                                $output{'nomatch'} = $compiled;
2191                        }
2192                }
2193        }
2194
2195
185
310
        my $output_code = render_args_hash(\%output);
2196
185
414
        my $new_code = ($new && (ref $new eq 'HASH')) ? render_args_hash($new) : '';
2197
2198
185
147
        my $transforms_code;
2199
185
231
        if(keys %transforms) {
2200
7
8
                foreach my $transform(keys %transforms) {
2201
10
17
                        my $properties = render_fallback($transforms{$transform}->{'properties'});
2202
2203
10
17
                        if($transforms_code) {
2204
3
2
                                $transforms_code .= "},\n";
2205                        }
2206                        $transforms_code .= "$transform => {\n" .
2207                                "\t'input' => { " .
2208                                render_args_hash($transforms{$transform}->{'input'}) .
2209                                "\t}, 'output' => { " .
2210
10
16
                                render_args_hash($transforms{$transform}->{'output'}) .
2211                                "\t}, 'properties' => $properties\n" .
2212                                "\t,\n";
2213                }
2214
7
7
                $transforms_code .= "}\n";
2215        }
2216
2217
185
179
        my $transform_properties_code = '';
2218
185
141
        my $use_properties = 0;
2219
2220
185
229
        if (keys %transforms && ($config{properties}{enable} // 0)) {
2221
4
3
                $use_properties = 1;
2222
2223                # Generate property-based tests for transforms
2224
4
11
                my $properties = _generate_transform_properties(
2225                        \%transforms,
2226                        $function,
2227                        $module,
2228                        \%input,
2229                        \%config,
2230                        $new
2231                );
2232
2233                # Convert to code for template
2234
3
4
                $transform_properties_code = _render_properties($properties);
2235        }
2236
2237
184
238
        if(keys %accessor) {
2238                # Sanity test
2239
18
28
                my $property = $accessor{property};
2240
18
18
                my $type = $accessor{type};
2241
2242
18
20
                if(!defined($new)) {
2243                        # Internal invariant — schema has a contradictory accessor+type combination;
2244                        # confess gives the full call chain to aid debugging
2245
0
0
                        confess("invariant violation: $property: accessor $type can only work on an object, incorrectly tagged as $type");
2246                }
2247
18
27
                if($type eq 'getset') {
2248
9
13
                        if(scalar(keys %input) != 1) {
2249
1
13
                                confess("invariant violation: $property: getset must take one input argument, incorrectly tagged as getset");
2250                        }
2251
8
12
                        if(scalar(keys %output) == 0) {
2252
1
9
                                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
182
327
        my $setup_code = ($module) ? "BEGIN { use_ok('$module') }" : '';
2259
182
124
        my $call_code;  # Code to call the function being test when used with named arguments
2260        my $position_code;      # Code to call the function being test when used with position arguments
2261
182
285
        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
182
175
        my $cmp_op = 'eq';
2269
182
271
        if(scalar(keys %input) == 1) {
2270
152
188
                my ($spec) = values %input;
2271
152
297
                my $type = (ref($spec) eq 'HASH') ? $spec->{type} : $spec;
2272
152
680
                $cmp_op = '==' if(defined($type) && !ref($type) && ($type =~ /^(?:integer|number|float)$/));
2273        }
2274
182
562
        if(defined($new) && defined($module)) {
2275                # keep use_ok regardless (user found earlier issue)
2276
29
42
                if($new_code eq '') {
2277
28
31
                        $new_code = "new_ok('$module')";
2278                } else {
2279
1
1
                        $new_code = "new_ok('$module' => [ $new_code ] )";
2280                }
2281
29
48
                $setup_code .= "\nmy \$obj = $new_code;";
2282
29
54
                if($has_positions) {
2283
12
22
                        $position_code = "\$result = (scalar(\@alist) == 1) ? \$obj->$function(\$alist[0]) : (scalar(\@alist) == 0) ? \$obj->$function() : \$obj->$function(\@alist);";
2284
12
25
                        if(defined($accessor{type})) {
2285
5
13
                                if($accessor{type} eq 'getter') {
2286
0
0
                                        $position_code .= "my \$prev_value = \$obj->{$accessor{property}};";
2287                                } elsif($accessor{type} eq 'getset') {
2288
5
8
                                        $position_code .= 'if(scalar(@alist) == 1) { ';
2289
5
6
                                        $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
5
5
                                        $position_code .= '}';
2291                                }
2292
5
9
                                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
5
3
                                        $position_code .= 'if(scalar(@alist) == 1) { ';
2295
5
6
                                        $position_code .= "cmp_ok(\$result, '$cmp_op', \$obj->{$accessor{property}}, 'getset function returns correct item');";
2296
5
9
                                        if($accessor{type} eq 'getter') {
2297
0
0
                                                $position_code .= "if(defined(\$prev_value)) { cmp_ok(\$result, 'eq', \$prev_value, 'getter does not change value'); } ";
2298                                        }
2299
5
4
                                        $position_code .= '}';
2300                                }
2301
5
7
                                if($output{'_returns_self'}) {
2302
0
0
                                        croak("$accessor{type} for $accessor{property} cannot return \$self");
2303                                }
2304                        }
2305                } else {
2306
17
16
                        $call_code = "\$result = \$obj->$function(_fuzz_args(\$input));";
2307
17
48
                        if($output{'_returns_self'}) {
2308
0
0
                                $call_code .= "ok(defined(\$result)); ok(\$result eq \$obj, '$function returns self')";
2309                        } elsif(defined($accessor{type}) && ($accessor{type} eq 'getset')) {
2310
2
2
                                $call_code .= "ok(\$obj->$function() $cmp_op \$result, 'test getset accessor');"
2311                        }
2312
17
49
                        if(scalar(keys %input) == 0) {
2313
12
30
                                if(defined($accessor{type}) && ($accessor{type} eq 'getter')) {
2314
9
14
                                        $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.
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
100
468
                if(($function eq 'new') || ($function eq 'import') || (defined($invocant) && ($invocant eq 'class') && !defined($new))) {
2325
4
13
                        if($has_positions) {
2326
0
0
                                $position_code = "\$result = (scalar(\@alist) == 1) ? ${module}\->$function(\$alist[0]) : (scalar(\@alist) == 0) ? ${module}\->$function() : ${module}\->$function(\@alist);";
2327                        } else {
2328
4
11
                                $call_code = "\$result = ${module}\->$function(_fuzz_args(\$input));";
2329                        }
2330                } else {
2331
96
123
                        if($has_positions) {
2332
76
169
                                $position_code = "\$result = (scalar(\@alist) == 1) ? ${module}::$function(\$alist[0]) : (scalar(\@alist) == 0) ? ${module}::$function() : ${module}::$function(\@alist);";
2333                        } else {
2334
20
19
                                $call_code = "\$result = ${module}::$function(_fuzz_args(\$input));";
2335                        }
2336                }
2337        } else {
2338
53
46
                if($has_positions) {
2339
7
10
                        $position_code = "\$result = $function(\@alist);";
2340                } else {
2341
46
40
                        $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
182
351
        if(($output{type} // '') eq 'array') {
2348
2
2
                if(defined($call_code)) {
2349
2
9
                        $call_code =~ s/\A\$result = ([^;]+);/my \@_r = ($1); \$result = \\\@_r;/;
2350                }
2351
2
3
                if(defined($position_code)) {
2352
0
0
                        $position_code =~ s/\A\$result = ([^;]+);/my \@_r = ($1); \$result = \\\@_r;/;
2353                }
2354        }
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
182
344
        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
9
11
                foreach my $code (\$call_code, \$position_code) {
2369
18
18
                        next unless(defined($$code));
2370
9
131
                        $$code =~ s/\Q$function\E\(_fuzz_args\(\$input\)\)/$function()/g;
2371                }
2372
9
18
                my $snapshot = 'my $getter_copy = eval { require Storable; Storable::dclone($obj) }; ';
2373
9
14
                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
9
13
                foreach my $code (\$call_code, \$position_code) {
2378
18
36
                        next unless(defined($$code) && ($config{'check_accessors'} // 1));
2379
8
11
                        $$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
182
328
        if(defined($accessor{type}) && ($accessor{type} eq 'getset') && defined($accessor{property})) {
2390
7
9
                my $property = perl_quote($accessor{property});
2391
7
9
                my $snapshot = 'my $setter_copy = eval { require Storable; Storable::dclone($obj) }; ';
2392
7
16
                my $check = 'if(defined($setter_copy) && eval { scalar(keys %{$setter_copy}); 1 }) {'
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
7
12
                foreach my $code (\$call_code, \$position_code) {
2397
14
32
                        next unless(defined($$code) && ($config{'check_accessors'} // 1));
2398
6
9
                        $$code = $snapshot . $$code . ' ' . $check;
2399                }
2400        }
2401
2402        # Build static corpus code
2403
182
183
        my $corpus_code = '';
2404
182
211
        if (%all_cases) {
2405
3
4
                $corpus_code = "\n# --- Static Corpus Tests ---\n" .
2406                        "diag('Running " . scalar(keys %all_cases) . " corpus tests');\n";
2407
2408
3
5
                for my $expected (sort keys %all_cases) {
2409
6
8
                        my $inputs = $all_cases{$expected};
2410
6
6
                        next unless($inputs);
2411
2412
6
5
                        my $expected_str = perl_quote($expected);
2413
6
10
                        my $status = ((ref($inputs) eq 'HASH') && $inputs->{'_STATUS'}) // 'OK';
2414
6
11
                        if($expected_str eq "'_STATUS:DIES'") {
2415
0
0
                                $status = 'DIES';
2416                        } elsif($expected_str eq "'_STATUS:WARNS'") {
2417
0
0
                                $status = 'WARNS';
2418                        }
2419
2420
6
7
                        if(ref($inputs) eq 'HASH') {
2421
0
0
                                $inputs = $inputs->{'input'};
2422                        }
2423
6
4
                        my $input_str;
2424
6
4
                        if(ref($inputs) eq 'ARRAY') {
2425
6
9
6
5
5
4
                                $input_str = join(', ', map { perl_quote($_) } @{$inputs});
2426                        } elsif(ref($inputs) eq 'HASH') {
2427
0
0
                                $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
0
0
                                $input_str =~ s/=> 'undef'/=> undef/gms;
2434                        } else {
2435
0
0
                                $input_str = $inputs;
2436                        }
2437
6
7
                        if(($input_str eq 'undef') && (!$config{'test_undef'})) {
2438
0
0
                                carp('corpus case set to undef, yet test_undef is not set in config');
2439                        }
2440
6
5
                        if($new) {
2441
0
0
                                if($status eq 'DIES') {
2442                                        $corpus_code .= "dies_ok { \$obj->$function($input_str) } " .
2443
0
0
0
0
                                                        "'$function(" . join(', ', map { $_ // '' } @$inputs ) . ") dies';\n";
2444                                } elsif($status eq 'WARNS') {
2445                                        $corpus_code .= "warnings_exist { \$obj->$function($input_str) } qr/./, " .
2446
0
0
0
0
                                                        "'$function(" . join(', ', map { $_ // '' } @$inputs ) . ") warns';\n";
2447                                } else {
2448                                        my $desc = sprintf("$function(%s) returns %s",
2449
0
0
0
0
                                                perl_quote(join(', ', map { $_ // '' } @$inputs )),
2450                                                $expected_str
2451                                        );
2452
0
0
                                        if(($output{'type'} // '') eq 'boolean') {
2453
0
0
                                                if($expected_str eq '1') {
2454
0
0
                                                        $corpus_code .= "ok(\$obj->$function($input_str), " . q_wrap($desc) . ");\n";
2455                                                } elsif($expected_str eq '0') {
2456
0
0
                                                        $corpus_code .= "ok(!\$obj->$function($input_str), " . q_wrap($desc) . ");\n";
2457                                                } else {
2458
0
0
                                                        croak("Boolean is expected to return $expected_str");
2459                                                }
2460                                        } else {
2461
0
0
                                                $corpus_code .= "is(\$obj->$function($input_str), $expected_str, " . q_wrap($desc) . ");\n";
2462                                        }
2463                                }
2464                        } else {
2465
6
10
                                if($status eq 'DIES') {
2466
0
0
                                        if($module) {
2467
0
0
                                                $corpus_code .= "dies_ok { $module\::$function($input_str) } " .
2468                                                        "'Corpus $expected dies';\n";
2469                                        } else {
2470
0
0
                                                $corpus_code .= "dies_ok { $function($input_str) } " .
2471                                                        "'Corpus $expected dies';\n";
2472                                        }
2473                                } elsif($status eq 'WARNS') {
2474
0
0
                                        if($module) {
2475
0
0
                                                $corpus_code .= "warnings_exist { $module\::$function($input_str) } qr/./, " .
2476                                                        "'Corpus $expected warns';\n";
2477                                        } else {
2478
0
0
                                                $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
6
9
6
9
11
4
                                                perl_quote((ref $inputs eq 'ARRAY') ? (join(', ', map { $_ // '' } @{$inputs})) : $inputs),
2484                                                $expected_str
2485                                        );
2486
6
9
                                        if(($output{'type'} // '') eq 'boolean') {
2487
0
0
                                                if($expected_str eq '1') {
2488
0
0
                                                        $corpus_code .= "ok(\$obj->$function($input_str), " . q_wrap($desc) . ");\n";
2489                                                } elsif($expected_str eq '0') {
2490
0
0
                                                        $corpus_code .= "ok(!\$obj->$function($input_str), " . q_wrap($desc) . ");\n";
2491                                                } else {
2492
0
0
                                                        croak("Boolean is expected to return $expected_str");
2493                                                }
2494                                        } else {
2495
6
12
                                                $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
182
146
        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
182
241
        my $seed_code = "our \$seed;\n";
2511
182
210
        if (defined $seed) {
2512                # ensure integer-ish
2513
14
13
                $seed = int($seed);
2514
14
16
                $seed_code .= "srand(\$seed = $seed);\n";
2515        }
2516
2517
182
315
        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
182
1215
        my $tt = Template->new({ ENCODING => 'utf8', TRIM => 1 });
2524
2525        # Read template from DATA handle
2526
182
541470
        my $template_package = __PACKAGE__ . '::Template';
2527
182
959
        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,
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,
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,
2546                iterations_code => int($iterations),
2547                use_properties => $use_properties,
2548                transform_properties_code => $transform_properties_code,
2549
182
265470
                property_trials => $config{properties}{trials} // $DEFAULT_PROPERTY_TRIALS,
2550                relationships_code => $relationships_code,
2551                module => $module,
2552                skip_reason => $skip_reason
2553        };
2554
2555
182
2291
        my $test;
2556
182
402
        $tt->process($template, $vars, \$test) or croak($tt->error());
2557
2558
182
3528534
        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.
2562
83
83
83
246
55
245
                no autodie qw(open);
2563
124
6232
                open my $fh, '>:encoding(UTF-8)', $test_file or croak "Cannot open $test_file: $!";
2564
124
82168
                print $fh "$test\n";
2565
124
473
                close $fh;
2566
124
25799
                if($module) {
2567
111
981
                        print "Generated $test_file for $module\::$function with fuzzing + corpus support\n";
2568                } else {
2569
13
130
                        print "Generated $test_file for $function with fuzzing + corpus support\n";
2570                }
2571        } else {
2572
58
184108
                print "$test\n";
2573        }
2574
2575
182
957
        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# --------------------------------------------------
2591sub _is_perl_builtin {
2592
34
8593
        my $name = $_[0];
2593
34
32
        return 0 unless defined $name;
2594
2595
32
404
26
380
        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
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
32
60
        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()
2655#             to avoid executing arbitrary code from
2656#             user-supplied config files.
2657# --------------------------------------------------
2658sub _load_schema {
2659
179
6343
        my $schema_file = $_[0];
2660
2661        # Validate the argument before touching the filesystem
2662
179
281
        croak(__PACKAGE__, ': Usage: _load_schema($schema_file)') unless defined $schema_file;
2663
2664
177
231
        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
2668
175
1112
        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
170
1128
        if(my $schema = Config::Abstraction->new(
2674                config_dirs  => ['.', ''],
2675                config_file  => $schema_file,
2676                no_fixate    => 1,
2677        )) {
2678
170
237689
                if($schema = $schema->all()) {
2679                        # Detect legacy Perl config files by the presence of
2680                        # variable declaration keys — these are no longer supported
2681
170
1734
                        if(exists($schema->{$LEGACY_PERL_KEY_1}) ||
2682                           exists($schema->{$LEGACY_PERL_KEY_2})) {
2683
1
8
                                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
169
1343
                        $schema->{$SOURCE_KEY} = $schema_file;
2688
169
978
                        return $schema;
2689                }
2690        }
2691
2692
0
0
        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
2700#             a hashref if present.
2701#
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
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.
2717# --------------------------------------------------
2718sub _load_schema_section {
2719
790
4911
        my ($schema, $section, $schema_file) = @_;
2720
2721        # Section absent — return empty hash as the safe default
2722
790
858
        return {} unless exists $schema->{$section};
2723
2724        # Section present and is a hashref — return it directly
2725        return $schema->{$section}
2726
406
916
                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
8
20
                   $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
5
35
                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.
2754#             Croaks on any structural error.
2755#             Carps on non-fatal warnings (unknown
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
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# --------------------------------------------------
2768sub _validate_config {
2769
209
22229
        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
209
343
        if(!defined($schema->{'module'}) && !defined($schema->{'function'})) {
2774
4
24
                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
205
357
        if(!defined($schema->{'input'}) && !defined($schema->{'output'})) {
2780
9
56
                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
205
1509
        if($schema->{'input'} && ref($schema->{input}) ne 'HASH') {
2785
3
4
                if($schema->{'input'} eq 'undef') {
2786
1
2
                        delete $schema->{'input'};
2787                } else {
2788
2
6
                        croak("Invalid input specification: expected hash, got '$schema->{'input'}'");
2789                }
2790        }
2791
2792        # Validate each input parameter if input is defined
2793
203
272
        if($schema->{input}) {
2794
183
379
                _validate_input_params($schema);
2795
180
354
                _validate_input_positions($schema);
2796
180
267
                _validate_input_semantics($schema);
2797        }
2798
2799        # Validate transform property definitions if present
2800
200
424
        if(exists($schema->{transforms}) && ref($schema->{transforms}) eq 'HASH') {
2801
13
36
                _validate_transform_properties($schema);
2802        }
2803
2804        # Validate any nested config sub-hash keys against known types
2805
200
416
        if(ref($schema->{config}) eq 'HASH') {
2806
103
103
93
279
                for my $k (keys %{$schema->{'config'}}) {
2807                        # %VALID_CONFIG_KEYS is the authoritative set — O(1) hash lookup
2808                        croak "unknown config setting '$k'"
2809
525
1747
                                unless $VALID_CONFIG_KEYS{$k};
2810                }
2811        }
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.
2828sub _validate_element_spec {
2829
9
16
        my ($element, $param, $allow_keys) = @_;
2830
2831
9
9
        return unless defined($element);
2832
9
9
        if(!ref($element)) {
2833
0
0
                croak("Invalid element type '$element' for '$param'")
2834                        unless _valid_nested_type($element);
2835
0
0
                return;
2836        }
2837
9
15
        croak("schema for parameter '$param' must be a hash or a type name")
2838                if ref($element) ne 'HASH';
2839
2840
9
20
        if($allow_keys && !exists($element->{type})) {
2841                croak("A hashref schema for '$param' with fixed keys needs at least one key")
2842
1
1
5
3
                        unless keys %{$element};
2843
1
1
4
6
                foreach my $key (sort keys %{$element}) {
2844
2
2
                        my $value = $element->{$key};
2845
2
6
                        if(!ref($value)) {
2846
1
5
                                croak("Invalid element type '$value' for '$param.$key'")
2847                                        unless _valid_nested_type($value);
2848
1
3
                                next;
2849                        }
2850
1
3
                        croak("Element schema for '$param.$key' must be a hash")
2851                                unless ref($value) eq 'HASH';
2852
1
24
                        _validate_element_spec($value, "$param.$key", 0);
2853                }
2854
1
2
                return;
2855        }
2856
2857        croak("Missing type in the element schema for '$param'")
2858
8
20
                unless defined($element->{type});
2859        croak("Invalid element type '$element->{type}' for '$param'")
2860
8
23
                unless !ref($element->{type}) && _valid_nested_type($element->{type});
2861        croak("Object element schema for '$param' needs 'isa' or 'can'")
2862
7
30
                if(($element->{type} eq 'object') && !defined($element->{isa}) && !defined($element->{can}));
2863
2864
6
24
        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
1
10
                _validate_element_spec($element->{schema}, $param, 1) if defined($element->{schema});
2868        } elsif($element->{type} eq 'hashref') {
2869
0
0
                _validate_element_spec($element->{schema}, $param, 1) if defined($element->{schema});
2870        }
2871}
2872
2873sub _valid_nested_type {
2874
9
11
        my ($type) = @_;
2875
2876
9
20
        return 0 unless defined($type) && !ref($type);
2877
9
28
        return 1 if($type eq 'array') || ($type eq 'coderef');
2878
9
16
        return _valid_type($type);
2879}
2880
2881sub _validate_input_params {
2882
189
4639
        my $schema = $_[0];
2883
2884
189
189
164
659
        for my $param (keys %{$schema->{input}}) {
2885                # Catch empty parameter names — these would produce
2886                # broken Perl variable names in the generated test
2887
206
498
                croak 'Empty input parameter name'
2888                        unless length($param);
2889
2890
205
294
                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
205
566
                if(ref($spec) eq 'HASH' && defined($spec->{sample_max})) {
2895                        croak("sample_max for parameter '$param' must be a non-negative number")
2896
3
8
                                unless !ref($spec->{sample_max}) && ($spec->{sample_max} =~ /\A\d+(?:\.\d+)?\z/);
2897                        croak("sample_max for parameter '$param' is above max")
2898
3
9
                                if defined($spec->{max}) && ($spec->{sample_max} > $spec->{max});
2899                        croak("sample_max for parameter '$param' is below min")
2900
2
7
                                if defined($spec->{min}) && ($spec->{sample_max} < $spec->{min});
2901                }
2902
2903                # Validate the type field — required for all parameters
2904
203
264
                if(ref($spec)) {
2905                        croak("Missing type for parameter '$param'")
2906
150
317
                                unless defined $spec->{type};
2907                        # 'coderef' is a SchemaExtractor-specific type, not one of the
2908                        # schema's value types: the harness satisfies it with a no-op
2909                        # coderef rather than generating values for it.
2910
149
220
                        next if $spec->{type} eq 'coderef';
2911                        croak("Invalid type '$spec->{type}' for parameter '$param'")
2912
149
342
                                unless _valid_type($spec->{type});
2913
2914
147
568
                        if(($spec->{type} eq 'arrayref') || ($spec->{type} eq 'array')) {
2915
12
33
                                _validate_element_spec($spec->{schema}, $param, 1) if defined($spec->{schema});
2916                        } elsif($spec->{type} eq 'hashref') {
2917
3
19
                                _validate_element_spec($spec->{schema}, $param, 1) if defined($spec->{schema});
2918                        }
2919                } else {
2920
53
73
                        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# --------------------------------------------------
2941sub _validate_input_positions {
2942
190
6588
        my $schema = $_[0];
2943
2944
190
168
        my $has_positions = 0;
2945
190
151
        my %positions;
2946
2947
190
190
180
299
        for my $param (keys %{$schema->{input}}) {
2948
215
204
                my $spec = $schema->{input}{$param};
2949
2950                # Only process params that explicitly declare a position
2951
215
502
                next unless ref($spec) eq 'HASH' && defined($spec->{position});
2952
2953
121
101
                $has_positions = 1;
2954
121
121
                my $pos = $spec->{position};
2955
2956                # Position must be a non-negative integer
2957
121
350
                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'"
2962
120
160
                        if exists $positions{$pos};
2963
2964
118
178
                $positions{$pos} = $param;
2965        }
2966
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
187
256
        if($has_positions) {
2972
103
103
92
150
                for my $param (keys %{$schema->{input}}) {
2973
121
117
                        my $spec = $schema->{input}{$param};
2974
121
322
                        next if(ref($spec) eq 'HASH' && defined($spec->{position}));
2975                        croak "Parameter '$param' missing position " .
2976                                '(give it one, or named: 1 for a trailing named option)'
2977
5
19
                                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
2982
101
17
219
24
                my @sorted = sort { $a <=> $b } keys %positions;
2983
101
182
                for my $i (0 .. $#sorted) {
2984
114
214
                        if($sorted[$i] != $i) {
2985
1
3
                                carp "Position sequence has gaps (positions: @sorted)";
2986
1
97
                                last;
2987                        }
2988                }
2989        }
2990}
2991
2992# --------------------------------------------------
2993# _validate_input_semantics
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.
3000#
3001# Exit:       Returns nothing. Croaks on conflicting
3002#             or malformed enum/memberof. Carps on
3003#             unknown semantic types.
3004# --------------------------------------------------
3005sub _validate_input_semantics {
3006
191
8829
        my $schema = $_[0];
3007
3008
191
444
        my $semantic_generators = _get_semantic_generators();
3009
3010
191
191
189
298
        for my $param (keys %{$schema->{input}}) {
3011
207
209
                my $spec = $schema->{input}{$param};
3012
207
461
                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
153
213
                if(defined($spec->{semantic})) {
3017
7
5
                        my $semantic = $spec->{semantic};
3018
7
9
                        unless(exists $semantic_generators->{$semantic}) {
3019                                carp "Unknown semantic type '$semantic' for parameter '$param'. " .
3020                                        'Available types: ' .
3021
2
2
4
16
                                        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
153
409
                if($spec->{'enum'} && $spec->{'memberof'}) {
3028
2
7
                        croak "$param: has both enum and memberof";
3029                }
3030
3031                # Both enum and memberof must be arrayrefs when present
3032
151
155
                for my $type ('enum', 'memberof') {
3033
301
670
                        if(exists $spec->{$type}) {
3034                                croak "$type must be an arrayref"
3035
11
40
                                        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# --------------------------------------------------
3055sub _validate_transform_properties {
3056
19
5657
        my $schema = $_[0];
3057
3058
19
29
        my $builtin_props = _get_builtin_properties();
3059
3060
19
19
13
129
        for my $transform_name (keys %{$schema->{transforms}}) {
3061
17
16
                my $transform = $schema->{transforms}{$transform_name};
3062
3063                # properties is optional — skip transforms that don't define it
3064
17
117
                next unless exists $transform->{properties};
3065
3066                croak "Transform '$transform_name': properties must be an array"
3067
6
9
                        unless ref($transform->{properties}) eq 'ARRAY';
3068
3069
5
5
1
6
                for my $prop (@{$transform->{properties}}) {
3070
5
6
                        if(!ref($prop)) {
3071                                # Plain string — must be a known builtin property name
3072
2
11
                                unless(exists $builtin_props->{$prop}) {
3073                                        carp "Transform '$transform_name': unknown built-in property '$prop'. " .
3074                                                'Available: ' .
3075
1
1
2
18
                                                join(', ', sort keys %{$builtin_props});
3076                                }
3077                        } elsif(ref($prop) eq 'HASH') {
3078                                # Custom property — must have both name and code fields
3079
2
11
                                unless($prop->{name} && $prop->{code}) {
3080
1
4
                                        croak "Transform '$transform_name': " .
3081                                                "custom properties must have 'name' and 'code' fields";
3082                                }
3083                        } else {
3084
1
4
                                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# --------------------------------------------------
3117sub _normalize_config {
3118
198
8954
        my $config = $_[0];
3119
3120
198
530
        for my $field (keys %VALID_CONFIG_KEYS) {
3121                # Non-boolean fields are handled separately
3122
2574
5711
                next if $field eq $CONFIG_PROPERTIES_KEY;
3123
2376
3669
                next if $field eq 'timeout';    # numeric, not boolean; absence means use generated-test default
3124
3125
2178
1993
                if(exists($config->{$field}) && defined($config->{$field})) {
3126                        # Convert string boolean representations to integers
3127                        # using the lookup table from Readonly::Values::Boolean
3128
1326
1336
                        if(defined(my $b = $Readonly::Values::Boolean::booleans{$config->{$field}})) {
3129
1326
3016
                                $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
852
606
                        $config->{$field} = 1;
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
198
349
        $config->{$CONFIG_PROPERTIES_KEY} = { enable => 0 } unless ref($config->{$CONFIG_PROPERTIES_KEY}) eq 'HASH';
3142}
3143
3144# --------------------------------------------------
3145# _valid_type
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#
3163#             'int' and 'bool' are accepted as
3164#             aliases for 'integer' and 'boolean'
3165#             respectively, for compatibility with
3166#             schemas generated by external tools
3167#             that use the shorter forms.
3168# --------------------------------------------------
3169sub _valid_type {
3170
272
12778
        my $type = $_[0];
3171
3172        # Undef is never a valid type
3173
272
288
        return 0 unless defined($type);
3174
3175        # Build the lookup table once and cache it for
3176        # the lifetime of the process via 'state'
3177
269
814
281
856
        state %VALID = map { $_ => 1 } qw(
3178                string boolean integer number float
3179                hashref arrayref object int bool any
3180        );
3181
3182
269
678
        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
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# --------------------------------------------------
3211sub _assert_identifier {
3212
357
9679
        my ($name, $what, %opts) = @_;
3213
3214
357
620
        croak(__PACKAGE__, ": $what is missing or empty")
3215                unless defined($name) && length($name);
3216
3217        my $re = $opts{package}
3218
355
575
                ? qr/^[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/
3219                : qr/^[A-Za-z_]\w*\z/;
3220
3221
355
1081
        croak(__PACKAGE__, ": $what '$name' is not a valid Perl identifier")
3222                unless $name =~ $re;
3223
3224
345
329
        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
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#
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# --------------------------------------------------
3274sub _validate_module {
3275
139
5719
        my ($module, $schema_file) = @_;
3276
3277        # Builtin functions have no module to validate
3278
139
208
        return 1 unless $module;
3279
3280        # Check whether the module is findable in @INC
3281
137
471
        my $mod_info = check_install(module => $module);
3282
3283
137
91275
        if($schema_file && !$mod_info) {
3284                # Non-fatal — emit a single consolidated warning so
3285                # the caller sees one message rather than four
3286
21
422
                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
21
2732
                return 0;
3293        }
3294
3295        # Check once and reuse — avoids evaluating two env vars twice
3296
116
277
        my $verbose = $ENV{$ENV_TEST_VERBOSE} || $ENV{$ENV_GENERATOR_VERBOSE};
3297
3298
116
785
        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
0
0
                if($mod_info) {
3305                        carp "Found module '$module' at: " .
3306                                ($mod_info->{'file'} // 'an unknown location') .
3307
0
0
                                ' (version ' . ($mod_info->{'version'} || 'unknown') . ')';
3308                } else {
3309
0
0
                        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
116
187
        if($ENV{$ENV_VALIDATE_LOAD}) {
3319
1
6
                my $loaded = can_load(modules => { $module => undef }, verbose => 0);
3320
3321
1
4314
                if(!$loaded) {
3322
0
0
                        my $err = $Module::Load::Conditional::ERROR || 'unknown error';
3323
0
0
                        carp(
3324                                "Module '$module' found but failed to load: $err\n" .
3325                                '  This might indicate a broken installation or missing dependencies.'
3326                        );
3327
0
0
                        return 0;
3328                }
3329
3330
1
1
                if($verbose) {
3331
0
0
                        carp "Successfully loaded module '$module'";
3332                }
3333        }
3334
3335
116
424
        return 1;
3336}
3337
3338 - 3386
=head2 render_fallback

Render any Perl value into a compact Perl source-code string using
L<Data::Dumper>. Used as a catch-all when no more specific renderer
applies.

    my $code = render_fallback({ key => 'value' });
    # returns: "{'key' => 'value'}"

=head3 Arguments

=over 4

=item * C<$v>

Any Perl value, including undef, scalars, refs, and blessed objects.

=back

=head3 Returns

A string of Perl source code that reproduces the value when evaluated.
Returns the string C<'undef'> when C<$v> is undef.

=head3 Side effects

Temporarily sets C<$Data::Dumper::Terse> and C<$Data::Dumper::Indent>
to produce compact single-line output. Both are restored on return via
C<local>.

=head3 Notes

The output is always a single line with no trailing newline. Suitable
for embedding in generated test code where readability is secondary to
correctness.

=head3 API SPECIFICATION

=head4 input

    { v => { type => 'any', optional => 1 } }

=head4 output

    { type => 'string' }

The mathematical description is in L</FORMAL SPECIFICATION>.

=cut
3387
3388sub render_fallback {
3389
43
5825
        my $v = $_[0];
3390
3391        # Handle undef explicitly rather than letting Dumper produce
3392        # 'undef' without the localised settings applied
3393
43
46
        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
31
41
        local $Data::Dumper::Terse  = 1;
3398
31
41
        local $Data::Dumper::Indent = 0;
3399
3400
31
103
        my $s = Dumper($v);
3401
3402        # Remove trailing newline that Dumper always appends
3403
31
1104
        chomp $s;
3404
31
54
        return $s;
3405}
3406
3407 - 3459
=head2 render_hash

Render a two-level hashref (parameter name => spec hashref) into Perl
source code suitable for embedding in a generated test file as the
input specification passed to L<Params::Validate::Strict>.

    my $code = render_hash(\%input);

=head3 Arguments

=over 4

=item * C<$href>

A hashref whose values are themselves hashrefs containing field
specifications. A scalar value that is a recognised type string (see
C<_valid_type>) is expanded to C<{ type =E<gt> $value }>. Any other
non-hashref value is skipped with a warning.

=back

=head3 Returns

A string of comma-separated Perl source-code lines, one per key, of
the form:

    'key' => { subkey => value, ... }

Returns an empty string if C<$href> is undef, empty, or not a hashref.

=head3 Notes

The C<matches> and C<nomatch> sub-keys are treated specially - their
values are compiled to C<Regexp> objects via C<eval { qr/.../ }> and
then rendered using C<perl_quote> so they appear as C<qr{...}> in the
generated test. This prevents unmatched bracket characters in the
pattern from causing compilation failures.

Other sub-keys are rendered via C<perl_quote>.

=head3 API SPECIFICATION

=head4 input

    { href => { type => 'any', optional => 1 } }

=head4 output

    { type => 'string' }

The mathematical description is in L</FORMAL SPECIFICATION>.

=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.
3463sub _render_nested_hash {
3464
46
55
        my ($href) = @_;
3465
3466
46
36
        my @pairs;
3467
46
46
44
65
        foreach my $key (sort keys %{$href}) {
3468
73
63
                my $value = $href->{$key};
3469
73
76
                next unless defined $value;
3470
73
89
                push @pairs, perl_quote($key) . ' => ' . (ref($value) eq 'HASH'
3471                        ? _render_nested_hash($value)
3472                        : perl_quote($value));
3473        }
3474
3475
46
111
        return '{ ' . join(', ', @pairs) . ' }';
3476}
3477
3478sub render_hash {
3479
154
13933
        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
154
432
        return '' unless $href && ref($href) eq 'HASH';
3484
3485
149
121
        my @lines;
3486
3487
149
149
134
264
        for my $k (sort keys %{$href}) {
3488
150
139
                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
150
392
                unless(defined($def) && ref($def) eq 'HASH') {
3494
6
23
                        if(defined($def) && !ref($def) && _valid_type($def)) {
3495                                # Expand scalar type shorthand to a full spec hashref
3496
4
5
                                $def = { type => $def };
3497                        } else {
3498
2
19
                                carp "render_hash: skipping key '$k' — value is not a hashref or recognised type string";
3499
2
196
                                next;
3500                        }
3501                }
3502
3503
148
109
                my @pairs;
3504
3505
148
148
140
266
                for my $subk (sort keys %{$def}) {
3506                        # Skip undef sub-values — they contribute nothing to the spec
3507
565
492
                        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
564
398
                        if(ref($def->{$subk})) {
3513
56
234
                                unless((ref($def->{$subk}) eq 'ARRAY') ||
3514                                       (ref($def->{$subk}) eq 'Regexp') ||
3515                                       (ref($def->{$subk}) eq 'HASH')) {
3516                                        croak(
3517                                                __PACKAGE__,
3518                                                ": $subk is a nested element, not yet supported (",
3519
0
0
                                                ref($def->{$subk}), ')'
3520                                        );
3521                                }
3522                        }
3523
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
564
538
                        if(($subk eq $KEY_MATCHES) || ($subk eq $KEY_NOMATCH)) {
3528                                my $re = ref($def->{$subk}) eq 'Regexp'
3529                                        ? $def->{$subk}
3530
14
9
51
82
                                        : eval { qr/$def->{$subk}/ };
3531
14
54
                                if($@ || !defined($re)) {
3532
0
0
                                        carp "render_hash: invalid $subk pattern '$def->{$subk}': $@";
3533
0
0
                                        next;
3534                                }
3535
14
30
                                push @pairs, "$subk => " . perl_quote($re);
3536                        } elsif(ref($def->{$subk}) eq 'HASH') {
3537
44
323
                                push @pairs, "$subk => " . _render_nested_hash($def->{$subk});
3538                        } else {
3539                                # All other sub-keys are rendered via perl_quote which
3540                                # handles scalars, arrayrefs, and Regexp objects correctly
3541
506
1923
                                push @pairs, "$subk => " . perl_quote($def->{$subk});
3542                        }
3543                }
3544
3545                # Use "\t" rather than a literal tab for clarity and grep-ability
3546
148
201
                push @lines, "\t" . perl_quote($k) . ' => { ' . join(', ', @pairs) . ' }';
3547        }
3548
3549
149
245
        return join(",\n", @lines);
3550}
3551
3552 - 3596
=head2 render_args_hash

Render a flat hashref into a Perl source-code argument list of the
form C<'key' => value, ...>, suitable for embedding in a function call
in a generated test file.

    my $code = render_args_hash({ type => 'string', min => 1 });
    # returns: "'min' => 1, 'type' => 'string'"

=head3 Arguments

=over 4

=item * C<$href>

A flat hashref of key-value pairs. Values may be scalars, arrayrefs,
or Regexp objects - all are handled by C<perl_quote>.

=back

=head3 Returns

A comma-separated string of C<key => value> pairs sorted by key.
Returns an empty string if C<$href> is undef, empty, or not a hashref.

=head3 Notes

Keys and values are both rendered via C<perl_quote>. In particular,
C<Regexp> values are rendered as C<qr{...}> which is correct for
L<Params::Validate::Strict> and L<Return::Set> schema arguments in
the generated test.

=head3 API SPECIFICATION

=head4 input

    { href => { type => 'any', optional => 1 } }

=head4 output

    { type => 'string' }

The mathematical description is in L</FORMAL SPECIFICATION>.

=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# --------------------------------------------------
3610sub _render_arg_value
3611{
3612
246
233
        my ($value) = @_;
3613
3614
246
413
        if(ref($value) eq 'HASH' && ($value->{'_path'} // '') =~ /^(?:file|directory)$/) {
3615                return '(do { require File::Temp; File::Temp::tempdir(CLEANUP => 1) })'
3616
1
4
                        if $value->{'_path'} eq 'directory';
3617
0
0
                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
245
247
        if(ref($value) eq 'ARRAY') {
3623
1
3
1
1
2
1
                return '[ ' . join(', ', map { _render_arg_value($_) } @{$value}) . ' ]';
3624        }
3625
3626
244
367
        if(ref($value) eq 'HASH' && ref($value->{'_stub'}) eq 'HASH') {
3627
0
0
                return '_build_stub_object(' . _render_stub_spec($value->{'_stub'}) . ')';
3628        }
3629
3630
244
241
        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.
3635sub _render_stub_spec
3636{
3637
0
0
        my ($spec) = @_;
3638
3639        my @methods = map {
3640
0
0
                perl_quote($_) . ' => ' . perl_quote($spec->{methods}{$_})
3641
0
0
0
0
        } sort keys %{ $spec->{methods} // {} };
3642
3643        return '{ isa => ' . perl_quote($spec->{isa})
3644
0
0
                . ', methods => { ' . join(', ', @methods) . ' } }';
3645}
3646
3647sub render_args_hash {
3648
238
10844
        my $href = $_[0];
3649
3650        # Return empty string for absent or non-hash input
3651
238
493
        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
243
240
                perl_quote($_) . ' => ' . _render_arg_value($href->{$_})
3657
234
234
172
243
        } sort keys %{$href};
3658
3659
234
351
        return join(', ', @pairs);
3660}
3661
3662 - 3707
=head2 render_arrayref_map

Render a hashref whose values are arrayrefs into a Perl source-code
fragment suitable for use as a hash literal in a generated test file.

    my $code = render_arrayref_map({ name => ['', 'a' x 100] });

=head3 Arguments

=over 4

=item * C<$href>

A hashref whose values are arrayrefs. Keys whose values are not
arrayrefs are silently skipped.

=back

=head3 Returns

A comma-separated string of C<'key' => [ val, ... ]> entries, one per
qualifying key, sorted alphabetically. Returns the string C<'()'> if
C<$href> is undef or not a hashref - this produces an empty
hash assignment in the generated test rather than a syntax error.
Returns an empty string if C<$href> is a hashref with no arrayref values.

=head3 Notes

Array element values are rendered via C<perl_quote> which handles
scalars, arrayrefs, and Regexp objects. Non-arrayref values are
skipped without warning - this is intentional since callers may pass
mixed-value hashes and only want the arrayref entries rendered.

=head3 API SPECIFICATION

=head4 input

    { href => { type => 'any', optional => 1 } }

=head4 output

    { type => 'string' }

The mathematical description is in L</FORMAL SPECIFICATION>.

=cut
3708
3709sub render_arrayref_map {
3710
383
10346
        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
383
665
        return '()' unless $href && ref($href) eq 'HASH';
3715
3716
380
212
        my @entries;
3717
3718
380
380
261
425
        for my $k (sort keys %{$href}) {
3719
10
8
                my $aref = $href->{$k};
3720
3721                # Skip non-arrayref values — mixed hashes are allowed by callers
3722
10
10
                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
7
12
7
8
11
4
                my $vals = join(', ', map { perl_quote($_) } @{$aref});
3727
3728                # Use "\t" rather than a literal tab for clarity
3729
7
7
                push @entries, "\t" . perl_quote($k) . " => [ $vals ]";
3730        }
3731
3732
380
478
        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# --------------------------------------------------
3755sub _has_positions {
3756
209
9743
        my $input_spec = $_[0];
3757
3758        # Guard against undef or non-hash input — keys %$undef would throw
3759
209
449
        return 0 unless defined($input_spec) && ref($input_spec) eq 'HASH';
3760
3761
205
205
143
243
        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
197
268
                next unless ref($input_spec->{$field}) eq 'HASH';
3765
3766                # Return immediately on first match — no need to scan further
3767
144
234
                return 1 if defined $input_spec->{$field}{position};
3768        }
3769
3770        # No positional arguments found in any field
3771
96
90
        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# --------------------------------------------------
3796sub q_wrap {
3797
118
15106
        my $s = $_[0];
3798
3799
118
88
        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
118
85
        return "''" unless defined $s;
3809
3810        # Try bracket-form q{} delimiters first — most readable
3811
115
153
        for my $p (@Q_BRACKET_PAIRS) {
3812
132
132
326
113
                my ($l, $r) = @{$p};
3813
3814                # Only use this bracket pair if neither bracket
3815                # appears in the string — both must be checked
3816
132
1349
                return "q$l$s$r" unless $s =~ /\Q$l\E|\Q$r\E/;
3817        }
3818
3819        # Try single-character delimiters in preference order
3820
4
9
        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
26
98
                return "q$d$s$d" if index($s, $d) == $INDEX_NOT_FOUND;
3825        }
3826
3827        # Last resort — single-quoted string with escaped apostrophes
3828
2
12
        (my $esc = $s) =~ s/'/\\'/g;
3829
2
4
        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# --------------------------------------------------
3856sub perl_sq {
3857
1020
170937
        my $s = $_[0];
3858
3859
1020
728
        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
1020
634
        return '' unless defined $s;
3864
3865        # Escape backslashes first so later substitutions
3866        # don't double-escape already-escaped sequences
3867
1018
674
        $s =~ s/\\/\\\\/g;
3868
3869        # Escape apostrophes so they don't terminate the
3870        # surrounding single-quoted string literal
3871
1018
537
        $s =~ s/'/\\'/g;
3872
3873        # Escape common control characters to their
3874        # printable two-character escape sequences
3875
1018
536
        $s =~ s/\n/\\n/g;
3876
1018
529
        $s =~ s/\r/\\r/g;
3877
1018
523
        $s =~ s/\t/\\t/g;
3878
1018
554
        $s =~ s/\f/\\f/g;
3879
3880        # Replace NUL bytes with \0 — valid only in
3881        # double-quoted string context in generated code
3882
1018
483
        $s =~ s/\0/\\0/g;
3883
3884
1018
1767
        return $s;
3885}
3886
3887 - 3919
=head2 perl_quote

Convert any Perl value into a source-code fragment that reproduces that value
when evaluated in a generated test file.

=head3 Arguments

=over 4

=item * C<$v>

Any Perl value. May be undef, a scalar, an arrayref, a Regexp, or a blessed
object. All types are handled - undef becomes C<'undef'>, the strings
C<'true'>/C<'false'> become the Perl boolean constants C<!!1>/C<!!0>,
numbers are unquoted, other strings are single-quoted, arrayrefs recurse,
Regexps become C<qr{...}>, and anything else (including hashrefs and
blessed objects) falls through to C<render_fallback>.

=back

=head3 API SPECIFICATION

=head4 input

    { v => { type => 'any', optional => 1 } }

=head4 output

    { type => 'string' }

The mathematical description is in L</FORMAL SPECIFICATION>.

=cut
3920
3921sub perl_quote {
3922
1398
206705
        my ($v) = @_;
3923
1398
930
        return _perl_quote($v, 0);
3924}
3925
3926sub _perl_quote {
3927
1535
912
        my ($v, $depth) = @_;
3928
83
83
83
179253
68
136958
        no warnings 'recursion';    ## no critic (TestingAndDebugging::ProhibitNoWarnings)
3929
1535
979
        croak('perl_quote: structure too deeply nested (circular reference?)') if $depth > 100;
3930
3931        # Undef produces the Perl literal 'undef'
3932
1534
979
        return 'undef' unless defined $v;
3933
3934        # Convert YAML boolean string literals to Perl
3935        # boolean constants so they survive round-tripping
3936
1529
923
        return '!!1' if $v eq 'true';
3937
1526
950
        return '!!0' if $v eq 'false';
3938
3939
1523
902
        if(ref($v)) {
3940                # Recursively quote each element of an arrayref
3941
161
143
                if(ref($v) eq 'ARRAY') {
3942
117
137
117
40
146
81
                        my @quoted_v = map { _perl_quote($_, $depth + 1) } @{$v};
3943
16
36
                        return '[ ' . join(', ', @quoted_v) . ' ]';
3944                }
3945
3946                # Render Regexp objects as qr{} with modifiers
3947
44
55
                if(ref($v) eq 'Regexp') {
3948
23
68
                        my ($pat, $mods) = regexp_pattern($v);
3949
23
21
                        my $re = "qr{$pat}";
3950
3951                        # Append modifiers (e.g. 'i', 'x') if present
3952
23
28
                        $re .= $mods if $mods;
3953
23
42
                        return $re;
3954                }
3955
3956                # Hashrefs and other reference types fall through
3957                # to render_fallback which uses Data::Dumper
3958
21
27
                return render_fallback($v);
3959        }
3960
3961        # Numeric values are emitted unquoted so the generated
3962        # test performs numeric rather than string comparison
3963
1362
1711
        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# --------------------------------------------------
4015sub _generate_transform_properties {
4016
11
7003
        my ($transforms, $function, $module, $input, $config, $new) = @_;
4017
4018
11
7
        my @properties;
4019
4020
11
11
8
12
        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
13
13
                _assert_identifier($transform_name, 'transform name');
4026
4027
12
9
                my $transform   = $transforms->{$transform_name};
4028
4029
12
6
                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
12
19
                if(!defined($input_spec) ||
4035                   (!ref($input_spec) && $input_spec eq 'undef')) {
4036
2
2
                        next;
4037                }
4038
4039                # Guard: skip transforms whose input is not a hashref —
4040                # must come before the helper calls below so we never
4041                # pass a non-hash to _detect_transform_properties or
4042                # _process_custom_properties
4043
10
11
                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
9
12
                my $output_spec = $transform->{output} // {};
4048
4049                # Detect automatic properties from the transform spec
4050                # (range constraints, type preservation, definedness)
4051
9
13
                my @detected_props = _detect_transform_properties(
4052                        $transform_name,
4053                        $input_spec,
4054                        $output_spec
4055                );
4056
4057                # Process any custom properties defined in the schema
4058
9
7
                my @custom_props = ();
4059
9
10
                if(exists($transform->{properties}) &&
4060                   ref($transform->{properties}) eq 'ARRAY') {
4061                        @custom_props = _process_custom_properties(
4062                                $transform->{properties},
4063
0
0
                                $function,
4064                                $module,
4065                                $input_spec,
4066                                $output_spec,
4067                                $new
4068                        );
4069                }
4070
4071                # Combine auto-detected and custom properties into one list
4072
9
9
                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
9
9
                next unless @all_props;
4077
4078                # Build the LectroTest generator specification string,
4079                # one entry per input field that has a generator
4080
9
8
                my @generators;
4081                my @var_names;
4082
4083
9
9
5
10
                for my $field (sort keys %{$input_spec}) {
4084
9
5
                        my $spec = $input_spec->{$field};
4085
4086                        # Skip non-hashref field specs — scalar types
4087                        # like 'string' have no generator sub-structure
4088
9
8
                        next unless ref($spec) eq 'HASH';
4089
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
9
8
                        _assert_identifier($field, 'input field name');
4095
4096
9
9
                        my $gen = _schema_to_lectrotest_generator($field, $spec);
4097
9
29
                        if(defined($gen) && length($gen)) {
4098
9
5
                                push @generators, $gen;
4099
9
9
                                push @var_names, $field;
4100                        }
4101                }
4102
4103
9
12
                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
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
9
5
                my $call_code;
4112
9
20
                if($module && defined($new)) {
4113                        # OO mode — construct a fresh object for each trial
4114
1
1
                        $call_code  = "my \$obj = new_ok('$module');";
4115
1
1
                        $call_code .= "\$obj->$function";
4116                } elsif($module && $module ne $MODULE_BUILTIN) {
4117                        # Functional mode with a named module
4118
0
0
                        $call_code = "$module\::$function";
4119                } else {
4120                        # Builtin or unqualified function call
4121
8
5
                        $call_code = $function;
4122                }
4123
4124                # Build the argument list, respecting positional order
4125                # if the input spec declares positions
4126
9
5
                my @args;
4127
9
11
                if(_has_positions($input_spec)) {
4128                        # Sort fields by declared position so the generated
4129                        # call passes arguments in the correct order, then pass
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
9
0
9
9
9
0
9
5
                        } grep { defined $input_spec->{$_}{position} } keys %{$input_spec};
4135
9
9
10
10
                        my @named = grep { !defined $input_spec->{$_}{position} } @var_names;
4136
9
9
0
9
14
0
                        @args = (map { "\$$_" } @sorted, map { "'$_' => \$$_" } @named);
4137                } else {
4138                        # No positions — use alphabetical order from @var_names
4139
0
0
0
0
                        @args = map { "\$$_" } @var_names;
4140                }
4141
4142
9
9
                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
9
29
8
19
                my @checks = map { $_->{code} } @all_props;
4148
9
12
                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
9
20
                my $should_die  = ($output_spec->{'_STATUS'} // '') eq 'DIES';
4153
9
8
                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
9
34
                        trials           => $config->{'properties'}{'trials'} // $DEFAULT_PROPERTY_TRIALS,
4163                };
4164        }
4165
4166
10
12
        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# --------------------------------------------------
4194sub _get_semantic_generators {
4195        return {
4196
197
8405
                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);
4202
4203                                        for(my $i = 0; $i < $len; $i++) {
4204                                                push @addr, pack('c', (int(rand 26))+97);
4205                                        }
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);
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))];
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                                }
4230                        },
4231                        description => 'Valid HTTP/HTTPS URLs',
4232                }, uuid => {
4233                        code => q{
4234                                Gen {
4235                                        require UUID::Tiny;
4236                                        UUID::Tiny::create_uuid_as_string(UUID::Tiny::UUID_V4());
4237                                }
4238                        },
4239                        description => 'Valid UUIDv4 identifiers',
4240                }, phone_us => {
4241                        code => q{
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                        },
4249                        description => 'US phone numbers (XXX-XXX-XXXX format)',
4250                }, phone_e164 => {
4251                        code => q{
4252                                Gen {
4253                                        my $country = 1 + int(rand(999));
4254                                        my $area = 100 + int(rand(900));
4255                                        my $number = int(rand(10000000));
4256                                        sprintf('+%d%03d%07d', $country, $area, $number);
4257                                }
4258                        },
4259                        description => 'E.164 international phone numbers',
4260                }, ipv4 => {
4261                        code => q{
4262                                Gen {
4263                                        join('.', map { int(rand(256)) } 1..4);
4264                                }
4265                        },
4266                        description => 'IPv4 addresses',
4267                }, ipv6 => {
4268                        code => q{
4269                                Gen {
4270                                        join(':', map { sprintf('%04x', int(rand(0x10000))) } 1..8);
4271                                }
4272                        },
4273                        description => 'IPv6 addresses',
4274                }, username => {
4275                        code => q{
4276                                Gen {
4277                                        my $len = 3 + int(rand(13));
4278                                        my @chars = ('a'..'z', '0'..'9', '_', '-');
4279                                        my $first = ('a'..'z')[int(rand(26))];
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{
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                        },
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                        },
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));
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));
4316                                        my $day = 1 + int(rand(28));
4317                                        my $hour = int(rand(24));
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                                }
4323                        },
4324                        description => 'ISO 8601 datetime format (YYYY-MM-DDTHH:MM:SSZ)',
4325                }, semver => {
4326                        code => q{
4327                                Gen {
4328                                        my $major = int(rand(10));
4329                                        my $minor = int(rand(20));
4330                                        my $patch = int(rand(50));
4331                                        "$major.$minor.$patch";
4332                                }
4333                        },
4334                        description => 'Semantic version strings (major.minor.patch)',
4335                }, jwt => {
4336                        code => q{
4337                                Gen {
4338                                        my @chars = ('A'..'Z', 'a'..'z', '0'..'9', '-', '_');
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                        },
4345                        description => 'JWT-like tokens (base64url format)',
4346                }, json => {
4347                        code => q{
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',
4356                }, base64 => {
4357                        code => q{
4358                                Gen {
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                        },
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# --------------------------------------------------
4460sub _get_builtin_properties {
4461        return {
4462                idempotent => {
4463                        description   => 'Function is idempotent: f(f(x)) == f(x)',
4464                        code_template => sub {
4465
2
8344
                                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
2
3
                                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
3
173
                                my ($function, $call_code, $input_vars) = @_;
4476
3
3
                                return '$result >= 0';
4477                        },
4478                        applicable_to => ['number', 'integer', 'float'],
4479                }, positive => {
4480                        description   => 'Result is always positive (> 0)',
4481                        code_template => sub {
4482
2
167
                                my ($function, $call_code, $input_vars) = @_;
4483
2
2
                                return '$result > 0';
4484                        },
4485                        applicable_to => ['number', 'integer', 'float'],
4486                }, non_empty => {
4487                        description   => 'Result is never empty',
4488                        code_template => sub {
4489
2
168
                                my ($function, $call_code, $input_vars) = @_;
4490
2
2
                                return 'length($result) > 0';
4491                        },
4492                        applicable_to => ['string'],
4493                },
4494
4495                length_preserved => {
4496                        description   => 'Output length equals input length',
4497                        code_template => sub {
4498
2
175
                                my ($function, $call_code, $input_vars) = @_;
4499
2
2
                                my $first_var = $input_vars->[0];
4500
2
2
                                return "length(\$result) == length(\$$first_var)";
4501                        },
4502                        applicable_to => ['string'],
4503                },
4504
4505                uppercase => {
4506                        description   => 'Result is all uppercase',
4507                        code_template => sub {
4508
2
170
                                my ($function, $call_code, $input_vars) = @_;
4509
2
3
                                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
2
180
                                my ($function, $call_code, $input_vars) = @_;
4518
2
10
                                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
2
168
                                my ($function, $call_code, $input_vars) = @_;
4527
2
2
                                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
2
88
                                my ($function, $call_code, $input_vars) = @_;
4536
2
2
                                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'],
4541                },
4542
4543                sorted_descending => {
4544                        description   => 'Array is sorted in descending order',
4545                        code_template => sub {
4546
2
181
                                my ($function, $call_code, $input_vars) = @_;
4547
2
3
                                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
4554                unique_elements => {
4555                        description   => 'Array has no duplicate elements',
4556                        code_template => sub {
4557
2
168
                                my ($function, $call_code, $input_vars) = @_;
4558
2
1
                                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
2
170
                                my ($function, $call_code, $input_vars) = @_;
4567
2
3
                                my $first_var = $input_vars->[0];
4568
2
3
                                return 'do { my @in  = sort keys %{$' . $first_var . '}; ' .
4569                                        'my @out = sort keys %$result; ' .
4570                                        'join(",", @in) eq join(",", @out) }';
4571                        },
4572
30
24002
                        applicable_to => ['hashref'],
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# --------------------------------------------------
4616sub _schema_to_lectrotest_generator {
4617
54
29645
        my ($field_name, $spec) = @_;
4618
4619        # Guard: must be a hashref to dereference safely
4620
54
121
        return unless defined($spec) && ref($spec) eq 'HASH';
4621
4622        # Default to string when no type is declared
4623
51
52
        my $type = $spec->{'type'} || $DEFAULT_FIELD_TYPE;
4624
4625        # --------------------------------------------------
4626        # Semantic generators take precedence for string
4627        # fields — they produce realistic domain-specific
4628        # values rather than random character sequences
4629        # --------------------------------------------------
4630
51
67
        if($type eq 'string' && defined($spec->{'semantic'})) {
4631
2
2
                my $semantic_type = $spec->{'semantic'};
4632
2
3
                my $generators    = _get_semantic_generators();
4633
4634
2
2
                if(exists($generators->{$semantic_type})) {
4635
2
4
                        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
2
4
                        $gen_code =~ s/^\s+//;
4640
2
11
                        $gen_code =~ s/\s+$//;
4641
2
6
                        $gen_code =~ s/\n\s+/ /g;
4642
4643
2
8
                        return "$field_name <- $gen_code";
4644                } else {
4645
0
0
                        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
49
40
        if($type eq 'integer') {
4655
10
11
                my $min = $spec->{'min'};
4656
10
7
                my $max = $spec->{'max'};
4657
4658
10
27
                if(!defined($min) && !defined($max)) {
4659                        # Unconstrained — use LectroTest's built-in Int
4660
4
6
                        return "$field_name <- Int";
4661                } elsif(!defined($min)) {
4662                        # Only max defined — generate 0 to max
4663
1
2
                        return "$field_name <- Int(sized => sub { int(rand($max + 1)) })";
4664                } elsif(!defined($max)) {
4665                        # Only min defined — generate min to min + range
4666
1
6
                        return "$field_name <- Int(sized => sub { $min + int(rand($DEFAULT_GENERATOR_RANGE)) })";
4667                } else {
4668                        # Both defined — generate within [min, max]
4669
4
4
                        my $range = $max - $min;
4670
4
12
                        return "$field_name <- Int(sized => sub { $min + int(rand($range + 1)) })";
4671                }
4672        }
4673
4674        # --------------------------------------------------
4675        # Float / number generator
4676        # --------------------------------------------------
4677
39
65
        if($type eq 'number' || $type eq 'float') {
4678
21
13
                my $min = $spec->{'min'};
4679
21
14
                my $max = $spec->{'max'};
4680
4681
21
44
                if(!defined($min) && !defined($max)) {
4682                        # Unconstrained — symmetric range around zero
4683
3
7
                        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
4687
7
11
                        if($max == $ZERO_BOUNDARY) {
4688                                # max=0: negative numbers only
4689
5
16
                                return "$field_name <- Float(sized => sub { -rand($DEFAULT_GENERATOR_RANGE) })";
4690                        } elsif($max > $ZERO_BOUNDARY) {
4691                                # Positive max: generate 0 to max
4692
1
5
                                return "$field_name <- Float(sized => sub { rand($max) })";
4693                        } else {
4694                                # Negative max: generate from (max - range) to max
4695
1
5
                                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
6
7
                        if($min == $ZERO_BOUNDARY) {
4701                                # min=0: positive numbers only
4702
4
12
                                return "$field_name <- Float(sized => sub { rand($DEFAULT_GENERATOR_RANGE) })";
4703                        } elsif($min > $ZERO_BOUNDARY) {
4704                                # Positive min: generate min to min + range
4705
1
4
                                return "$field_name <- Float(sized => sub { $min + rand($DEFAULT_GENERATOR_RANGE) })";
4706                        } else {
4707                                # Negative min: generate from min to min + range
4708
1
4
                                return "$field_name <- Float(sized => sub { $min + rand(-$min + $DEFAULT_GENERATOR_RANGE) })";
4709                        }
4710
4711                } else {
4712                        # Both min and max defined — validate then generate
4713
5
5
                        my $range = $max - $min;
4714
5
9
                        if($range <= $ZERO_BOUNDARY) {
4715
4
39
                                carp "Invalid range for '$field_name': min=$min, max=$max";
4716                                # Return undef rather than emitting a degenerate
4717                                # generator that would silently produce wrong values
4718
4
340
                                return;
4719                        }
4720
1
4
                        return "$field_name <- Float(sized => sub { $min + rand($range) })";
4721                }
4722        }
4723
4724        # --------------------------------------------------
4725        # String generator
4726        # --------------------------------------------------
4727
18
20
        if($type eq 'string') {
4728
10
17
                my $min_len = $spec->{'min'} // 0;
4729
10
25
                my $max_len = $spec->{'max'} // $DEFAULT_MAX_STRING_LEN;
4730
4731                # If a regex pattern is declared, delegate to
4732                # Data::Random::String::Matches for pattern-aware generation
4733
10
32
                if(defined($spec->{'matches'})) {
4734
6
5
                        my $pattern = $spec->{'matches'};
4735
4736                        # Compile the pattern safely rather than splicing the raw
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
6
3
10
25
                        my $compiled = ref($pattern) eq 'Regexp' ? $pattern : eval { qr/$pattern/ };
4744
6
15
                        if($@ || !defined($compiled)) {
4745
0
0
                                carp "Invalid matches pattern '$pattern' for field '$field_name': $@";
4746
0
0
                                return "$field_name <- String(length => [$min_len, $max_len])";
4747                        }
4748
6
15
                        my ($pat, $mods) = regexp_pattern($compiled);
4749
6
10
                        my $safe_re = "qr{$pat}" . ($mods // '');
4750
4751
6
10
                        if(defined($spec->{'max'})) {
4752
1
3
                                return "$field_name <- Gen { Data::Random::String::Matches->create_random_string({ regex => $safe_re, length => $spec->{'max'} }) }";
4753                        } elsif(defined($spec->{'min'})) {
4754
1
3
                                return "$field_name <- Gen { Data::Random::String::Matches->create_random_string({ regex => $safe_re, length => $spec->{'min'} }) }";
4755                        } else {
4756
4
8
                                return "$field_name <- Gen { Data::Random::String::Matches->create_random_string({ regex => $safe_re }) }";
4757                        }
4758                }
4759
4760
4
7
                return "$field_name <- String(length => [$min_len, $max_len])";
4761        }
4762
4763        # --------------------------------------------------
4764        # Boolean generator
4765        # --------------------------------------------------
4766
8
9
        if($type eq 'boolean') {
4767
2
3
                return "$field_name <- Bool";
4768        }
4769
4770        # --------------------------------------------------
4771        # Arrayref generator
4772        # --------------------------------------------------
4773
6
8
        if($type eq 'arrayref') {
4774
2
5
                my $min_size = $spec->{'min'} // 0;
4775
2
8
                my $max_size = $spec->{'max'} // $DEFAULT_MAX_COLLECTION_SIZE;
4776
2
8
                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
4
6
        if($type eq 'hashref') {
4785
3
7
                my $min_keys = $spec->{'min'} // 0;
4786
3
7
                my $max_keys = $spec->{'max'} // $DEFAULT_MAX_COLLECTION_SIZE;
4787
3
9
                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
1
7
        carp "Unknown type '$type' for '$field_name' LectroTest generator, using String";
4794
1
186
        return "$field_name <- String";
4795}
4796
4797# --------------------------------------------------
4798# _is_numeric_transform
4799#
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
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# --------------------------------------------------
4816sub _is_numeric_transform {
4817
37
2921
        my ($input_spec, $output_spec) = @_;
4818
4819        # $input_spec is currently unused — reserved for future
4820        # input-side type checking when detecting mixed transforms
4821
37
50
        my $out_type = ($output_spec // {})->{'type'} // '';
4822
4823
37
73
        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# --------------------------------------------------
4844sub _is_string_transform {
4845
31
2362
        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
31
37
        my $out_type = ($output_spec // {})->{'type'} // '';
4850
4851
31
35
        return($out_type eq 'string');
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.
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# --------------------------------------------------
4880sub _same_type {
4881
31
3151
        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
31
34
        my $in_type  = _get_dominant_type($input_spec  // {});
4887
31
47
        my $out_type = _get_dominant_type($output_spec // {});
4888
4889
31
44
        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# --------------------------------------------------
4912sub _get_dominant_type {
4913
93
4563
        my $spec = $_[0];
4914
4915        # Guard: return default for undef or non-hash input
4916
93
101
        return $DEFAULT_FIELD_TYPE
4917                unless defined($spec) && ref($spec) eq 'HASH';
4918
4919        # Flat spec — type declared directly
4920
91
77
        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
36
36
18
32
        for my $field (keys %{$spec}) {
4925
31
37
                next unless ref($spec->{$field}) eq 'HASH';
4926                return $spec->{$field}{'type'}
4927
29
36
                        if defined($spec->{$field}{'type'});
4928        }
4929
4930        # No type found anywhere — return the safe default
4931
8
9
        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# --------------------------------------------------
4964sub _render_properties {
4965
12
6967
        my $properties = $_[0];
4966
4967        # Return empty string for absent or non-array input —
4968        # callers treat '' as no property block to emit
4969
12
29
        return '' unless defined($properties) && ref($properties) eq 'ARRAY';
4970
9
9
7
12
        return '' unless @{$properties};
4971
4972
7
6
        my $code = "use_ok('Test::LectroTest::Compat');\n\n";
4973
4974
7
7
4
8
        for my $prop (@{$properties}) {
4975                # Emit a labelled Property block for each transform property
4976
10
10
                $code .= "# Transform property: $prop->{'name'}\n";
4977
10
11
                $code .= "my \$$prop->{'name'} = Property {\n";
4978
10
9
                $code .= "    ##[ $prop->{'generator_spec'} ]##\n";
4979
10
5
                $code .= "    \n";
4980
10
9
                $code .= "    my \$result = eval { $prop->{'call_code'} };\n";
4981
4982
10
10
                if($prop->{'should_die'}) {
4983                        # For transforms that expect death, pass if the
4984                        # eval caught an exception
4985
2
3
                        $code .= "    my \$died = defined(\$\@) && \$\@;\n";
4986
2
2
                        $code .= "    \$died;\n";
4987                } else {
4988                        # For normal transforms, pass only if no exception
4989                        # was thrown and all property checks hold
4990
8
6
                        $code .= "    my \$error = \$\@;\n";
4991
8
6
                        $code .= "    \n";
4992
8
6
                        $code .= "    !\$error && (\n";
4993
8
9
                        $code .= "        $prop->{'property_checks'}\n";
4994
8
10
                        $code .= "    );\n";
4995                }
4996
4997
10
11
                $code .= "}, name => '$prop->{'name'}', trials => $prop->{'trials'};\n\n";
4998
10
6
                $code .= "holds(\$$prop->{'name'});\n";
4999        }
5000
5001
7
11
        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# --------------------------------------------------
5038sub _detect_transform_properties {
5039
28
9765
        my ($transform_name, $input_spec, $output_spec) = @_;
5040
5041
28
20
        my @properties;
5042
5043        # Guard: skip undef input and the YAML scalar 'undef'
5044
28
23
        return @properties unless defined($input_spec);
5045
26
28
        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
24
21
        $output_spec //= {};
5050
5051        # --------------------------------------------------
5052        # Property 1: Output range constraints (numeric)
5053        # --------------------------------------------------
5054
24
20
        if(_is_numeric_transform($input_spec, $output_spec)) {
5055
15
14
                if(defined($output_spec->{'min'})) {
5056
11
11
                        my $min = $output_spec->{'min'};
5057
11
16
                        push @properties, {
5058                                name => 'min_constraint',
5059                                code => "defined(\$result) && looks_like_number(\$result) && \$result >= $min",
5060                        };
5061                }
5062
5063
15
13
                if(defined($output_spec->{'max'})) {
5064
2
2
                        my $max = $output_spec->{'max'};
5065
2
4
                        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
15
24
                if($transform_name =~ /$TRANSFORM_POSITIVE_PATTERN/i) {
5074
6
22
                        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
24
62
        if(defined($output_spec->{'value'})) {
5085
2
2
                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
2
7
                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
24
20
        if(_is_string_transform($input_spec, $output_spec)) {
5101
6
6
                if(defined($output_spec->{'min'})) {
5102
2
4
                        push @properties, {
5103                                name => 'min_length',
5104                                code => "length(\$result) >= $output_spec->{'min'}",
5105                        };
5106                }
5107
5108
6
6
                if(defined($output_spec->{'max'})) {
5109
0
0
                        push @properties, {
5110                                name => 'max_length',
5111                                code => "length(\$result) <= $output_spec->{'max'}",
5112                        };
5113                }
5114
5115
6
7
                if(defined($output_spec->{'matches'})) {
5116
0
0
                        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
0
0
0
0
                        my $compiled = ref($pattern) eq 'Regexp' ? $pattern : eval { qr/$pattern/ };
5123
0
0
                        if($@ || !defined($compiled)) {
5124
0
0
                                carp "Invalid matches pattern '$pattern' for transform '$transform_name': $@";
5125                        } else {
5126
0
0
                                my ($pat, $mods) = regexp_pattern($compiled);
5127
0
0
                                my $safe_re = "qr{$pat}" . ($mods // '');
5128
0
0
                                push @properties, {
5129                                        name => 'pattern_match',
5130                                        code => "\$result =~ $safe_re",
5131                                };
5132                        }
5133                }
5134        }
5135
5136        # --------------------------------------------------
5137        # Property 4: Type preservation
5138        # --------------------------------------------------
5139
24
20
        if(_same_type($input_spec, $output_spec)) {
5140
22
11
                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
22
47
                if($type eq 'number' || $type eq 'integer' || $type eq 'float') {
5145
15
15
                        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
24
30
        unless(($output_spec->{'type'} // '') eq 'undef') {
5159
22
18
                push @properties, {
5160                        name => 'defined',
5161                        code => 'defined($result)',
5162                };
5163        }
5164
5165
24
26
        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# --------------------------------------------------
5213sub _process_custom_properties {
5214
7
7467
        my ($properties_spec, $function, $module, $input_spec, $output_spec, $new) = @_;
5215
5216
7
6
        my @properties;
5217
7
2
        my $builtin_properties = _get_builtin_properties();
5218
5219
7
7
5
5
        for my $prop_def (@{$properties_spec}) {
5220
6
6
                my $prop_name;
5221                my $prop_code;
5222
6
0
                my $prop_desc;
5223
5224
6
6
                if(!ref($prop_def)) {
5225                        # Plain string — look up as a named builtin property
5226
2
2
                        $prop_name = $prop_def;
5227
5228
2
3
                        unless(exists($builtin_properties->{$prop_name})) {
5229
1
6
                                carp "Unknown built-in property '$prop_name', skipping";
5230
1
74
                                next;
5231                        }
5232
5233
1
1
                        my $builtin = $builtin_properties->{$prop_name};
5234
5235                        # Build the argument list, respecting positional order
5236
1
1
1
2
                        my @var_names = sort keys %{$input_spec};
5237
1
1
                        my @args;
5238
1
1
                        if(_has_positions($input_spec)) {
5239
0
0
                                my @sorted = sort { $input_spec->{$a}{'position'} <=> $input_spec->{$b}{'position'} }
5240
1
1
1
2
                                        grep { defined $input_spec->{$_}{'position'} } @var_names;
5241
1
1
1
2
                                my @named = grep { !defined $input_spec->{$_}{'position'} } @var_names;
5242
1
1
0
2
1
0
                                @args = (map { "\$$_" } @sorted, map { "'$_' => \$$_" } @named);
5243                        } else {
5244
0
0
0
0
                                @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
1
1
                        my $call_code;
5251
1
4
                        if($module && defined($new)) {
5252                                # OO mode — fresh object per trial
5253
0
0
                                $call_code  = "my \$obj = new_ok('$module');";
5254
0
0
                                $call_code .= "\$obj->$function";
5255                        } elsif($module && $module ne $MODULE_BUILTIN) {
5256                                # Functional mode with a named module
5257
0
0
                                $call_code = "$module\::$function";
5258                        } else {
5259                                # Builtin or unqualified function call
5260
1
1
                                $call_code = $function;
5261                        }
5262
1
1
                        $call_code .= '(' . join(', ', @args) . ')';
5263
5264                        # Instantiate the builtin's code template with the
5265                        # call expression and input variable list
5266
1
2
                        $prop_code = $builtin->{'code_template'}->($function, $call_code, \@var_names);
5267
1
1
                        $prop_desc = $builtin->{'description'};
5268
5269                } elsif(ref($prop_def) eq 'HASH') {
5270                        # Hashref — custom property with inline Perl code
5271
3
5
                        $prop_name = $prop_def->{'name'} || 'custom_property';
5272
3
2
                        $prop_code = $prop_def->{'code'};
5273
3
6
                        $prop_desc = $prop_def->{'description'} || "Custom property: $prop_name";
5274
5275
3
1
                        unless($prop_code) {
5276
1
4
                                carp "Custom property '$prop_name' missing 'code' field, skipping";
5277
1
69
                                next;
5278                        }
5279
5280                        # Sanity-check: code must contain at least a variable
5281                        # reference or a word character to be meaningful
5282
2
5
                        unless($prop_code =~ /\$/ || $prop_code =~ /\w+/) {
5283
0
0
                                carp "Custom property '$prop_name' code looks invalid: $prop_code";
5284
0
0
                                next;
5285                        }
5286
5287                } else {
5288                        # Neither string nor hashref — unrecognised definition type
5289
1
2
                        carp 'Invalid property definition: ', render_fallback($prop_def);
5290
1
60
                        next;
5291                }
5292
5293
3
5
                push @properties, {
5294                        name        => $prop_name,
5295                        code        => $prop_code,
5296                        description => $prop_desc,
5297                };
5298        }
5299
5300
7
63
        return @properties;
5301}
5302
5303 - 5527
=head1 NOTES

C<seed> and C<iterations> really should be within C<config>.

=head1 SEE ALSO

=over 4

=item * L<Test Dashboard|https://nigelhorne.github.io/App-Test-Generator/coverage/>

=item * L<App::Test::Generator::Template> - Template of the file of tests created by C<App::Test::Generator>

=item * L<App::Test::Generator::SchemaExtractor> - Create schemas from Perl programs

=item * L<Params::Validate::Strict>: Schema Definition

=item * L<Params::Get>: Input validation

=item * L<Return::Set>: Output validation

=item * L<Test::LectroTest>

=item * L<Test::Most>

=item * L<YAML::XS>

=back

=head1 AUTHOR

Nigel Horne, C<< <njh at nigelhorne.com> >>

Portions of this module's initial design and documentation were created with the
assistance of AI.

=head1 SUPPORT

This module is provided as-is without any warranty.

You can find documentation for this module with the perldoc command.

    perldoc App::Test::Generator

You can also look for information at:

=over 4

=item * MetaCPAN

L<https://metacpan.org/release/App-Test-Generator>

=item * GitHub

L<https://github.com/nigelhorne/App-Test-Generator>

=item * CPANTS

L<http://cpants.cpanauthors.org/dist/App-Test-Generator>

=item * CPAN Testers' Matrix

L<http://matrix.cpantesters.org/?dist=App-Test-Generator>

=item * CPAN Testers Dependencies

L<http://deps.cpantesters.org/?module=App::Test::Generator>

=back

=head1 FORMAL SPECIFICATION

This section describes the documented routines in Z notation.  It is for
readers who want an exact, mathematical statement.  You do not need it to use
the module.

How to read it: a name ending in C<?> is an input and a name ending in C<!> is
an output.  None of these routines keeps any state between calls, so there is
no state schema.  C<quote(v)> stands for the result of C<perl_quote(v)>.

=head2 generate

    â”Œâ”€ Generate ────────────────────────────────────────
    â”‚ schema_file? : STRING
    â”‚ output_file? : STRING ∪ { undef }
    â”‚ test : STRING
    â”‚ result! : BOOLEAN
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ pre   schema_file? names a readable schema
    â”‚       the schema defines function
    â”‚       every name in the schema is an identifier
    â”‚ post  test is a complete Perl test file for function
    â”‚       output_file? ≠ undef ⇒ file output_file? holds test
    â”‚       output_file? = undef ⇒ test is printed on STDOUT
    â”‚       result! = 1
    â””───────────────────────────────────────────────────

    no arguments                     â‡’ croak 'Usage: generate(...)'
    output_file? cannot be written   â‡’ croak 'Cannot open ...'

=head2 render_fallback

    â”Œâ”€ RenderFallback ──────────────────────────────────
    â”‚ v? : VALUE
    â”‚ result! : STRING
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ post  v? = undef ⇒ result! = 'undef'
    â”‚       v? ≠ undef ⇒ result! is one line of Perl source
    â”‚                     âˆ§ eval(result!) is a copy of v?
    â””───────────────────────────────────────────────────

=head2 render_hash

    â”Œâ”€ RenderHash ──────────────────────────────────────
    â”‚ href? : VALUE
    â”‚ result! : STRING
    â”‚ kept : â„™ STRING
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ post  ref(href?) ≠ 'HASH' ∨ href? = ∅ ⇒ result! = ''
    â”‚       ref(href?) = 'HASH' ⇒
    â”‚           kept = { k : dom href? | href?(k) is a hashref
    â”‚                    âˆ¨ href?(k) is a type name }
    â”‚           result! has one "'k' => { ... }" entry for each
    â”‚           k in kept, in sorted order
    â””───────────────────────────────────────────────────

=head2 render_args_hash

    â”Œâ”€ RenderArgsHash ──────────────────────────────────
    â”‚ href? : VALUE
    â”‚ result! : STRING
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ post  ref(href?) ≠ 'HASH' ∨ href? = ∅ ⇒ result! = ''
    â”‚       ref(href?) = 'HASH' ⇒
    â”‚           result! = join(', ', ⟨ k : sort(dom href?) •
    â”‚                       quote(k) . ' => ' . quote(href?(k)) ⟩)
    â””───────────────────────────────────────────────────

=head2 render_arrayref_map

    â”Œâ”€ RenderArrayrefMap ───────────────────────────────
    â”‚ href? : VALUE
    â”‚ result! : STRING
    â”‚ kept : â„™ STRING
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ post  href? is false ∨ ref(href?) ≠ 'HASH' ⇒ result! = '()'
    â”‚       ref(href?) = 'HASH' ⇒
    â”‚           kept = { k : dom href? | ref(href?(k)) = 'ARRAY' }
    â”‚           kept = ∅ ⇒ result! = ''
    â”‚           result! has one "'k' => [ ... ]" entry for each
    â”‚           k in kept, in sorted order
    â””───────────────────────────────────────────────────

=head2 perl_quote

    â”Œâ”€ PerlQuote ───────────────────────────────────────
    â”‚ v? : VALUE
    â”‚ result! : STRING
    â”œâ”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
    â”‚ pre   v? is nested no more than 100 levels deep
    â”‚ post  v? = undef            â‡’ result! = 'undef'
    â”‚       v? = 'true'           â‡’ result! = '!!1'
    â”‚       v? = 'false'          â‡’ result! = '!!0'
    â”‚       v? looks like a number ⇒ result! = v?
    â”‚       v? is any other string ⇒ result! = v? in single quotes,
    â”‚                                with ' and \ escaped
    â”‚       ref(v?) = 'ARRAY'     â‡’ result! = '[ ' . join(', ',
    â”‚                                âŸ¨ e : v? • quote(e) ⟩) . ' ]'
    â”‚       ref(v?) = 'Regexp'    â‡’ result! = 'qr{...}'
    â”‚       otherwise             â‡’ result! = render_fallback(v?)
    â””───────────────────────────────────────────────────

    nested more than 100 levels deep ⇒ croak 'structure too deeply nested'

=head1 STATE DIAGRAM

C<generate> is a class method and keeps no state.  One call runs from start
to finish through these stages, and any stage may stop it by croaking.

                +-------------+
                |    START    |
                +-------------+
                       |
                       | generate(schema_file, output_file)
                       v
                +-------------+   no arguments, file not readable
                | LOAD SCHEMA |--------------------------------------+
                +-------------+                                      |
                       |                                             |
                       | schema parsed                               |
                       v                                             |
                +-------------+   missing function, bad name,        |
                |  VALIDATE   |   contradictory input spec           |
                +-------------+--------------------------------------+
                       |                                             |
                       | schema is good                              |
                       v                                             v
                +-------------+                               +-------------+
                |   RENDER    |                               |   CROAKED   |
                +-------------+                               +-------------+
                       |                                             ^
                       | test source built                           |
                       v                                             |
                +-------------+   output_file cannot be opened       |
                |    WRITE    |--------------------------------------+
                +-------------+
                       |
                       | file written, or source printed on STDOUT
                       v
                +-------------+
                |    DONE     |
                +-------------+

Side effects: C<generate> writes C<output_file> and prints one line saying so,
or prints the test source when no output file is given.  The C<render_*>
routines and C<perl_quote> write no files and print nothing.

=head1 LICENCE AND COPYRIGHT

Copyright 2025-2026 Nigel Horne.

Usage is subject to the terms of GPL2.
If you use it,
please let me know.

=cut
5528
55291;