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