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