Debian Codegraph @

lib/Test2/Harness/TestFile.pm

raw
1 package Test2::Harness::TestFile;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use Carp qw/croak/;
8
9 use Time::HiRes qw/time/;
10
11 use List::Util 1.45 qw/uniq/;
12
13 use Test2::Harness::Util qw/open_file clean_path/;
14
15 use Test2::Harness::Util::UUID qw/gen_uuid/;
16
17 use File::Spec;
18
19 use Test2::Harness::Util::HashBase qw{
20 <file +relative <_scanned <_headers +_shbang <is_binary <non_perl
21 input env_vars test_args
22 queue_args
23 job_class
24 comment
25 _category _stage _duration _min_slots _max_slots
26 };
27
28 sub set_duration { $_[0]->set__duration(lc($_[1])) }
29 sub set_category { $_[0]->set__category(lc($_[1])) }
30
31 sub set_stage { $_[0]->set__stage($_[1]) }
32 sub set_min_slots { $_[0]->set__min_slots($_[1]) }
33 sub set_max_slots { $_[0]->set__max_slots($_[1]) }
34
35 sub retry { $_[0]->headers->{retry} }
36 sub set_retry {
37 my $self = shift;
38 my $val = @_ ? $_[0] : 1;
39
40 $self->scan;
41
42 $self->{+_HEADERS}->{retry} = $val;
43 }
44
45 sub retry_isolated { $_[0]->headers->{retry_isolated} }
46 sub set_retry_isolated {
47 my $self = shift;
48 my $val = @_ ? $_[0] : 1;
49
50 $self->scan;
51
52 $self->{+_HEADERS}->{retry_isolated} = $val;
53 }
54
55 sub set_smoke {
56 my $self = shift;
57 my $val = @_ ? $_[0] : 1;
58
59 $self->scan;
60
61 $self->{+_HEADERS}->{features}->{smoke} = $val;
62 }
63
64 sub init {
65 my $self = shift;
66
67 my $file = $self->file;
68
69 # We want absolute path
70 $file = clean_path($file, 0);
71 $self->{+FILE} = $file;
72
73 $self->{+QUEUE_ARGS} ||= [];
74
75 croak "Invalid test file '$file'" unless -f $file;
76
77 if($self->{+IS_BINARY} = -B $file && !-z $file) {
78 $self->{+NON_PERL} = 1;
79 die "Cannot run binary test file '$file': file is not executable.\n"
80 unless $self->is_executable;
81 }
82 }
83
84 sub relative {
85 my $self = shift;
86 return $self->{+RELATIVE} //= File::Spec->abs2rel($self->{+FILE});
87 }
88
89 my %DEFAULTS = (
90 timeout => 1,
91 fork => 1,
92 preload => 1,
93 stream => 1,
94 run => 1,
95 isolation => 0,
96 smoke => 0,
97 io_events => 1,
98 );
99
100 sub check_feature {
101 my $self = shift;
102 my ($feature, $default) = @_;
103
104 $default = $DEFAULTS{$feature} unless defined $default;
105
106 return $default unless defined $self->headers->{features}->{$feature};
107 return 1 if $self->headers->{features}->{$feature};
108 return 0;
109 }
110
111 sub check_stage {
112 my $self = shift;
113
114 return $self->{+_STAGE} if $self->{+_STAGE};
115
116 $self->_scan unless $self->{+_SCANNED};
117 return $self->{+_HEADERS}->{stage} || undef;
118 }
119
120 sub check_min_slots {
121 my $self = shift;
122
123 return $self->{+_MIN_SLOTS} if $self->{+_MIN_SLOTS};
124
125 $self->_scan unless $self->{+_SCANNED};
126 return $self->{+_HEADERS}->{min_slots} // undef;
127 }
128
129 sub check_max_slots {
130 my $self = shift;
131
132 return $self->{+_MAX_SLOTS} if $self->{+_MAX_SLOTS};
133
134 $self->_scan unless $self->{+_SCANNED};
135 return $self->{+_HEADERS}->{max_slots} // undef;
136 }
137
138 sub meta {
139 my $self = shift;
140 my ($key) = @_;
141
142 $self->_scan unless $self->{+_SCANNED};
143 my $meta = $self->{+_HEADERS}->{meta} or return ();
144
145 return () unless $key && $meta->{$key};
146
147 return @{$meta->{$key}};
148 }
149
150 sub check_duration {
151 my $self = shift;
152
153 return $self->{+_DURATION} if $self->{+_DURATION};
154
155 $self->_scan unless $self->{+_SCANNED};
156 my $duration = $self->{+_HEADERS}->{duration};
157 return $duration if $duration;
158
159 my $timeout = $self->check_feature(timeout => 1);
160
161 # 'long' for anything with no timeout
162 return 'long' unless $timeout;
163
164 return 'medium';
165 }
166
167 sub check_category {
168 my $self = shift;
169
170 return $self->{+_CATEGORY} if $self->{+_CATEGORY};
171
172 $self->_scan unless $self->{+_SCANNED};
173 my $category = $self->{+_HEADERS}->{category};
174
175 return $category if $category;
176
177 my $isolate = $self->check_feature(isolation => 0);
178
179 # 'isolation' queue if isolation requested
180 return 'isolation' if $isolate;
181
182 return 'general';
183 }
184
185 sub event_timeout { $_[0]->headers->{timeout}->{event} }
186 sub post_exit_timeout { $_[0]->headers->{timeout}->{postexit} }
187
188 sub conflicts_list {
189 return $_[0]->headers->{conflicts} || []; # Assure conflicts is always an array ref.
190 }
191
192 sub shares_list {
193 return $_[0]->headers->{shares} || []; # Assure shares is always an array ref.
194 }
195
196 sub headers {
197 my $self = shift;
198 $self->_scan unless $self->{+_SCANNED};
199 return {} unless $self->{+_HEADERS};
200 return {%{$self->{+_HEADERS}}};
201 }
202
203 sub shbang {
204 my $self = shift;
205 $self->_scan unless $self->{+_SCANNED};
206 return {} unless $self->{+_SHBANG};
207 return {%{$self->{+_SHBANG}}};
208 }
209
210 sub switches {
211 my $self = shift;
212
213 my $shbang = $self->shbang or return [];
214 my $switches = $shbang->{switches} or return [];
215
216 return $switches;
217 }
218
219 sub is_executable {
220 my $self = shift;
221 my ($file) = @_;
222 $file //= $self->{+FILE};
223 return -x $file;
224 }
225
226 sub scan {
227 my $self = shift;
228 $self->_scan();
229 return;
230 }
231
232 sub _scan {
233 my $self = shift;
234
235 return if $self->{+_SCANNED}++;
236 return if $self->{+IS_BINARY};
237
238 my $fh = open_file($self->{+FILE});
239 my $comment = $self->{+COMMENT} // '#';
240
241 my %headers;
242 for (my $ln = 1; my $line = <$fh>; $ln++) {
243 chomp($line);
244 next if $line =~ m/^\s*$/;
245
246 if ($ln == 1 && $line =~ m/^#!/) {
247 my $shbang = $self->_parse_shbang($line);
248 if ($shbang) {
249 $self->{+_SHBANG} = $shbang;
250
251 if ($shbang->{non_perl}) {
252 $self->{+NON_PERL} = 1;
253 }
254
255 next;
256 }
257 }
258
259 # Uhg, breaking encapsulation between yath and the harness
260 if ($line =~ m/^\s*#\s*THIS IS A GENERATED YATH RUNNER TEST/) {
261 $headers{features}->{run} = 0;
262 next;
263 }
264
265 next if $line =~ m/^\s*#/ && $line !~ m/^\s*#\s*HARNESS-.+/; # Ignore commented lines which aren't HARNESS-?
266 next if $line =~ m/^\s*(use|require|BEGIN|package)\b/; # Only supports single line BEGINs
267 last unless $line =~ m/^\s*\Q$comment\E\s*HARNESS-(.+)$/;
268
269 my ($dir, $rest) = split /[-\s]+/, $1, 2;
270 $dir = lc($dir);
271 my @args;
272 if ($dir eq 'meta') {
273 @args = split /\s+/, $rest, 2; # Check for white space delimited
274 @args = split(/[-]+/, $rest, 2) if scalar @args == 1; # Check for dash delimited
275 $args[1] =~ s/\s+(?:#.*)?$// if defined $args[1]; # Strip trailing white space and comment if present
276 }
277 elsif ($rest) {
278 $rest =~ s/\s+(?:#.*)?$//; # Strip trailing white space and comment if present
279 @args = split /[-\s]+/, $rest;
280 }
281
282 if ($dir eq 'no') {
283 my $feature = lc(join '_' => @args);
284 if ($feature eq 'retry') {
285 $headers{retry} = 0
286 } else {
287 $headers{features}->{$feature} = 0;
288 }
289 }
290 elsif ($dir eq 'smoke') {
291 $headers{features}->{smoke} = 1;
292 }
293 elsif ($dir eq 'retry') {
294 $headers{retry} = 1 unless @args || defined $headers{retry};
295 for my $arg (@args) {
296 if ($arg =~ m/^\d+$/) {
297 $headers{retry} = int $arg;
298 }
299 elsif ($arg =~ m/^iso/i) {
300 $headers{retry} //= 1;
301 $headers{retry_isolated} = 1;
302 }
303 else {
304 warn "Unknown 'HARNESS-RETRY' argument '$arg' at $self->{+FILE} line $ln.\n";
305 }
306 }
307 }
308 elsif ($dir eq 'yes' || $dir eq 'use') {
309 my $feature = lc(join '_' => @args);
310 $headers{features}->{$feature} = 1;
311 }
312 elsif ($dir eq 'stage') {
313 my ($name) = @args;
314 $headers{stage} = $name;
315 }
316 elsif ($dir eq 'meta') {
317 my ($key, $val) = @args;
318 $key = lc($key);
319 push @{$headers{meta}->{$key}} => $val;
320 }
321 elsif ($dir eq 'duration' || $dir eq 'dur') {
322 my ($name) = @args;
323 $name = lc($name);
324 $headers{duration} = $name;
325 }
326 elsif ($dir eq 'category' || $dir eq 'cat') {
327 my ($name) = @args;
328 $name = lc($name);
329 if ($name =~ m/^(long|medium|short)$/i) {
330 $headers{duration} = $name;
331 }
332 else {
333 $headers{category} = $name;
334 }
335 }
336 elsif ($dir eq 'conflicts') {
337 my @conflicts_array;
338
339 foreach my $arg (@args) {
340 push @conflicts_array, lc($arg);
341 }
342
343 # Allow multiple lines with # HARNESS-CONFLICTS FOO
344 $headers{conflicts} ||= [];
345 push @{$headers{conflicts}}, @conflicts_array;
346
347 # Make sure no more than 1 conflict is ever present.
348 @{$headers{conflicts}} = uniq @{$headers{conflicts}};
349 }
350 elsif ($dir eq 'shares') {
351 # Allow multiple lines with # HARNESS-SHARES FOO
352 $headers{shares} ||= [];
353 push @{$headers{shares}}, map { lc($_) } @args;
354
355 # Make sure no more than 1 share of a name is ever present.
356 @{$headers{shares}} = uniq @{$headers{shares}};
357 }
358 elsif ($dir eq 'timeout') {
359 my ($type, $num, $extra) = @args;
360 $type = lc($type);
361 $num = lc($num);
362
363 ($type, $num) = ('postexit', $extra) if $type eq 'post' && $num eq 'exit';
364
365 warn "'" . uc($type) . "' is not a valid timeout type, use 'EVENT' or 'POSTEXIT' at $self->{+FILE} line $ln.\n"
366 unless $type =~ m/^(event|postexit)$/;
367
368 $headers{timeout}->{$type} = $num;
369 }
370 elsif ($dir eq 'job' && $rest =~ m/slots\s+(\d+)(?:\s+(\d+))?$/i) {
371 $headers{min_slots} //= $1;
372 $headers{max_slots} //= $2 ? $2 : $1;
373 }
374 else {
375 warn "Unknown harness directive '$dir' at $self->{+FILE} line $ln.\n";
376 }
377 }
378
379 # An exclusive lock on a name gazumps a shared one, so if a file asks for
380 # both we keep the exclusive and drop the shared. This is probably a
381 # mistake on the author's part, so warn.
382 if ($headers{conflicts} && $headers{shares}) {
383 my %exclusive = map { ($_ => 1) } @{$headers{conflicts}};
384
385 for my $both (grep { $exclusive{$_} } @{$headers{shares}}) {
386 warn "'$both' is listed as both a conflict and a share in $self->{+FILE}, treating it as a conflict.\n";
387 }
388
389 @{$headers{shares}} = grep { !$exclusive{$_} } @{$headers{shares}};
390 }
391
392 $self->{+_HEADERS} = \%headers;
393 }
394
395 sub _parse_shbang {
396 my $self = shift;
397 my $line = shift;
398
399 return {} if !defined $line;
400
401 my %shbang;
402
403 # NOTE: Test this, the dashes should be included with the switches
404 my $shbang_re = qr{
405 ^
406 \#!.*perl.*? # the perl path
407 (?: \s (-.+) )? # the switches, maybe
408 \s*
409 $
410 }xi;
411
412 if ($line =~ $shbang_re) {
413 my @switches;
414 @switches = grep { m/\S/ } split /\s+/, $1 if defined $1;
415 $shbang{switches} = \@switches;
416 $shbang{line} = $line;
417 }
418 elsif ($line =~ m/^#!/ && $line !~ m/perl/i) {
419 $shbang{line} = $line;
420 $shbang{non_perl} = 1;
421 }
422
423 return \%shbang;
424 }
425
426 sub queue_item {
427 my $self = shift;
428 my ($job_name, $run_id, %inject) = @_;
429
430 die "The '$self->{+FILE}' test specifies that it should not be run by Test2::Harness.\n"
431 unless $self->check_feature(run => 1);
432
433 my $category = $self->check_category;
434 my $duration = $self->check_duration;
435 my $stage = $self->check_stage;
436 my $min_slots = $self->check_min_slots;
437 my $max_slots = $self->check_max_slots;
438
439 my $smoke = $self->check_feature(smoke => 0);
440 my $fork = $self->check_feature(fork => 1);
441 my $preload = $self->check_feature(preload => 1);
442 my $timeout = $self->check_feature(timeout => 1);
443 my $stream = $self->check_feature(stream => 1);
444 my $io_events = $self->check_feature(io_events => 1);
445
446 my $retry = $self->retry;
447 my $retry_isolated = $self->retry_isolated;
448
449 my $binary = $self->{+IS_BINARY} ? 1 : 0;
450 my $non_perl = $self->{+NON_PERL} ? 1 : 0;
451
452 my $et = $self->event_timeout;
453 my $pet = $self->post_exit_timeout;
454
455 my $job_class = $self->job_class;
456
457 my $input = $self->input;
458 my $test_args = $self->test_args;
459
460 my $env_vars = $self->env_vars;
461 if ($env_vars) {
462 my $mix = delete $inject{env_vars};
463 $env_vars = {%$mix, %$env_vars} if $mix;
464 }
465
466 return {
467 binary => $binary,
468 category => $category,
469 conflicts => $self->conflicts_list,
470 shares => $self->shares_list,
471 duration => $duration,
472 file => $self->file,
473 rel_file => $self->relative,
474 job_id => gen_uuid(),
475 job_name => $job_name,
476 run_id => $run_id,
477 non_perl => $non_perl,
478 stage => $stage,
479 stamp => time,
480 switches => $self->switches,
481 use_fork => $fork,
482 use_preload => $preload,
483 use_stream => $stream,
484 use_timeout => $timeout,
485 smoke => $smoke,
486 io_events => $io_events,
487 rank => $self->rank,
488
489 defined($input) ? (input => $input) : (),
490 defined($env_vars) ? (env_vars => $env_vars) : (),
491 defined($test_args) ? (test_args => $test_args) : (),
492 defined($job_class) ? (job_class => $job_class) : (),
493 defined($retry) ? (retry => $retry) : (),
494 defined($retry_isolated) ? (retry_isolated => $retry_isolated) : (),
495 defined($et) ? (event_timeout => $et) : (),
496 defined($pet) ? (post_exit_timeout => $self->post_exit_timeout) : (),
497 defined($min_slots) ? (min_slots => $min_slots) : (),
498 defined($max_slots) ? (max_slots => $max_slots) : (),
499
500 @{$self->{+QUEUE_ARGS}},
501
502 %inject,
503 };
504 }
505
506 my %RANK = (
507 smoke => 1,
508 immiscible => 10,
509 long => 20,
510 medium => 50,
511 short => 80,
512 isolation => 100,
513 );
514
515 sub rank {
516 my $self = shift;
517
518 return $RANK{smoke} if $self->check_feature('smoke');
519
520 my $rank = $RANK{$self->check_category};
521 $rank ||= $RANK{$self->check_duration};
522 $rank ||= 1;
523
524 return $rank;
525 }
526
527 1;
528
529 __END__
530
531 =pod
532
533 =encoding UTF-8
534
535 =head1 NAME
536
537 Test2::Harness::TestFile - Abstraction of a test file and its meta-data.
538
539 =head1 DESCRIPTION
540
541 When Test2::Harness finds test files to run each one gets an instance of this
542 class to represent it. This class will scan test files to find important meta
543 data (binary vs script, inline harness directives, etc). The meta-data this
544 class can find helps yath decide when and how to run the test.
545
546 If you write a custom L<Test2::Harness::Finder> or use some
547 L<Test2::Harness::Plugin> callbacks you may have to use, or even construct
548 instances of this class.
549
550 =head1 SYNOPSIS
551
552 use Test2::Harness::TestFile;
553
554 my $tf = Test2::Harness::TestFile->new(file => "path/to/file.t");
555
556 # For an example 1, 1 works, but normally they are job_name and run_id.
557 my $meta_data = $tf->queue_item(1, 1);
558
559
560 =head1 ATTRIBUTES
561
562 =over 4
563
564 =item $filename = $tf->file
565
566 Set during object construction, and cannot be changed.
567
568 =item $bool = $tf->is_binary
569
570 Automatically set during construction, cannot be changed or set manually.
571
572 =item $bool = $tf->non_perl
573
574 Automatically set during construction, cannot be changed or set manually.
575
576 =item $string = $tf->comment
577
578 =item $tf->set_comment($string)
579
580 Defaults to '#' can be set during construction, or changed if needed.
581
582 This is used to tell yath what character(s) are used to denote a comment. This
583 is necessary for finding harness directives. In perl the '#' character is used,
584 and that is the default value. This is here to support non-perl tests.
585
586 =item $class = $tf->job_class
587
588 =item $tf->set_job_class($class)
589
590 Default it undef (let the runner pick). You can change this if you want the
591 test to run with a custom job subclass.
592
593 =item $arrayref = $tf->queue_args
594
595 =item $tf->set_queue_args(\@ARGS)
596
597 Key/Value pairs to append to the queue_item() data.
598
599 =back
600
601 =head1 METHODS
602
603 =over 4
604
605 =item $cat = $tf->check_category()
606
607 =item $tf->set_category($cat)
608
609 This is how you find the category for a file. You can use C<set_category()> to
610 assign/override a category.
611
612 =item $dur = $tf->check_duration()
613
614 =item $tf->set_duration($dur)
615
616 Get the duration of the test file ('LONG', 'MEDIUM', 'SHORT'). You can override
617 with C<set_duration()>.
618
619 =item $stage = $tf->check_stage()
620
621 =item $tf->set_stage($stage)
622
623 Get the preload stage the test file thinks it should be run in. You can
624 override with C<set_stage()>.
625
626 =item $bool = $tf->check_feature($name)
627
628 This checks for the C<# HARNESS-NO-NAME> or C<# HARNESS-USE-NAME> or
629 C<# HARNESS-YES-NAME> directives. C<NO> will result in a false boolean. C<YES>
630 and C<USE> will result in a true boolean. If no directive is found then
631 C<undef> will be returned.
632
633 =item $arrayref = $tf->conflicts_list()
634
635 Get a list of conflict markers.
636
637 =item $arrayref = $tf->shares_list()
638
639 Get a list of shared-use markers.
640
641 =item $seconds = $tf->event_timeout()
642
643 If they test specifies an event timeout this will return it.
644
645 =item %headers = $tf->headers()
646
647 This returns the header data from the test file.
648
649 =item $bool = $tf->is_executable()
650
651 Check if the test file is executable or not.
652
653 =item $data = $tf->meta($key)
654
655 Get the meta-data for the specific key.
656
657 =item $seconds = $tf->post_exit_timeout()
658
659 If the test file has a custom post-exit timeout, this will return it.
660
661 =item $hashref = $tf->queue_item($job_name, $run_id)
662
663 This returns the data used to add the test file to the runner queue.
664
665 =item $int = $tf->rank()
666
667 Returns an integer value used to sort tests into an efficient run order.
668
669 =item $path = $tf->relative()
670
671 Relative path to the test file.
672
673 =item $tf->scan()
674
675 Scan the file and populate the header data. Return nothing, takes no arguments.
676 Automatically run by things that require the scan data. Results are cached.
677
678 =item $tf->set_smoke($bool)
679
680 Set smoke status. Smoke tests go to the front of the line when tests are
681 sorted.
682
683 =item $hashref = $tf->shbang()
684
685 Get data gathered from parsing the tests shbang line.
686
687 =item $arrayref = $tf->switches()
688
689 A list of switches passed to perl, usually from the shbang line.
690
691 =back
692
693 =head1 SOURCE
694
695 The source code repository for Test2-Harness can be found at
696 F<http://github.com/Test-More/Test2-Harness/>.
697
698 =head1 MAINTAINERS
699
700 =over 4
701
702 =item Chad Granum E<lt>[email protected]<gt>
703
704 =back
705
706 =head1 AUTHORS
707
708 =over 4
709
710 =item Chad Granum E<lt>[email protected]<gt>
711
712 =back
713
714 =head1 COPYRIGHT
715
716 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
717
718 This program is free software; you can redistribute it and/or
719 modify it under the same terms as Perl itself.
720
721 See F<http://dev.perl.org/licenses/>
722
723 =cut