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