File Coverage

File:blib/lib/App/Test/Generator/Mutation/Feedback.pm
Coverage:78.3%

linestmtbrancondsubtimecode
1package App::Test::Generator::Mutation::Feedback;
2
3
58
58
58
237
42
475
use strict;
4
58
58
58
60
33
906
use warnings;
5
58
58
58
73
30
1073
use Carp qw(croak carp);
6
58
58
58
66
33
419
use File::Spec;
7
58
58
58
65
23
39316
use JSON::MaybeXS qw(decode_json);
8
9our $VERSION = '0.52';
10
11 - 240
=head1 NAME

App::Test::Generator::Mutation::Feedback - Turn surviving mutants into boundary
cases and schema constraints

=head1 VERSION

Version 0.52

=head1 SYNOPSIS

    use App::Test::Generator::Mutation::Feedback;

    my $feedback = App::Test::Generator::Mutation::Feedback->new(
        mutation_results => 'mutation.json',
        module           => 'My::Module',
    );

    my $applied = $feedback->apply_to_schema($schema);
    printf "added %s = %s to %s\n",
        $_->{constraint}, $_->{value}, $_->{field} for @{$applied};

=head1 DESCRIPTION

A mutation survivor is a mutant the test suite did not notice.  Until now a
survivor was only counted and printed; this module reads the survivors from
the JSON written by C<test-generator-mutate --json> and proposes concrete
inputs that would have killed them.

For a surviving numeric-boundary mutant the source line is read back and the
comparison it mutated is recovered, for example C<< $count > 10 >>.  That
comparison is then translated into a schema constraint:

    source comparison     proposed constraint
    $x >  N               min => N + 1
    $x >= N               min => N
    $x <  N               max => N - 1
    $x <= N               max => N

Integer literals only.  The constraint makes L<App::Test::Generator::Template>
generate values on both sides of the boundary, which is what the survivor
showed was missing.

Constraints are only applied to a field of the schema's C<input> section
whose name matches the variable in the source comparison, after normalising
case and punctuation.  An existing constraint is never replaced: a bound the
POD or the code already declares wins over a proposed one.

Survivors that do not describe a numeric comparison - conditional inversions,
boolean negations and so on - produce a C<manual> proposal instead of an
automatic change, because no single data value is known to distinguish them.
They are still returned by L</proposals> so a reviewer can see what survived.

Only survivors belonging to C<module>'s own file are used when C<module> is
given, so a mutation run over a whole C<lib> directory feeds only the matching
module's schema.

=head2 new

Construct a feedback object.

    my $feedback = App::Test::Generator::Mutation::Feedback->new(
        mutation_results => 'mutation.json',
        module           => 'My::Module',
        source_root      => '.',
    );

=head3 Arguments

=over 4

=item * C<mutation_results>

Required.  Either the path to a mutation results JSON file or an already
decoded hashref with the same shape.  The file must contain a C<survived>
arrayref whose entries have C<id>, C<file> and C<line> keys; entries with a
C<status> other than C<Survived> are ignored.

=item * C<module>

Optional module name, e.g. C<My::Module>.  When given, only survivors whose
C<file> names that module's file (C<My/Module.pm>) are proposed, so results
from a whole-directory mutation run can be fed to one schema safely.

=item * C<source_root>

Optional directory used to resolve the relative C<file> paths in the results.
Defaults to the current directory.

=back

=head3 Returns

A blessed hashref.  Croaks when C<mutation_results> is missing, unreadable or
not valid JSON, and when no module file can be matched but C<module> is set.

=head3 API SPECIFICATION

=head4 input

    {
        mutation_results => { type => 'any' },
        module           => { type => 'string', optional => 1 },
        source_root      => { type => 'string', optional => 1 },
    }

C<mutation_results> is a file name or a hashref, so no single type is
declared for it.

=head4 output

    { type => OBJECT, isa => 'App::Test::Generator::Mutation::Feedback' }

=head2 survivors

