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