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;
30 open(my $fh, '<', $path) or die "open $path: $!";
31 require PublicInbox::Eml;
32 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
38 unless (defined $base) {
39 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
41 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
42 ($tmpdir->dirname, $tmpdir);
49 Type => Socket::SOCK_STREAM(),
54 die 'IPv4-only' if $ENV{TEST_IPV4_ONLY};
55 require IO::Socket::INET6;
56 IO::Socket::INET6->new(%opt, LocalAddr => '[::1]')
58 die 'IPv6-only' if $ENV{TEST_IPV6_ONLY};
59 IO::Socket::INET->new(%opt, LocalAddr => '127.0.0.1')
60 } || BAIL_OUT "failed to create TCP server: $! ($@)";
63 sub tcp_host_port ($) {
65 my ($h, $p) = ($s->sockhost, $s->sockport);
66 my $ipv4 = $s->sockdomain == Socket::AF_INET();
68 $ipv4 ? ($h, $p) : ("[$h]", $p);
70 $ipv4 ? "$h:$p" : "[$h]:$p";
75 my ($dest, %opt) = @_;
76 my $addr = tcp_host_port($dest);
77 my $s = ref($dest)->new(
79 Type => Socket::SOCK_STREAM(),
82 ) or BAIL_OUT "failed to connect to $addr: $!";
87 sub require_git ($;$) {
88 my ($req, $maybe) = @_;
89 my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
90 my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
91 =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
93 my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
94 my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
95 if ($cur_int < $req_int) {
98 "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
105 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
107 while (my $mod = shift(@mods)) {
108 if ($mod eq 'json') {
109 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||'.
112 if ($mod eq 'Search::Xapian') {
113 if (eval { require PublicInbox::Search } &&
114 PublicInbox::Search::load_xapian()) {
117 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
118 if (eval { require PublicInbox::SearchIdx } &&
119 PublicInbox::SearchIdx::load_xapian_writable()){
122 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
124 for my $m (split(/\Q||\E/, $mod)) {
136 } elsif ($mod eq 'IO::Socket::SSL' &&
137 # old versions of IO::Socket::SSL aren't supported
138 # by libnet, at least:
139 # https://rt.cpan.org/Ticket/Display.html?id=100529
140 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
145 my $m = join(', ', @need)." missing for $0";
146 skip($m, $maybe) if $maybe;
152 return $key if ($key eq 'git' || index($key, '/') >= 0);
153 # n.b. we may have scripts which don't start with "public-inbox" in
155 $key =~ s/\A([-\.])/public-inbox$1/;
159 my @io_mode = ([ *STDIN{IO}, '+<&' ], [ *STDOUT{IO}, '+>&' ],
160 [ *STDERR{IO}, '+>&' ]);
162 sub _prepare_redirects ($) {
165 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
166 my $fh = $fhref->[$fd] or next;
167 my ($oldfh, $mode) = @{$io_mode[$fd]};
168 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
169 $orig_io->[$fd] = $orig;
170 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
175 sub _undo_redirects ($) {
177 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
178 my $fh = $orig_io->[$fd] or next;
179 my ($oldfh, $mode) = @{$io_mode[$fd]};
180 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
184 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
185 # three ways to spawn our own short-lived Perl scripts for testing:
187 # 0 - (fork|vfork) + execve, the most realistic but slowest
188 # 1 - (not currently implemented)
189 # 2 - preloading and running in current process (slightly faster than 1)
191 # 2 is not compatible with scripts which use "exit" (which we'll try to
192 # avoid in the future).
194 our $run_script_exit_code;
195 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
196 sub run_script_exit {
197 $run_script_exit_code = $_[0] // 0;
204 $cached_scripts{$key} //= do {
205 my $f = key2script($key);
206 open my $fh, '<', $f or die "open $f: $!";
207 my $str = do { local $/; <$fh> };
208 my $pkg = (split(m!/!, $f))[-1];
209 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
212 $pkg = "PublicInbox::TestScript::$pkg";
218 *exit = \\&PublicInbox::TestCommon::run_script_exit;
220 # the below "line" directive is a magic comment, see perlsyn(1) manpage
232 my ($sub, $key, $argv) = @_;
233 local @ARGV = @$argv;
234 $run_script_exit_code = undef;
235 my $exit_code = eval { $sub->(@$argv) };
236 if ($@ eq RUN_SCRIPT_EXIT) {
238 $exit_code = $run_script_exit_code;
239 $? = ($exit_code << 8);
240 } elsif (defined($exit_code)) {
241 $? = ($exit_code << 8);
242 } elsif ($@) { # mimic die() behavior when uncaught
243 warn "E: eval-ed $key: $@\n";
244 $? = ($! << 8) if $!;
245 $? = (255 << 8) if $? == 0;
247 die "BUG: eval-ed $key: no exit code or \$@\n";
251 sub run_script ($;$$) {
252 my ($cmd, $env, $opt) = @_;
253 my ($key, @argv) = @$cmd;
254 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
255 my $sub = $run_mode == 0 ? undef : key2sub($key);
259 my $redir = $opt->{$fd};
260 my $ref = ref($redir);
261 if ($ref eq 'SCALAR') {
262 open my $fh, '+>', undef or die "open: $!";
264 $spawn_opt->{$fd} = $fh;
267 print $fh $$redir or die "print: $!";
268 seek($fh, 0, SEEK_SET) or die "seek: $!";
269 } elsif ($ref eq 'GLOB') {
270 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
272 die "unable to deal with $ref $redir";
275 if ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
276 unshift @argv, '--no-fsync';
278 if ($run_mode == 0) {
279 # spawn an independent new process, like real-world use cases:
280 require PublicInbox::Spawn;
281 my $cmd = [ key2script($key), @argv ];
282 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
284 my $r = waitpid($pid, 0) // die "waitpid: $!";
285 $r == $pid or die "waitpid: expected $pid, got $r";
287 } else { # localize and run everything in the same process:
288 # note: "local *STDIN = *STDIN;" and so forth did not work in
289 # old versions of perl
290 local %ENV = $env ? (%ENV, %$env) : %ENV;
292 local $0 = join(' ', @$cmd);
293 my $orig_io = _prepare_redirects($fhref);
294 _run_sub($sub, $key, \@argv);
295 eval { PublicInbox::Inbox::cleanup_task() };
296 _undo_redirects($orig_io);
300 # slurp the redirects back into user-supplied strings
302 my $fh = $fhref->[$fd] or next;
303 seek($fh, 0, SEEK_SET) or die "seek: $!";
304 my $redir = $opt->{$fd};
312 my $tick = shift // 0.1;
313 select undef, undef, undef, $tick;
317 sub wait_for_tail ($;$) {
318 my ($tail_pid, $want) = @_;
320 if ($^O eq 'linux') { # GNU tail may use inotify
321 state $tail_has_inotify;
322 return tick if $want < 0 && $tail_has_inotify;
323 my $end = time + $wait;
327 readlink($_) =~ /\binotify\b/
328 } glob("/proc/$tail_pid/fd/*");
329 } while (!@ino && time <= $end and tick);
331 $tail_has_inotify = 1;
332 $ino[0] =~ s!/fd/!/fdinfo/!;
335 if (open my $fh, '<', $ino[0]) {
337 @info = grep(/^inotify wd:/, <$fh>);
339 } while (scalar(@info) < $want && time <= $end and tick);
345 # like system() built-in, but uses spawn() for env/rdr + vfork
347 my ($cmd, $env, $rdr) = @_;
355 run_script($cmd, $env, { %$rdr, run_mode => 0 });
359 sub xsys_e { # like "/bin/sh -e"
361 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
364 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
366 my ($cmd, $env, $rdr) = @_;
368 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
369 wantarray ? split(/^/m, $out) : $out;
373 my ($cmd, $env, $opt) = @_;
374 my ($key, @argv) = @$cmd;
375 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
376 my $sub = $run_mode == 0 ? undef : key2sub($key);
378 if (my $tail_cmd = $ENV{TAIL}) {
381 next unless /\A--std(?:err|out)=(.+)\z/;
386 my $f = $opt->{$_} or next;
389 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
391 my $f = readlink "/proc/$$/fd/$fd";
392 push @paths, $f if -e $f;
397 $tail_pid = fork // die "fork: $!";
398 if ($tail_pid == 0) {
399 # make sure files exist, first
400 open my $fh, '>>', $_ for @paths;
401 open(STDOUT, '>&STDERR') or die "1>&2: $!";
402 exec(split(' ', $tail_cmd), @paths);
403 die "$tail_cmd failed: $!";
405 wait_for_tail($tail_pid, scalar @paths);
408 my $pid = fork // die "fork: $!\n";
410 eval { PublicInbox::DS->Reset };
411 # pretend to be systemd (cf. sd_listen_fds(3))
412 # 3 == SD_LISTEN_FDS_START
414 for ($fd = 0; 1; $fd++) {
416 last if $fd >= 3 && !defined($s);
418 my $fl = fcntl($s, F_GETFD, 0);
419 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
420 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
422 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
423 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
425 %ENV = (%ENV, %$env) if $env;
428 $ENV{LISTEN_PID} = $$;
429 $ENV{LISTEN_FDS} = $fds;
431 $0 = join(' ', @$cmd);
433 eval { PublicInbox::DS->Reset };
434 _run_sub($sub, $key, \@argv);
435 POSIX::_exit($? >> 8);
437 exec(key2script($key), @argv);
438 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
441 PublicInboxTestProcess->new($pid, $tail_pid);
444 sub have_xapian_compact () {
445 require PublicInbox::Spawn;
446 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
447 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
450 our ($err_skip, $lei_opt, $lei_out, $lei_err);
451 # favor lei() or lei_ok() over $lei for new code
453 my ($cmd, $env, $xopt) = @_;
454 $lei_out = $lei_err = '';
456 ($env, $xopt) = grep { (!defined) || ref } @_;
457 $cmd = [ grep { defined && !ref } @_ ];
459 my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
461 $lei_err = join('', grep(!/$err_skip/, split(/^/m, $lei_err)));
462 if ($lei_err ne '') {
463 if ($lei_err =~ /Use of uninitialized/ ||
464 $lei_err =~ m!\bArgument .*? isn't numeric in !) {
465 fail "lei_err=$lei_err";
467 diag "lei_err=$lei_err" if $lei_loud;
474 state $PWD = $ENV{PWD} // Cwd::getcwd();
475 my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
476 my $tmpdir = quotemeta(File::Spec->tmpdir);
477 # filter out anything that looks like a path name for consistent logs
478 my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
481 s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/!;
482 s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!g;
483 s!\Q$PWD\E\b!\$PWD!g;
486 ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or diag $lei_err;
490 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
496 my $test_opt = shift // {};
497 require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
498 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
499 require PublicInbox::Config;
501 delete $ENV{XDG_DATA_HOME};
502 delete $ENV{XDG_CONFIG_HOME};
503 $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
504 $ENV{GIT_COMMITTER_NAME} = 'lei user';
505 my (undef, $fn, $lineno) = caller(0);
506 my $t = "$fn:$lineno";
507 require PublicInbox::Spawn;
508 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
509 eval { require Socket::MsgHdr; 1 };
510 # XXX fix and move this inside daemon-only before 1.7 release
511 skip <<'EOM', 1 unless $lei_daemon;
512 Socket::MsgHdr missing or Inline::C is unconfigured/missing
514 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
515 my ($daemon_pid, $for_destroy, $daemon_xrd);
516 my $tmpdir = $test_opt->{tmpdir};
517 ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
518 state $persist_xrd = $ENV{TEST_LEI_DAEMON_PERSIST_DIR};
520 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
521 my $home = "$tmpdir/lei-daemon";
522 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
523 local $ENV{HOME} = $home;
525 if ($persist_xrd && !$test_opt->{daemon_only}) {
526 $persist = $daemon_xrd = $persist_xrd;
528 $daemon_xrd = "$home/xdg_run";
529 mkdir($daemon_xrd, 0700) or BAIL_OUT "mkdir: $!";
531 local $ENV{XDG_RUNTIME_DIR} = $daemon_xrd;
534 lei_ok(qw(daemon-pid), \"daemon-pid after $t");
535 chomp($daemon_pid = $lei_out);
537 fail("daemon not running after $t");
538 skip 'daemon died unexpectedly', 2;
540 ok(kill(0, $daemon_pid), "daemon running after $t");
541 lei_ok(qw(daemon-kill), \"daemon-kill after $t");
543 }; # SKIP for lei_daemon
544 unless ($test_opt->{daemon_only}) {
545 $ENV{TEST_LEI_DAEMON_ONLY} and
546 skip 'TEST_LEI_DAEMON_ONLY set', 1;
547 require_ok 'PublicInbox::LEI';
548 my $home = "$tmpdir/lei-oneshot";
549 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
550 local $ENV{HOME} = $home;
551 # force sun_path[108] overflow:
552 my $xrd = "$home/1shot-test".('.sun_path' x 108);
553 local $err_skip = qr!\Q$xrd!; # for lei() filtering
554 local $ENV{XDG_RUNTIME_DIR} = $xrd;
559 kill(0, $daemon_pid) or last;
562 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
563 my $f = "$daemon_xrd/lei/errors.log";
564 open my $fh, '<', $f or BAIL_OUT "$f: $!";
567 "$t daemon XDG_RUNTIME_DIR/lei/errors.log empty");
569 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
572 # returns the pathname to a ~/.public-inbox/config in scalar context,
573 # ($test_home, $pi_config_pathname) in list context
574 sub setup_public_inboxes () {
575 my $test_home = "t/home2";
576 my $pi_config = "$test_home/.public-inbox/config";
577 my $stamp = "$test_home/setup-stamp";
578 my @ret = ($test_home, $pi_config);
579 return @ret if -f $stamp;
581 require PublicInbox::Lock;
582 my $lk = bless { lock_path => "$test_home/setup.lock" },
584 my $end = $lk->lock_for_scope;
585 return @ret if -f $stamp;
587 local $ENV{PI_CONFIG} = $pi_config;
589 run_script([qw(-init --skip-docdata), "-V$V",
590 '--newsgroup', "t.v$V", "t$V",
591 "$test_home/t$V", "http://example.com/t$V",
592 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
594 require PublicInbox::Config;
595 require PublicInbox::InboxWritable;
596 my $cfg = PublicInbox::Config->new;
598 $cfg->each_inbox(sub {
600 $ibx->{-no_fsync} = 1;
601 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
602 my $V = $ibx->version;
603 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
605 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
606 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
611 $seen or BAIL_OUT 'no imports';
612 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
616 sub create_inbox ($$;@) {
620 require PublicInbox::Lock;
621 require PublicInbox::InboxWritable;
622 my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
623 my $dir = "t/data-gen/$base.$ident";
626 mkdir $dir; # may race
627 -d $dir or BAIL_OUT "$dir could not be created: $!";
629 my $lk = bless { lock_path => "$dir/creat.lock" }, 'PublicInbox::Lock';
630 $opt{inboxdir} = File::Spec->rel2abs($dir);
631 $opt{name} //= $ident;
632 my $scope = $lk->lock_for_scope;
633 my $pre_cb = delete $opt{pre_cb};
634 $pre_cb->($dir) if $pre_cb && $new;
636 my $no_gc = delete $opt{-no_gc};
637 my $tmpdir = delete $opt{tmpdir};
638 my $addr = $opt{address} // [];
639 $opt{-primary_address} //= $addr->[0] // "$ident\@example.com";
640 my $parallel = delete($opt{importer_parallel}) // 0;
641 my $creat_opt = { nproc => delete($opt{nproc}) // 1 };
642 my $ibx = PublicInbox::InboxWritable->new({ %opt }, $creat_opt);
643 if (!-f "$dir/creat.stamp") {
644 my $im = $ibx->importer($parallel);
648 my @to_gc = $ibx->version == 1 ? ($ibx->{inboxdir}) :
649 glob("$ibx->{inboxdir}/git/*.git");
650 for my $dir (@to_gc) {
651 xsys_e([ qw(git gc -q) ], { GIT_DIR => $dir });
654 open my $s, '>', "$dir/creat.stamp" or
655 BAIL_OUT "error creating $dir/creat.stamp: $!";
659 xsys([qw(/bin/cp -Rp), $dir, $tmpdir]) == 0 or
660 BAIL_OUT "cp $dir $tmpdir";
661 $opt{inboxdir} = $tmpdir;
662 $ibx = PublicInbox::InboxWritable->new(\%opt);
667 sub test_httpd ($$;$) {
668 my ($env, $client, $skip) = @_;
669 for (qw(PI_CONFIG TMPDIR)) {
670 $env->{$_} or BAIL_OUT "$_ unset";
673 require_mods(qw(Plack::Test::ExternalServer), $skip // 1);
674 my $sock = tcp_server() or die;
675 my ($out, $err) = map { "$env->{TMPDIR}/std$_.log" } qw(out err);
676 my $cmd = [ qw(-httpd -W0), "--stdout=$out", "--stderr=$err" ];
677 my $td = start_script($cmd, $env, { 3 => $sock });
678 my ($h, $p) = tcp_host_port($sock);
679 local $ENV{PLACK_TEST_EXTERNALSERVER_URI} = "http://$h:$p";
680 Plack::Test::ExternalServer::test_psgi(client => $client);
682 open my $fh, '<', $err or BAIL_OUT $!;
683 my $e = do { local $/; <$fh> };
684 if ($e =~ s/^Plack::Middleware::ReverseProxy missing,\n//gms) {
685 $e =~ s/^URL generation for redirects .*\n//gms;
687 is($e, '', 'no errors');
692 package PublicInboxTestProcess;
695 # prevent new threads from inheriting these objects
699 my ($klass, $pid, $tail_pid) = @_;
700 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
704 my ($self, $sig) = @_;
705 CORE::kill($sig // 'TERM', $self->{pid});
709 my ($self, $sig) = @_;
710 my $pid = delete $self->{pid} or return;
711 CORE::kill($sig, $pid) if defined $sig;
712 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
713 $ret == $pid or die "waitpid($pid) != $ret";
718 return if $self->{owner} != $$;
719 if (my $tail_pid = delete $self->{tail_pid}) {
720 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
721 CORE::kill('TERM', $tail_pid);
726 package PublicInbox::TestCommon::InboxWakeup;
728 sub on_inbox_unlock { ${$_[0]}->($_[1]) }