Return the survivors from the results, filtered to the configured module.

    my $survivors = $feedback->survivors;

=head3 Returns

An arrayref of survivor hashrefs, in the order they appear in the results.

=head3 API SPECIFICATION

=head4 input

    { self => { type => OBJECT, isa => 'App::Test::Generator::Mutation::Feedback' } }

=head4 output

    { type => ARRAYREF, items => { type => HASHREF } }

=head2 proposals

Return one proposal per survivor.

    my $proposals = $feedback->proposals;

=head3 Returns

An arrayref of hashrefs with these keys:

=over 4

=item * C<kind> - C<constraint> for a numeric comparison that yields an
automatic schema constraint, or C<manual> when a test has to be written by
hand.

=item * C<survivor_id>, C<file>, C<line>, C<description> - copied from the
survivor, so the proposal can be traced back to the mutation report.

=item * C<parameter> - the input field the source comparison constrains,
derived from the variable in the comparison.  Only present for
C<constraint> proposals.

=item * C<values> - the boundary values a test should exercise, one either
side of the literal.  Only present for C<constraint> proposals.

=item * C<constraint> - a hashref such as C<< { min => 11 } >>, suitable for
merging into a schema input field.  Only present for C<constraint>
proposals.

=item * C<hint> - human-readable advice for C<manual> proposals.

=back

=head3 API SPECIFICATION

=head4 input

    { self => { type => OBJECT, isa => 'App::Test::Generator::Mutation::Feedback' } }

=head4 output

    { type => ARRAYREF, items => { type => HASHREF } }

=head2 apply_to_schema

Merge constraint proposals into a schema.

    my $applied = $feedback->apply_to_schema($schema);

=head3 Arguments

=over 4

=item * C<$schema>

A schema hashref as loaded from YAML.  Its C<input> section is modified in
place.

=back

=head3 Returns

An arrayref of change hashrefs, one per constraint added, each with C<field>,
C<constraint>, C<value>, C<survivor_id>, C<file> and C<line>.  An empty
arrayref means nothing could be applied; the C<proposals> are still available
for reporting.

Constraints already present on the field are left alone, as are proposals
whose parameter has no matching input field.

=head3 API SPECIFICATION

=head4 input

    {
        self   => { type => OBJECT, isa => 'App::Test::Generator::Mutation::Feedback' },
        schema => { type => HASHREF },
    }

=head4 output

    { type => ARRAYREF, items => { type => HASHREF } }

=head1 AUTHOR

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

=head1 LICENCE AND COPYRIGHT

Copyright 2026 Nigel Horne.

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

