]> Sergey Matveev's repositories - public-inbox.git/blob - t/run.perl
lei forget-mail-sync: new command to drop sync information
[public-inbox.git] / t / run.perl
1 #!/usr/bin/perl -w
2 # Copyright (C) 2019-2021 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 PublicInbox::Spawn;
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 use File::Temp ();
23 my $jobs = 1;
24 my $repeat = 1;
25 $| = 1;
26 our $log_suffix = '.log';
27 my ($shuffle, %pids, @err);
28 GetOptions('j|jobs=i' => \$jobs,
29         'repeat=i' => \$repeat,
30         'log=s' => \$log_suffix,
31         's|shuffle' => \$shuffle,
32 ) or die "Usage: $0 [-j JOBS] [--log=SUFFIX] [--repeat RUNS]";
33 if (($ENV{TEST_RUN_MODE} // 2) == 0) {
34         die "$0 is not compatible with TEST_RUN_MODE=0\n";
35 }
36 my @tests = scalar(@ARGV) ? @ARGV : glob('t/*.t');
37 open my $cwd_fh, '<', '.' or die "open .: $!";
38 open my $OLDOUT, '>&STDOUT' or die "dup STDOUT: $!";
39 open my $OLDERR, '>&STDERR' or die "dup STDERR: $!";
40 $OLDOUT->autoflush(1);
41 $OLDERR->autoflush(1);
42
43 my ($run_log, $tmp_rl);
44 my $rl = $ENV{TEST_RUN_LOG};
45 unless ($rl) {
46         $tmp_rl = File::Temp->new(CLEANUP => 1);
47         $rl = $tmp_rl->filename;
48 }
49 open $run_log, '+>>', $rl or die "open $rl: $!";
50 $run_log->autoflush(1); # one reader, many writers
51
52 key2sub($_) for @tests; # precache
53
54 my ($for_destroy, $lei_env, $lei_daemon_pid, $owner_pid);
55 if (!$ENV{TEST_LEI_DAEMON_PERSIST_DIR} &&
56                 (PublicInbox::Spawn->can('recv_cmd4') ||
57                         eval { require Socket::MsgHdr })) {
58         $lei_env = {};
59         ($lei_env->{XDG_RUNTIME_DIR}, $for_destroy) = tmpdir;
60         $ENV{TEST_LEI_DAEMON_PERSIST_DIR} = $lei_env->{XDG_RUNTIME_DIR};
61         run_script([qw(lei daemon-pid)], $lei_env, { 1 => \$lei_daemon_pid });
62         chomp $lei_daemon_pid;
63         $lei_daemon_pid =~ /\A[0-9]+\z/ or die "no daemon pid: $lei_daemon_pid";
64         kill(0, $lei_daemon_pid) or die "kill $lei_daemon_pid: $!";
65         if (my $t = $ENV{GNU_TAIL}) {
66                 system("$t --pid=$lei_daemon_pid -F " .
67                         "$lei_env->{XDG_RUNTIME_DIR}/lei/errors.log >&2 &");
68         }
69         if (my $strace_cmd = $ENV{STRACE_CMD}) {
70                 system("$strace_cmd -p $lei_daemon_pid &");
71         }
72         $owner_pid = $$;
73 }
74
75 if ($shuffle) {
76         require List::Util;
77 } elsif (open(my $prove_state, '<', '.prove') && eval { require YAML::XS }) {
78         # reuse "prove --state=save" data to start slowest tests, first
79         my $state = YAML::XS::Load(do { local $/; <$prove_state> });
80         my $t = $state->{tests};
81         @tests = sort {
82                 ($t->{$b}->{elapsed} // 0) <=> ($t->{$a}->{elapsed} // 0)
83         } @tests;
84 }
85
86 our $tb = Test::More->builder;
87
88 sub DIE (;$) {
89         print $OLDERR @_;
90         exit(1);
91 }
92
93 our ($worker, $worker_test);
94
95 sub test_status () {
96         $? = 255 if $? == 0 && !$tb->is_passing;
97         my $status = $? ? 'not ok' : 'ok';
98         chdir($cwd_fh) or DIE "fchdir: $!";
99         if ($log_suffix ne '') {
100                 my $log = $worker_test;
101                 $log =~ s/\.t\z/$log_suffix/;
102                 my $skip = '';
103                 if (open my $fh, '<', $log) {
104                         my @not_ok = grep(!/^(?:ok |[ \t]*#)/ms, <$fh>);
105                         my $last = $not_ok[-1] // '';
106                         pop @not_ok if $last =~ /^[0-9]+\.\.[0-9]+$/;
107                         my $pfx = "# $log: ";
108                         print $OLDERR map { $pfx.$_ } @not_ok;
109                         seek($fh, 0, SEEK_SET) or die "seek: $!";
110
111                         # show unique skip texts and the number of times
112                         # each text was skipped
113                         local $/;
114                         my @sk = (<$fh> =~ m/^ok [0-9]+ (# skip [^\n]+)/mgs);
115                         if (@sk) {
116                                 my %nr;
117                                 my @err = grep { !$nr{$_}++ } @sk;
118                                 print $OLDERR "$pfx$_ ($nr{$_})\n" for @err;
119                                 $skip = ' # total skipped: '.scalar(@sk);
120                         }
121                 } else {
122                         print $OLDERR "could not open: $log: $!\n";
123                 }
124                 print $OLDOUT "$status $worker_test$skip\n";
125         }
126 }
127
128 # Test::Builder or Test2::Hub may call exit() from plan(skip_all => ...)
129 END { test_status() if (defined($worker_test) && $worker == $$) }
130
131 sub run_test ($) {
132         my ($test) = @_;
133         syswrite($run_log, "$$ $test\n");
134         my $log_fh;
135         if ($log_suffix ne '') {
136                 my $log = $test;
137                 $log =~ s/\.[^\.]+\z/$log_suffix/ or DIE "can't log for $test";
138                 open $log_fh, '>', $log or DIE "open $log: $!";
139                 $log_fh->autoflush(1);
140                 $tb->output($log_fh);
141                 $tb->failure_output($log_fh);
142                 $tb->todo_output($log_fh);
143                 open STDOUT, '>&', $log_fh or DIE "1>$log: $!";
144                 open STDERR, '>&', $log_fh or DIE "2>$log: $!";
145         }
146         $worker_test = $test;
147         run_script([$test]);
148         test_status();
149         $worker_test = undef;
150         push @err, "$test ($?)" if $?;
151 }
152
153 sub UINT_SIZE () { 4 }
154
155 # worker processes will SIGUSR1 the producer process when it
156 # sees EOF on the pipe.  On FreeBSD 11.2 and Perl 5.30.0,
157 # sys/ioctl.ph gives the wrong value for FIONREAD().
158 my $producer = $$;
159 my $eof; # we stop respawning if true
160
161 my $start_worker = sub {
162         my ($j, $rd, $wr, $todo) = @_;
163         my $pid = fork // DIE "fork: $!";
164         if ($pid == 0) {
165                 close $wr if $wr;
166                 $worker = $$;
167                 while (1) {
168                         my $r = sysread($rd, my $buf, UINT_SIZE);
169                         if (!defined($r)) {
170                                 next if $! == EINTR;
171                                 DIE "sysread: $!";
172                         }
173                         last if $r == 0;
174                         DIE "short read $r" if $r != UINT_SIZE;
175                         my $t = unpack('I', $buf);
176                         run_test($todo->[$t]);
177                         $tb->reset;
178                 }
179                 kill 'USR1', $producer if !$eof; # sets $eof in $producer
180                 DIE join('', map { "E: $_\n" } @err) if @err;
181                 exit(0);
182         } else {
183                 $pids{$pid} = $j;
184         }
185 };
186
187 # negative $repeat means loop forever:
188 for (my $i = $repeat; $i != 0; $i--) {
189         my @todo = $shuffle ? List::Util::shuffle(@tests) : @tests;
190
191         # single-producer, multi-consumer queue relying on POSIX pipe semantics
192         # POSIX.1-2008 stipulates a regular file should work, but Linux <3.14
193         # had broken read(2) semantics according to the read(2) manpage
194         pipe(my ($rd, $wr)) or DIE "pipe: $!";
195
196         # fill the queue before forking so children can start earlier
197         my $n = (_POSIX_PIPE_BUF / UINT_SIZE);
198         if ($n >= $#todo) {
199                 print $wr join('', map { pack('I', $_) } (0..$#todo)) or DIE;
200                 undef $wr;
201         } else { # write what we can...
202                 $wr->autoflush(1);
203                 print $wr join('', map { pack('I', $_) } (0..$n)) or DIE;
204                 $n += 1; # and send more ($n..$#todo), later
205         }
206         $eof = undef;
207         local $SIG{USR1} = sub { $eof = 1 };
208         my $sigchld = sub {
209                 my ($sig) = @_;
210                 my $flags = $sig ? WNOHANG : 0;
211                 while (1) {
212                         my $pid = waitpid(-1, $flags) or return;
213                         return if $pid < 0;
214                         my $j = delete $pids{$pid};
215                         if (!defined($j)) {
216                                 push @err, "reaped unknown $pid ($?)";
217                                 next;
218                         }
219                         if ($?) {
220                                 seek($run_log, 0, SEEK_SET);
221                                 chomp(my @t = grep(/^$pid /, <$run_log>));
222                                 $t[0] //= "$pid unknown";
223                                 push @err, "job[$j] ($?) PID=$t[-1]";
224                         }
225                         # skip_all can exit(0), respawn if needed:
226                         if (!$eof) {
227                                 print $OLDERR "# respawning job[$j]\n";
228                                 $start_worker->($j, $rd, $wr, \@todo);
229                         }
230                 }
231         };
232
233         # start the workers to consume the queue
234         for (my $j = 0; $j < $jobs; $j++) {
235                 $start_worker->($j, $rd, $wr, \@todo);
236         }
237         if ($wr) {
238                 local $SIG{CHLD} = $sigchld;
239                 # too many tests to fit in the pipe before starting workers,
240                 # send the rest now the workers are running
241                 print $wr join('', map { pack('I', $_) } ($n..$#todo)) or DIE;
242                 undef $wr;
243         }
244
245         $sigchld->(0) while scalar(keys(%pids));
246         DIE join('', map { "E: $_\n" } @err) if @err;
247 }
248
249 print $OLDOUT "1..".($repeat * scalar(@tests))."\n" if $repeat >= 0;
250 if ($lei_env && $$ == $owner_pid) {
251         my $opt = { 1 => $OLDOUT, 2 => $OLDERR };
252         run_script([qw(lei daemon-kill)], $lei_env, $opt);
253 }