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