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