Debian Codegraph @

lib/Test2/Harness/Log/CoverageAggregator.pm

raw
1 package Test2::Harness::Log::CoverageAggregator;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use File::Find qw/find/;
8 use Test2::Harness::Util qw/clean_path/;
9 use Test2::Harness::Util::HashBase qw/<touched <job_map +can_touch +can_start_test +can_stop_test +can_record_coverage <file +io <encode/;
10
11 sub init {
12 my $self = shift;
13 $self->{+TOUCHED} //= {};
14 $self->{+JOB_MAP} //= {};
15
16 $self->{+CAN_TOUCH} = !!$self->can('touch');
17 $self->{+CAN_START_TEST} = !!$self->can('start_test');
18 $self->{+CAN_STOP_TEST} = !!$self->can('stop_test');
19 $self->{+CAN_RECORD_COVERAGE} = !!$self->can('record_coverage');
20
21 if (my $file = $self->{+FILE}) {
22 open(my $fh, '>', $file) or die "Could not open file '$file' for writing: $!";
23 $self->{+IO} = $fh;
24 }
25 }
26
27 sub flush { }
28 sub finalize { $_[0]->write }
29 sub record_metrics { }
30
31 sub write {
32 my $self = shift;
33
34 my $list = $self->flush() or return;
35 my $io = $self->{+IO} or return $list;
36
37 my $encode = $self->{+ENCODE};
38 for my $item (@$list) {
39 my $encoded = $encode ? $encode->($item) : $item;
40 print $io $encoded;
41 }
42
43 return $list;
44 }
45
46 sub process_event {
47 my $self = shift;
48 my ($e) = @_;
49
50 return unless $e;
51 return unless keys %$e;
52
53 my $job_map = $self->{+JOB_MAP} //= {};
54 my $job_id = $e->{job_id} // 0;
55
56 my $test = $job_map->{$job_id};
57
58 if (my $start = $e->{facet_data}->{harness_job_start}) {
59 $test //= $start->{rel_file};
60
61 $self->start_test($test, $e) if $self->{+CAN_START_TEST};
62 }
63
64 if (my $end = $e->{facet_data}->{harness_job_end}) {
65 $test //= $end->{rel_file};
66
67 $self->stop_test($test, $e) if $self->{+CAN_STOP_TEST};
68 }
69
70 $job_map->{$job_id} //= $test if $test;
71
72 if (my $c = $e->{facet_data}->{coverage}) {
73 die "Got coverage data before test start! (Weird event order?)" unless $test;
74 $self->_touch_coverage($test, $c, $e);
75 $self->record_coverage($test, $c, $e) if $self->{+CAN_RECORD_COVERAGE};
76 }
77
78 return $self->write();
79 }
80
81 sub _touch_coverage {
82 my $self = shift;
83 my ($test, $data, $e) = @_;
84
85 if (my $new = $data->{files}) {
86 for my $file (keys %$new) {
87 my $ndata = $new->{$file} // next;
88 for my $sub (keys %$ndata) {
89 $self->{+TOUCHED}->{$file}->{$sub}++;
90
91 next unless $self->{+CAN_TOUCH};
92 $self->touch(source => $file, sub => $sub, test => $test, manager_data => $ndata->{$sub}, event => $e);
93 }
94 }
95 }
96 }
97
98 my %PERL_TYPES = (
99 pl => 1,
100 pm => 1,
101 t => 1,
102 tx => 1,
103 t2 => 1,
104 pmc => 1,
105 );
106
107 sub build_metrics {
108 my $self = shift;
109 my %params = @_;
110
111 my $private = $params{exclude_private};
112
113 my $dirs = $params{dirs} // ['lib'];
114 my $types = $params{types} // ['pm', 'pl'];
115 my $touched = $self->{+TOUCHED} //= {};
116 my $exclude = [map { clean_path($_) } @{$params{exclude_dirs} // []}];
117
118 my $metrics = {
119 files => {total => 0, tested => 0},
120 subs => {total => 0, tested => 0},
121 untested => {files => [], subs => {}},
122 };
123
124 my $untested = $metrics->{untested};
125
126 my %type_check = map { m/\.?([^\.]+)$/g; (lc($1) => 1) } @$types;
127
128 my $raw_untested = {};
129 find(
130 {
131 no_chdir => 1,
132 wanted => sub {
133 if ($self->_excluded($File::Find::name, $exclude)) {
134 $File::Find::prune = 1;
135 return;
136 }
137
138 my $type = lc($_);
139 $type =~ s/^.*\.([^\.]+)$/$1/;
140 return unless $type_check{$type};
141 $metrics->{files}->{total}++;
142
143 my $file = $File::Find::name;
144 my $cfile = $touched->{$file};
145
146 if ($cfile) {
147 $metrics->{files}->{tested}++
148 }
149 else {
150 push @{$untested->{files}} => $file;
151 }
152
153 for my $sub ($PERL_TYPES{$type} ? $self->scan_subs($file) : ('<>')) {
154 next if $sub =~ m/^_/ && $private;
155
156 my $special_sub = $sub !~ m/^\w/;
157
158 $metrics->{subs}->{total}++ unless $special_sub;
159
160 if ($cfile && $cfile->{$sub}) {
161 $metrics->{subs}->{tested}++ unless $special_sub;
162 }
163 else {
164 $raw_untested->{$file}->{$sub} = 1;
165 }
166 }
167 },
168 },
169 @$dirs
170 );
171
172 for my $file (keys %$raw_untested) {
173 my @val = keys %{$raw_untested->{$file}};
174 next unless @val;
175
176 if (@val == 1 && $val[0] eq '<>') {
177 push @{$untested->{files}} => $file;
178 }
179 else {
180 $untested->{subs}->{$file} = [sort @val];
181 }
182 }
183
184 my %seen;
185 @{$untested->{files}} = sort grep { !$seen{$_}++ } @{$untested->{files}};
186
187 $self->record_metrics($metrics);
188
189 return $metrics;
190 }
191
192 # File coverage drops these paths before the event is sent, so counting them
193 # here would report an excluded tree as untested source.
194 sub _excluded {
195 my $self = shift;
196 my ($file, $exclude) = @_;
197
198 return 0 unless @$exclude;
199
200 my $path = clean_path($file);
201
202 for my $root (@$exclude) {
203 return 1 if $path eq $root;
204 return 1 if index($path, "$root/") == 0;
205 }
206
207 return 0;
208 }
209
210 sub scan_subs {
211 my $self = shift;
212 my ($file) = @_;
213
214 my @subs;
215
216 my $fh;
217 unless (open($fh, '<', $file)) {
218 warn "Could not open file '$file': $!";
219 return;
220 }
221
222 my $in_pod = 0;
223 while (my $line = <$fh>) {
224 $in_pod = 1 if $line =~ m/^=\w/;
225
226 if ($in_pod) {
227 next unless $line =~ m/^=cut/i;
228 $in_pod = 0;
229 next;
230 }
231
232 last if $line =~ m/^__(END|DATA)__$/;
233
234 next unless $line =~ m/^\s*sub\s+(\w+)/;
235 push @subs => $1;
236 }
237
238 return @subs;
239 }
240
241 1;
242
243 __END__
244
245 =pod
246
247 =encoding UTF-8
248
249 =head1 NAME
250
251 Test2::Harness::Log::CoverageAggregator - Module for aggregating coverage data
252 from a stream of events.
253
254 =head1 DESCRIPTION
255
256 This module takes a stream of events and produces aggregated coverage data.
257
258 =head1 SYNOPSIS
259
260 use Test2::Harness::Log::CoverageAggregator;
261
262 my $agg = Test2::Harness::Log::CoverageAggregator->new();
263
264 while (my $e = $log->next_event) {
265 $agg->process_event($e);
266 }
267
268 # Get a structure like { source_file => { source_method => $touched_count, ... }, ...}
269 my $touched_source = $agg->touched;
270
271 # Get a structure like
272 # {
273 # files => {total => 5, tested => 2},
274 # subs => {total => 20, tested => 12},
275 # untested => {files => \@file_list, subs => {file => \@sub_list, ...}},
276 # }
277 my $metrics = $agg->metrics;
278
279
280 =head1 METHODS
281
282 =head2 IMPLEMENTABLE IN SUBCLASSES
283
284 If you implement these in a subclass they will be called for you at the proper
285 times, making subclassing much easier. In most cases you can avoid overriding
286 process_event().
287
288 =over 4
289
290 =item $agg->start_test($test, $event)
291
292 This is called once per test when it starts.
293
294 B<Note:> If a test is run more than once (re-run) it will start and stop again
295 for each re-run. The event is also provided as an argument so that you can
296 check for a try-id or similar in the event that re-runs matter to you.
297
298 =item $agg->stop_test($test, $event)
299
300 This is called once per test when it stops.
301
302 B<Note:> If a test is run more than once (re-run) it will start and stop again
303 for each re-run. The event is also provided as an argument so that you can
304 check for a try-id or similar in the event that re-runs matter to you.
305
306 =item $agg->record_coverage($test, $coverage_data, $event)
307
308 This is called once per coverage event (there can be several in a test,
309 specially if it forks or uses threads).
310
311 In most cases you probably want to leave this unimplemented and implement the
312 C<touch()> method instead of iterating over the coverage structure yourself.
313
314 =item $agg->touch(source => $file, sub => $sub, test => $test, manager_data => $mdata, event => $event)
315
316 Every touch applied to a source file (and sub) will trigger this method call.
317
318 =over 4
319
320 =item source => $file
321
322 The source file that was touched
323
324 =item sub => $sub
325
326 The source subroutine that was touched. B<Note:> This may be '<>' if the source
327 file was opened via C<open()> or '*' if code outside of a subroutine was
328 executed by the test.
329
330 =item test => $test
331
332 The test file that did the touching.
333
334 =item manager_data => $mdata
335
336 If the test file makes use of a source manager to attach extra data to
337 coverage, this is where that data will be. A good example would be test suites
338 that use tools similar to Test::Class or Test::Class::Moose where all tests are
339 run in methods and you want to track what test method does the touching. Please
340 note that this level of coverage tracking is not automatic.
341
342 =item event => $event
343
344 The full event being processed.
345
346 =back
347
348 =back
349
350 =head2 PUBLIC API
351
352 =over 4
353
354 =item $agg->process_event($event)
355
356 Process the event, aggregating any coverage info it may contain.
357
358 =item $touched = $add->touched()
359
360 Returns the following structure, which tells you how many times a specific
361 source file's subroutines were called. There are also "special" subroutines
362 '<>' and '*' which mean "file was opened via open" and "code outside of a
363 subroutine".
364
365 {
366 source_file => {
367 source_method => $touched_count,
368 ...
369 },
370 ...
371 }
372
373 =item $metrics = $agg->build_metrics()
374
375 =item $metrics = $agg->build_metrics(exclude_private => $BOOL)
376
377 =item $metrics = $agg->build_metrics(exclude_dirs => \@paths)
378
379 Will build metrics, and include them in the output from C<< $agg->coverage() >>
380 next time it is called.
381
382 The C<exclude_private> option, when set to true, will exclude any method that
383 begins with an underscore from the coverage metrics and untested sub list.
384
385 The C<exclude_dirs> option takes an arrayref of directories to leave out. A
386 file at one of those paths, or under one at any depth, is counted in neither
387 the totals nor the untested lists. Paths are resolved before they are
388 compared, so they may be given relative to the current directory.
389
390 Metrics:
391
392 {
393 files => {total => 20, tested => 18},
394 subs => {total => 80, tested => 70},
395
396 untested => {
397 files => \@file_list,
398 subs => {
399 file => \@sub_list,
400 ...
401 }
402 },
403 }
404
405 =back
406
407 =head1 SOURCE
408
409 The source code repository for Test2-Harness can be found at
410 F<http://github.com/Test-More/Test2-Harness/>.
411
412 =head1 MAINTAINERS
413
414 =over 4
415
416 =item Chad Granum E<lt>[email protected]<gt>
417
418 =back
419
420 =head1 AUTHORS
421
422 =over 4
423
424 =item Chad Granum E<lt>[email protected]<gt>
425
426 =back
427
428 =head1 COPYRIGHT
429
430 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
431
432 This program is free software; you can redistribute it and/or
433 modify it under the same terms as Perl itself.
434
435 See F<http://dev.perl.org/licenses/>
436
437 =cut