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};
15 our ($lei_opt, $lei_out, $lei_err, $lei_cwdfh);
17 @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
18 run_script start_script key2sub xsys xsys_e xqx eml_load tick
19 have_xapian_compact json_utf8 setup_public_inboxes create_inbox
20 tcp_host_port test_lei lei lei_ok $lei_out $lei_err $lei_opt
23 my @methods = grep(!/\W/, @Test::More::EXPORT);
24 eval(join('', map { "*$_=\\&Test::More::$_;" } @methods));
26 push @EXPORT, @methods;
29 sub xbail (@) { BAIL_OUT join(' ', map { ref() ? (explain($_)) : ($_) } @_) }
33 open(my $fh, '<', $path) or die "open $path: $!";
34 require PublicInbox::Eml;
35 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
41 unless (defined $base) {
42 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
44 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXX", TMPDIR => 1);
45 ($tmpdir->dirname, $tmpdir);
52 Type => Socket::SOCK_STREAM(),
57 die 'IPv4-only' if $ENV{TEST_IPV4_ONLY};
58 require IO::Socket::INET6;
59 IO::Socket::INET6->new(%opt, LocalAddr => '[::1]')
61 die 'IPv6-only' if $ENV{TEST_IPV6_ONLY};
62 IO::Socket::INET->new(%opt, LocalAddr => '127.0.0.1')
63 } || BAIL_OUT "failed to create TCP server: $! ($@)";
66 sub tcp_host_port ($) {
68 my ($h, $p) = ($s->sockhost, $s->sockport);
69 my $ipv4 = $s->sockdomain == Socket::AF_INET();
71 $ipv4 ? ($h, $p) : ("[$h]", $p);
73 $ipv4 ? "$h:$p" : "[$h]:$p";
78 my ($dest, %opt) = @_;
79 my $addr = tcp_host_port($dest);
80 my $s = ref($dest)->new(
82 Type => Socket::SOCK_STREAM(),
85 ) or BAIL_OUT "failed to connect to $addr: $!";
90 sub require_git ($;$) {
91 my ($req, $maybe) = @_;
92 my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
93 my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
94 =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
96 my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
97 my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
98 if ($cur_int < $req_int) {
101 "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
108 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
110 while (my $mod = shift(@mods)) {
112 require_git(2.6, $maybe ? $maybe : ());
113 push @mods, qw(DBD::SQLite Search::Xapian);
114 $mod = 'json'; # fall-through
116 if ($mod eq 'json') {
117 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||JSON||JSON::PP'
118 } elsif ($mod eq '-httpd') {
119 push @mods, qw(Plack::Builder Plack::Util);
121 } elsif ($mod eq '-imapd') {
122 push @mods, qw(Parse::RecDescent DBD::SQLite
123 Email::Address::XS||Mail::Address);
125 } elsif ($mod eq '-nntpd') {
126 push @mods, qw(DBD::SQLite);
129 if ($mod eq 'Search::Xapian') {
130 if (eval { require PublicInbox::Search } &&
131 PublicInbox::Search::load_xapian()) {
134 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
136 for my $m (split(/\Q||\E/, $mod)) {
148 } elsif ($mod eq 'IO::Socket::SSL' &&
149 # old versions of IO::Socket::SSL aren't supported
150 # by libnet, at least:
151 # https://rt.cpan.org/Ticket/Display.html?id=100529
152 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
157 my $m = join(', ', @need)." missing for $0";
158 skip($m, $maybe) if $maybe;
164 return $key if ($key eq 'git' || index($key, '/') >= 0);
165 # n.b. we may have scripts which don't start with "public-inbox" in
167 $key =~ s/\A([-\.])/public-inbox$1/;
171 my @io_mode = ([ *STDIN{IO}, '+<&' ], [ *STDOUT{IO}, '+>&' ],
172 [ *STDERR{IO}, '+>&' ]);
174 sub _prepare_redirects ($) {
177 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
178 my $fh = $fhref->[$fd] or next;
179 my ($oldfh, $mode) = @{$io_mode[$fd]};
180 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
181 $orig_io->[$fd] = $orig;
182 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
187 sub _undo_redirects ($) {
189 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
190 my $fh = $orig_io->[$fd] or next;
191 my ($oldfh, $mode) = @{$io_mode[$fd]};
192 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
196 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
197 # three ways to spawn our own short-lived Perl scripts for testing:
199 # 0 - (fork|vfork) + execve, the most realistic but slowest
200 # 1 - (not currently implemented)
201 # 2 - preloading and running in current process (slightly faster than 1)
203 # 2 is not compatible with scripts which use "exit" (which we'll try to
204 # avoid in the future).
206 our $run_script_exit_code;
207 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
208 sub run_script_exit {
209 $run_script_exit_code = $_[0] // 0;
216 $cached_scripts{$key} //= do {
217 my $f = key2script($key);
218 open my $fh, '<', $f or die "open $f: $!";
219 my $str = do { local $/; <$fh> };
220 my $pkg = (split(m!/!, $f))[-1];
221 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
224 $pkg = "PublicInbox::TestScript::$pkg";
230 *exit = \\&PublicInbox::TestCommon::run_script_exit;
232 # the below "line" directive is a magic comment, see perlsyn(1) manpage
244 my ($sub, $key, $argv) = @_;
245 local @ARGV = @$argv;
246 $run_script_exit_code = undef;
247 my $exit_code = eval { $sub->(@$argv) };
248 if ($@ eq RUN_SCRIPT_EXIT) {
250 $exit_code = $run_script_exit_code;
251 $? = ($exit_code << 8);
252 } elsif (defined($exit_code)) {
253 $? = ($exit_code << 8);
254 } elsif ($@) { # mimic die() behavior when uncaught
255 warn "E: eval-ed $key: $@\n";
256 $? = ($! << 8) if $!;
257 $? = (255 << 8) if $? == 0;
259 die "BUG: eval-ed $key: no exit code or \$@\n";
263 sub run_script ($;$$) {
264 my ($cmd, $env, $opt) = @_;
265 my ($key, @argv) = @$cmd;
266 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
267 my $sub = $run_mode == 0 ? undef : key2sub($key);
271 my $redir = $opt->{$fd};
272 my $ref = ref($redir);
273 if ($ref eq 'SCALAR') {
274 open my $fh, '+>', undef or die "open: $!";
276 $spawn_opt->{$fd} = $fh;
279 print $fh $$redir or die "print: $!";
280 seek($fh, 0, SEEK_SET) or die "seek: $!";
281 } elsif ($ref eq 'GLOB') {
282 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
284 die "unable to deal with $ref $redir";
287 if ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
288 unshift @argv, '--no-fsync';
290 if ($run_mode == 0) {
291 # spawn an independent new process, like real-world use cases:
292 require PublicInbox::Spawn;
293 my $cmd = [ key2script($key), @argv ];
294 if (my $d = $opt->{'-C'}) {
295 $cmd->[0] = File::Spec->rel2abs($cmd->[0]);
296 $spawn_opt->{'-C'} = $d;
298 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
300 my $r = waitpid($pid, 0) // die "waitpid: $!";
301 $r == $pid or die "waitpid: expected $pid, got $r";
303 } else { # localize and run everything in the same process:
304 # note: "local *STDIN = *STDIN;" and so forth did not work in
305 # old versions of perl
306 local %ENV = $env ? (%ENV, %$env) : %ENV;
308 local $0 = join(' ', @$cmd);
309 my $orig_io = _prepare_redirects($fhref);
310 my $cwdfh = $lei_cwdfh;
311 if (my $d = $opt->{'-C'}) {
313 opendir $cwdfh, '.' or die "opendir .: $!";
315 chdir $d or die "chdir $d: $!";
317 _run_sub($sub, $key, \@argv);
318 eval { PublicInbox::Inbox::cleanup_task() };
319 die "fchdir(restore): $!" if $cwdfh && !chdir($cwdfh);
320 _undo_redirects($orig_io);
324 # slurp the redirects back into user-supplied strings
326 my $fh = $fhref->[$fd] or next;
328 seek($fh, 0, SEEK_SET) or die "seek: $!";
329 my $redir = $opt->{$fd};
337 my $tick = shift // 0.1;
338 select undef, undef, undef, $tick;
342 sub wait_for_tail ($;$) {
343 my ($tail_pid, $want) = @_;
345 if ($^O eq 'linux') { # GNU tail may use inotify
346 state $tail_has_inotify;
347 return tick if $want < 0 && $tail_has_inotify;
348 my $end = time + $wait;
352 readlink($_) =~ /\binotify\b/
353 } glob("/proc/$tail_pid/fd/*");
354 } while (!@ino && time <= $end and tick);
356 $tail_has_inotify = 1;
357 $ino[0] =~ s!/fd/!/fdinfo/!;
360 if (open my $fh, '<', $ino[0]) {
362 @info = grep(/^inotify wd:/, <$fh>);
364 } while (scalar(@info) < $want && time <= $end and tick);
370 # like system() built-in, but uses spawn() for env/rdr + vfork
372 my ($cmd, $env, $rdr) = @_;
380 run_script($cmd, $env, { %$rdr, run_mode => 0 });
384 sub xsys_e { # like "/bin/sh -e"
386 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
389 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
391 my ($cmd, $env, $rdr) = @_;
393 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
394 wantarray ? split(/^/m, $out) : $out;
398 my ($cmd, $env, $opt) = @_;
399 my ($key, @argv) = @$cmd;
400 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
401 my $sub = $run_mode == 0 ? undef : key2sub($key);
403 if (my $tail_cmd = $ENV{TAIL}) {
406 next unless /\A--std(?:err|out)=(.+)\z/;
411 my $f = $opt->{$_} or next;
414 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
416 my $f = readlink "/proc/$$/fd/$fd";
417 push @paths, $f if -e $f;
422 $tail_pid = fork // die "fork: $!";
423 if ($tail_pid == 0) {
424 # make sure files exist, first
425 open my $fh, '>>', $_ for @paths;
426 open(STDOUT, '>&STDERR') or die "1>&2: $!";
427 exec(split(' ', $tail_cmd), @paths);
428 die "$tail_cmd failed: $!";
430 wait_for_tail($tail_pid, scalar @paths);
433 my $pid = fork // die "fork: $!\n";
435 eval { PublicInbox::DS->Reset };
436 # pretend to be systemd (cf. sd_listen_fds(3))
437 # 3 == SD_LISTEN_FDS_START
439 for ($fd = 0; 1; $fd++) {
441 last if $fd >= 3 && !defined($s);
443 my $fl = fcntl($s, F_GETFD, 0);
444 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
445 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
447 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
448 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
450 %ENV = (%ENV, %$env) if $env;
453 $ENV{LISTEN_PID} = $$;
454 $ENV{LISTEN_FDS} = $fds;
456 $0 = join(' ', @$cmd);
458 eval { PublicInbox::DS->Reset };
459 _run_sub($sub, $key, \@argv);
460 POSIX::_exit($? >> 8);
462 exec(key2script($key), @argv);
463 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
466 PublicInboxTestProcess->new($pid, $tail_pid);
469 sub have_xapian_compact () {
470 require PublicInbox::Spawn;
471 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
472 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
475 # favor lei() or lei_ok() over $lei for new code
477 my ($cmd, $env, $xopt) = @_;
478 $lei_out = $lei_err = '';
480 ($env, $xopt) = grep { (!defined) || ref } @_;
481 $cmd = [ grep { defined && !ref } @_ ];
483 my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
484 if ($lei_err ne '') {
485 if ($lei_err =~ /Use of uninitialized/ ||
486 $lei_err =~ m!\bArgument .*? isn't numeric in !) {
487 fail "lei_err=$lei_err";
489 diag "lei_err=$lei_err" if $lei_loud;
496 state $PWD = $ENV{PWD} // Cwd::getcwd();
497 my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
498 my $tmpdir = quotemeta(File::Spec->tmpdir);
499 # filter out anything that looks like a path name for consistent logs
500 my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
503 s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/!;
504 s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!g;
505 s!\Q$PWD\E\b!\$PWD!g;
508 ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or
509 diag "\$?=$? err=$lei_err";
513 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
519 my $test_opt = shift // {};
521 opendir $lei_cwdfh, '.' or xbail "opendir .: $!";
522 require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
523 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
524 require PublicInbox::Config;
527 delete $ENV{XDG_DATA_HOME};
528 delete $ENV{XDG_CONFIG_HOME};
529 $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
530 $ENV{GIT_COMMITTER_NAME} = 'lei user';
531 my (undef, $fn, $lineno) = caller(0);
532 my $t = "$fn:$lineno";
533 require PublicInbox::Spawn;
534 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
535 eval { require Socket::MsgHdr; 1 };
536 # XXX fix and move this inside daemon-only before 1.7 release
537 skip <<'EOM', 1 unless $lei_daemon;
538 Socket::MsgHdr missing or Inline::C is unconfigured/missing
540 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
541 my ($daemon_pid, $for_destroy, $daemon_xrd);
542 my $tmpdir = $test_opt->{tmpdir};
543 File::Path::mkpath($tmpdir) if (defined $tmpdir && !-d $tmpdir);
544 ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
545 state $persist_xrd = $ENV{TEST_LEI_DAEMON_PERSIST_DIR};
547 $ENV{TEST_LEI_ONESHOT} and
548 xbail 'TEST_LEI_ONESHOT no longer supported';
549 my $home = "$tmpdir/lei-daemon";
550 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
551 local $ENV{HOME} = $home;
553 if ($persist_xrd && !$test_opt->{daemon_only}) {
554 $persist = $daemon_xrd = $persist_xrd;
556 $daemon_xrd = "$home/xdg_run";
557 mkdir($daemon_xrd, 0700) or BAIL_OUT "mkdir: $!";
559 local $ENV{XDG_RUNTIME_DIR} = $daemon_xrd;
562 lei_ok(qw(daemon-pid), \"daemon-pid after $t");
563 chomp($daemon_pid = $lei_out);
565 fail("daemon not running after $t");
566 skip 'daemon died unexpectedly', 2;
568 ok(kill(0, $daemon_pid), "daemon running after $t");
569 lei_ok(qw(daemon-kill), \"daemon-kill after $t");
571 }; # SKIP for lei_daemon
574 kill(0, $daemon_pid) or last;
577 ok(!kill(0, $daemon_pid), "$t daemon stopped");
578 my $f = "$daemon_xrd/lei/errors.log";
579 open my $fh, '<', $f or BAIL_OUT "$f: $!";
582 "$t daemon XDG_RUNTIME_DIR/lei/errors.log empty");
584 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
587 # returns the pathname to a ~/.public-inbox/config in scalar context,
588 # ($test_home, $pi_config_pathname) in list context
589 sub setup_public_inboxes () {
590 my $test_home = "t/home2";
591 my $pi_config = "$test_home/.public-inbox/config";
592 my $stamp = "$test_home/setup-stamp";
593 my @ret = ($test_home, $pi_config);
594 return @ret if -f $stamp;
596 require PublicInbox::Lock;
597 my $lk = bless { lock_path => "$test_home/setup.lock" },
599 my $end = $lk->lock_for_scope;
600 return @ret if -f $stamp;
602 local $ENV{PI_CONFIG} = $pi_config;
604 run_script([qw(-init --skip-docdata), "-V$V",
605 '--newsgroup', "t.v$V", "t$V",
606 "$test_home/t$V", "http://example.com/t$V",
607 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
609 require PublicInbox::Config;
610 require PublicInbox::InboxWritable;
611 my $cfg = PublicInbox::Config->new;
613 $cfg->each_inbox(sub {
615 $ibx->{-no_fsync} = 1;
616 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
617 my $V = $ibx->version;
618 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
620 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
621 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
626 $seen or BAIL_OUT 'no imports';
627 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
631 sub create_inbox ($$;@) {
635 require PublicInbox::Lock;
636 require PublicInbox::InboxWritable;
637 my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
638 my $dir = "t/data-gen/$base.$ident";
641 mkdir $dir; # may race
642 -d $dir or BAIL_OUT "$dir could not be created: $!";
644 my $lk = bless { lock_path => "$dir/creat.lock" }, 'PublicInbox::Lock';
645 $opt{inboxdir} = File::Spec->rel2abs($dir);
646 $opt{name} //= $ident;
647 my $scope = $lk->lock_for_scope;
648 my $pre_cb = delete $opt{pre_cb};
649 $pre_cb->($dir) if $pre_cb && $new;
651 my $no_gc = delete $opt{-no_gc};
652 my $tmpdir = delete $opt{tmpdir};
653 my $addr = $opt{address} // [];
654 $opt{-primary_address} //= $addr->[0] // "$ident\@example.com";
655 my $parallel = delete($opt{importer_parallel}) // 0;
656 my $creat_opt = { nproc => delete($opt{nproc}) // 1 };
657 my $ibx = PublicInbox::InboxWritable->new({ %opt }, $creat_opt);
658 if (!-f "$dir/creat.stamp") {
659 my $im = $ibx->importer($parallel);
663 my @to_gc = $ibx->version == 1 ? ($ibx->{inboxdir}) :
664 glob("$ibx->{inboxdir}/git/*.git");
665 for my $dir (@to_gc) {
666 xsys_e([ qw(git gc -q) ], { GIT_DIR => $dir });
669 open my $s, '>', "$dir/creat.stamp" or
670 BAIL_OUT "error creating $dir/creat.stamp: $!";
674 xsys([qw(/bin/cp -Rp), $dir, $tmpdir]) == 0 or
675 BAIL_OUT "cp $dir $tmpdir";
676 $opt{inboxdir} = $tmpdir;
677 $ibx = PublicInbox::InboxWritable->new(\%opt);
682 sub test_httpd ($$;$) {
683 my ($env, $client, $skip) = @_;
684 for (qw(PI_CONFIG TMPDIR)) {
685 $env->{$_} or BAIL_OUT "$_ unset";
688 require_mods(qw(Plack::Test::ExternalServer), $skip // 1);
689 my $sock = tcp_server() or die;
690 my ($out, $err) = map { "$env->{TMPDIR}/std$_.log" } qw(out err);
691 my $cmd = [ qw(-httpd -W0), "--stdout=$out", "--stderr=$err" ];
692 my $td = start_script($cmd, $env, { 3 => $sock });
693 my ($h, $p) = tcp_host_port($sock);
694 local $ENV{PLACK_TEST_EXTERNALSERVER_URI} = "http://$h:$p";
695 Plack::Test::ExternalServer::test_psgi(client => $client);
697 open my $fh, '<', $err or BAIL_OUT $!;
698 my $e = do { local $/; <$fh> };
699 if ($e =~ s/^Plack::Middleware::ReverseProxy missing,\n//gms) {
700 $e =~ s/^URL generation for redirects .*\n//gms;
702 is($e, '', 'no errors');
707 package PublicInboxTestProcess;
710 # prevent new threads from inheriting these objects
714 my ($klass, $pid, $tail_pid) = @_;
715 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
719 my ($self, $sig) = @_;
720 CORE::kill($sig // 'TERM', $self->{pid});
724 my ($self, $sig) = @_;
725 my $pid = delete $self->{pid} or return;
726 CORE::kill($sig, $pid) if defined $sig;
727 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
728 $ret == $pid or die "waitpid($pid) != $ret";
733 return if $self->{owner} != $$;
734 if (my $tail_pid = delete $self->{tail_pid}) {
735 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
736 CORE::kill('TERM', $tail_pid);
741 package PublicInbox::TestCommon::InboxWakeup;
743 sub on_inbox_unlock { ${$_[0]}->($_[1]) }