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