=cut
241
242# --------------------------------------------------
243# A variable on the left of a comparison: $name,
244# $self->{name}, $self->{name}[0] and so on.  The
245# last identifier is the parameter name.
246# --------------------------------------------------
247my $COMPARISON_RE = qr{
248        (?<var>\$[A-Za-z_]\w*
249                (?:\s*(?:->\s*\{?\s*[A-Za-z_]\w*\s*\}?|\[\s*-?\d+\s*\])*)
250        )
251        \s*(?<op>>=|<=|==|!=|>|<)\s*
252        (?<num>-?\d+(?:\.\d+)?)
253}x;
254
255sub new {
256
6
70562
        my ($class, %args) = @_;
257
258        croak 'mutation_results is required'
259
6
6
                unless defined($args{mutation_results});
260
261
6
6
        my $results = $args{mutation_results};
262
6
6
        if(!ref($results)) {
263
6
29
                croak "mutation_results '$results' does not exist"
264                        unless -f $results;
265
266
6
65
                open(my $fh, '<', $results)
267                        or croak "Cannot read mutation_results '$results': $!";
268
6
6
6
6
6
58
                my $raw = do { local $/; <$fh> };
269
6
17
                close($fh);
270
271
6
6
4
56
                $results = eval { decode_json($raw) };
272
6
12
                croak "mutation_results '$args{mutation_results}' is not valid JSON: $@"
273                        if $@;
274        }
275
276
6
6
        croak 'mutation_results must decode to a hashref'
277                unless ref($results) eq 'HASH';
278
279        return bless {
280                results     => $results,
281                module      => $args{module},
282
6
22
                source_root => $args{source_root} // '.',
283        }, $class;
284}
285
286sub survivors {
287
6
4
        my ($self) = @_;
288
289
6
6
        my %seen;
290        my @survivors = grep {
291                (my $status = $_->{status} // 'Survived') eq 'Survived'
292
24
45
                        && !$seen{ $_->{id} // '' }++
293
6
6
2
7
        } @{ $self->{results}{survived} || [] };
294
295
6
24
8
14
        return [ grep { $self->_matches_module($_) } @survivors ];
296}
297
298sub proposals {
299
6
6
        my ($self) = @_;
300
301
6
15
5
10
11
5
        $self->{proposals} //= [ map { $self->_proposal_for($_) } @{ $self->survivors } ];
302
303
6
9
        return $self->{proposals};
304}
305
306sub apply_to_schema {
307
4
12
        my ($self, $schema) = @_;
308
309
4
3
        croak 'apply_to_schema needs a schema hashref'
310                unless ref($schema) eq 'HASH';
311
4
6
        return [] unless ref($schema->{input}) eq 'HASH';
312
313
4
2
        my %field_for;
314
4
4
3
4
        foreach my $field (keys %{ $schema->{input} }) {
315
4
4
                $field_for{ _normalise($field) } //= $field;
316        }
317
318
4
3
        my @applied;
319        my %already;
320
4
4
3
3
        foreach my $proposal (@{ $self->proposals }) {
321
12
12
                next unless $proposal->{kind} eq 'constraint';
322
323
8
4
                my $field = $field_for{ _normalise($proposal->{parameter}) };
324
8
6
                next unless defined($field);
325
326
8
4
                my $spec = $schema->{input}{$field};
327
8
7
                next unless ref($spec) eq 'HASH';
328
329
8
8
3
19
                foreach my $constraint (sort keys %{ $proposal->{constraint} }) {
330
8
7
                        my $value = $proposal->{constraint}{$constraint};
331
8
8
                        next if exists($spec->{$constraint}) && defined($spec->{$constraint});
332
7
8
                        next if $already{"$field\0$constraint"}++;
333
334
7
5
                        $spec->{$constraint} = $value;
335                        $spec->{_constraint_source} = {
336
7
7
3
12
                                %{ $spec->{_constraint_source} || {} },
337                                $constraint => 'mutation',
338                        };
339
340                        push @applied, {
341                                field       => $field,
342                                constraint  => $constraint,
343                                value       => $value,
344                                survivor_id => $proposal->{survivor_id},
345                                file        => $proposal->{file},
346                                line        => $proposal->{line},
347
7
19
                        };
348                }
349        }
350
351
4
12
        return \@applied;
352}
353
354sub _matches_module {
355
24
22
        my ($self, $survivor) = @_;
356
357
24
25
        return 1 unless defined($self->{module}) && length($self->{module});
358
359
24
13
        my $expected = $self->{module};
360
24
27
        $expected =~ s{::}{/}g;
361
24
10
        $expected .= '.pm';
362
363
24
19
        my $file = $survivor->{file} // '';
364
24
11
        $file =~ s{^\./}{};
365
366
24
79
        return ($file eq $expected) || ($file =~ m{(?:^|/)\Q$expected\E$}) ? 1 : 0;
367}
368
369sub _proposal_for {
370
15
10
        my ($self, $survivor) = @_;
371
372        my %proposal = (
373                kind        => 'manual',
374                survivor_id => $survivor->{id},
375                file        => $survivor->{file},
376                line        => $survivor->{line},
377                description => $survivor->{description},
378                hint        => $survivor->{hint}
379
15
31
                        // 'Review the surviving mutant and add a test that tells it apart',
380        );
381
382
15
13
        my $id = $survivor->{id} // '';
383
15
19
        my ($line, $column) = $id =~ /^NUM_BOUNDARY_(\d+)_(\d+)_/;
384
15
24
        my ($original) = ($survivor->{description} // '')
385                =~ /Numeric boundary flip\s+(\S+)\s+to\s+\S+/;
386
387
15
22
        return \%proposal unless defined($line) && defined($original);
388
389        my ($var, $literal) = $self->_numeric_comparison(
390
10
10
                $survivor->{file}, $line, $column, $original,
391        );
392
10
11
        return \%proposal unless defined($var) && defined($literal);
393
394
10
10
        my $constraint = _constraint_for($original, $literal);
395
10
9
        return \%proposal unless $constraint;
396
397
10
5
        $proposal{kind}       = 'constraint';
398
10
9
        $proposal{parameter}  = _parameter_name($var);
399
10
10
        $proposal{values}     = [ $literal - 1, $literal, $literal + 1 ];
400
10
7
        $proposal{constraint} = $constraint;
401
10
8
        $proposal{hint}       = "Add cases at the boundary of $original $literal";
402
403
10
9
        return \%proposal;
404}
405
406# Read the line a mutant targets and find the comparison it mutated.  When a
407# line holds several comparisons, the one nearest the mutant's column wins.
408sub _numeric_comparison {
409
10
9
        my ($self, $file, $line_number, $column, $original) = @_;
410
411
10
9
        my $source = $self->_source_line($file, $line_number);
412
10
7
        return unless defined($source);
413
414
10
7
        my ($best_var, $best_literal, $best_distance);
415
10
43
        while($source =~ /$COMPARISON_RE/g) {
416
10
20
                next unless $+{op} eq $original;
417
418                my $distance = (defined($column) && length($column))
419
10
30
                        ? abs(($-[0] + index($&, $+{op}) + 1) - $column)
420                        : 0;
421
422
10
11
                next if defined($best_distance) && ($distance >= $best_distance);
423
424
10
27
                ($best_var, $best_literal, $best_distance) = ($+{var}, $+{num}, $distance);
425        }
426
427
10
12
        return ($best_var, $best_literal);
428}
429
430sub _source_line {
431
10
12
        my ($self, $file, $line_number) = @_;
432
433
10
12
        return unless defined($file) && defined($line_number);
434
435        my $path = File::Spec->file_name_is_absolute($file)
436                ? $file
437
10
45
                : File::Spec->catfile($self->{source_root}, $file);
438
10
35
        return unless -f $path;
439
440
10
66
        open(my $fh, '<', $path) or return;
441
10
6
        my $current = 0;
442
10
36
        while(my $line = <$fh>) {
443
110
82
                if(++$current == $line_number) {
444
10
26
                        close($fh);
445
10
7
                        chomp($line);
446
10
12
                        return $line;
447                }
448        }
449
0
0
        close($fh);
450
451
0
0
        return;
452}
453
454# Integer literals only: one step either side of a float is not a boundary
455# in the same sense, so those survivors stay manual proposals.
456sub _constraint_for {
457
10
7
        my ($operator, $literal) = @_;
458
459
10
17
        return unless defined($literal) && ($literal =~ /^-?\d+$/);
460
461
10
10
        return { min => $literal + 1 } if $operator eq '>';
462
5
3
        return { min => $literal     } if $operator eq '>=';
463
5
7
        return { max => $literal - 1 } if $operator eq '<';
464
0
0
        return { max => $literal     } if $operator eq '<=';
465
0
0
        return;
466}
467
468sub _parameter_name {
469
10
7
        my ($var) = @_;
470
471
10
14
        my @identifiers = $var =~ /([A-Za-z_]\w*)/g;
472
473
10
10
        return $identifiers[-1];
474}
475
476sub _normalise {
477
12
18
        my ($name) = @_;
478
479
12
7
        $name = '' unless defined($name);
480
12
10
        $name = lc($name);
481
12
9
        $name =~ s/[^a-z0-9]//g;
482
483
12
16
        return $name;
484}
485
4861;