File Coverage

File:blib/lib/Devel/App/Test/Generator/LCSAJ/Runtime.pm
Coverage:85.0%

linestmtbrancondsubtimecode
1package Devel::App::Test::Generator::LCSAJ::Runtime;
2
3
2
2
2
51499
1
15
use strict;
4
2
2
2
2
2
26
use warnings;
5
2
2
2
154
4444
2
use autodie     qw(open close);
6
2
2
2
284
1
30
use Carp        qw(croak);
7
2
2
2
3
0
19
use Config;
8
2
2
2
2
1
33
use Cwd         qw(abs_path);
9
2
2
2
2
0
31
use JSON::MaybeXS;
10
2
2
2
3
1
22
use File::Path  qw(make_path);
11
2
2
2
182
1203
174
use Readonly;
12
13# --------------------------------------------------
14# Output directory for per-process hit JSON files.
15# One file is written per process (PID) so parallel
16# test runs do not overwrite each other's output.
17# --------------------------------------------------
18Readonly my $OUT_DIR => 'cover_html/lcsaj_hits';
19
20 - 28
=head1 NAME

Devel::App::Test::Generator::LCSAJ::Runtime - Debugger backend for LCSAJ coverage

=head1 VERSION

Version 0.52

=cut
29
30our $VERSION = '0.52';
31
32 - 64
=head1 SYNOPSIS

  PERL5OPT='-d:App::Test::Generator::LCSAJ::Runtime -Mblib' prove -l t

=head1 DESCRIPTION

This module is loaded as a Perl debugger backend using the C<-d:Module> flag.

When Perl sees C<-d:App::Test::Generator::LCSAJ::Runtime> it prepends C<Devel::>
and loads C<Devel/App/Test/Generator/LCSAJ/Runtime.pm> from C<@INC>.
The file must therefore live at that path - typically C<lib/Devel/App/Test/Generator/LCSAJ/Runtime.pm>.

Perl automatically calls C<DB::DB> before executing each statement while the
debugger is active. We record (file, line) pairs to build runtime hit data for
later LCSAJ analysis.

Results are written to C<cover_html/lcsaj_hits/hits_PID.json> at process exit,
one file per process so that parallel test runs do not overwrite each other.

=head1 ENVIRONMENT

=over 4

=item LCSAJ_TARGETS

Optional list of B<absolute> paths (as produced by C<realpath>), separated by
C<$Config{path_sep}> (C<:> on Unix, C<;> on Windows, as in C<PATH>), to
restrict recording to specific source files. When empty or unset every
non-internal file is recorded.

=back

=cut
65
66# --------------------------------------------------
67# %HITS       - { normalised_path => { line_number => hit_count } }
68# %TARGET     - set of normalised paths to record (empty means record everything)
69# %NORM_CACHE - { raw_file => normalised_path }, memoises abs_path()
70#               since DB::DB sees the same $file on every consecutive
71#               statement within a source file
72#
73# These must be package globals (our) rather than lexicals because DB::DB
74# is called by the Perl debugger infrastructure and needs to access them
75# without a closure. Lexical vars would not be visible in DB::DB.
76# --------------------------------------------------
77our %HITS;
78our %TARGET;
79our %NORM_CACHE;
80
81# --------------------------------------------------
82# Populate %TARGET from LCSAJ_TARGETS at compile time.
83# The env var contains absolute realpath() output
84# separated by $Config{path_sep}; a colon would split
85# a Windows drive letter off its path. Stray newlines
86# from broken shell pipelines are stripped defensively.
87# --------------------------------------------------
88BEGIN {
89
2
5
        my $targets_env = $ENV{LCSAJ_TARGETS} // '';
90
2
2
        $targets_env =~ s/\n//g;
91
92
2
233
        for my $t (split /\Q$Config{path_sep}\E/, $targets_env) {
93
0
0
                next unless length $t;
94
95                # Inline normalisation — cannot call _normalize here since
96                # BEGIN runs before named subs are compiled when BEGIN
97                # appears at the top of the file
98
0
0
                my $f = $t;
99
0
0
                $f =~ tr{\\}{/};
100
0
0
                $f =~ s{^.*/blib/lib/}{lib/};
101
0
0
                $f =~ s{^.*/lib/}{lib/};
102
0
0
                $TARGET{$f} = 1;
103        }
104}
105
106END {
107
2
3470
        _write_results();
108}
109
110# --------------------------------------------------
111# _normalize
112#
113# Convert an absolute or build-tree path
114#             to a canonical lib-relative form so that
115#             paths recorded at runtime match the
116#             targets derived from LCSAJ_TARGETS.
117#
118# Entry:      $path - an absolute or relative file path.
119#
120# Exit:       Returns a lib-relative path string,
121#             e.g. lib/Foo/Bar.pm
122#
123# Notes:      Must be defined before the BEGIN block
124#             that calls it, since BEGIN runs at compile
125#             time and later subs may not yet be compiled.
126#
127# Examples:
128#   /home/user/proj/blib/lib/Foo/Bar.pm  ->  lib/Foo/Bar.pm
129#   /home/user/proj/lib/Foo/Bar.pm       ->  lib/Foo/Bar.pm
130#   D:\a\proj\blib\lib\Foo\Bar.pm        ->  lib/Foo/Bar.pm
131# --------------------------------------------------
132sub _normalize {
133
12
187962
        my $f = $_[0];
134
135        # Windows paths (abs_path, %INC, caller) may use either separator
136
12
14
        $f =~ tr{\\}{/};
137
138        # Strip everything up to and including blib/lib/ or lib/
139
12
18
        $f =~ s{^.*/blib/lib/}{lib/};
140
12
16
        $f =~ s{^.*/lib/}{lib/};
141
12
26
        return $f;
142}
143
144# --------------------------------------------------
145# DB::DB
146#
147# Called by the Perl debugger before every
148#             statement. Records (file, line) hits for
149#             later LCSAJ coverage analysis.
150#
151# Entry:      No arguments — caller(0) is used to get
152#             the current file and line number.
153#
154# Exit:       Returns nothing. Updates %HITS in place.
155#
156# Side effects: Increments %HITS{$norm}{$line}.
157#
158# Notes:      This sub lives in the DB:: package as
159#             required by Perl's debugger protocol.
160#             It is called for every statement executed
161#             while the debugger is active, so it must
162#             be as fast as possible.
163#             Internal files and out-of-target files
164#             are skipped immediately.
165#             abs_path() resolution is memoised in
166#             %NORM_CACHE per raw $file, since the same
167#             file is seen on every consecutive statement.
168# --------------------------------------------------
169 - 207
=head2 DB::DB

