Debian Codegraph @

lib/App/Yath/Plugin/Cover.pm

raw
1 package App::Yath::Plugin::Cover;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use Test2::Harness::Util qw/clean_path mod2file/;
8 use Test2::Harness::Util::JSON qw/encode_json stream_json_l/;
9 use Test2::Harness::Util::UUID qw/gen_uuid/;
10
11 use parent 'App::Yath::Plugin';
12 use Test2::Harness::Util::HashBase qw/-aggregator -no_aggregate +metrics +outfile/;
13
14 use App::Yath::Options;
15
16 option_group {prefix => 'cover', category => "Cover Options"} => sub {
17 post \&post_process;
18
19 option types => (
20 alt => ['cover-type'],
21 type => 'm',
22 default => sub { [qw/pl pm/] },
23 );
24
25 option dirs => (
26 alt => ['cover-dir'],
27 type => 'm',
28 default => sub { ['lib'] },
29
30 action => sub {
31 my ($prefix, $field, $raw, $norm, $slot, $settings) = @_;
32 push @$$slot => glob($norm);
33 },
34 );
35
36 option exclude_dirs => (
37 alt => ['cover-exclude-dir'],
38 type => 'm',
39 description => "Directory to leave out of file coverage and coverage metrics, along with everything under it at any depth. May be specified multiple times. Wildcards are expanded when the option is parsed, so a pattern matching nothing excludes nothing. Values are word-split first, so a path containing whitespace must be quoted or backslash-escaped. A resolved path may not contain a comma.",
40
41 action => sub {
42 my ($prefix, $field, $raw, $norm, $slot, $settings, $handler) = @_;
43
44 for my $path (map { clean_path($_) } glob($norm)) {
45 # The resolved path is what gets transmitted, so a comma in an
46 # ancestor directory breaks a value that had none of its own.
47 if ($path =~ m/,/) {
48 my $from = $path eq $raw ? "" : " (from '$raw')";
49 die "--cover-exclude-dirs cannot use a path containing a comma. '$path'$from has one. Coverage plugin arguments reach each test as a comma separated list, so such a path cannot survive.\n";
50 }
51
52 $handler->($slot, $path);
53 }
54 },
55 );
56
57 option exclude_private => (
58 type => 'b',
59 default => 0,
60 description => "",
61 );
62
63 option files => (
64 type => 'b',
65 description => "Use Test2::Plugin::Cover to collect coverage data for what files are touched by what tests. Unlike Devel::Cover this has very little performance impact (About 4% difference)",
66 );
67
68 option metrics => (
69 type => 'b',
70 description => '',
71 );
72
73 option write => (
74 type => 'd',
75 normalize => \&clean_path,
76 long_examples => ['', '=coverage.jsonl', '=coverage.json'],
77 description => "Create a json or jsonl file of all coverage data seen during the run (This implies --cover-files).",
78 action => sub {
79 my ($prefix, $field, $raw, $norm, $slot, $settings) = @_;
80
81 return $$slot = clean_path("coverage.jsonl") if $raw eq '1';
82 return $$slot = $norm;
83 },
84 );
85
86 option aggregator => (
87 alt => ['cover-agg'],
88 type => 's',
89 long_examples => [' ByTest', ' ByRun', ' +Custom::Aggregator'],
90 description => 'Choose a custom aggregator subclass',
91 normalize => sub {
92 my ($agg) = @_;
93 return $agg if $agg =~ s/^\+//;
94 return "Test2::Harness::Log::CoverageAggregator::$agg";
95 },
96 );
97
98 option class => (
99 type => 's',
100 description => 'Choose a Test2::Plugin::Cover subclass',
101 default => 'Test2::Plugin::Cover',
102 );
103
104 option manager => (
105 type => 's',
106 description => "Coverage 'from' manager to use when coverage data does not provide one",
107 long_examples => [' My::Coverage::Manager'],
108 applicable => \&changes_applicable,
109 );
110
111 option from_type => (
112 type => 's',
113 description => 'File type for coverage source. Usually it can be detected, but when it cannot be you should specify. "json" is old style single-blob coverage data, "jsonl" is the new by-test style, "log" is a logfile from a previous run.',
114 long_examples => [' json', ' jsonl', ' log'],
115 );
116
117 option maybe_from_type => (
118 type => 's',
119 'description' => 'Same as "from_type" but for "maybe_from". Defaults to "from_type" if that is specified, otherwise auto-detect',
120 long_examples => [' json', ' jsonl', ' log'],
121 );
122
123 option from => (
124 type => 's',
125 description => "This can be a test log, a coverage dump (old style json or new jsonl format), or a url to any of the previous. Tests will not be run if the file/url is invalid.",
126 long_examples => [' path/to/log.jsonl', ' http://example.com/coverage', ' path/to/coverage.jsonl']
127 );
128
129 option maybe_from => (
130 type => 's',
131 description => "This can be a test log, a coverage dump (old style json or new jsonl format), or a url to any of the previous. Tests will continue even if the coverage file/url is invalid.",
132 long_examples => [' path/to/log.jsonl', ' http://example.com/coverage', ' path/to/coverage.jsonl']
133 );
134 };
135
136 sub changes_applicable {
137 my ($option, $options) = @_;
138
139 # Cannot use this options with projects
140 return 0 if $options->command_class && $options->command_class->isa('App::Yath::Command::projects');
141 return 1;
142 }
143
144 sub spawn_args {
145 my $self = shift;
146 my ($settings) = @_;
147
148 return () unless $settings->cover->files || $settings->cover->metrics || $settings->cover->write;
149
150 my $class = $settings->cover->class;
151 return ('-M' . $class . '=disabled,1');
152 }
153
154 sub post_process {
155 my %params = @_;
156 my $settings = $params{settings};
157
158 my $cover = $settings->cover;
159
160 if ($cover->files || $cover->write || $cover->metrics) {
161 my $cover_class = $cover->class // 'Test2::Plugin::Cover';
162
163 eval { require(mod2file($cover_class)); 1 } or die "Could not enable file coverage, could not load '$cover_class': $@";
164
165 # Older versions accept the 'exclude' parameter and ignore it, which
166 # would record an excluded tree while reporting success.
167 eval { $cover_class->VERSION('0.000029'); 1 } or die "Could not enable file coverage: $@";
168
169 push @{$settings->run->load_import->{'@'}} => $cover_class;
170
171 # Repeated pairs, not a single arrayref: this list is joined with
172 # commas into a -M argument for tests that do not run under a preload.
173 $settings->run->load_import->{$cover_class} = [map { (exclude => $_) } @{$cover->exclude_dirs // []}];
174 }
175 }
176
177 sub annotate_event {
178 my $self = shift;
179 return if $self->{+NO_AGGREGATE};
180 my ($e, $settings) = @_;
181
182 unless ($self->{+AGGREGATOR}) {
183 my $do_cover = $settings->cover->files;
184 my $file = $settings->cover->write;
185 my $metrics = $settings->cover->metrics;
186
187 unless ($file || $metrics || $do_cover) {
188 $self->{+NO_AGGREGATE} = 1;
189 return;
190 }
191
192 my $agg = $settings->cover->aggregator;
193 if (!$agg) {
194 if ($file) {
195 if ($file =~ m/\.json$/) {
196 $agg = 'Test2::Harness::Log::CoverageAggregator::ByRun';
197 }
198 elsif ($file =~ m/\.jsonl$/) {
199 $agg = 'Test2::Harness::Log::CoverageAggregator::ByTest';
200 }
201 }
202 else {
203 $agg = 'Test2::Harness::Log::CoverageAggregator::ByTest';
204 }
205 }
206
207 my $encode;
208 if ($agg eq 'Test2::Harness::Log::CoverageAggregator::ByRun') {
209 $encode = \&encode_json;
210 }
211 elsif ($agg eq 'Test2::Harness::Log::CoverageAggregator::ByTest') {
212 $encode = sub { encode_json($_[0]) . "\n" };
213 }
214
215 require(mod2file($agg));
216 $self->{+AGGREGATOR} = $agg->new(
217 $file ? (file => $file) : (),
218 $encode ? (encode => $encode) : (),
219 );
220 }
221
222 my $fd = $e->{facet_data};
223
224 my @out;
225
226 if ($fd->{coverage} || $fd->{harness_job_end} || $fd->{harness_job_start}) {
227 if (my $list = $self->{+AGGREGATOR}->process_event($e)) {
228 die "Aggregator flushed without a job end!" unless $fd->{harness_job_end};
229 die "Aggregator flushed more than 1 job!" unless @$list == 1;
230 push @out => (job_coverage => {details => 'Job Coverage', manager => $list->[0]->{manager}, files => $list->[0]->{files}, test => $list->[0]->{test}});
231 }
232 }
233
234 if ($fd->{harness_final}) {
235 my $cover = $settings->cover;
236 my $aggregator = $self->{+AGGREGATOR} or return;
237 my $metrics;
238 $metrics = $self->metrics($settings) if $cover->metrics;
239 my $final = $aggregator->finalize();
240
241 my $percentages = $self->_percentages($metrics);
242 my $raw = join ", ", map { "$_->[0]: $_->[2]/$_->[1] ($_->[3])" } @$percentages;
243 my $details = join ", ", map { "$_->[0] $_->[3]" } @$percentages;
244
245 $details = "coverage metrics" unless length $details;
246
247 push @out => (
248 run_fields => [
249 {name => 'coverage', details => $details, data => $metrics, $raw ? (raw => $raw) : ()},
250 ],
251 );
252
253 push @out => (
254 run_coverage => {
255 details => 'Run Coverage',
256 files => $final->[0]->{files},
257 testmeta => $final->[0]->{testmeta},
258 },
259 ) if $final && @$final;
260 }
261
262 return @out;
263 }
264
265 sub metrics {
266 my $self = shift;
267 my ($settings) = @_;
268
269 my $cover = $settings->cover;
270
271 return unless $cover->metrics;
272
273 my $aggregator = $self->{+AGGREGATOR};
274
275 return $self->{+METRICS} //= $aggregator->build_metrics(
276 dirs => $cover->dirs,
277 types => $cover->types,
278 exclude_private => $cover->exclude_private,
279 exclude_dirs => $cover->exclude_dirs,
280 );
281 }
282
283 sub _percentages {
284 my $self = shift;
285 my ($metrics) = @_;
286
287 return unless $metrics;
288
289 my @out;
290
291 for my $metric (sort keys %$metrics) {
292 next if $metric eq 'untested';
293 my $data = $metrics->{$metric} or next;
294 my ($total, $tested) = @{$data}{qw/total tested/};
295 push @out => [$metric, $total, $tested, $total ? (int(($tested / $total) * 100) . '%') : '100%'];
296 }
297
298 return \@out;
299 }
300
301 sub finalize {
302 my $self = shift;
303 my ($settings) = @_;
304
305 my $cover = $settings->cover;
306 my $file = $cover->write;
307 my $metrics = $cover->metrics;
308
309 return unless $file || $metrics;
310 print "\nCoverage:\n";
311
312 my $aggregator = $self->{+AGGREGATOR};
313
314 if ($metrics) {
315 my $data = $self->metrics($settings);
316
317 require Term::Table;
318 my $table = Term::Table->new(
319 header => [qw/METRIC TOTAL TESTED PERCENTAGE/],
320 rows => $self->_percentages($data),
321 );
322 print map { "$_\n" } $table->render;
323 }
324
325 print "Wrote coverage file: $file\n" if $file;
326
327 print "\n";
328 }
329
330 sub _deduce_content_type {
331 my ($path, $type) = @_;
332
333 if ($type) {
334 if ($type eq 'json') {
335 return {
336 content_type => 'application/json',
337 parser => 'json',
338 format => $type,
339 };
340 }
341 elsif ($type eq 'jsonl' || $type eq 'log') {
342 return {
343 content_type => 'application/jsonl',
344 parser => 'jsonl',
345 format => $type,
346 };
347 }
348 }
349
350 if ($path =~ m/\.jsonl/) {
351 return {
352 content_type => 'application/jsonl',
353 parser => 'jsonl',
354 format => undef,
355 };
356 }
357
358 if ($path =~ m/\.json/) {
359 return {
360 content_type => 'application/json',
361 parser => 'json',
362 format => undef,
363 };
364 }
365
366 return {};
367 }
368
369 sub get_coverage_tests {
370 my $self = shift;
371 my ($settings, $changes) = @_;
372
373 my $cover = $settings->cover;
374 my $from = $cover->from;
375 my $maybe = $cover->maybe_from;
376
377 return unless $from || $maybe;
378
379 if ($maybe) {
380 my $type_data = $self->_deduce_content_type($maybe, $cover->maybe_from_type);
381
382 my @out;
383 my $ok = eval { @out = $self->_get_coverage_tests($settings, $changes, $maybe, $type_data); 1 };
384 my $err = $@;
385 return @out if $ok;
386 warn "Could not get coverage from '$maybe', continuing anyway... error was: $err";
387 }
388
389 return $self->_get_coverage_tests($settings, $changes, $from)
390 if $from;
391
392 return;
393 }
394
395 sub _get_coverage_tests {
396 my $self = shift;
397 my ($settings, $changes, $source, $type_data) = @_;
398
399 my @out;
400
401 stream_json_l(
402 $source => sub { push @out => $self->coverage_handler($settings, $changes, $type_data, @_) },
403 $type_data->{content_type} ? (http_args => [{headers => {'Content-Type' => $type_data->{content_type}}}]) : (),
404 );
405
406 return @out;
407 }
408
409 sub coverage_handler {
410 my $self = shift;
411 my ($settings, $changes, $type_data, $set, $res) = @_;
412
413 return unless $set;
414
415 my ($agg, $data);
416 if (my $fd = $set->{facet_data}) {
417 if ($data = $fd->{job_coverage}) {
418 require 'Test2/Harness/Log/CoverageAggregator/ByTest.pm' unless $INC{'Test2/Harness/Log/CoverageAggregator/ByTest.pm'};
419 $agg = 'Test2::Harness::Log::CoverageAggregator::ByTest';
420 }
421 elsif ($data = $fd->{run_coverage}) {
422 require 'Test2/Harness/Log/CoverageAggregator/ByRun.pm' unless $INC{'Test2/Harness/Log/CoverageAggregator/ByRun.pm'};
423 $agg = 'Test2::Harness::Log::CoverageAggregator::ByRun';
424 }
425 else {
426 return;
427 }
428 }
429 else {
430 $data = $set;
431 $agg = $set->{aggregator} // return;
432 my $aggfile = mod2file($agg);
433 require($aggfile) unless $INC{$aggfile};
434 }
435
436 return $agg->get_coverage_tests($settings, $changes, $data);
437 }
438
439 1;
440
441 __END__
442
443
444 =pod
445
446 =encoding UTF-8
447
448 =head1 NAME
449
450 App::Yath::Plugin::Cover - Plugin to collect and report basic coverage data
451
452 =head1 DESCRIPTION
453
454 Simple coverage data, file and sub coverage only. Use L<Devel::Cover> if you
455 want deep coverage stats.
456
457 =head1 PROVIDED OPTIONS
458
459 =head2 COMMAND OPTIONS
460
461 =head3 Cover Options
462
463 =over 4
464
465 =item --cover-aggregator ByTest
466
467 =item --cover-aggregator ByRun
468
469 =item --cover-aggregator +Custom::Aggregator
470
471 =item --cover-agg ByTest
472
473 =item --cover-agg ByRun
474
475 =item --cover-agg +Custom::Aggregator
476
477 =item --no-cover-aggregator
478
479 Choose a custom aggregator subclass
480
481
482 =item --cover-class ARG
483
484 =item --cover-class=ARG
485
486 =item --no-cover-class
487
488 Choose a Test2::Plugin::Cover subclass
489
490
491 =item --cover-dirs ARG
492
493 =item --cover-dirs=ARG
494
495 =item --cover-dir ARG
496
497 =item --cover-dir=ARG
498
499 =item --no-cover-dirs
500
501 NO DESCRIPTION - FIX ME
502
503 Can be specified multiple times
504
505
506 =item --cover-exclude-dirs ARG
507
508 =item --cover-exclude-dirs=ARG
509
510 =item --cover-exclude-dir ARG
511
512 =item --cover-exclude-dir=ARG
513
514 =item --no-cover-exclude-dirs
515
516 Directory to leave out of file coverage and coverage metrics, along with everything under it at any depth. May be specified multiple times. Wildcards are expanded when the option is parsed, so a pattern matching nothing excludes nothing. Values are word-split first, so a path containing whitespace must be quoted or backslash-escaped. A resolved path may not contain a comma.
517
518 Can be specified multiple times
519
520
521 =item --cover-exclude-private
522
523 =item --no-cover-exclude-private
524
525
526
527
528 =item --cover-files
529
530 =item --no-cover-files
531
532 Use Test2::Plugin::Cover to collect coverage data for what files are touched by what tests. Unlike Devel::Cover this has very little performance impact (About 4% difference)
533
534
535 =item --cover-from path/to/log.jsonl
536
537 =item --cover-from http://example.com/coverage
538
539 =item --cover-from path/to/coverage.jsonl
540
541 =item --no-cover-from
542
543 This can be a test log, a coverage dump (old style json or new jsonl format), or a url to any of the previous. Tests will not be run if the file/url is invalid.
544
545
546 =item --cover-from-type json
547
548 =item --cover-from-type jsonl
549
550 =item --cover-from-type log
551
552 =item --no-cover-from-type
553
554 File type for coverage source. Usually it can be detected, but when it cannot be you should specify. "json" is old style single-blob coverage data, "jsonl" is the new by-test style, "log" is a logfile from a previous run.
555
556
557 =item --cover-manager My::Coverage::Manager
558
559 =item --no-cover-manager
560
561 Coverage 'from' manager to use when coverage data does not provide one
562
563
564 =item --cover-maybe-from path/to/log.jsonl
565
566 =item --cover-maybe-from http://example.com/coverage
567
568 =item --cover-maybe-from path/to/coverage.jsonl
569
570 =item --no-cover-maybe-from
571
572 This can be a test log, a coverage dump (old style json or new jsonl format), or a url to any of the previous. Tests will continue even if the coverage file/url is invalid.
573
574
575 =item --cover-maybe-from-type json
576
577 =item --cover-maybe-from-type jsonl
578
579 =item --cover-maybe-from-type log
580
581 =item --no-cover-maybe-from-type
582
583 Same as "from_type" but for "maybe_from". Defaults to "from_type" if that is specified, otherwise auto-detect
584
585
586 =item --cover-metrics
587
588 =item --no-cover-metrics
589
590
591
592
593 =item --cover-types ARG
594
595 =item --cover-types=ARG
596
597 =item --cover-type ARG
598
599 =item --cover-type=ARG
600
601 =item --no-cover-types
602
603 NO DESCRIPTION - FIX ME
604
605 Can be specified multiple times
606
607
608 =item --cover-write
609
610 =item --cover-write=coverage.jsonl
611
612 =item --cover-write=coverage.json
613
614 =item --no-cover-write
615
616 Create a json or jsonl file of all coverage data seen during the run (This implies --cover-files).
617
618
619 =back
620
621 =head1 SOURCE
622
623 The source code repository for Test2-Harness can be found at
624 F<http://github.com/Test-More/Test2-Harness/>.
625
626 =head1 MAINTAINERS
627
628 =over 4
629
630 =item Chad Granum E<lt>[email protected]<gt>
631
632 =back
633
634 =head1 AUTHORS
635
636 =over 4
637
638 =item Chad Granum E<lt>[email protected]<gt>
639
640 =back
641
642 =head1 COPYRIGHT
643
644 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
645
646 This program is free software; you can redistribute it and/or
647 modify it under the same terms as Perl itself.
648
649 See F<http://dev.perl.org/licenses/>
650
651 =cut