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