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