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>
4 # internal APIs used only for tests
5 package PublicInbox::TestCommon;
7 use parent qw(Exporter);
9 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
14 my $lei_loud = $ENV{TEST_LEI_ERR_LOUD};
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
22 my @methods = grep(!/\W/, @Test::More::EXPORT);
23 eval(join('', map { "*$_=\\&Test::More::$_;" } @methods));
25 push @EXPORT, @methods;
28 sub xbail (@) { BAIL_OUT join(' ', map { ref ? (explain($_)) : ($_) } @_) }
32 open(my $fh, '<', $path) or die "open $path: $!";
33 require PublicInbox::Eml;
34 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
40 unless (defined $base) {
41 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
43 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXX", TMPDIR => 1);
44 ($tmpdir->dirname, $tmpdir);
51 Type => Socket::SOCK_STREAM(),
56 die 'IPv4-only' if $ENV{TEST_IPV4_ONLY};
57 require IO::Socket::INET6;
58 IO::Socket::INET6->new(%opt, LocalAddr => '[::1]')
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: $! ($@)";
65 sub tcp_host_port ($) {
67 my ($h, $p) = ($s->sockhost, $s->sockport);
68 my $ipv4 = $s->sockdomain == Socket::AF_INET();
70 $ipv4 ? ($h, $p) : ("[$h]", $p);
72 $ipv4 ? "$h:$p" : "[$h]:$p";
77 my ($dest, %opt) = @_;
78 my $addr = tcp_host_port($dest);
79 my $s = ref($dest)->new(
81 Type => Socket::SOCK_STREAM(),
84 ) or BAIL_OUT "failed to connect to $addr: $!";
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+))?/);
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) {
100 "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
107 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
109 while (my $mod = shift(@mods)) {
111 require_git(2.6, $maybe ? $maybe : ());
112 push @mods, qw(DBD::SQLite Search::Xapian);
113 $mod = 'json'; # fall-through
115 if ($mod eq 'json') {
116 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||JSON||JSON::PP'
117 } elsif ($mod eq '-httpd') {
118 push @mods, qw(Plack::Builder Plack::Util);
120 } elsif ($mod eq '-imapd') {
121 push @mods, qw(Parse::RecDescent DBD::SQLite
122 Email::Address::XS||Mail::Address);
124 } elsif ($mod eq '-nntpd') {
125 push @mods, qw(DBD::SQLite);
128 if ($mod eq 'Search::Xapian') {
129 if (eval { require PublicInbox::Search } &&
130 PublicInbox::Search::load_xapian()) {
133 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
135 for my $m (split(/\Q||\E/, $mod)) {
147 } elsif ($mod eq 'IO::Socket::SSL' &&
148 # old versions of IO::Socket::SSL aren't supported
149 # by libnet, at least:
150 # https://rt.cpan.org/Ticket/Display.html?id=100529
151 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
156 my $m = join(', ', @need)." missing for $0";
157 skip($m, $maybe) if $maybe;
163 return $key if ($key eq 'git' || index($key, '/') >= 0);
164 # n.b. we may have scripts which don't start with "public-inbox" in
166 $key =~ s/\A([-\.])/public-inbox$1/;
170 my @io_mode = ([ *STDIN{IO}, '+<&' ], [ *STDOUT{IO}, '+>&' ],
171 [ *STDERR{IO}, '+>&' ]);
173 sub _prepare_redirects ($) {
176 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
177 my $fh = $fhref->[$fd] or next;
178 my ($oldfh, $mode) = @{$io_mode[$fd]};
179 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
180 $orig_io->[$fd] = $orig;
181 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
186 sub _undo_redirects ($) {
188 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
189 my $fh = $orig_io->[$fd] or next;
190 my ($oldfh, $mode) = @{$io_mode[$fd]};
191 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
195 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
196 # three ways to spawn our own short-lived Perl scripts for testing:
198 # 0 - (fork|vfork) + execve, the most realistic but slowest
199 # 1 - (not currently implemented)
200 # 2 - preloading and running in current process (slightly faster than 1)
202 # 2 is not compatible with scripts which use "exit" (which we'll try to
203 # avoid in the future).
205 our $run_script_exit_code;
206 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
207 sub run_script_exit {
208 $run_script_exit_code = $_[0] // 0;
215 $cached_scripts{$key} //= do {
216 my $f = key2script($key);
217 open my $fh, '<', $f or die "open $f: $!";
218 my $str = do { local $/; <$fh> };
219 my $pkg = (split(m!/!, $f))[-1];
220 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
223 $pkg = "PublicInbox::TestScript::$pkg";
229 *exit = \\&PublicInbox::TestCommon::run_script_exit;
231 # the below "line" directive is a magic comment, see perlsyn(1) manpage
243 my ($sub, $key, $argv) = @_;
244 local @ARGV = @$argv;
245 $run_script_exit_code = undef;
246 my $exit_code = eval { $sub->(@$argv) };
247 if ($@ eq RUN_SCRIPT_EXIT) {
249 $exit_code = $run_script_exit_code;
250 $? = ($exit_code << 8);
251 } elsif (defined($exit_code)) {
252 $? = ($exit_code << 8);
253 } elsif ($@) { # mimic die() behavior when uncaught
254 warn "E: eval-ed $key: $@\n";
255 $? = ($! << 8) if $!;
256 $? = (255 << 8) if $? == 0;
258 die "BUG: eval-ed $key: no exit code or \$@\n";
262 sub run_script ($;$$) {
263 my ($cmd, $env, $opt) = @_;
264 my ($key, @argv) = @$cmd;
265 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
266 my $sub = $run_mode == 0 ? undef : key2sub($key);
270 my $redir = $opt->{$fd};
271 my $ref = ref($redir);
272 if ($ref eq 'SCALAR') {
273 open my $fh, '+>', undef or die "open: $!";
275 $spawn_opt->{$fd} = $fh;
278 print $fh $$redir or die "print: $!";
279 seek($fh, 0, SEEK_SET) or die "seek: $!";
280 } elsif ($ref eq 'GLOB') {
281 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
283 die "unable to deal with $ref $redir";
286 if ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
287 unshift @argv, '--no-fsync';
289 if ($run_mode == 0) {
290 # spawn an independent new process, like real-world use cases:
291 require PublicInbox::Spawn;
292 my $cmd = [ key2script($key), @argv ];
293 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
295 my $r = waitpid($pid, 0) // die "waitpid: $!";
296 $r == $pid or die "waitpid: expected $pid, got $r";
298 } else { # localize and run everything in the same process:
299 # note: "local *STDIN = *STDIN;" and so forth did not work in
300 # old versions of perl
301 local %ENV = $env ? (%ENV, %$env) : %ENV;
303 local $0 = join(' ', @$cmd);
304 my $orig_io = _prepare_redirects($fhref);
305 _run_sub($sub, $key, \@argv);
306 eval { PublicInbox::Inbox::cleanup_task() };
307 _undo_redirects($orig_io);
311 # slurp the redirects back into user-supplied strings
313 my $fh = $fhref->[$fd] or next;
314 seek($fh, 0, SEEK_SET) or die "seek: $!";
315 my $redir = $opt->{$fd};
323 my $tick = shift // 0.1;
324 select undef, undef, undef, $tick;
328 sub wait_for_tail ($;$) {
329 my ($tail_pid, $want) = @_;
331 if ($^O eq 'linux') { # GNU tail may use inotify
332 state $tail_has_inotify;
333 return tick if $want < 0 && $tail_has_inotify;
334 my $end = time + $wait;
338 readlink($_) =~ /\binotify\b/
339 } glob("/proc/$tail_pid/fd/*");
340 } while (!@ino && time <= $end and tick);
342 $tail_has_inotify = 1;
343 $ino[0] =~ s!/fd/!/fdinfo/!;
346 if (open my $fh, '<', $ino[0]) {
348 @info = grep(/^inotify wd:/, <$fh>);
350 } while (scalar(@info) < $want && time <= $end and tick);
356 # like system() built-in, but uses spawn() for env/rdr + vfork
358 my ($cmd, $env, $rdr) = @_;
366 run_script($cmd, $env, { %$rdr, run_mode => 0 });
370 sub xsys_e { # like "/bin/sh -e"
372 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
375 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
377 my ($cmd, $env, $rdr) = @_;
379 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
380 wantarray ? split(/^/m, $out) : $out;
384 my ($cmd, $env, $opt) = @_;
385 my ($key, @argv) = @$cmd;
386 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
387 my $sub = $run_mode == 0 ? undef : key2sub($key);
389 if (my $tail_cmd = $ENV{TAIL}) {
392 next unless /\A--std(?:err|out)=(.+)\z/;
397 my $f = $opt->{$_} or next;
400 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
402 my $f = readlink "/proc/$$/fd/$fd";
403 push @paths, $f if -e $f;
408 $tail_pid = fork // die "fork: $!";
409 if ($tail_pid == 0) {
410 # make sure files exist, first
411 open my $fh, '>>', $_ for @paths;
412 open(STDOUT, '>&STDERR') or die "1>&2: $!";
413 exec(split(' ', $tail_cmd), @paths);
414 die "$tail_cmd failed: $!";
416 wait_for_tail($tail_pid, scalar @paths);
419 my $pid = fork // die "fork: $!\n";
421 eval { PublicInbox::DS->Reset };
422 # pretend to be systemd (cf. sd_listen_fds(3))
423 # 3 == SD_LISTEN_FDS_START
425 for ($fd = 0; 1; $fd++) {
427 last if $fd >= 3 && !defined($s);
429 my $fl = fcntl($s, F_GETFD, 0);
430 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
431 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
433 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
434 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
436 %ENV = (%ENV, %$env) if $env;
439 $ENV{LISTEN_PID} = $$;
440 $ENV{LISTEN_FDS} = $fds;
442 $0 = join(' ', @$cmd);
444 eval { PublicInbox::DS->Reset };
445 _run_sub($sub, $key, \@argv);
446 POSIX::_exit($? >> 8);
448 exec(key2script($key), @argv);
449 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
452 PublicInboxTestProcess->new($pid, $tail_pid);
455 sub have_xapian_compact () {
456 require PublicInbox::Spawn;
457 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
458 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
461 our ($err_skip, $lei_opt, $lei_out, $lei_err);
462 # favor lei() or lei_ok() over $lei for new code
464 my ($cmd, $env, $xopt) = @_;
465 $lei_out = $lei_err = '';
467 ($env, $xopt) = grep { (!defined) || ref } @_;
468 $cmd = [ grep { defined && !ref } @_ ];
470 my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
472 $lei_err = join('', grep(!/$err_skip/, split(/^/m, $lei_err)));
473 if ($lei_err ne '') {
474 if ($lei_err =~ /Use of uninitialized/ ||
475 $lei_err =~ m!\bArgument .*? isn't numeric in !) {
476 fail "lei_err=$lei_err";
478 diag "lei_err=$lei_err" if $lei_loud;
485 state $PWD = $ENV{PWD} // Cwd::getcwd();
486 my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
487 my $tmpdir = quotemeta(File::Spec->tmpdir);
488 # filter out anything that looks like a path name for consistent logs
489 my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
492 s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/!;
493 s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!g;
494 s!\Q$PWD\E\b!\$PWD!g;
497 ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or diag $lei_err;
501 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
507 my $test_opt = shift // {};
508 require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
509 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
510 require PublicInbox::Config;
512 delete $ENV{XDG_DATA_HOME};
513 delete $ENV{XDG_CONFIG_HOME};
514 $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
515 $ENV{GIT_COMMITTER_NAME} = 'lei user';
516 my (undef, $fn, $lineno) = caller(0);
517 my $t = "$fn:$lineno";
518 require PublicInbox::Spawn;
519 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
520 eval { require Socket::MsgHdr; 1 };
521 # XXX fix and move this inside daemon-only before 1.7 release
522 skip <<'EOM', 1 unless $lei_daemon;
523 Socket::MsgHdr missing or Inline::C is unconfigured/missing
525 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
526 my ($daemon_pid, $for_destroy, $daemon_xrd);
527 my $tmpdir = $test_opt->{tmpdir};
528 ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
529 state $persist_xrd = $ENV{TEST_LEI_DAEMON_PERSIST_DIR};
531 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
532 my $home = "$tmpdir/lei-daemon";
533 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
534 local $ENV{HOME} = $home;
536 if ($persist_xrd && !$test_opt->{daemon_only}) {
537 $persist = $daemon_xrd = $persist_xrd;
539 $daemon_xrd = "$home/xdg_run";
540 mkdir($daemon_xrd, 0700) or BAIL_OUT "mkdir: $!";
542 local $ENV{XDG_RUNTIME_DIR} = $daemon_xrd;
545 lei_ok(qw(daemon-pid), \"daemon-pid after $t");
546 chomp($daemon_pid = $lei_out);
548 fail("daemon not running after $t");
549 skip 'daemon died unexpectedly', 2;
551 ok(kill(0, $daemon_pid), "daemon running after $t");
552 lei_ok(qw(daemon-kill), \"daemon-kill after $t");
554 }; # SKIP for lei_daemon
555 unless ($test_opt->{daemon_only}) {
556 $ENV{TEST_LEI_DAEMON_ONLY} and
557 skip 'TEST_LEI_DAEMON_ONLY set', 1;
558 require_ok 'PublicInbox::LEI';
559 my $home = "$tmpdir/lei-oneshot";
560 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
561 local $ENV{HOME} = $home;
562 # force sun_path[108] overflow:
563 my $xrd = "$home/1shot-test".('.sun_path' x 108);
564 local $err_skip = qr!\Q$xrd!; # for lei() filtering
565 local $ENV{XDG_RUNTIME_DIR} = $xrd;
570 kill(0, $daemon_pid) or last;
573 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
574 my $f = "$daemon_xrd/lei/errors.log";
575 open my $fh, '<', $f or BAIL_OUT "$f: $!";
578 "$t daemon XDG_RUNTIME_DIR/lei/errors.log empty");
580 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
583 # returns the pathname to a ~/.public-inbox/config in scalar context,
584 # ($test_home, $pi_config_pathname) in list context
585 sub setup_public_inboxes () {
586 my $test_home = "t/home2";
587 my $pi_config = "$test_home/.public-inbox/config";
588 my $stamp = "$test_home/setup-stamp";
589 my @ret = ($test_home, $pi_config);
590 return @ret if -f $stamp;
592 require PublicInbox::Lock;
593 my $lk = bless { lock_path => "$test_home/setup.lock" },
595 my $end = $lk->lock_for_scope;
596 return @ret if -f $stamp;
598 local $ENV{PI_CONFIG} = $pi_config;
600 run_script([qw(-init --skip-docdata), "-V$V",
601 '--newsgroup', "t.v$V", "t$V",
602 "$test_home/t$V", "http://example.com/t$V",
603 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
605 require PublicInbox::Config;
606 require PublicInbox::InboxWritable;
607 my $cfg = PublicInbox::Config->new;
609 $cfg->each_inbox(sub {
611 $ibx->{-no_fsync} = 1;
612 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
613 my $V = $ibx->version;
614 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
616 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
617 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
622 $seen or BAIL_OUT 'no imports';
623 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
627 sub create_inbox ($$;@) {
631 require PublicInbox::Lock;
632 require PublicInbox::InboxWritable;
633 my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
634 my $dir = "t/data-gen/$base.$ident";
637 mkdir $dir; # may race
638 -d $dir or BAIL_OUT "$dir could not be created: $!";
640 my $lk = bless { lock_path => "$dir/creat.lock" }, 'PublicInbox::Lock';
641 $opt{inboxdir} = File::Spec->rel2abs($dir);
642 $opt{name} //= $ident;
643 my $scope = $lk->lock_for_scope;
644 my $pre_cb = delete $opt{pre_cb};
645 $pre_cb->($dir) if $pre_cb && $new;
647 my $no_gc = delete $opt{-no_gc};
648 my $tmpdir = delete $opt{tmpdir};
649 my $addr = $opt{address} // [];
650 $opt{-primary_address} //= $addr->[0] // "$ident\@example.com";
651 my $parallel = delete($opt{importer_parallel}) // 0;
652 my $creat_opt = { nproc => delete($opt{nproc}) // 1 };
653 my $ibx = PublicInbox::InboxWritable->new({ %opt }, $creat_opt);
654 if (!-f "$dir/creat.stamp") {
655 my $im = $ibx->importer($parallel);
659 my @to_gc = $ibx->version == 1 ? ($ibx->{inboxdir}) :
660 glob("$ibx->{inboxdir}/git/*.git");
661 for my $dir (@to_gc) {
662 xsys_e([ qw(git gc -q) ], { GIT_DIR => $dir });
665 open my $s, '>', "$dir/creat.stamp" or
666 BAIL_OUT "error creating $dir/creat.stamp: $!";
670 xsys([qw(/bin/cp -Rp), $dir, $tmpdir]) == 0 or
671 BAIL_OUT "cp $dir $tmpdir";
672 $opt{inboxdir} = $tmpdir;
673 $ibx = PublicInbox::InboxWritable->new(\%opt);
678 sub test_httpd ($$;$) {
679 my ($env, $client, $skip) = @_;
680 for (qw(PI_CONFIG TMPDIR)) {
681 $env->{$_} or BAIL_OUT "$_ unset";
684 require_mods(qw(Plack::Test::ExternalServer), $skip // 1);
685 my $sock = tcp_server() or die;
686 my ($out, $err) = map { "$env->{TMPDIR}/std$_.log" } qw(out err);
687 my $cmd = [ qw(-httpd -W0), "--stdout=$out", "--stderr=$err" ];
688 my $td = start_script($cmd, $env, { 3 => $sock });
689 my ($h, $p) = tcp_host_port($sock);
690 local $ENV{PLACK_TEST_EXTERNALSERVER_URI} = "http://$h:$p";
691 Plack::Test::ExternalServer::test_psgi(client => $client);
693 open my $fh, '<', $err or BAIL_OUT $!;
694 my $e = do { local $/; <$fh> };
695 if ($e =~ s/^Plack::Middleware::ReverseProxy missing,\n//gms) {
696 $e =~ s/^URL generation for redirects .*\n//gms;
698 is($e, '', 'no errors');
703 package PublicInboxTestProcess;
706 # prevent new threads from inheriting these objects
710 my ($klass, $pid, $tail_pid) = @_;
711 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
715 my ($self, $sig) = @_;
716 CORE::kill($sig // 'TERM', $self->{pid});
720 my ($self, $sig) = @_;
721 my $pid = delete $self->{pid} or return;
722 CORE::kill($sig, $pid) if defined $sig;
723 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
724 $ret == $pid or die "waitpid($pid) != $ret";
729 return if $self->{owner} != $$;
730 if (my $tail_pid = delete $self->{tail_pid}) {
731 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
732 CORE::kill('TERM', $tail_pid);
737 package PublicInbox::TestCommon::InboxWakeup;
739 sub on_inbox_unlock { ${$_[0]}->($_[1]) }