]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/TestCommon.pm
lei: TSTP affects all curl and related subprocesses
[public-inbox.git] / lib / PublicInbox / TestCommon.pm
1 # Copyright (C) 2015-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # internal APIs used only for tests
5 package PublicInbox::TestCommon;
6 use strict;
7 use parent qw(Exporter);
8 use v5.10.1;
9 use PublicInbox::AutoReap;
10 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
11 use POSIX qw(dup2);
12 use IO::Socket::INET;
13 use File::Spec;
14 our @EXPORT;
15 my $lei_loud = $ENV{TEST_LEI_ERR_LOUD};
16 my $tail_cmd = $ENV{TAIL};
17 our ($lei_opt, $lei_out, $lei_err, $lei_cwdfh);
18 BEGIN {
19         @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
20                 run_script start_script key2sub xsys xsys_e xqx eml_load tick
21                 have_xapian_compact json_utf8 setup_public_inboxes create_inbox
22                 tcp_host_port test_lei lei lei_ok $lei_out $lei_err $lei_opt
23                 test_httpd xbail require_cmd is_xdeeply tail_f);
24         require Test::More;
25         my @methods = grep(!/\W/, @Test::More::EXPORT);
26         eval(join('', map { "*$_=\\&Test::More::$_;" } @methods));
27         die $@ if $@;
28         push @EXPORT, @methods;
29 }
30
31 sub xbail (@) { BAIL_OUT join(' ', map { ref() ? (explain($_)) : ($_) } @_) }
32
33 sub eml_load ($) {
34         my ($path, $cb) = @_;
35         open(my $fh, '<', $path) or die "open $path: $!";
36         require PublicInbox::Eml;
37         PublicInbox::Eml->new(\(do { local $/; <$fh> }));
38 }
39
40 sub tmpdir (;$) {
41         my ($base) = @_;
42         require File::Temp;
43         unless (defined $base) {
44                 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
45         }
46         my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXX", TMPDIR => 1);
47         ($tmpdir->dirname, $tmpdir);
48 }
49
50 sub tcp_server () {
51         my %opt = (
52                 ReuseAddr => 1,
53                 Proto => 'tcp',
54                 Type => Socket::SOCK_STREAM(),
55                 Listen => 1024,
56                 Blocking => 0,
57         );
58         eval {
59                 die 'IPv4-only' if $ENV{TEST_IPV4_ONLY};
60                 require IO::Socket::INET6;
61                 IO::Socket::INET6->new(%opt, LocalAddr => '[::1]')
62         } || eval {
63                 die 'IPv6-only' if $ENV{TEST_IPV6_ONLY};
64                 IO::Socket::INET->new(%opt, LocalAddr => '127.0.0.1')
65         } || BAIL_OUT "failed to create TCP server: $! ($@)";
66 }
67
68 sub tcp_host_port ($) {
69         my ($s) = @_;
70         my ($h, $p) = ($s->sockhost, $s->sockport);
71         my $ipv4 = $s->sockdomain == Socket::AF_INET();
72         if (wantarray) {
73                 $ipv4 ? ($h, $p) : ("[$h]", $p);
74         } else {
75                 $ipv4 ? "$h:$p" : "[$h]:$p";
76         }
77 }
78
79 sub tcp_connect {
80         my ($dest, %opt) = @_;
81         my $addr = tcp_host_port($dest);
82         my $s = ref($dest)->new(
83                 Proto => 'tcp',
84                 Type => Socket::SOCK_STREAM(),
85                 PeerAddr => $addr,
86                 %opt,
87         ) or BAIL_OUT "failed to connect to $addr: $!";
88         $s->autoflush(1);
89         $s;
90 }
91
92 sub require_cmd ($;$) {
93         my ($cmd, $maybe) = @_;
94         require PublicInbox::Spawn;
95         my $bin = PublicInbox::Spawn::which($cmd);
96         return $bin if $bin;
97         $maybe ? 0 : plan(skip_all => "$cmd missing from PATH for $0");
98 }
99
100 sub have_xapian_compact () {
101         require_cmd($ENV{XAPIAN_COMPACT} || 'xapian-compact', 1);
102 }
103
104 sub require_git ($;$) {
105         my ($req, $maybe) = @_;
106         my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
107         my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
108                         =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
109
110         my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
111         my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
112         if ($cur_int < $req_int) {
113                 return 0 if $maybe;
114                 plan skip_all =>
115                         "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
116         }
117         1;
118 }
119
120 sub require_mods {
121         my @mods = @_;
122         my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
123         my @need;
124         while (my $mod = shift(@mods)) {
125                 if ($mod eq 'lei') {
126                         require_git(2.6, $maybe ? $maybe : ());
127                         push @mods, qw(DBD::SQLite Search::Xapian);
128                         $mod = 'json'; # fall-through
129                 }
130                 if ($mod eq 'json') {
131                         $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||JSON||JSON::PP'
132                 } elsif ($mod eq '-httpd') {
133                         push @mods, qw(Plack::Builder Plack::Util);
134                         next;
135                 } elsif ($mod eq '-imapd') {
136                         push @mods, qw(Parse::RecDescent DBD::SQLite
137                                         Email::Address::XS||Mail::Address);
138                         next;
139                 } elsif ($mod eq '-nntpd') {
140                         push @mods, qw(DBD::SQLite);
141                         next;
142                 }
143                 if ($mod eq 'Search::Xapian') {
144                         if (eval { require PublicInbox::Search } &&
145                                 PublicInbox::Search::load_xapian()) {
146                                 next;
147                         }
148                 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
149                         my $ok;
150                         for my $m (split(/\Q||\E/, $mod)) {
151                                 eval "require $m";
152                                 next if $@;
153                                 $ok = $m;
154                                 last;
155                         }
156                         next if $ok;
157                 } else {
158                         eval "require $mod";
159                 }
160                 if ($@) {
161                         diag "require $mod: $@" if $mod =~ /Gcf2/;
162                         push @need, $mod;
163                 } elsif ($mod eq 'IO::Socket::SSL' &&
164                         # old versions of IO::Socket::SSL aren't supported
165                         # by libnet, at least:
166                         # https://rt.cpan.org/Ticket/Display.html?id=100529
167                                 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
168                         push @need, $@;
169                 }
170         }
171         return unless @need;
172         my $m = join(', ', @need)." missing for $0";
173         skip($m, $maybe) if $maybe;
174         plan(skip_all => $m)
175 }
176
177 sub key2script ($) {
178         my ($key) = @_;
179         return $key if ($key eq 'git' || index($key, '/') >= 0);
180         # n.b. we may have scripts which don't start with "public-inbox" in
181         # the future:
182         $key =~ s/\A([-\.])/public-inbox$1/;
183         'blib/script/'.$key;
184 }
185
186 my @io_mode = ([ *STDIN{IO}, '+<&' ], [ *STDOUT{IO}, '+>&' ],
187                 [ *STDERR{IO}, '+>&' ]);
188
189 sub _prepare_redirects ($) {
190         my ($fhref) = @_;
191         my $orig_io = [];
192         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
193                 my $fh = $fhref->[$fd] or next;
194                 my ($oldfh, $mode) = @{$io_mode[$fd]};
195                 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
196                 $orig_io->[$fd] = $orig;
197                 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
198         }
199         $orig_io;
200 }
201
202 sub _undo_redirects ($) {
203         my ($orig_io) = @_;
204         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
205                 my $fh = $orig_io->[$fd] or next;
206                 my ($oldfh, $mode) = @{$io_mode[$fd]};
207                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
208         }
209 }
210
211 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
212 # three ways to spawn our own short-lived Perl scripts for testing:
213 #
214 # 0 - (fork|vfork) + execve, the most realistic but slowest
215 # 1 - (not currently implemented)
216 # 2 - preloading and running in current process (slightly faster than 1)
217 #
218 # 2 is not compatible with scripts which use "exit" (which we'll try to
219 # avoid in the future).
220 # The default is 2.
221 our $run_script_exit_code;
222 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
223 sub run_script_exit {
224         $run_script_exit_code = $_[0] // 0;
225         die RUN_SCRIPT_EXIT;
226 }
227
228 our %cached_scripts;
229 sub key2sub ($) {
230         my ($key) = @_;
231         $cached_scripts{$key} //= do {
232                 my $f = key2script($key);
233                 open my $fh, '<', $f or die "open $f: $!";
234                 my $str = do { local $/; <$fh> };
235                 my $pkg = (split(m!/!, $f))[-1];
236                 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
237                 $pkg .= "_T" if $3;
238                 $pkg =~ tr/-.//d;
239                 $pkg = "PublicInbox::TestScript::$pkg";
240                 eval <<EOF;
241 package $pkg;
242 use strict;
243 use subs qw(exit);
244
245 *exit = \\&PublicInbox::TestCommon::run_script_exit;
246 sub main {
247 # the below "line" directive is a magic comment, see perlsyn(1) manpage
248 # line 1 "$f"
249 $str
250         0;
251 }
252 1;
253 EOF
254                 $pkg->can('main');
255         }
256 }
257
258 sub _run_sub ($$$) {
259         my ($sub, $key, $argv) = @_;
260         local @ARGV = @$argv;
261         $run_script_exit_code = undef;
262         my $exit_code = eval { $sub->(@$argv) };
263         if ($@ eq RUN_SCRIPT_EXIT) {
264                 $@ = '';
265                 $exit_code = $run_script_exit_code;
266                 $? = ($exit_code << 8);
267         } elsif (defined($exit_code)) {
268                 $? = ($exit_code << 8);
269         } elsif ($@) { # mimic die() behavior when uncaught
270                 warn "E: eval-ed $key: $@\n";
271                 $? = ($! << 8) if $!;
272                 $? = (255 << 8) if $? == 0;
273         } else {
274                 die "BUG: eval-ed $key: no exit code or \$@\n";
275         }
276 }
277
278 sub run_script ($;$$) {
279         my ($cmd, $env, $opt) = @_;
280         my ($key, @argv) = @$cmd;
281         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
282         my $sub = $run_mode == 0 ? undef : key2sub($key);
283         my $fhref = [];
284         my $spawn_opt = {};
285         my @tail_paths;
286         for my $fd (0..2) {
287                 my $redir = $opt->{$fd};
288                 my $ref = ref($redir);
289                 if ($ref eq 'SCALAR') {
290                         my $fh;
291                         if ($tail_cmd && $ENV{TAIL_ALL} && $fd > 0) {
292                                 require File::Temp;
293                                 $fh = File::Temp->new("fd.$fd-XXXX", TMPDIR=>1);
294                                 push @tail_paths, $fh->filename;
295                         } else {
296                                 open $fh, '+>', undef;
297                         }
298                         $fh or xbail $!;
299                         $fhref->[$fd] = $fh;
300                         $spawn_opt->{$fd} = $fh;
301                         next if $fd > 0;
302                         $fh->autoflush(1);
303                         print $fh $$redir or die "print: $!";
304                         seek($fh, 0, SEEK_SET) or die "seek: $!";
305                 } elsif ($ref eq 'GLOB') {
306                         $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
307                 } elsif ($ref) {
308                         die "unable to deal with $ref $redir";
309                 }
310         }
311         my $tail = @tail_paths ? tail_f(@tail_paths) : undef;
312         if ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
313                 unshift @argv, '--no-fsync';
314         }
315         if ($run_mode == 0) {
316                 # spawn an independent new process, like real-world use cases:
317                 require PublicInbox::Spawn;
318                 my $cmd = [ key2script($key), @argv ];
319                 if (my $d = $opt->{'-C'}) {
320                         $cmd->[0] = File::Spec->rel2abs($cmd->[0]);
321                         $spawn_opt->{'-C'} = $d;
322                 }
323                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
324                 if (defined $pid) {
325                         my $r = waitpid($pid, 0) // die "waitpid: $!";
326                         $r == $pid or die "waitpid: expected $pid, got $r";
327                 }
328         } else { # localize and run everything in the same process:
329                 # note: "local *STDIN = *STDIN;" and so forth did not work in
330                 # old versions of perl
331                 my $umask = umask;
332                 local %ENV = $env ? (%ENV, %$env) : %ENV;
333                 local @SIG{keys %SIG} = map { undef } values %SIG;
334                 local $SIG{FPE} = 'IGNORE'; # Perl default
335                 local $0 = join(' ', @$cmd);
336                 my $orig_io = _prepare_redirects($fhref);
337                 my $cwdfh = $lei_cwdfh;
338                 if (my $d = $opt->{'-C'}) {
339                         unless ($cwdfh) {
340                                 opendir $cwdfh, '.' or die "opendir .: $!";
341                         }
342                         chdir $d or die "chdir $d: $!";
343                 }
344                 _run_sub($sub, $key, \@argv);
345                 eval { PublicInbox::Inbox::cleanup_task() };
346                 die "fchdir(restore): $!" if $cwdfh && !chdir($cwdfh);
347                 _undo_redirects($orig_io);
348                 select STDOUT;
349                 umask($umask);
350         }
351
352         { local $?; undef $tail };
353         # slurp the redirects back into user-supplied strings
354         for my $fd (1..2) {
355                 my $fh = $fhref->[$fd] or next;
356                 next unless -f $fh;
357                 seek($fh, 0, SEEK_SET) or die "seek: $!";
358                 my $redir = $opt->{$fd};
359                 local $/;
360                 $$redir = <$fh>;
361         }
362         $? == 0;
363 }
364
365 sub tick (;$) {
366         my $tick = shift // 0.1;
367         select undef, undef, undef, $tick;
368         1;
369 }
370
371 sub wait_for_tail {
372         my ($tail_pid, $want) = @_;
373         my $wait = 2; # "tail -F" sleeps 1.0s at-a-time w/o inotify/kevent
374         if ($^O eq 'linux') { # GNU tail may use inotify
375                 state $tail_has_inotify;
376                 return tick if !$want && $tail_has_inotify; # before TERM
377                 my $end = time + $wait; # wait for startup:
378                 my @ino;
379                 do {
380                         @ino = grep {
381                                 readlink($_) =~ /\binotify\b/
382                         } glob("/proc/$tail_pid/fd/*");
383                 } while (!@ino && time <= $end and tick);
384                 return if !@ino;
385                 $tail_has_inotify = 1;
386                 $ino[0] =~ s!/fd/!/fdinfo/!;
387                 my @info;
388                 do {
389                         if (open my $fh, '<', $ino[0]) {
390                                 local $/ = "\n";
391                                 @info = grep(/^inotify wd:/, <$fh>);
392                         }
393                 } while (scalar(@info) < $want && time <= $end and tick);
394         } else {
395                 sleep($wait);
396         }
397 }
398
399 # like system() built-in, but uses spawn() for env/rdr + vfork
400 sub xsys {
401         my ($cmd, $env, $rdr) = @_;
402         if (ref($cmd)) {
403                 $rdr ||= {};
404         } else {
405                 $cmd = [ @_ ];
406                 $env = undef;
407                 $rdr = {};
408         }
409         run_script($cmd, $env, { %$rdr, run_mode => 0 });
410         $? >> 8
411 }
412
413 sub xsys_e { # like "/bin/sh -e"
414         xsys(@_) == 0 or
415                 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
416 }
417
418 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
419 sub xqx {
420         my ($cmd, $env, $rdr) = @_;
421         $rdr //= {};
422         run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
423         wantarray ? split(/^/m, $out) : $out;
424 }
425
426 sub tail_f (@) {
427         $tail_cmd or return; # "tail -F" or "tail -f"
428         for (@_) { open(my $fh, '>>', $_) or die $! };
429         my $cmd = [ split(/ /, $tail_cmd), @_ ];
430         require PublicInbox::Spawn;
431         my $pid = PublicInbox::Spawn::spawn($cmd, undef, { 1 => 2 });
432         wait_for_tail($pid, scalar @_);
433         PublicInbox::AutoReap->new($pid, \&wait_for_tail);
434 }
435
436 sub start_script {
437         my ($cmd, $env, $opt) = @_;
438         my ($key, @argv) = @$cmd;
439         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
440         my $sub = $run_mode == 0 ? undef : key2sub($key);
441         my $tail;
442         if ($tail_cmd) {
443                 my @paths;
444                 for (@argv) {
445                         next unless /\A--std(?:err|out)=(.+)\z/;
446                         push @paths, $1;
447                 }
448                 if ($opt) {
449                         for (1, 2) {
450                                 my $f = $opt->{$_} or next;
451                                 if (!ref($f)) {
452                                         push @paths, $f;
453                                 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
454                                         my $fd = fileno($f);
455                                         my $f = readlink "/proc/$$/fd/$fd";
456                                         push @paths, $f if -e $f;
457                                 }
458                         }
459                 }
460                 $tail = tail_f(@paths);
461         }
462         my $pid = fork // die "fork: $!\n";
463         if ($pid == 0) {
464                 eval { PublicInbox::DS->Reset };
465                 # pretend to be systemd (cf. sd_listen_fds(3))
466                 # 3 == SD_LISTEN_FDS_START
467                 my $fd;
468                 for ($fd = 0; 1; $fd++) {
469                         my $s = $opt->{$fd};
470                         last if $fd >= 3 && !defined($s);
471                         next unless $s;
472                         my $fl = fcntl($s, F_GETFD, 0);
473                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
474                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
475                         }
476                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
477                         dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
478                 }
479                 %ENV = (%ENV, %$env) if $env;
480                 my $fds = $fd - 3;
481                 if ($fds > 0) {
482                         $ENV{LISTEN_PID} = $$;
483                         $ENV{LISTEN_FDS} = $fds;
484                 }
485                 if ($opt->{-C}) { chdir($opt->{-C}) or die "chdir: $!" }
486                 $0 = join(' ', @$cmd);
487                 if ($sub) {
488                         eval { PublicInbox::DS->Reset };
489                         _run_sub($sub, $key, \@argv);
490                         POSIX::_exit($? >> 8);
491                 } else {
492                         exec(key2script($key), @argv);
493                         die "FAIL: ",join(' ', $key, @argv), ": $!\n";
494                 }
495         }
496         my $td = PublicInbox::AutoReap->new($pid);
497         $td->{-extra} = $tail;
498         $td;
499 }
500
501 # favor lei() or lei_ok() over $lei for new code
502 sub lei (@) {
503         my ($cmd, $env, $xopt) = @_;
504         $lei_out = $lei_err = '';
505         if (!ref($cmd)) {
506                 ($env, $xopt) = grep { (!defined) || ref } @_;
507                 $cmd = [ grep { defined && !ref } @_ ];
508         }
509         my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
510         if ($lei_err ne '') {
511                 if ($lei_err =~ /Use of uninitialized/ ||
512                         $lei_err =~ m!\bArgument .*? isn't numeric in !) {
513                         fail "lei_err=$lei_err";
514                 } else {
515                         diag "lei_err=$lei_err" if $lei_loud;
516                 }
517         }
518         $res;
519 };
520
521 sub lei_ok (@) {
522         state $PWD = $ENV{PWD} // Cwd::getcwd();
523         my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
524         my $tmpdir = quotemeta(File::Spec->tmpdir);
525         # filter out anything that looks like a path name for consistent logs
526         my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
527         if (!$lei_loud) {
528                 for (@msg) {
529                         s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/!;
530                         s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!g;
531                         s!\Q$PWD\E\b!\$PWD!g;
532                 }
533         }
534         ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or
535                 diag "\$?=$? err=$lei_err";
536 }
537
538 sub json_utf8 () {
539         state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
540 }
541
542 sub is_xdeeply ($$$) {
543         my ($x, $y, $desc) = @_;
544         my $ok = is_deeply($x, $y, $desc);
545         diag explain([$x, '!=', $y]) if !$ok;
546         $ok;
547 }
548
549 sub test_lei {
550 SKIP: {
551         my ($cb) = pop @_;
552         my $test_opt = shift // {};
553         local $lei_cwdfh;
554         opendir $lei_cwdfh, '.' or xbail "opendir .: $!";
555         require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
556         my $mods = $test_opt->{mods} // [ 'lei' ];
557         require_mods(@$mods, 2);
558         require PublicInbox::Config;
559         require File::Path;
560         local %ENV = %ENV;
561         delete $ENV{XDG_DATA_HOME};
562         delete $ENV{XDG_CONFIG_HOME};
563         $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
564         $ENV{GIT_COMMITTER_NAME} = 'lei user';
565         my (undef, $fn, $lineno) = caller(0);
566         my $t = "$fn:$lineno";
567         require PublicInbox::Spawn;
568         state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
569                                 eval { require Socket::MsgHdr; 1 };
570         unless ($lei_daemon) {
571                 skip('Inline::C unconfigured/missing '.
572 '(mkdir -p ~/.cache/public-inbox/inline-c) OR Socket::MsgHdr missing',
573                         1);
574         }
575         $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
576         my ($daemon_pid, $for_destroy, $daemon_xrd);
577         my $tmpdir = $test_opt->{tmpdir};
578         File::Path::mkpath($tmpdir) if (defined $tmpdir && !-d $tmpdir);
579         ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
580         state $persist_xrd = $ENV{TEST_LEI_DAEMON_PERSIST_DIR};
581         SKIP: {
582                 $ENV{TEST_LEI_ONESHOT} and
583                         xbail 'TEST_LEI_ONESHOT no longer supported';
584                 my $home = "$tmpdir/lei-daemon";
585                 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
586                 local $ENV{HOME} = $home;
587                 my $persist;
588                 if ($persist_xrd && !$test_opt->{daemon_only}) {
589                         $persist = $daemon_xrd = $persist_xrd;
590                 } else {
591                         $daemon_xrd = "$home/xdg_run";
592                         mkdir($daemon_xrd, 0700) or BAIL_OUT "mkdir: $!";
593                 }
594                 local $ENV{XDG_RUNTIME_DIR} = $daemon_xrd;
595                 $cb->();
596                 if ($persist) { # remove before ~/.local gets removed
597                         File::Path::rmtree([glob("$home/*")]);
598                         File::Path::rmtree("$home/.config");
599                 } else {
600                         lei_ok(qw(daemon-pid), \"daemon-pid after $t");
601                         chomp($daemon_pid = $lei_out);
602                         if (!$daemon_pid) {
603                                 fail("daemon not running after $t");
604                                 skip 'daemon died unexpectedly', 2;
605                         }
606                         ok(kill(0, $daemon_pid), "daemon running after $t");
607                         lei_ok(qw(daemon-kill), \"daemon-kill after $t");
608                 }
609         }; # SKIP for lei_daemon
610         if ($daemon_pid) {
611                 for (0..10) {
612                         kill(0, $daemon_pid) or last;
613                         tick;
614                 }
615                 ok(!kill(0, $daemon_pid), "$t daemon stopped");
616                 my $f = "$daemon_xrd/lei/errors.log";
617                 open my $fh, '<', $f or BAIL_OUT "$f: $!";
618                 my @l = <$fh>;
619                 is_xdeeply(\@l, [],
620                         "$t daemon XDG_RUNTIME_DIR/lei/errors.log empty");
621         }
622 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
623 } # /test_lei
624
625 # returns the pathname to a ~/.public-inbox/config in scalar context,
626 # ($test_home, $pi_config_pathname) in list context
627 sub setup_public_inboxes () {
628         my $test_home = "t/home2";
629         my $pi_config = "$test_home/.public-inbox/config";
630         my $stamp = "$test_home/setup-stamp";
631         my @ret = ($test_home, $pi_config);
632         return @ret if -f $stamp;
633
634         require PublicInbox::Lock;
635         my $lk = bless { lock_path => "$test_home/setup.lock" },
636                         'PublicInbox::Lock';
637         my $end = $lk->lock_for_scope;
638         return @ret if -f $stamp;
639
640         local $ENV{PI_CONFIG} = $pi_config;
641         for my $V (1, 2) {
642                 run_script([qw(-init --skip-docdata), "-V$V",
643                                 '--newsgroup', "t.v$V", "t$V",
644                                 "$test_home/t$V", "http://example.com/t$V",
645                                 "t$V\@example.com" ]) or xbail "init v$V";
646                 unlink "$test_home/t$V/description" or xbail "unlink $!";
647         }
648         require PublicInbox::Config;
649         require PublicInbox::InboxWritable;
650         my $cfg = PublicInbox::Config->new;
651         my $seen = 0;
652         $cfg->each_inbox(sub {
653                 my ($ibx) = @_;
654                 $ibx->{-no_fsync} = 1;
655                 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
656                 my $V = $ibx->version;
657                 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
658                 for (@eml) {
659                         next if $_ eq 't/psgi_v2-old.eml'; # dup mid
660                         $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
661                         $seen++;
662                 }
663                 $im->done;
664         });
665         $seen or BAIL_OUT 'no imports';
666         open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
667         @ret;
668 }
669
670 sub create_inbox ($$;@) {
671         my $ident = shift;
672         my $cb = pop;
673         my %opt = @_;
674         require PublicInbox::Lock;
675         require PublicInbox::InboxWritable;
676         my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
677         my $dir = "t/data-gen/$base.$ident";
678         my $new = !-d $dir;
679         if ($new) {
680                 mkdir $dir; # may race
681                 -d $dir or BAIL_OUT "$dir could not be created: $!";
682         }
683         my $lk = bless { lock_path => "$dir/creat.lock" }, 'PublicInbox::Lock';
684         $opt{inboxdir} = File::Spec->rel2abs($dir);
685         $opt{name} //= $ident;
686         my $scope = $lk->lock_for_scope;
687         my $pre_cb = delete $opt{pre_cb};
688         $pre_cb->($dir) if $pre_cb && $new;
689         $opt{-no_fsync} = 1;
690         my $no_gc = delete $opt{-no_gc};
691         my $tmpdir = delete $opt{tmpdir};
692         my $addr = $opt{address} // [];
693         $opt{-primary_address} //= $addr->[0] // "$ident\@example.com";
694         my $parallel = delete($opt{importer_parallel}) // 0;
695         my $creat_opt = { nproc => delete($opt{nproc}) // 1 };
696         my $ibx = PublicInbox::InboxWritable->new({ %opt }, $creat_opt);
697         if (!-f "$dir/creat.stamp") {
698                 my $im = $ibx->importer($parallel);
699                 $cb->($im, $ibx);
700                 $im->done if $im;
701                 unless ($no_gc) {
702                         my @to_gc = $ibx->version == 1 ? ($ibx->{inboxdir}) :
703                                         glob("$ibx->{inboxdir}/git/*.git");
704                         for my $dir (@to_gc) {
705                                 xsys_e([ qw(git gc -q) ], { GIT_DIR => $dir });
706                         }
707                 }
708                 open my $s, '>', "$dir/creat.stamp" or
709                         BAIL_OUT "error creating $dir/creat.stamp: $!";
710         }
711         if ($tmpdir) {
712                 undef $ibx;
713                 xsys([qw(/bin/cp -Rp), $dir, $tmpdir]) == 0 or
714                         BAIL_OUT "cp $dir $tmpdir";
715                 $opt{inboxdir} = $tmpdir;
716                 $ibx = PublicInbox::InboxWritable->new(\%opt);
717         }
718         $ibx;
719 }
720
721 sub test_httpd ($$;$) {
722         my ($env, $client, $skip) = @_;
723         for (qw(PI_CONFIG TMPDIR)) {
724                 $env->{$_} or BAIL_OUT "$_ unset";
725         }
726         SKIP: {
727                 require_mods(qw(Plack::Test::ExternalServer), $skip // 1);
728                 my $sock = tcp_server() or die;
729                 my ($out, $err) = map { "$env->{TMPDIR}/std$_.log" } qw(out err);
730                 my $cmd = [ qw(-httpd -W0), "--stdout=$out", "--stderr=$err" ];
731                 my $td = start_script($cmd, $env, { 3 => $sock });
732                 my ($h, $p) = tcp_host_port($sock);
733                 local $ENV{PLACK_TEST_EXTERNALSERVER_URI} = "http://$h:$p";
734                 Plack::Test::ExternalServer::test_psgi(client => $client);
735                 $td->join('TERM');
736                 open my $fh, '<', $err or BAIL_OUT $!;
737                 my $e = do { local $/; <$fh> };
738                 if ($e =~ s/^Plack::Middleware::ReverseProxy missing,\n//gms) {
739                         $e =~ s/^URL generation for redirects .*\n//gms;
740                 }
741                 is($e, '', 'no errors');
742         }
743 };
744
745
746 package PublicInbox::TestCommon::InboxWakeup;
747 use strict;
748 sub on_inbox_unlock { ${$_[0]}->($_[1]) }
749
750 1;