]> Sergey Matveev's repositories - public-inbox.git/blob - t/run.perl
t/run: Perl future proofing
[public-inbox.git] / t / run.perl
1 #!/usr/bin/perl -w
2 # Copyright (C) 2019-2020 all contributors <meta@public-inbox.org>
3 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 #
5 # Parallel test runner which preloads code and reuses worker processes
6 # to give a nice speedup over prove(1).  It also generates per-test
7 # .log files (similar to automake tests).
8 #
9 # *.t files run by this should not rely on global state.
10 #
11 # Usage: $PERL -I lib -w t/run.perl -j4
12 # Or via prove(1): prove -lvw t/run.perl :: -j4
13 use strict;
14 use v5.10.1;
15 use IO::Handle; # ->autoflush
16 use PublicInbox::TestCommon;
17 use Cwd qw(getcwd);
18 use Getopt::Long qw(:config gnu_getopt no_ignore_case auto_abbrev);
19 use Errno qw(EINTR);
20 use Fcntl qw(:seek);
21 use POSIX qw(_POSIX_PIPE_BUF WNOHANG);
22 my $jobs = 1;
23 my $repeat = 1;
24 $| = 1;
25 our $log_suffix = '.log';
26 my ($shuffle, %pids, @err);
27 GetOptions('j|jobs=i' => \$jobs,
28         'repeat=i' => \$repeat,
29         'log=s' => \$log_suffix,
30         's|shuffle' => \$shuffle,
31 ) or die "Usage: $0 [-j JOBS] [--log=SUFFIX] [--repeat RUNS]";
32 if (($ENV{TEST_RUN_MODE} // 2) == 0) {
33         die "$0 is not compatible with TEST_RUN_MODE=0\n";
34 }
35 my @tests = scalar(@ARGV) ? @ARGV : glob('t/*.t');
36 my $cwd = getcwd();
37 open my $OLDOUT, '>&STDOUT' or die "dup STDOUT: $!";
38 open my $OLDERR, '>&STDERR' or die "dup STDERR: $!";
39 $OLDOUT->autoflush(1);
40 $OLDERR->autoflush(1);
41
42 key2sub($_) for @tests; # precache
43
44 if ($shuffle) {
45         require List::Util;
46 } elsif (open(my $prove_state, '<', '.prove') && eval { require YAML::XS }) {
47         # reuse "prove --state=save" data to start slowest tests, first
48         my $state = YAML::XS::Load(do { local $/; <$prove_state> });
49         my $t = $state->{tests};
50         @tests = sort {
51                 ($t->{$b}->{elapsed} // 0) <=> ($t->{$a}->{elapsed} // 0)
52         } @tests;
53 }
54
55 our $tb = Test::More->builder;
56
57 sub DIE (;$) {
58         print $OLDERR @_;
59         exit(1);
60 }
61
62 our ($worker, $worker_test);
63
64 sub test_status () {
65         $? = 255 if $? == 0 && !$tb->is_passing;
66         my $status = $? ? 'not ok' : 'ok';
67         chdir($cwd) or DIE "chdir($cwd): $!";
68         if ($log_suffix ne '') {
69                 my $log = $worker_test;
70                 $log =~ s/\.t\z/$log_suffix/;
71                 my $skip = '';
72                 if (open my $fh, '<', $log) {
73                         my @not_ok = grep(!/^(?:ok |[ \t]*#)/ms, <$fh>);
74                         pop @not_ok if $not_ok[-1] =~ /^[0-9]+\.\.[0-9]+$/;
75                         my $pfx = "# $log: ";
76                         print $OLDERR map { $pfx.$_ } @not_ok;
77                         seek($fh, 0, SEEK_SET) or die "seek: $!";
78
79                         # show unique skip texts and the number of times
80                         # each text was skipped
81                         local $/;
82                         my @sk = (<$fh> =~ m/^ok [0-9]+ (# skip [^\n]+)/mgs);
83                         if (@sk) {
84                                 my %nr;
85                                 my @err = grep { !$nr{$_}++ } @sk;
86                                 print $OLDERR "$pfx$_ ($nr{$_})\n" for @err;
87                                 $skip = ' # total skipped: '.scalar(@sk);
88                         }
89                 } else {
90                         print $OLDERR "could not open: $log: $!\n";
91                 }
92                 print $OLDOUT "$status $worker_test$skip\n";
93         }
94 }
95
96 # Test::Builder or Test2::Hub may call exit() from plan(skip_all => ...)
97 END { test_status() if (defined($worker_test) && $worker == $$) }
98
99 sub run_test ($) {
100         my ($test) = @_;
101         my $log_fh;
102         if ($log_suffix ne '') {
103                 my $log = $test;
104                 $log =~ s/\.[^\.]+\z/$log_suffix/ or DIE "can't log for $test";
105                 open $log_fh, '>', $log or DIE "open $log: $!";
106                 $log_fh->autoflush(1);
107                 $tb->output($log_fh);
108                 $tb->failure_output($log_fh);
109                 $tb->todo_output($log_fh);
110                 open STDOUT, '>&', $log_fh or DIE "1>$log: $!";
111                 open STDERR, '>&', $log_fh or DIE "2>$log: $!";
112         }
113         $worker_test = $test;
114         run_script([$test]);
115         test_status();
116         $worker_test = undef;
117         push @err, "$test ($?)" if $?;
118 }
119
120 sub UINT_SIZE () { 4 }
121
122 # worker processes will SIGUSR1 the producer process when it
123 # sees EOF on the pipe.  On FreeBSD 11.2 and Perl 5.30.0,
124 # sys/ioctl.ph gives the wrong value for FIONREAD().
125 my $producer = $$;
126 my $eof; # we stop respawning if true
127
128 my $start_worker = sub {
129         my ($i, $j, $rd, $todo) = @_;
130         defined(my $pid = fork) or DIE "fork: $!";
131         if ($pid == 0) {
132                 $worker = $$;
133                 while (1) {
134                         my $r = sysread($rd, my $buf, UINT_SIZE);
135                         if (!defined($r)) {
136                                 next if $! == EINTR;
137                                 DIE "sysread: $!";
138                         }
139                         last if $r == 0;
140                         DIE "short read $r" if $r != UINT_SIZE;
141                         my $t = unpack('I', $buf);
142                         run_test($todo->[$t]);
143                         $tb->reset;
144                 }
145                 kill 'USR1', $producer if !$eof; # sets $eof in $producer
146                 DIE join('', map { "E: $_\n" } @err) if @err;
147                 exit(0);
148         } else {
149                 $pids{$pid} = $j;
150         }
151 };
152
153 # negative $repeat means loop forever:
154 for (my $i = $repeat; $i != 0; $i--) {
155         my @todo = $shuffle ? List::Util::shuffle(@tests) : @tests;
156
157         # single-producer, multi-consumer queue relying on POSIX semantics
158         pipe(my ($rd, $wr)) or DIE "pipe: $!";
159
160         # fill the queue before forking so children can start earlier
161         my $n = (_POSIX_PIPE_BUF / UINT_SIZE);
162         if ($n >= $#todo) {
163                 print $wr join('', map { pack('I', $_) } (0..$#todo)) or DIE;
164                 close $wr or die;
165                 $wr = undef;
166         } else { # write what we can...
167                 $wr->autoflush(1);
168                 print $wr join('', map { pack('I', $_) } (0..$n)) or DIE;
169                 $n += 1; # and send more ($n..$#todo), later
170         }
171         $eof = undef;
172         local $SIG{USR1} = sub { $eof = 1 };
173         my $sigchld = sub {
174                 my ($sig) = @_;
175                 my $flags = $sig ? WNOHANG : 0;
176                 while (1) {
177                         my $pid = waitpid(-1, $flags) or return;
178                         return if $pid < 0;
179                         my $j = delete $pids{$pid};
180                         if (!defined($j)) {
181                                 push @err, "reaped unknown $pid ($?)";
182                                 next;
183                         }
184                         push @err, "job[$j] ($?)" if $?;
185                         # skip_all can exit(0), respawn if needed:
186                         if (!$eof) {
187                                 print $OLDERR "# respawning job[$j]\n";
188                                 $start_worker->($i, $j, $rd, \@todo);
189                         }
190                 }
191         };
192
193         # start the workers to consume the queue
194         for (my $j = 0; $j < $jobs; $j++) {
195                 $start_worker->($i, $j, $rd, \@todo);
196         }
197
198         if ($wr) {
199                 local $SIG{CHLD} = $sigchld;
200                 # too many tests to fit in the pipe before starting workers,
201                 # send the rest now the workers are running
202                 print $wr join('', map { pack('I', $_) } ($n..$#todo)) or DIE;
203                 close $wr or die;
204         }
205
206         $sigchld->(0) while scalar(keys(%pids));
207         DIE join('', map { "E: $_\n" } @err) if @err;
208 }
209
210 print $OLDOUT "1..".($repeat * scalar(@tests))."\n" if $repeat >= 0;