blib/lib/Test/CPAN/Health/Check/TestCoverage.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/Test/CPAN/Health/Check/StaleDeps.pm ↑ Summary blib/lib/Test/CPAN/Health/Check/VersionSync.pm »
1 package Test::CPAN::Health::Check::TestCoverage;
2  
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 use Carp qw(croak carp);
8 use File::Path qw(remove_tree);
9 use File::Spec;
10 use Readonly;
11 use Params::Validate::Strict qw(validate_strict);
12  
13 use parent 'Test::CPAN::Health::Check';
14  
15 our $VERSION = '0.1.0';
16  
17 Readonly::Scalar my $SCORE_PASS => 80;
18 Readonly::Scalar my $SCORE_WARN => 60;
19  
20 =head1 NAME
21  
22 Test::CPAN::Health::Check::TestCoverage - Measure test suite statement coverage
23  
24 =head1 SYNOPSIS
25  
26 use Test::CPAN::Health::Check::TestCoverage;
27  
28 my $check = Test::CPAN::Health::Check::TestCoverage->new;
29 my $result = $check->run($dist);
30  
31 printf "%s: %s\n", $result->status, $result->summary;
32  
33 =head1 DESCRIPTION
34  
35 Runs the distribution's own test suite under L<Devel::Cover> and reports the
36 overall statement-coverage percentage as the check score.
37  
38 The check proceeds in three steps inside the distribution's root directory:
39  
40 =over 4
41  
42 =item 1.
43  
44 Generates C<Makefile> (via C<perl Makefile.PL>) or C<Build> (via
45 C<perl Build.PL>) if the build file is absent.
46  
47 =item 2.
48  
49 Runs C<make test> (or C<./Build test>) with
50 C<HARNESS_PERL_SWITCHES=-MDevel::Cover> and C<PERL5OPT=-MDevel::Cover>
51 set in the environment, causing the test harness to record coverage into
52 C<cover_db/>.
53  
54 =item 3.
55  
56 Invokes C<cover -report text> to generate a coverage summary, then parses
57 the statement-coverage percentage from the C<Total> row.
58  
59 =back
60  
61 The check is skipped when any of the following apply:
62  
63 =over 4
64  
65 =item * C<--no-cover> was passed (C<no_cover> constructor flag).
66  
67 =item * L<Devel::Cover> is not installed.
68  
69 =item * No C<.t> files exist under C<t/>.
70  
71 =item * Neither C<Makefile.PL> nor C<Build.PL> exists.
72  
73 =item * The C<cover> binary cannot be located.
74  
75 =back
76  
77 Score = integer part of the statement-coverage percentage.
78 Status thresholds: pass E<ge> 80, warn E<ge> 60, fail otherwise.
79  
80 =head1 LIMITATIONS
81  
82 =over 4
83  
84 =item * Running the test suite is slow; expect 2-5x the normal test time.
85  
86 =item * The check temporarily changes the process working directory to the
87 distribution root and restores it afterwards.
88  
89 =item * Requires C<make> (ExtUtils::MakeMaker dists) or a C<Build> script
90 (Module::Build dists).
91  
92 =back
93  
94 =cut
95  
96 sub id { return 'test_coverage' }
97 sub name { return 'Test Coverage' }
98 sub description { return 'Measures statement coverage of the test suite via Devel::Cover' }
99 sub weight { return 7 }
100 sub category { return 'ci' }
101  
102 =head2 run
103  
104 =head3 PURPOSE
105  
106 Execute the distribution's test suite under C<Devel::Cover> and return the
107 statement-coverage percentage as a 0-100 score.
108  
109 =head3 API SPECIFICATION
110  
111 =head4 INPUT
112  
113 dist Test::CPAN::Health::Distribution required
114 context Hashref optional
115  
116 =head4 OUTPUT
117  
118 L<Test::CPAN::Health::Result> with check_id C<'test_coverage'>.
119  
120 =head3 MESSAGES
121  
122 Code | Severity | Message | Resolution
123 ------+----------+--------------------------------------------------+-----------
124 TC001 | SKIP | Skipped (--no-cover is set) | Remove --no-cover
125 TC002 | SKIP | Devel::Cover is not installed | cpanm Devel::Cover
126 TC003 | SKIP | No test files found under t/ | Add tests
127 TC004 | SKIP | No Makefile.PL or Build.PL found | Add build file
128 TC005 | SKIP | cover binary not found | Install Devel::Cover
129 TC006 | ERROR | Failed to run coverage check: ... | See error detail
130 TC007 | ERROR | Could not parse statement coverage from report | Check cover output
131 TC008 | PASS | Statement coverage: N% |
132 TC009 | WARN | Statement coverage: N% | Add more tests
133 TC010 | FAIL | Statement coverage: N% | Add more tests
134  
135 =head3 FORMAL SPECIFICATION
136  
137 -- Z schema (placeholder) --
138 TestCoverageOp
139 stmt_pct : 0..100
140 score : 0..100
141 -------------------------------------------------------
142 no_cover = true => status = skip
143 Devel::Cover unavailable => status = skip
144 t_files = {} => status = skip
145 no build file => status = skip
146 score >= 80 => status = pass
147 score >= 60 => status = warn
148 score < 60 => status = fail
149  
150 =head3 SIDE EFFECTS
151  
152 Runs the full test suite in a subprocess with coverage tracing enabled.
153 Writes C<cover_db/> inside the distribution root. Temporarily changes
154 and then restores the process working directory.
155  
156 =head3 USAGE EXAMPLE
157  
158 my $result = Test::CPAN::Health::Check::TestCoverage->new->run($dist);
159 printf "Statement coverage: %s\n", $result->summary;
160  
161 =cut
162  
163 sub run {
164 my ($self, $dist, $context) = @_;
165  
166 croak 'dist must be a Test::CPAN::Health::Distribution'
167 unless ref($dist) && $dist->isa('Test::CPAN::Health::Distribution');
168  
169 my $skip = $self->_check_preconditions($dist);
170 return $skip if $skip;
171  
172 my $cover_bin = _find_cover_bin();
173 return $self->_skip('cover binary not found') unless $cover_bin;
174  
175 my $has_makefile_pl = $dist->file_path('Makefile.PL') ? 1 : 0;
176 my $has_build_pl = $dist->file_path('Build.PL') ? 1 : 0;
177  
178 my ($output, $run_err, $tests_failed)
179 = _collect_coverage($dist, $has_makefile_pl, $has_build_pl, $cover_bin);
180  
181 return $self->_error("Failed to run coverage check: $run_err") if $run_err;
182  
183 return $self->_parse_and_score($output, $tests_failed);
184 }
185  
186 ## no critic (ProhibitUnusedPrivateSubroutines)
187 sub _check_preconditions {
188 my ($self, $dist) = @_;
189  
190 return $self->_skip('Skipped (--no-cover is set)') if $self->no_cover;
191  
192 my $has_cover = eval { require Devel::Cover; 1 };
193 return $self->_skip('Devel::Cover is not installed') unless $has_cover;
194  
195 my @t_files = @{ $dist->t_files };
196 return $self->_skip('No test files found under t/') unless @t_files;
197  
198 unless ($dist->file_path('Makefile.PL') || $dist->file_path('Build.PL')) {
199 return $self->_skip('No Makefile.PL or Build.PL found');
200 }
201  
202 return;
203 }
204  
205 ## no critic (ProhibitUnusedPrivateSubroutines)
206 sub _parse_and_score {
207 my ($self, $output, $tests_failed) = @_;
208  
209 # Parse statement coverage from the Total row of the text report.
210 # "Total 91.7 88.2 50.0 100.0 75.0 100.0 88.2" (spaces or tabs)
211 my $stmt_pct;
212 if (defined $output && $output =~ / ^ Total [\s\t]+ ([\d.]+) /mx) {
213 $stmt_pct = $1 + 0;
214 }
215  
216 unless (defined $stmt_pct) {
217 my $snippet = defined $output ? substr($output, 0, 300) : '(no output)';
218 $snippet =~ s/ \s+ / /gx;
219 return $self->_error(
220 "Could not parse statement coverage from cover output. "
221 . "First 300 chars: $snippet"
222 );
223 }
224  
225 my $score = int($stmt_pct);
226 $score = 100 if $score > 100;
227 my $status = $score >= $SCORE_PASS ? 'pass'
228 : $score >= $SCORE_WARN ? 'warn'
229 : 'fail';
230  
231 my @details;
232 push @details, 'Warning: some tests failed during the coverage run' if $tests_failed;
233  
234 return $self->_result(
235 status => $status,
236 score => $score,
237 summary => sprintf('Statement coverage: %.1f%%', $stmt_pct),
238 details => \@details,
239 data => {
240 name => $self->name,
241 statement_coverage => $stmt_pct,
242 tests_failed => $tests_failed ? 1 : 0,
243 },
244 );
245 }
246  
247 # ---------------------------------------------------------------------------
248 # Private helpers
249 # ---------------------------------------------------------------------------
250  
251 sub _collect_coverage {
252 my ($dist, $has_makefile_pl, $has_build_pl, $cover_bin) = @_;
253  
254 require Cwd;
255 my $orig_dir = Cwd::getcwd();
256 my ($output, $run_err, $tests_failed);
257  
258 my $ok = eval {
259 chdir $dist->path;
260  
261 remove_tree('cover_db') if -d 'cover_db';
262  
263 if ($has_makefile_pl && !-f 'Makefile') {
264 system($^X, 'Makefile.PL') == 0
265 or croak "perl Makefile.PL failed (exit $?)";
266 } elsif ($has_build_pl && !-f 'Build') {
267 system($^X, 'Build.PL') == 0
268 or croak "perl Build.PL failed (exit $?)";
269 }
270  
271 ## no critic (ProhibitPackageVars)
272 local $ENV{HARNESS_PERL_SWITCHES} = '-MDevel::Cover';
273 local $ENV{PERL5OPT} = '-MDevel::Cover';
274  
275 my $make = _make_command();
276 {
277 no autodie;
278 if (-f 'Build') {
279 $tests_failed = 1 if system('./Build', 'test') != 0;
280 } else {
281 $tests_failed = 1 if system($make, 'test') != 0;
282 }
283 }
284  
285 open my $fh, '-|', $cover_bin, '-report', 'text'
286 or croak "Cannot exec $cover_bin -report text: $!";
287 {
288 local $/ = undef;
289 $output = <$fh>;
290 }
291 {
292 no autodie 'close';
293 close $fh;
294 }
295 1;
296 };
297 $run_err = $ok ? undef : $@;
298  
299 {
300 no autodie 'chdir';
301 chdir $orig_dir;
302 }
303  
304 return ($output, $run_err, $tests_failed);
305 }
306  
307 # Locate the 'cover' binary from Devel::Cover's installation directory,
308 # falling back to a PATH scan. Returns the binary path or undef.
309 sub _find_cover_bin {
310 require Config;
311  
312 ## no critic (ProhibitPackageVars)
313 for my $dir (
314 $Config::Config{sitebin},
315 $Config::Config{bin},
316 $Config::Config{installbin},
317 ) {
318 next unless defined $dir && length $dir;
319 my $candidate = File::Spec->catfile($dir, 'cover');
320 return $candidate if -x $candidate;
321 }
322  
323 for my $dir (File::Spec->path()) {
324 my $candidate = File::Spec->catfile($dir, 'cover');
325 return $candidate if -x $candidate;
326 }
327  
328 return;
329 }
330  
331 # Return the configured make command for this perl installation.
332 sub _make_command {
333 require Config;
334 ## no critic (ProhibitPackageVars)
335 return $Config::Config{make} || 'make';
336 }
337  
338 =head1 AUTHOR
339  
340 Nigel Horne, C<< <njh at nigelhorne.com> >>
341  
342 =head1 LICENSE AND COPYRIGHT
343  
344 Copyright (C) 2025-2026 Nigel Horne.
345  
346 This program is free software; you can redistribute it and/or modify it
347 under the terms of the GNU General Public License as published by the Free
348 Software Foundation; either version 2 of the License, or (at your option)
349 any later version.
350  
351 =cut
352  
353 1;
« blib/lib/Test/CPAN/Health/Check/StaleDeps.pm ↑ Summary blib/lib/Test/CPAN/Health/Check/VersionSync.pm »