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