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 @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
15 run_script start_script key2sub xsys xsys_e xqx eml_load tick
16 have_xapian_compact json_utf8 setup_public_inboxes
17 tcp_host_port test_lei $lei $lei_out $lei_err $lei_opt);
19 my @methods = grep(!/\W/, @Test::More::EXPORT);
20 eval(join('', map { "*$_=\\&Test::More::$_;" } @methods));
22 push @EXPORT, @methods;
27 open(my $fh, '<', $path) or die "open $path: $!";
28 require PublicInbox::Eml;
29 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
35 unless (defined $base) {
36 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
38 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
39 ($tmpdir->dirname, $tmpdir);
46 Type => Socket::SOCK_STREAM(),
51 die 'IPv4-only' if $ENV{TEST_IPV4_ONLY};
52 require IO::Socket::INET6;
53 IO::Socket::INET6->new(%opt, LocalAddr => '[::1]')
55 die 'IPv6-only' if $ENV{TEST_IPV6_ONLY};
56 IO::Socket::INET->new(%opt, LocalAddr => '127.0.0.1')
57 } || BAIL_OUT "failed to create TCP server: $! ($@)";
60 sub tcp_host_port ($) {
62 my ($h, $p) = ($s->sockhost, $s->sockport);
63 my $ipv4 = $s->sockdomain == Socket::AF_INET();
65 $ipv4 ? ($h, $p) : ("[$h]", $p);
67 $ipv4 ? "$h:$p" : "[$h]:$p";
72 my ($dest, %opt) = @_;
73 my $addr = tcp_host_port($dest);
74 my $s = ref($dest)->new(
76 Type => Socket::SOCK_STREAM(),
79 ) or BAIL_OUT "failed to connect to $addr: $!";
84 sub require_git ($;$) {
85 my ($req, $maybe) = @_;
86 my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
87 my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
88 =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
90 my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
91 my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
92 if ($cur_int < $req_int) {
95 "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
102 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
104 while (my $mod = shift(@mods)) {
105 if ($mod eq 'json') {
106 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||'.
109 if ($mod eq 'Search::Xapian') {
110 if (eval { require PublicInbox::Search } &&
111 PublicInbox::Search::load_xapian()) {
114 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
115 if (eval { require PublicInbox::SearchIdx } &&
116 PublicInbox::SearchIdx::load_xapian_writable()){
119 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
121 for my $m (split(/\Q||\E/, $mod)) {
133 } elsif ($mod eq 'IO::Socket::SSL' &&
134 # old versions of IO::Socket::SSL aren't supported
135 # by libnet, at least:
136 # https://rt.cpan.org/Ticket/Display.html?id=100529
137 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
142 my $m = join(', ', @need)." missing for $0";
143 skip($m, $maybe) if $maybe;
149 return $key if ($key eq 'git' || index($key, '/') >= 0);
150 # n.b. we may have scripts which don't start with "public-inbox" in
152 $key =~ s/\A([-\.])/public-inbox$1/;
156 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
157 [ *STDERR{IO}, '>&' ]);
159 sub _prepare_redirects ($) {
162 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
163 my $fh = $fhref->[$fd] or next;
164 my ($oldfh, $mode) = @{$io_mode[$fd]};
165 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
166 $orig_io->[$fd] = $orig;
167 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
172 sub _undo_redirects ($) {
174 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
175 my $fh = $orig_io->[$fd] or next;
176 my ($oldfh, $mode) = @{$io_mode[$fd]};
177 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
181 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
182 # three ways to spawn our own short-lived Perl scripts for testing:
184 # 0 - (fork|vfork) + execve, the most realistic but slowest
185 # 1 - (not currently implemented)
186 # 2 - preloading and running in current process (slightly faster than 1)
188 # 2 is not compatible with scripts which use "exit" (which we'll try to
189 # avoid in the future).
191 our $run_script_exit_code;
192 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
193 sub run_script_exit {
194 $run_script_exit_code = $_[0] // 0;
201 $cached_scripts{$key} //= do {
202 my $f = key2script($key);
203 open my $fh, '<', $f or die "open $f: $!";
204 my $str = do { local $/; <$fh> };
205 my $pkg = (split(m!/!, $f))[-1];
206 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
209 $pkg = "PublicInbox::TestScript::$pkg";
215 *exit = \\&PublicInbox::TestCommon::run_script_exit;
217 # the below "line" directive is a magic comment, see perlsyn(1) manpage
229 my ($sub, $key, $argv) = @_;
230 local @ARGV = @$argv;
231 $run_script_exit_code = undef;
232 my $exit_code = eval { $sub->(@$argv) };
233 if ($@ eq RUN_SCRIPT_EXIT) {
235 $exit_code = $run_script_exit_code;
236 $? = ($exit_code << 8);
237 } elsif (defined($exit_code)) {
238 $? = ($exit_code << 8);
239 } elsif ($@) { # mimic die() behavior when uncaught
240 warn "E: eval-ed $key: $@\n";
241 $? = ($! << 8) if $!;
242 $? = (255 << 8) if $? == 0;
244 die "BUG: eval-ed $key: no exit code or \$@\n";
248 sub run_script ($;$$) {
249 my ($cmd, $env, $opt) = @_;
250 my ($key, @argv) = @$cmd;
251 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
252 my $sub = $run_mode == 0 ? undef : key2sub($key);
256 my $redir = $opt->{$fd};
257 my $ref = ref($redir);
258 if ($ref eq 'SCALAR') {
259 open my $fh, '+>', undef or die "open: $!";
261 $spawn_opt->{$fd} = $fh;
264 print $fh $$redir or die "print: $!";
265 seek($fh, 0, SEEK_SET) or die "seek: $!";
266 } elsif ($ref eq 'GLOB') {
267 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
269 die "unable to deal with $ref $redir";
272 if ($run_mode == 0) {
273 # spawn an independent new process, like real-world use cases:
274 require PublicInbox::Spawn;
275 my $cmd = [ key2script($key), @argv ];
276 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
278 my $r = waitpid($pid, 0) // die "waitpid: $!";
279 $r == $pid or die "waitpid: expected $pid, got $r";
281 } else { # localize and run everything in the same process:
282 # note: "local *STDIN = *STDIN;" and so forth did not work in
283 # old versions of perl
284 local %ENV = $env ? (%ENV, %$env) : %ENV;
286 local $0 = join(' ', @$cmd);
287 my $orig_io = _prepare_redirects($fhref);
288 _run_sub($sub, $key, \@argv);
289 _undo_redirects($orig_io);
293 # slurp the redirects back into user-supplied strings
295 my $fh = $fhref->[$fd] or next;
296 seek($fh, 0, SEEK_SET) or die "seek: $!";
297 my $redir = $opt->{$fd};
305 my $tick = shift // 0.1;
306 select undef, undef, undef, $tick;
310 sub wait_for_tail ($;$) {
311 my ($tail_pid, $want) = @_;
313 if ($^O eq 'linux') { # GNU tail may use inotify
314 state $tail_has_inotify;
315 return tick if $want < 0 && $tail_has_inotify;
316 my $end = time + $wait;
320 readlink($_) =~ /\binotify\b/
321 } glob("/proc/$tail_pid/fd/*");
322 } while (!@ino && time <= $end and tick);
324 $tail_has_inotify = 1;
325 $ino[0] =~ s!/fd/!/fdinfo/!;
328 if (open my $fh, '<', $ino[0]) {
330 @info = grep(/^inotify wd:/, <$fh>);
332 } while (scalar(@info) < $want && time <= $end and tick);
338 # like system() built-in, but uses spawn() for env/rdr + vfork
340 my ($cmd, $env, $rdr) = @_;
348 run_script($cmd, $env, { %$rdr, run_mode => 0 });
352 sub xsys_e { # like "/bin/sh -e"
354 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
357 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
359 my ($cmd, $env, $rdr) = @_;
361 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
362 wantarray ? split(/^/m, $out) : $out;
366 my ($cmd, $env, $opt) = @_;
367 my ($key, @argv) = @$cmd;
368 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
369 my $sub = $run_mode == 0 ? undef : key2sub($key);
371 if (my $tail_cmd = $ENV{TAIL}) {
374 next unless /\A--std(?:err|out)=(.+)\z/;
379 my $f = $opt->{$_} or next;
382 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
384 my $f = readlink "/proc/$$/fd/$fd";
385 push @paths, $f if -e $f;
390 $tail_pid = fork // die "fork: $!";
391 if ($tail_pid == 0) {
392 # make sure files exist, first
393 open my $fh, '>>', $_ for @paths;
394 open(STDOUT, '>&STDERR') or die "1>&2: $!";
395 exec(split(' ', $tail_cmd), @paths);
396 die "$tail_cmd failed: $!";
398 wait_for_tail($tail_pid, scalar @paths);
401 my $pid = fork // die "fork: $!\n";
403 eval { PublicInbox::DS->Reset };
404 # pretend to be systemd (cf. sd_listen_fds(3))
405 # 3 == SD_LISTEN_FDS_START
407 for ($fd = 0; 1; $fd++) {
409 last if $fd >= 3 && !defined($s);
411 my $fl = fcntl($s, F_GETFD, 0);
412 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
413 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
415 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
416 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
418 %ENV = (%ENV, %$env) if $env;
421 $ENV{LISTEN_PID} = $$;
422 $ENV{LISTEN_FDS} = $fds;
424 $0 = join(' ', @$cmd);
426 eval { PublicInbox::DS->Reset };
427 _run_sub($sub, $key, \@argv);
428 POSIX::_exit($? >> 8);
430 exec(key2script($key), @argv);
431 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
434 PublicInboxTestProcess->new($pid, $tail_pid);
437 sub have_xapian_compact () {
438 require PublicInbox::Spawn;
439 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
440 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
443 our ($err_skip, $lei_opt, $lei_out, $lei_err);
445 my ($cmd, $env, $xopt) = @_;
446 $lei_out = $lei_err = '';
448 ($env, $xopt) = grep { (!defined) || ref } @_;
449 $cmd = [ grep { defined && !ref } @_ ];
451 my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
453 $lei_err = join('', grep(!/$err_skip/, split(/^/m, $lei_err)));
458 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
464 my $test_opt = shift // {};
465 require_git(2.6) or skip('git 2.6+ required for lei test', 2);
466 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
467 require PublicInbox::Config;
468 delete local $ENV{XDG_DATA_HOME};
469 delete local $ENV{XDG_CONFIG_HOME};
470 local $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
471 local $ENV{GIT_COMMITTER_NAME} = 'lei user';
472 my (undef, $fn, $lineno) = caller(0);
473 my $t = "$fn:$lineno";
474 require PublicInbox::Spawn;
475 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
476 eval { require Socket::MsgHdr; 1 };
477 # XXX fix and move this inside daemon-only before 1.7 release
478 skip <<'EOM', 1 unless $lei_daemon;
479 Socket::MsgHdr missing or Inline::C is unconfigured/missing
481 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
482 my ($daemon_pid, $for_destroy);
483 my $tmpdir = $test_opt->{tmpdir};
484 ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
486 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
487 my $home = "$tmpdir/lei-daemon";
488 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
489 local $ENV{HOME} = $home;
490 my $xrd = "$home/xdg_run";
491 mkdir($xrd, 0700) or BAIL_OUT "mkdir: $!";
492 local $ENV{XDG_RUNTIME_DIR} = $xrd;
494 ok($lei->(qw(daemon-pid)), "daemon-pid after $t");
495 chomp($daemon_pid = $lei_out);
497 ok(kill(0, $daemon_pid), "daemon running after $t");
498 ok($lei->(qw(daemon-kill)), "daemon-kill after $t");
500 fail("daemon not running after $t");
502 }; # SKIP for lei_daemon
503 unless ($test_opt->{daemon_only}) {
504 require_ok 'PublicInbox::LEI';
505 my $home = "$tmpdir/lei-oneshot";
506 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
507 local $ENV{HOME} = $home;
508 # force sun_path[108] overflow:
509 my $xrd = "$home/1shot-test".('.sun_path' x 108);
510 local $err_skip = qr!\Q$xrd!; # for $lei->() filtering
511 local $ENV{XDG_RUNTIME_DIR} = $xrd;
516 kill(0, $daemon_pid) or last;
519 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
521 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
524 # returns the pathname to a ~/.public-inbox/config in scalar context,
525 # ($test_home, $pi_config_pathname) in list context
526 sub setup_public_inboxes () {
527 my $test_home = "t/home1";
528 my $pi_config = "$test_home/.public-inbox/config";
529 my $stamp = "$test_home/setup-stamp";
530 my @ret = ($test_home, $pi_config);
531 return @ret if -f $stamp;
533 require PublicInbox::Lock;
534 my $lk = bless { lock_path => "$test_home/setup.lock" },
536 my $end = $lk->lock_for_scope;
537 return @ret if -f $stamp;
539 require PublicInbox::InboxWritable;
540 local $ENV{PI_CONFIG} = $pi_config;
542 run_script([qw(-init), "-V$V", "t$V",
543 '--newsgroup', "t.$V",
544 "$test_home/t$V", "http://example.com/t$V",
545 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
547 my $cfg = PublicInbox::Config->new;
549 $cfg->each_inbox(sub {
551 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
552 my $V = $ibx->version;
553 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
555 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
556 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
561 run_script(['-index', $ibx->{inboxdir}]) or
565 $seen or BAIL_OUT 'no imports';
566 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
570 package PublicInboxTestProcess;
573 # prevent new threads from inheriting these objects
577 my ($klass, $pid, $tail_pid) = @_;
578 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
582 my ($self, $sig) = @_;
583 CORE::kill($sig // 'TERM', $self->{pid});
587 my ($self, $sig) = @_;
588 my $pid = delete $self->{pid} or return;
589 CORE::kill($sig, $pid) if defined $sig;
590 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
591 $ret == $pid or die "waitpid($pid) != $ret";
596 return if $self->{owner} != $$;
597 if (my $tail_pid = delete $self->{tail_pid}) {
598 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
599 CORE::kill('TERM', $tail_pid);
604 package PublicInbox::TestCommon::InboxWakeup;
606 sub on_inbox_unlock { ${$_[0]}->($_[1]) }