Perl debugger hook, automatically invoked by the interpreter before every
statement while this module is active as a C<-d:> debugger backend.
Records a per-(file, line) hit count used later for LCSAJ coverage
analysis.

=head3 Arguments

None. Perl calls this sub directly; the current execution location is
obtained internally via C<caller(0)>.

=head3 Returns

Nothing meaningful - this is a void debugger callback.

=head3 Side effects

Increments C<%HITS{$norm}{$line}> for the normalised path and line number
of the statement about to execute. Resolves each distinct raw filename
via C<Cwd::abs_path> once, memoising the result in C<%NORM_CACHE>.

=head3 Usage example

Not called directly - activated via the Perl debugger flag:

    PERL5OPT='-d:App::Test::Generator::LCSAJ::Runtime -Mblib' prove -l t

=head3 API specification

=head4 input

    { }

=head4 output

    { type => UNDEF }

=cut
208
209sub DB::DB {
210
7
67443
        my (undef, $file, $line) = caller(0);
211
212
7
51
        return unless defined $file && defined $line;
213
214        # Resolve symlinks and relative components to a stable absolute path,
215        # cached per raw $file to avoid a stat() on every statement
216
7
23
        my $norm = $NORM_CACHE{$file} //= _normalize(abs_path($file) // $file);
217
218        # Never record hits inside this module itself — suffix match is used
219        # so it works regardless of CWD or install prefix
220
7
10
        return if $norm =~ m{(?:^|/)Devel/App/Test/Generator/LCSAJ/Runtime\.pm$};
221
222        # If a target list was provided, skip files not in it
223
6
6
        if(%TARGET) {
224
2
3
                return unless $TARGET{$norm};
225        }
226
227
5
7
        $HITS{$norm}{$line}++;
228}
229
230# --------------------------------------------------
231# _write_results
232#
233# Serialise %HITS to a per-process JSON
234#             file in the output directory.
235#
236# Entry:      None. Reads %HITS and $OUT_DIR.
237#
238# Exit:       Returns nothing. Writes a JSON file.
239#             Returns immediately if %HITS is empty.
240#
241# Side effects: Creates $OUT_DIR if absent.
242#               Writes cover_html/lcsaj_hits/hits_PID.json
243#
244# Notes:      Called from END so it runs even when
245#             prove exits non-zero — mutation tests
246#             are expected to fail. PID is included
247#             in the filename so parallel test runs
248#             produce separate files without collision.
249# --------------------------------------------------
250sub _write_results {
251
5
4425
        return unless %HITS;
252
253        # Include PID in filename to support parallel test runs
254
2
4
        my $out_file = "$OUT_DIR/hits_$$.json";
255
256
2
6
        make_path($OUT_DIR) unless -d $OUT_DIR;
257
258        # autodie is disabled for this open -- under "use autodie qw(open)"
259        # open() never returns false on failure, it throws its own exception
260        # instead, which would silently make the "or croak" below dead code
261
2
2
2
4
1
4
        no autodie qw(open);
262
2
176
        open my $fh, '>', $out_file or croak "Cannot write $out_file: $!";
263
264
1
7
        print $fh encode_json(\%HITS);
265
1
4
        close $fh;
266}
267
2681;
269