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 $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 ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
273 unshift @argv, '--no-fsync';
275 if ($run_mode == 0) {
276 # spawn an independent new process, like real-world use cases:
277 require PublicInbox::Spawn;
278 my $cmd = [ key2script($key), @argv ];
279 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
281 my $r = waitpid($pid, 0) // die "waitpid: $!";
282 $r == $pid or die "waitpid: expected $pid, got $r";
284 } else { # localize and run everything in the same process:
285 # note: "local *STDIN = *STDIN;" and so forth did not work in
286 # old versions of perl
287 local %ENV = $env ? (%ENV, %$env) : %ENV;
289 local $0 = join(' ', @$cmd);
290 my $orig_io = _prepare_redirects($fhref);
291 _run_sub($sub, $key, \@argv);
292 _undo_redirects($orig_io);
296 # slurp the redirects back into user-supplied strings
298 my $fh = $fhref->[$fd] or next;
299 seek($fh, 0, SEEK_SET) or die "seek: $!";
300 my $redir = $opt->{$fd};
308 my $tick = shift // 0.1;
309 select undef, undef, undef, $tick;
313 sub wait_for_tail ($;$) {
314 my ($tail_pid, $want) = @_;
316 if ($^O eq 'linux') { # GNU tail may use inotify
317 state $tail_has_inotify;
318 return tick if $want < 0 && $tail_has_inotify;
319 my $end = time + $wait;
323 readlink($_) =~ /\binotify\b/
324 } glob("/proc/$tail_pid/fd/*");
325 } while (!@ino && time <= $end and tick);
327 $tail_has_inotify = 1;
328 $ino[0] =~ s!/fd/!/fdinfo/!;
331 if (open my $fh, '<', $ino[0]) {
333 @info = grep(/^inotify wd:/, <$fh>);
335 } while (scalar(@info) < $want && time <= $end and tick);
341 # like system() built-in, but uses spawn() for env/rdr + vfork
343 my ($cmd, $env, $rdr) = @_;
351 run_script($cmd, $env, { %$rdr, run_mode => 0 });
355 sub xsys_e { # like "/bin/sh -e"
357 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
360 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
362 my ($cmd, $env, $rdr) = @_;
364 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
365 wantarray ? split(/^/m, $out) : $out;
369 my ($cmd, $env, $opt) = @_;
370 my ($key, @argv) = @$cmd;
371 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
372 my $sub = $run_mode == 0 ? undef : key2sub($key);
374 if (my $tail_cmd = $ENV{TAIL}) {
377 next unless /\A--std(?:err|out)=(.+)\z/;
382 my $f = $opt->{$_} or next;
385 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
387 my $f = readlink "/proc/$$/fd/$fd";
388 push @paths, $f if -e $f;
393 $tail_pid = fork // die "fork: $!";
394 if ($tail_pid == 0) {
395 # make sure files exist, first
396 open my $fh, '>>', $_ for @paths;
397 open(STDOUT, '>&STDERR') or die "1>&2: $!";
398 exec(split(' ', $tail_cmd), @paths);
399 die "$tail_cmd failed: $!";
401 wait_for_tail($tail_pid, scalar @paths);
404 my $pid = fork // die "fork: $!\n";
406 eval { PublicInbox::DS->Reset };
407 # pretend to be systemd (cf. sd_listen_fds(3))
408 # 3 == SD_LISTEN_FDS_START
410 for ($fd = 0; 1; $fd++) {
412 last if $fd >= 3 && !defined($s);
414 my $fl = fcntl($s, F_GETFD, 0);
415 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
416 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
418 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
419 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
421 %ENV = (%ENV, %$env) if $env;
424 $ENV{LISTEN_PID} = $$;
425 $ENV{LISTEN_FDS} = $fds;
427 $0 = join(' ', @$cmd);
429 eval { PublicInbox::DS->Reset };
430 _run_sub($sub, $key, \@argv);
431 POSIX::_exit($? >> 8);
433 exec(key2script($key), @argv);
434 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
437 PublicInboxTestProcess->new($pid, $tail_pid);
440 sub have_xapian_compact () {
441 require PublicInbox::Spawn;
442 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
443 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
446 our ($err_skip, $lei_opt, $lei_out, $lei_err);
448 my ($cmd, $env, $xopt) = @_;
449 $lei_out = $lei_err = '';
451 ($env, $xopt) = grep { (!defined) || ref } @_;
452 $cmd = [ grep { defined && !ref } @_ ];
454 my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
456 $lei_err = join('', grep(!/$err_skip/, split(/^/m, $lei_err)));
460 sub lei (@) { $lei->(@_) }
463 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
469 my $test_opt = shift // {};
470 require_git(2.6) or skip('git 2.6+ required for lei test', 2);
471 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
472 require PublicInbox::Config;
473 delete local $ENV{XDG_DATA_HOME};
474 delete local $ENV{XDG_CONFIG_HOME};
475 local $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
476 local $ENV{GIT_COMMITTER_NAME} = 'lei user';
477 my (undef, $fn, $lineno) = caller(0);
478 my $t = "$fn:$lineno";
479 require PublicInbox::Spawn;
480 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
481 eval { require Socket::MsgHdr; 1 };
482 # XXX fix and move this inside daemon-only before 1.7 release
483 skip <<'EOM', 1 unless $lei_daemon;
484 Socket::MsgHdr missing or Inline::C is unconfigured/missing
486 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
487 my ($daemon_pid, $for_destroy);
488 my $tmpdir = $test_opt->{tmpdir};
489 ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
491 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
492 my $home = "$tmpdir/lei-daemon";
493 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
494 local $ENV{HOME} = $home;
495 my $xrd = "$home/xdg_run";
496 mkdir($xrd, 0700) or BAIL_OUT "mkdir: $!";
497 local $ENV{XDG_RUNTIME_DIR} = $xrd;
499 ok($lei->(qw(daemon-pid)), "daemon-pid after $t");
500 chomp($daemon_pid = $lei_out);
502 ok(kill(0, $daemon_pid), "daemon running after $t");
503 ok($lei->(qw(daemon-kill)), "daemon-kill after $t");
505 fail("daemon not running after $t");
507 }; # SKIP for lei_daemon
508 unless ($test_opt->{daemon_only}) {
509 require_ok 'PublicInbox::LEI';
510 my $home = "$tmpdir/lei-oneshot";
511 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
512 local $ENV{HOME} = $home;
513 # force sun_path[108] overflow:
514 my $xrd = "$home/1shot-test".('.sun_path' x 108);
515 local $err_skip = qr!\Q$xrd!; # for $lei->() filtering
516 local $ENV{XDG_RUNTIME_DIR} = $xrd;
521 kill(0, $daemon_pid) or last;
524 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
526 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
529 # returns the pathname to a ~/.public-inbox/config in scalar context,
530 # ($test_home, $pi_config_pathname) in list context
531 sub setup_public_inboxes () {
532 my $test_home = "t/home1";
533 my $pi_config = "$test_home/.public-inbox/config";
534 my $stamp = "$test_home/setup-stamp";
535 my @ret = ($test_home, $pi_config);
536 return @ret if -f $stamp;
538 require PublicInbox::Lock;
539 my $lk = bless { lock_path => "$test_home/setup.lock" },
541 my $end = $lk->lock_for_scope;
542 return @ret if -f $stamp;
544 require PublicInbox::InboxWritable;
545 local $ENV{PI_CONFIG} = $pi_config;
547 run_script([qw(-init), "-V$V", "t$V",
548 '--newsgroup', "t.$V",
549 "$test_home/t$V", "http://example.com/t$V",
550 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
552 my $cfg = PublicInbox::Config->new;
554 $cfg->each_inbox(sub {
556 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
557 my $V = $ibx->version;
558 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
560 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
561 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
566 run_script(['-index', $ibx->{inboxdir}]) or
570 $seen or BAIL_OUT 'no imports';
571 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
575 package PublicInboxTestProcess;
578 # prevent new threads from inheriting these objects
582 my ($klass, $pid, $tail_pid) = @_;
583 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
587 my ($self, $sig) = @_;
588 CORE::kill($sig // 'TERM', $self->{pid});
592 my ($self, $sig) = @_;
593 my $pid = delete $self->{pid} or return;
594 CORE::kill($sig, $pid) if defined $sig;
595 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
596 $ret == $pid or die "waitpid($pid) != $ret";
601 return if $self->{owner} != $$;
602 if (my $tail_pid = delete $self->{tail_pid}) {
603 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
604 CORE::kill('TERM', $tail_pid);
609 package PublicInbox::TestCommon::InboxWakeup;
611 sub on_inbox_unlock { ${$_[0]}->($_[1]) }