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