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
18 tcp_host_port test_lei lei lei_ok
19 $lei $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);
450 my ($cmd, $env, $xopt) = @_;
451 $lei_out = $lei_err = '';
453 ($env, $xopt) = grep { (!defined) || ref } @_;
454 $cmd = [ grep { defined && !ref } @_ ];
456 my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
458 $lei_err = join('', grep(!/$err_skip/, split(/^/m, $lei_err)));
462 sub lei (@) { $lei->(@_) }
465 my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
466 my $tmpdir = quotemeta(File::Spec->tmpdir);
467 # filter out anything that looks like a path name for consistent logs
468 my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
470 s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/! ||
471 s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!;
473 ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or diag $lei_err;
477 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
483 my $test_opt = shift // {};
484 require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
485 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
486 require PublicInbox::Config;
487 delete local $ENV{XDG_DATA_HOME};
488 delete local $ENV{XDG_CONFIG_HOME};
489 local $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
490 local $ENV{GIT_COMMITTER_NAME} = 'lei user';
491 my (undef, $fn, $lineno) = caller(0);
492 my $t = "$fn:$lineno";
493 require PublicInbox::Spawn;
494 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
495 eval { require Socket::MsgHdr; 1 };
496 # XXX fix and move this inside daemon-only before 1.7 release
497 skip <<'EOM', 1 unless $lei_daemon;
498 Socket::MsgHdr missing or Inline::C is unconfigured/missing
500 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
501 my ($daemon_pid, $for_destroy);
502 my $tmpdir = $test_opt->{tmpdir};
503 ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
505 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
506 my $home = "$tmpdir/lei-daemon";
507 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
508 local $ENV{HOME} = $home;
509 my $xrd = "$home/xdg_run";
510 mkdir($xrd, 0700) or BAIL_OUT "mkdir: $!";
511 local $ENV{XDG_RUNTIME_DIR} = $xrd;
513 ok($lei->(qw(daemon-pid)), "daemon-pid after $t");
514 chomp($daemon_pid = $lei_out);
516 ok(kill(0, $daemon_pid), "daemon running after $t");
517 ok($lei->(qw(daemon-kill)), "daemon-kill after $t");
519 fail("daemon not running after $t");
521 }; # SKIP for lei_daemon
522 unless ($test_opt->{daemon_only}) {
523 $ENV{TEST_LEI_DAEMON_ONLY} and
524 skip 'TEST_LEI_DAEMON_ONLY set', 1;
525 require_ok 'PublicInbox::LEI';
526 my $home = "$tmpdir/lei-oneshot";
527 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
528 local $ENV{HOME} = $home;
529 # force sun_path[108] overflow:
530 my $xrd = "$home/1shot-test".('.sun_path' x 108);
531 local $err_skip = qr!\Q$xrd!; # for $lei->() filtering
532 local $ENV{XDG_RUNTIME_DIR} = $xrd;
537 kill(0, $daemon_pid) or last;
540 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
542 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
545 # returns the pathname to a ~/.public-inbox/config in scalar context,
546 # ($test_home, $pi_config_pathname) in list context
547 sub setup_public_inboxes () {
548 my $test_home = "t/home2";
549 my $pi_config = "$test_home/.public-inbox/config";
550 my $stamp = "$test_home/setup-stamp";
551 my @ret = ($test_home, $pi_config);
552 return @ret if -f $stamp;
554 require PublicInbox::Lock;
555 my $lk = bless { lock_path => "$test_home/setup.lock" },
557 my $end = $lk->lock_for_scope;
558 return @ret if -f $stamp;
560 local $ENV{PI_CONFIG} = $pi_config;
562 run_script([qw(-init), "-V$V", "t$V",
563 '--newsgroup', "t.v$V",
564 "$test_home/t$V", "http://example.com/t$V",
565 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
567 require PublicInbox::Config;
568 require PublicInbox::InboxWritable;
569 my $cfg = PublicInbox::Config->new;
571 $cfg->each_inbox(sub {
573 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
574 my $V = $ibx->version;
575 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
577 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
578 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
583 run_script(['-index', $ibx->{inboxdir}]) or
587 $seen or BAIL_OUT 'no imports';
588 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
592 package PublicInboxTestProcess;
595 # prevent new threads from inheriting these objects
599 my ($klass, $pid, $tail_pid) = @_;
600 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
604 my ($self, $sig) = @_;
605 CORE::kill($sig // 'TERM', $self->{pid});
609 my ($self, $sig) = @_;
610 my $pid = delete $self->{pid} or return;
611 CORE::kill($sig, $pid) if defined $sig;
612 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
613 $ret == $pid or die "waitpid($pid) != $ret";
618 return if $self->{owner} != $$;
619 if (my $tail_pid = delete $self->{tail_pid}) {
620 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
621 CORE::kill('TERM', $tail_pid);
626 package PublicInbox::TestCommon::InboxWakeup;
628 sub on_inbox_unlock { ${$_[0]}->($_[1]) }