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-$$-XXXXXX", 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)) {
110 if ($mod eq 'json') {
111 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||'.
114 if ($mod eq 'Search::Xapian') {
115 if (eval { require PublicInbox::Search } &&
116 PublicInbox::Search::load_xapian()) {
119 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
120 if (eval { require PublicInbox::SearchIdx } &&
121 PublicInbox::SearchIdx::load_xapian_writable()){
124 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
126 for my $m (split(/\Q||\E/, $mod)) {
138 } elsif ($mod eq 'IO::Socket::SSL' &&
139 # old versions of IO::Socket::SSL aren't supported
140 # by libnet, at least:
141 # https://rt.cpan.org/Ticket/Display.html?id=100529
142 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
147 my $m = join(', ', @need)." missing for $0";
148 skip($m, $maybe) if $maybe;
154 return $key if ($key eq 'git' || index($key, '/') >= 0);
155 # n.b. we may have scripts which don't start with "public-inbox" in
157 $key =~ s/\A([-\.])/public-inbox$1/;
161 my @io_mode = ([ *STDIN{IO}, '+<&' ], [ *STDOUT{IO}, '+>&' ],
162 [ *STDERR{IO}, '+>&' ]);
164 sub _prepare_redirects ($) {
167 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
168 my $fh = $fhref->[$fd] or next;
169 my ($oldfh, $mode) = @{$io_mode[$fd]};
170 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
171 $orig_io->[$fd] = $orig;
172 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
177 sub _undo_redirects ($) {
179 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
180 my $fh = $orig_io->[$fd] or next;
181 my ($oldfh, $mode) = @{$io_mode[$fd]};
182 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
186 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
187 # three ways to spawn our own short-lived Perl scripts for testing:
189 # 0 - (fork|vfork) + execve, the most realistic but slowest
190 # 1 - (not currently implemented)
191 # 2 - preloading and running in current process (slightly faster than 1)
193 # 2 is not compatible with scripts which use "exit" (which we'll try to
194 # avoid in the future).
196 our $run_script_exit_code;
197 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
198 sub run_script_exit {
199 $run_script_exit_code = $_[0] // 0;
206 $cached_scripts{$key} //= do {
207 my $f = key2script($key);
208 open my $fh, '<', $f or die "open $f: $!";
209 my $str = do { local $/; <$fh> };
210 my $pkg = (split(m!/!, $f))[-1];
211 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
214 $pkg = "PublicInbox::TestScript::$pkg";
220 *exit = \\&PublicInbox::TestCommon::run_script_exit;
222 # the below "line" directive is a magic comment, see perlsyn(1) manpage
234 my ($sub, $key, $argv) = @_;
235 local @ARGV = @$argv;
236 $run_script_exit_code = undef;
237 my $exit_code = eval { $sub->(@$argv) };
238 if ($@ eq RUN_SCRIPT_EXIT) {
240 $exit_code = $run_script_exit_code;
241 $? = ($exit_code << 8);
242 } elsif (defined($exit_code)) {
243 $? = ($exit_code << 8);
244 } elsif ($@) { # mimic die() behavior when uncaught
245 warn "E: eval-ed $key: $@\n";
246 $? = ($! << 8) if $!;
247 $? = (255 << 8) if $? == 0;
249 die "BUG: eval-ed $key: no exit code or \$@\n";
253 sub run_script ($;$$) {
254 my ($cmd, $env, $opt) = @_;
255 my ($key, @argv) = @$cmd;
256 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
257 my $sub = $run_mode == 0 ? undef : key2sub($key);
261 my $redir = $opt->{$fd};
262 my $ref = ref($redir);
263 if ($ref eq 'SCALAR') {
264 open my $fh, '+>', undef or die "open: $!";
266 $spawn_opt->{$fd} = $fh;
269 print $fh $$redir or die "print: $!";
270 seek($fh, 0, SEEK_SET) or die "seek: $!";
271 } elsif ($ref eq 'GLOB') {
272 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
274 die "unable to deal with $ref $redir";
277 if ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
278 unshift @argv, '--no-fsync';
280 if ($run_mode == 0) {
281 # spawn an independent new process, like real-world use cases:
282 require PublicInbox::Spawn;
283 my $cmd = [ key2script($key), @argv ];
284 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
286 my $r = waitpid($pid, 0) // die "waitpid: $!";
287 $r == $pid or die "waitpid: expected $pid, got $r";
289 } else { # localize and run everything in the same process:
290 # note: "local *STDIN = *STDIN;" and so forth did not work in
291 # old versions of perl
292 local %ENV = $env ? (%ENV, %$env) : %ENV;
294 local $0 = join(' ', @$cmd);
295 my $orig_io = _prepare_redirects($fhref);
296 _run_sub($sub, $key, \@argv);
297 eval { PublicInbox::Inbox::cleanup_task() };
298 _undo_redirects($orig_io);
302 # slurp the redirects back into user-supplied strings
304 my $fh = $fhref->[$fd] or next;
305 seek($fh, 0, SEEK_SET) or die "seek: $!";
306 my $redir = $opt->{$fd};
314 my $tick = shift // 0.1;
315 select undef, undef, undef, $tick;
319 sub wait_for_tail ($;$) {
320 my ($tail_pid, $want) = @_;
322 if ($^O eq 'linux') { # GNU tail may use inotify
323 state $tail_has_inotify;
324 return tick if $want < 0 && $tail_has_inotify;
325 my $end = time + $wait;
329 readlink($_) =~ /\binotify\b/
330 } glob("/proc/$tail_pid/fd/*");
331 } while (!@ino && time <= $end and tick);
333 $tail_has_inotify = 1;
334 $ino[0] =~ s!/fd/!/fdinfo/!;
337 if (open my $fh, '<', $ino[0]) {
339 @info = grep(/^inotify wd:/, <$fh>);
341 } while (scalar(@info) < $want && time <= $end and tick);
347 # like system() built-in, but uses spawn() for env/rdr + vfork
349 my ($cmd, $env, $rdr) = @_;
357 run_script($cmd, $env, { %$rdr, run_mode => 0 });
361 sub xsys_e { # like "/bin/sh -e"
363 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
366 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
368 my ($cmd, $env, $rdr) = @_;
370 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
371 wantarray ? split(/^/m, $out) : $out;
375 my ($cmd, $env, $opt) = @_;
376 my ($key, @argv) = @$cmd;
377 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
378 my $sub = $run_mode == 0 ? undef : key2sub($key);
380 if (my $tail_cmd = $ENV{TAIL}) {
383 next unless /\A--std(?:err|out)=(.+)\z/;
388 my $f = $opt->{$_} or next;
391 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
393 my $f = readlink "/proc/$$/fd/$fd";
394 push @paths, $f if -e $f;
399 $tail_pid = fork // die "fork: $!";
400 if ($tail_pid == 0) {
401 # make sure files exist, first
402 open my $fh, '>>', $_ for @paths;
403 open(STDOUT, '>&STDERR') or die "1>&2: $!";
404 exec(split(' ', $tail_cmd), @paths);
405 die "$tail_cmd failed: $!";
407 wait_for_tail($tail_pid, scalar @paths);
410 my $pid = fork // die "fork: $!\n";
412 eval { PublicInbox::DS->Reset };
413 # pretend to be systemd (cf. sd_listen_fds(3))
414 # 3 == SD_LISTEN_FDS_START
416 for ($fd = 0; 1; $fd++) {
418 last if $fd >= 3 && !defined($s);
420 my $fl = fcntl($s, F_GETFD, 0);
421 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
422 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
424 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
425 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
427 %ENV = (%ENV, %$env) if $env;
430 $ENV{LISTEN_PID} = $$;
431 $ENV{LISTEN_FDS} = $fds;
433 $0 = join(' ', @$cmd);
435 eval { PublicInbox::DS->Reset };
436 _run_sub($sub, $key, \@argv);
437 POSIX::_exit($? >> 8);
439 exec(key2script($key), @argv);
440 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
443 PublicInboxTestProcess->new($pid, $tail_pid);
446 sub have_xapian_compact () {
447 require PublicInbox::Spawn;
448 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
449 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
452 our ($err_skip, $lei_opt, $lei_out, $lei_err);
453 # favor lei() or lei_ok() over $lei for new code
455 my ($cmd, $env, $xopt) = @_;
456 $lei_out = $lei_err = '';
458 ($env, $xopt) = grep { (!defined) || ref } @_;
459 $cmd = [ grep { defined && !ref } @_ ];
461 my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
463 $lei_err = join('', grep(!/$err_skip/, split(/^/m, $lei_err)));
464 if ($lei_err ne '') {
465 if ($lei_err =~ /Use of uninitialized/ ||
466 $lei_err =~ m!\bArgument .*? isn't numeric in !) {
467 fail "lei_err=$lei_err";
469 diag "lei_err=$lei_err" if $lei_loud;
476 state $PWD = $ENV{PWD} // Cwd::getcwd();
477 my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
478 my $tmpdir = quotemeta(File::Spec->tmpdir);
479 # filter out anything that looks like a path name for consistent logs
480 my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
483 s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/!;
484 s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!g;
485 s!\Q$PWD\E\b!\$PWD!g;
488 ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or diag $lei_err;
492 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
498 my $test_opt = shift // {};
499 require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
500 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
501 require PublicInbox::Config;
503 delete $ENV{XDG_DATA_HOME};
504 delete $ENV{XDG_CONFIG_HOME};
505 $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
506 $ENV{GIT_COMMITTER_NAME} = 'lei user';
507 my (undef, $fn, $lineno) = caller(0);
508 my $t = "$fn:$lineno";
509 require PublicInbox::Spawn;
510 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
511 eval { require Socket::MsgHdr; 1 };
512 # XXX fix and move this inside daemon-only before 1.7 release
513 skip <<'EOM', 1 unless $lei_daemon;
514 Socket::MsgHdr missing or Inline::C is unconfigured/missing
516 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
517 my ($daemon_pid, $for_destroy, $daemon_xrd);
518 my $tmpdir = $test_opt->{tmpdir};
519 ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
520 state $persist_xrd = $ENV{TEST_LEI_DAEMON_PERSIST_DIR};
522 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
523 my $home = "$tmpdir/lei-daemon";
524 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
525 local $ENV{HOME} = $home;
527 if ($persist_xrd && !$test_opt->{daemon_only}) {
528 $persist = $daemon_xrd = $persist_xrd;
530 $daemon_xrd = "$home/xdg_run";
531 mkdir($daemon_xrd, 0700) or BAIL_OUT "mkdir: $!";
533 local $ENV{XDG_RUNTIME_DIR} = $daemon_xrd;
536 lei_ok(qw(daemon-pid), \"daemon-pid after $t");
537 chomp($daemon_pid = $lei_out);
539 fail("daemon not running after $t");
540 skip 'daemon died unexpectedly', 2;
542 ok(kill(0, $daemon_pid), "daemon running after $t");
543 lei_ok(qw(daemon-kill), \"daemon-kill after $t");
545 }; # SKIP for lei_daemon
546 unless ($test_opt->{daemon_only}) {
547 $ENV{TEST_LEI_DAEMON_ONLY} and
548 skip 'TEST_LEI_DAEMON_ONLY set', 1;
549 require_ok 'PublicInbox::LEI';
550 my $home = "$tmpdir/lei-oneshot";
551 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
552 local $ENV{HOME} = $home;
553 # force sun_path[108] overflow:
554 my $xrd = "$home/1shot-test".('.sun_path' x 108);
555 local $err_skip = qr!\Q$xrd!; # for lei() filtering
556 local $ENV{XDG_RUNTIME_DIR} = $xrd;
561 kill(0, $daemon_pid) or last;
564 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
565 my $f = "$daemon_xrd/lei/errors.log";
566 open my $fh, '<', $f or BAIL_OUT "$f: $!";
569 "$t daemon XDG_RUNTIME_DIR/lei/errors.log empty");
571 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
574 # returns the pathname to a ~/.public-inbox/config in scalar context,
575 # ($test_home, $pi_config_pathname) in list context
576 sub setup_public_inboxes () {
577 my $test_home = "t/home2";
578 my $pi_config = "$test_home/.public-inbox/config";
579 my $stamp = "$test_home/setup-stamp";
580 my @ret = ($test_home, $pi_config);
581 return @ret if -f $stamp;
583 require PublicInbox::Lock;
584 my $lk = bless { lock_path => "$test_home/setup.lock" },
586 my $end = $lk->lock_for_scope;
587 return @ret if -f $stamp;
589 local $ENV{PI_CONFIG} = $pi_config;
591 run_script([qw(-init --skip-docdata), "-V$V",
592 '--newsgroup', "t.v$V", "t$V",
593 "$test_home/t$V", "http://example.com/t$V",
594 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
596 require PublicInbox::Config;
597 require PublicInbox::InboxWritable;
598 my $cfg = PublicInbox::Config->new;
600 $cfg->each_inbox(sub {
602 $ibx->{-no_fsync} = 1;
603 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
604 my $V = $ibx->version;
605 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
607 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
608 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
613 $seen or BAIL_OUT 'no imports';
614 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
618 sub create_inbox ($$;@) {
622 require PublicInbox::Lock;
623 require PublicInbox::InboxWritable;
624 my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
625 my $dir = "t/data-gen/$base.$ident";
628 mkdir $dir; # may race
629 -d $dir or BAIL_OUT "$dir could not be created: $!";
631 my $lk = bless { lock_path => "$dir/creat.lock" }, 'PublicInbox::Lock';
632 $opt{inboxdir} = File::Spec->rel2abs($dir);
633 $opt{name} //= $ident;
634 my $scope = $lk->lock_for_scope;
635 my $pre_cb = delete $opt{pre_cb};
636 $pre_cb->($dir) if $pre_cb && $new;
638 my $no_gc = delete $opt{-no_gc};
639 my $tmpdir = delete $opt{tmpdir};
640 my $addr = $opt{address} // [];
641 $opt{-primary_address} //= $addr->[0] // "$ident\@example.com";
642 my $parallel = delete($opt{importer_parallel}) // 0;
643 my $creat_opt = { nproc => delete($opt{nproc}) // 1 };
644 my $ibx = PublicInbox::InboxWritable->new({ %opt }, $creat_opt);
645 if (!-f "$dir/creat.stamp") {
646 my $im = $ibx->importer($parallel);
650 my @to_gc = $ibx->version == 1 ? ($ibx->{inboxdir}) :
651 glob("$ibx->{inboxdir}/git/*.git");
652 for my $dir (@to_gc) {
653 xsys_e([ qw(git gc -q) ], { GIT_DIR => $dir });
656 open my $s, '>', "$dir/creat.stamp" or
657 BAIL_OUT "error creating $dir/creat.stamp: $!";
661 xsys([qw(/bin/cp -Rp), $dir, $tmpdir]) == 0 or
662 BAIL_OUT "cp $dir $tmpdir";
663 $opt{inboxdir} = $tmpdir;
664 $ibx = PublicInbox::InboxWritable->new(\%opt);
669 sub test_httpd ($$;$) {
670 my ($env, $client, $skip) = @_;
671 for (qw(PI_CONFIG TMPDIR)) {
672 $env->{$_} or BAIL_OUT "$_ unset";
675 require_mods(qw(Plack::Test::ExternalServer), $skip // 1);
676 my $sock = tcp_server() or die;
677 my ($out, $err) = map { "$env->{TMPDIR}/std$_.log" } qw(out err);
678 my $cmd = [ qw(-httpd -W0), "--stdout=$out", "--stderr=$err" ];
679 my $td = start_script($cmd, $env, { 3 => $sock });
680 my ($h, $p) = tcp_host_port($sock);
681 local $ENV{PLACK_TEST_EXTERNALSERVER_URI} = "http://$h:$p";
682 Plack::Test::ExternalServer::test_psgi(client => $client);
684 open my $fh, '<', $err or BAIL_OUT $!;
685 my $e = do { local $/; <$fh> };
686 if ($e =~ s/^Plack::Middleware::ReverseProxy missing,\n//gms) {
687 $e =~ s/^URL generation for redirects .*\n//gms;
689 is($e, '', 'no errors');
694 package PublicInboxTestProcess;
697 # prevent new threads from inheriting these objects
701 my ($klass, $pid, $tail_pid) = @_;
702 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
706 my ($self, $sig) = @_;
707 CORE::kill($sig // 'TERM', $self->{pid});
711 my ($self, $sig) = @_;
712 my $pid = delete $self->{pid} or return;
713 CORE::kill($sig, $pid) if defined $sig;
714 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
715 $ret == $pid or die "waitpid($pid) != $ret";
720 return if $self->{owner} != $$;
721 if (my $tail_pid = delete $self->{tail_pid}) {
722 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
723 CORE::kill('TERM', $tail_pid);
728 package PublicInbox::TestCommon::InboxWakeup;
730 sub on_inbox_unlock { ${$_[0]}->($_[1]) }