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);
15 @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
16 run_script start_script key2sub xsys xsys_e xqx eml_load tick
17 have_xapian_compact json_utf8 setup_public_inboxes create_inbox
18 tcp_host_port test_lei lei lei_ok $lei_out $lei_err $lei_opt
21 my @methods = grep(!/\W/, @Test::More::EXPORT);
22 eval(join('', map { "*$_=\\&Test::More::$_;" } @methods));
24 push @EXPORT, @methods;
29 open(my $fh, '<', $path) or die "open $path: $!";
30 require PublicInbox::Eml;
31 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
37 unless (defined $base) {
38 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
40 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
41 ($tmpdir->dirname, $tmpdir);
48 Type => Socket::SOCK_STREAM(),
53 die 'IPv4-only' if $ENV{TEST_IPV4_ONLY};
54 require IO::Socket::INET6;
55 IO::Socket::INET6->new(%opt, LocalAddr => '[::1]')
57 die 'IPv6-only' if $ENV{TEST_IPV6_ONLY};
58 IO::Socket::INET->new(%opt, LocalAddr => '127.0.0.1')
59 } || BAIL_OUT "failed to create TCP server: $! ($@)";
62 sub tcp_host_port ($) {
64 my ($h, $p) = ($s->sockhost, $s->sockport);
65 my $ipv4 = $s->sockdomain == Socket::AF_INET();
67 $ipv4 ? ($h, $p) : ("[$h]", $p);
69 $ipv4 ? "$h:$p" : "[$h]:$p";
74 my ($dest, %opt) = @_;
75 my $addr = tcp_host_port($dest);
76 my $s = ref($dest)->new(
78 Type => Socket::SOCK_STREAM(),
81 ) or BAIL_OUT "failed to connect to $addr: $!";
86 sub require_git ($;$) {
87 my ($req, $maybe) = @_;
88 my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
89 my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
90 =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
92 my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
93 my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
94 if ($cur_int < $req_int) {
97 "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
104 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
106 while (my $mod = shift(@mods)) {
107 if ($mod eq 'json') {
108 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||'.
111 if ($mod eq 'Search::Xapian') {
112 if (eval { require PublicInbox::Search } &&
113 PublicInbox::Search::load_xapian()) {
116 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
117 if (eval { require PublicInbox::SearchIdx } &&
118 PublicInbox::SearchIdx::load_xapian_writable()){
121 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
123 for my $m (split(/\Q||\E/, $mod)) {
135 } elsif ($mod eq 'IO::Socket::SSL' &&
136 # old versions of IO::Socket::SSL aren't supported
137 # by libnet, at least:
138 # https://rt.cpan.org/Ticket/Display.html?id=100529
139 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
144 my $m = join(', ', @need)." missing for $0";
145 skip($m, $maybe) if $maybe;
151 return $key if ($key eq 'git' || index($key, '/') >= 0);
152 # n.b. we may have scripts which don't start with "public-inbox" in
154 $key =~ s/\A([-\.])/public-inbox$1/;
158 my @io_mode = ([ *STDIN{IO}, '+<&' ], [ *STDOUT{IO}, '+>&' ],
159 [ *STDERR{IO}, '+>&' ]);
161 sub _prepare_redirects ($) {
164 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
165 my $fh = $fhref->[$fd] or next;
166 my ($oldfh, $mode) = @{$io_mode[$fd]};
167 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
168 $orig_io->[$fd] = $orig;
169 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
174 sub _undo_redirects ($) {
176 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
177 my $fh = $orig_io->[$fd] or next;
178 my ($oldfh, $mode) = @{$io_mode[$fd]};
179 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
183 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
184 # three ways to spawn our own short-lived Perl scripts for testing:
186 # 0 - (fork|vfork) + execve, the most realistic but slowest
187 # 1 - (not currently implemented)
188 # 2 - preloading and running in current process (slightly faster than 1)
190 # 2 is not compatible with scripts which use "exit" (which we'll try to
191 # avoid in the future).
193 our $run_script_exit_code;
194 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
195 sub run_script_exit {
196 $run_script_exit_code = $_[0] // 0;
203 $cached_scripts{$key} //= do {
204 my $f = key2script($key);
205 open my $fh, '<', $f or die "open $f: $!";
206 my $str = do { local $/; <$fh> };
207 my $pkg = (split(m!/!, $f))[-1];
208 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
211 $pkg = "PublicInbox::TestScript::$pkg";
217 *exit = \\&PublicInbox::TestCommon::run_script_exit;
219 # the below "line" directive is a magic comment, see perlsyn(1) manpage
231 my ($sub, $key, $argv) = @_;
232 local @ARGV = @$argv;
233 $run_script_exit_code = undef;
234 my $exit_code = eval { $sub->(@$argv) };
235 if ($@ eq RUN_SCRIPT_EXIT) {
237 $exit_code = $run_script_exit_code;
238 $? = ($exit_code << 8);
239 } elsif (defined($exit_code)) {
240 $? = ($exit_code << 8);
241 } elsif ($@) { # mimic die() behavior when uncaught
242 warn "E: eval-ed $key: $@\n";
243 $? = ($! << 8) if $!;
244 $? = (255 << 8) if $? == 0;
246 die "BUG: eval-ed $key: no exit code or \$@\n";
250 sub run_script ($;$$) {
251 my ($cmd, $env, $opt) = @_;
252 my ($key, @argv) = @$cmd;
253 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
254 my $sub = $run_mode == 0 ? undef : key2sub($key);
258 my $redir = $opt->{$fd};
259 my $ref = ref($redir);
260 if ($ref eq 'SCALAR') {
261 open my $fh, '+>', undef or die "open: $!";
263 $spawn_opt->{$fd} = $fh;
266 print $fh $$redir or die "print: $!";
267 seek($fh, 0, SEEK_SET) or die "seek: $!";
268 } elsif ($ref eq 'GLOB') {
269 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
271 die "unable to deal with $ref $redir";
274 if ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
275 unshift @argv, '--no-fsync';
277 if ($run_mode == 0) {
278 # spawn an independent new process, like real-world use cases:
279 require PublicInbox::Spawn;
280 my $cmd = [ key2script($key), @argv ];
281 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
283 my $r = waitpid($pid, 0) // die "waitpid: $!";
284 $r == $pid or die "waitpid: expected $pid, got $r";
286 } else { # localize and run everything in the same process:
287 # note: "local *STDIN = *STDIN;" and so forth did not work in
288 # old versions of perl
289 local %ENV = $env ? (%ENV, %$env) : %ENV;
291 local $0 = join(' ', @$cmd);
292 my $orig_io = _prepare_redirects($fhref);
293 _run_sub($sub, $key, \@argv);
294 _undo_redirects($orig_io);
298 # slurp the redirects back into user-supplied strings
300 my $fh = $fhref->[$fd] or next;
301 seek($fh, 0, SEEK_SET) or die "seek: $!";
302 my $redir = $opt->{$fd};
310 my $tick = shift // 0.1;
311 select undef, undef, undef, $tick;
315 sub wait_for_tail ($;$) {
316 my ($tail_pid, $want) = @_;
318 if ($^O eq 'linux') { # GNU tail may use inotify
319 state $tail_has_inotify;
320 return tick if $want < 0 && $tail_has_inotify;
321 my $end = time + $wait;
325 readlink($_) =~ /\binotify\b/
326 } glob("/proc/$tail_pid/fd/*");
327 } while (!@ino && time <= $end and tick);
329 $tail_has_inotify = 1;
330 $ino[0] =~ s!/fd/!/fdinfo/!;
333 if (open my $fh, '<', $ino[0]) {
335 @info = grep(/^inotify wd:/, <$fh>);
337 } while (scalar(@info) < $want && time <= $end and tick);
343 # like system() built-in, but uses spawn() for env/rdr + vfork
345 my ($cmd, $env, $rdr) = @_;
353 run_script($cmd, $env, { %$rdr, run_mode => 0 });
357 sub xsys_e { # like "/bin/sh -e"
359 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
362 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
364 my ($cmd, $env, $rdr) = @_;
366 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
367 wantarray ? split(/^/m, $out) : $out;
371 my ($cmd, $env, $opt) = @_;
372 my ($key, @argv) = @$cmd;
373 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
374 my $sub = $run_mode == 0 ? undef : key2sub($key);
376 if (my $tail_cmd = $ENV{TAIL}) {
379 next unless /\A--std(?:err|out)=(.+)\z/;
384 my $f = $opt->{$_} or next;
387 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
389 my $f = readlink "/proc/$$/fd/$fd";
390 push @paths, $f if -e $f;
395 $tail_pid = fork // die "fork: $!";
396 if ($tail_pid == 0) {
397 # make sure files exist, first
398 open my $fh, '>>', $_ for @paths;
399 open(STDOUT, '>&STDERR') or die "1>&2: $!";
400 exec(split(' ', $tail_cmd), @paths);
401 die "$tail_cmd failed: $!";
403 wait_for_tail($tail_pid, scalar @paths);
406 my $pid = fork // die "fork: $!\n";
408 eval { PublicInbox::DS->Reset };
409 # pretend to be systemd (cf. sd_listen_fds(3))
410 # 3 == SD_LISTEN_FDS_START
412 for ($fd = 0; 1; $fd++) {
414 last if $fd >= 3 && !defined($s);
416 my $fl = fcntl($s, F_GETFD, 0);
417 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
418 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
420 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
421 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
423 %ENV = (%ENV, %$env) if $env;
426 $ENV{LISTEN_PID} = $$;
427 $ENV{LISTEN_FDS} = $fds;
429 $0 = join(' ', @$cmd);
431 eval { PublicInbox::DS->Reset };
432 _run_sub($sub, $key, \@argv);
433 POSIX::_exit($? >> 8);
435 exec(key2script($key), @argv);
436 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
439 PublicInboxTestProcess->new($pid, $tail_pid);
442 sub have_xapian_compact () {
443 require PublicInbox::Spawn;
444 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
445 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
448 our ($err_skip, $lei_opt, $lei_out, $lei_err);
449 # favor lei() or lei_ok() over $lei for new code
451 my ($cmd, $env, $xopt) = @_;
452 $lei_out = $lei_err = '';
454 ($env, $xopt) = grep { (!defined) || ref } @_;
455 $cmd = [ grep { defined && !ref } @_ ];
457 my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
459 $lei_err = join('', grep(!/$err_skip/, split(/^/m, $lei_err)));
460 if ($lei_err ne '') {
461 if ($lei_err =~ /Use of uninitialized/ ||
462 $lei_err =~ m!\bArgument .*? isn't numeric in !) {
463 fail "lei_err=$lei_err";
465 state $loud = $ENV{TEST_LEI_ERR_LOUD};
466 diag "lei_err=$lei_err" if $loud;
473 my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
474 my $tmpdir = quotemeta(File::Spec->tmpdir);
475 # filter out anything that looks like a path name for consistent logs
476 my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
478 s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/! ||
479 s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!;
481 ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or diag $lei_err;
485 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
491 my $test_opt = shift // {};
492 require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
493 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
494 require PublicInbox::Config;
496 delete $ENV{XDG_DATA_HOME};
497 delete $ENV{XDG_CONFIG_HOME};
498 $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
499 $ENV{GIT_COMMITTER_NAME} = 'lei user';
500 my (undef, $fn, $lineno) = caller(0);
501 my $t = "$fn:$lineno";
502 require PublicInbox::Spawn;
503 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
504 eval { require Socket::MsgHdr; 1 };
505 # XXX fix and move this inside daemon-only before 1.7 release
506 skip <<'EOM', 1 unless $lei_daemon;
507 Socket::MsgHdr missing or Inline::C is unconfigured/missing
509 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
510 my ($daemon_pid, $for_destroy);
511 my $tmpdir = $test_opt->{tmpdir};
512 ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
514 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
515 my $home = "$tmpdir/lei-daemon";
516 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
517 local $ENV{HOME} = $home;
518 my $xrd = "$home/xdg_run";
519 mkdir($xrd, 0700) or BAIL_OUT "mkdir: $!";
520 local $ENV{XDG_RUNTIME_DIR} = $xrd;
522 lei_ok(qw(daemon-pid), \"daemon-pid after $t");
523 chomp($daemon_pid = $lei_out);
525 ok(kill(0, $daemon_pid), "daemon running after $t");
526 lei_ok(qw(daemon-kill), \"daemon-kill after $t");
528 fail("daemon not running after $t");
530 }; # SKIP for lei_daemon
531 unless ($test_opt->{daemon_only}) {
532 $ENV{TEST_LEI_DAEMON_ONLY} and
533 skip 'TEST_LEI_DAEMON_ONLY set', 1;
534 require_ok 'PublicInbox::LEI';
535 my $home = "$tmpdir/lei-oneshot";
536 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
537 local $ENV{HOME} = $home;
538 # force sun_path[108] overflow:
539 my $xrd = "$home/1shot-test".('.sun_path' x 108);
540 local $err_skip = qr!\Q$xrd!; # for lei() filtering
541 local $ENV{XDG_RUNTIME_DIR} = $xrd;
546 kill(0, $daemon_pid) or last;
549 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
551 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
554 # returns the pathname to a ~/.public-inbox/config in scalar context,
555 # ($test_home, $pi_config_pathname) in list context
556 sub setup_public_inboxes () {
557 my $test_home = "t/home2";
558 my $pi_config = "$test_home/.public-inbox/config";
559 my $stamp = "$test_home/setup-stamp";
560 my @ret = ($test_home, $pi_config);
561 return @ret if -f $stamp;
563 require PublicInbox::Lock;
564 my $lk = bless { lock_path => "$test_home/setup.lock" },
566 my $end = $lk->lock_for_scope;
567 return @ret if -f $stamp;
569 local $ENV{PI_CONFIG} = $pi_config;
571 run_script([qw(-init --skip-docdata), "-V$V",
572 '--newsgroup', "t.v$V", "t$V",
573 "$test_home/t$V", "http://example.com/t$V",
574 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
576 require PublicInbox::Config;
577 require PublicInbox::InboxWritable;
578 my $cfg = PublicInbox::Config->new;
580 $cfg->each_inbox(sub {
582 $ibx->{-no_fsync} = 1;
583 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
584 my $V = $ibx->version;
585 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
587 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
588 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
593 $seen or BAIL_OUT 'no imports';
594 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
598 sub create_inbox ($$;@) {
602 require PublicInbox::Lock;
603 require PublicInbox::InboxWritable;
604 my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
605 my $dir = "t/data-gen/$base.$ident";
608 mkdir $dir; # may race
609 -d $dir or BAIL_OUT "$dir could not be created: $!";
611 my $lk = bless { lock_path => "$dir/creat.lock" }, 'PublicInbox::Lock';
612 $opt{inboxdir} = File::Spec->rel2abs($dir);
613 $opt{name} //= $ident;
614 my $scope = $lk->lock_for_scope;
615 my $pre_cb = delete $opt{pre_cb};
616 $pre_cb->($dir) if $pre_cb && $new;
618 my $no_gc = delete $opt{-no_gc};
619 my $tmpdir = delete $opt{tmpdir};
620 my $addr = $opt{address} // [];
621 $opt{-primary_address} //= $addr->[0] // "$ident\@example.com";
622 my $parallel = delete($opt{importer_parallel}) // 0;
623 my $creat_opt = { nproc => delete($opt{nproc}) // 1 };
624 my $ibx = PublicInbox::InboxWritable->new({ %opt }, $creat_opt);
625 if (!-f "$dir/creat.stamp") {
626 my $im = $ibx->importer($parallel);
630 my @to_gc = $ibx->version == 1 ? ($ibx->{inboxdir}) :
631 glob("$ibx->{inboxdir}/git/*.git");
632 for my $dir (@to_gc) {
633 xsys_e([ qw(git gc -q) ], { GIT_DIR => $dir });
636 open my $s, '>', "$dir/creat.stamp" or
637 BAIL_OUT "error creating $dir/creat.stamp: $!";
641 xsys([qw(/bin/cp -Rp), $dir, $tmpdir]) == 0 or
642 BAIL_OUT "cp $dir $tmpdir";
643 $opt{inboxdir} = $tmpdir;
644 $ibx = PublicInbox::InboxWritable->new(\%opt);
649 sub test_httpd ($$;$) {
650 my ($env, $client, $skip) = @_;
651 for (qw(PI_CONFIG TMPDIR)) {
652 $env->{$_} or BAIL_OUT "$_ unset";
655 require_mods(qw(Plack::Test::ExternalServer), $skip // 1);
656 my $sock = tcp_server() or die;
657 my ($out, $err) = map { "$env->{TMPDIR}/std$_.log" } qw(out err);
658 my $cmd = [ qw(-httpd -W0), "--stdout=$out", "--stderr=$err" ];
659 my $td = start_script($cmd, $env, { 3 => $sock });
660 my ($h, $p) = tcp_host_port($sock);
661 local $ENV{PLACK_TEST_EXTERNALSERVER_URI} = "http://$h:$p";
662 Plack::Test::ExternalServer::test_psgi(client => $client);
664 open my $fh, '<', $err or BAIL_OUT $!;
665 my $e = do { local $/; <$fh> };
666 if ($e =~ s/^Plack::Middleware::ReverseProxy missing,\n//gms) {
667 $e =~ s/^URL generation for redirects .*\n//gms;
669 is($e, '', 'no errors');
674 package PublicInboxTestProcess;
677 # prevent new threads from inheriting these objects
681 my ($klass, $pid, $tail_pid) = @_;
682 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
686 my ($self, $sig) = @_;
687 CORE::kill($sig // 'TERM', $self->{pid});
691 my ($self, $sig) = @_;
692 my $pid = delete $self->{pid} or return;
693 CORE::kill($sig, $pid) if defined $sig;
694 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
695 $ret == $pid or die "waitpid($pid) != $ret";
700 return if $self->{owner} != $$;
701 if (my $tail_pid = delete $self->{tail_pid}) {
702 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
703 CORE::kill('TERM', $tail_pid);
708 package PublicInbox::TestCommon::InboxWakeup;
710 sub on_inbox_unlock { ${$_[0]}->($_[1]) }