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);
20 my @methods = grep(!/\W/, @Test::More::EXPORT);
21 eval(join('', map { "*$_=\\&Test::More::$_;" } @methods));
23 push @EXPORT, @methods;
28 open(my $fh, '<', $path) or die "open $path: $!";
29 require PublicInbox::Eml;
30 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
36 unless (defined $base) {
37 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
39 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
40 ($tmpdir->dirname, $tmpdir);
47 Type => Socket::SOCK_STREAM(),
52 die 'IPv4-only' if $ENV{TEST_IPV4_ONLY};
53 require IO::Socket::INET6;
54 IO::Socket::INET6->new(%opt, LocalAddr => '[::1]')
56 die 'IPv6-only' if $ENV{TEST_IPV6_ONLY};
57 IO::Socket::INET->new(%opt, LocalAddr => '127.0.0.1')
58 } || BAIL_OUT "failed to create TCP server: $! ($@)";
61 sub tcp_host_port ($) {
63 my ($h, $p) = ($s->sockhost, $s->sockport);
64 my $ipv4 = $s->sockdomain == Socket::AF_INET();
66 $ipv4 ? ($h, $p) : ("[$h]", $p);
68 $ipv4 ? "$h:$p" : "[$h]:$p";
73 my ($dest, %opt) = @_;
74 my $addr = tcp_host_port($dest);
75 my $s = ref($dest)->new(
77 Type => Socket::SOCK_STREAM(),
80 ) or BAIL_OUT "failed to connect to $addr: $!";
85 sub require_git ($;$) {
86 my ($req, $maybe) = @_;
87 my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
88 my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
89 =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
91 my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
92 my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
93 if ($cur_int < $req_int) {
96 "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
103 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
105 while (my $mod = shift(@mods)) {
106 if ($mod eq 'json') {
107 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||'.
110 if ($mod eq 'Search::Xapian') {
111 if (eval { require PublicInbox::Search } &&
112 PublicInbox::Search::load_xapian()) {
115 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
116 if (eval { require PublicInbox::SearchIdx } &&
117 PublicInbox::SearchIdx::load_xapian_writable()){
120 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
122 for my $m (split(/\Q||\E/, $mod)) {
134 } elsif ($mod eq 'IO::Socket::SSL' &&
135 # old versions of IO::Socket::SSL aren't supported
136 # by libnet, at least:
137 # https://rt.cpan.org/Ticket/Display.html?id=100529
138 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
143 my $m = join(', ', @need)." missing for $0";
144 skip($m, $maybe) if $maybe;
150 return $key if ($key eq 'git' || index($key, '/') >= 0);
151 # n.b. we may have scripts which don't start with "public-inbox" in
153 $key =~ s/\A([-\.])/public-inbox$1/;
157 my @io_mode = ([ *STDIN{IO}, '+<&' ], [ *STDOUT{IO}, '+>&' ],
158 [ *STDERR{IO}, '+>&' ]);
160 sub _prepare_redirects ($) {
163 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
164 my $fh = $fhref->[$fd] or next;
165 my ($oldfh, $mode) = @{$io_mode[$fd]};
166 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
167 $orig_io->[$fd] = $orig;
168 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
173 sub _undo_redirects ($) {
175 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
176 my $fh = $orig_io->[$fd] or next;
177 my ($oldfh, $mode) = @{$io_mode[$fd]};
178 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
182 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
183 # three ways to spawn our own short-lived Perl scripts for testing:
185 # 0 - (fork|vfork) + execve, the most realistic but slowest
186 # 1 - (not currently implemented)
187 # 2 - preloading and running in current process (slightly faster than 1)
189 # 2 is not compatible with scripts which use "exit" (which we'll try to
190 # avoid in the future).
192 our $run_script_exit_code;
193 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
194 sub run_script_exit {
195 $run_script_exit_code = $_[0] // 0;
202 $cached_scripts{$key} //= do {
203 my $f = key2script($key);
204 open my $fh, '<', $f or die "open $f: $!";
205 my $str = do { local $/; <$fh> };
206 my $pkg = (split(m!/!, $f))[-1];
207 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
210 $pkg = "PublicInbox::TestScript::$pkg";
216 *exit = \\&PublicInbox::TestCommon::run_script_exit;
218 # the below "line" directive is a magic comment, see perlsyn(1) manpage
230 my ($sub, $key, $argv) = @_;
231 local @ARGV = @$argv;
232 $run_script_exit_code = undef;
233 my $exit_code = eval { $sub->(@$argv) };
234 if ($@ eq RUN_SCRIPT_EXIT) {
236 $exit_code = $run_script_exit_code;
237 $? = ($exit_code << 8);
238 } elsif (defined($exit_code)) {
239 $? = ($exit_code << 8);
240 } elsif ($@) { # mimic die() behavior when uncaught
241 warn "E: eval-ed $key: $@\n";
242 $? = ($! << 8) if $!;
243 $? = (255 << 8) if $? == 0;
245 die "BUG: eval-ed $key: no exit code or \$@\n";
249 sub run_script ($;$$) {
250 my ($cmd, $env, $opt) = @_;
251 my ($key, @argv) = @$cmd;
252 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
253 my $sub = $run_mode == 0 ? undef : key2sub($key);
257 my $redir = $opt->{$fd};
258 my $ref = ref($redir);
259 if ($ref eq 'SCALAR') {
260 open my $fh, '+>', undef or die "open: $!";
262 $spawn_opt->{$fd} = $fh;
265 print $fh $$redir or die "print: $!";
266 seek($fh, 0, SEEK_SET) or die "seek: $!";
267 } elsif ($ref eq 'GLOB') {
268 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
270 die "unable to deal with $ref $redir";
273 if ($key =~ /-(index|convert|extindex|convert|xcpdb)\z/) {
274 unshift @argv, '--no-fsync';
276 if ($run_mode == 0) {
277 # spawn an independent new process, like real-world use cases:
278 require PublicInbox::Spawn;
279 my $cmd = [ key2script($key), @argv ];
280 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
282 my $r = waitpid($pid, 0) // die "waitpid: $!";
283 $r == $pid or die "waitpid: expected $pid, got $r";
285 } else { # localize and run everything in the same process:
286 # note: "local *STDIN = *STDIN;" and so forth did not work in
287 # old versions of perl
288 local %ENV = $env ? (%ENV, %$env) : %ENV;
290 local $0 = join(' ', @$cmd);
291 my $orig_io = _prepare_redirects($fhref);
292 _run_sub($sub, $key, \@argv);
293 _undo_redirects($orig_io);
297 # slurp the redirects back into user-supplied strings
299 my $fh = $fhref->[$fd] or next;
300 seek($fh, 0, SEEK_SET) or die "seek: $!";
301 my $redir = $opt->{$fd};
309 my $tick = shift // 0.1;
310 select undef, undef, undef, $tick;
314 sub wait_for_tail ($;$) {
315 my ($tail_pid, $want) = @_;
317 if ($^O eq 'linux') { # GNU tail may use inotify
318 state $tail_has_inotify;
319 return tick if $want < 0 && $tail_has_inotify;
320 my $end = time + $wait;
324 readlink($_) =~ /\binotify\b/
325 } glob("/proc/$tail_pid/fd/*");
326 } while (!@ino && time <= $end and tick);
328 $tail_has_inotify = 1;
329 $ino[0] =~ s!/fd/!/fdinfo/!;
332 if (open my $fh, '<', $ino[0]) {
334 @info = grep(/^inotify wd:/, <$fh>);
336 } while (scalar(@info) < $want && time <= $end and tick);
342 # like system() built-in, but uses spawn() for env/rdr + vfork
344 my ($cmd, $env, $rdr) = @_;
352 run_script($cmd, $env, { %$rdr, run_mode => 0 });
356 sub xsys_e { # like "/bin/sh -e"
358 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
361 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
363 my ($cmd, $env, $rdr) = @_;
365 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
366 wantarray ? split(/^/m, $out) : $out;
370 my ($cmd, $env, $opt) = @_;
371 my ($key, @argv) = @$cmd;
372 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
373 my $sub = $run_mode == 0 ? undef : key2sub($key);
375 if (my $tail_cmd = $ENV{TAIL}) {
378 next unless /\A--std(?:err|out)=(.+)\z/;
383 my $f = $opt->{$_} or next;
386 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
388 my $f = readlink "/proc/$$/fd/$fd";
389 push @paths, $f if -e $f;
394 $tail_pid = fork // die "fork: $!";
395 if ($tail_pid == 0) {
396 # make sure files exist, first
397 open my $fh, '>>', $_ for @paths;
398 open(STDOUT, '>&STDERR') or die "1>&2: $!";
399 exec(split(' ', $tail_cmd), @paths);
400 die "$tail_cmd failed: $!";
402 wait_for_tail($tail_pid, scalar @paths);
405 my $pid = fork // die "fork: $!\n";
407 eval { PublicInbox::DS->Reset };
408 # pretend to be systemd (cf. sd_listen_fds(3))
409 # 3 == SD_LISTEN_FDS_START
411 for ($fd = 0; 1; $fd++) {
413 last if $fd >= 3 && !defined($s);
415 my $fl = fcntl($s, F_GETFD, 0);
416 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
417 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
419 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
420 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
422 %ENV = (%ENV, %$env) if $env;
425 $ENV{LISTEN_PID} = $$;
426 $ENV{LISTEN_FDS} = $fds;
428 $0 = join(' ', @$cmd);
430 eval { PublicInbox::DS->Reset };
431 _run_sub($sub, $key, \@argv);
432 POSIX::_exit($? >> 8);
434 exec(key2script($key), @argv);
435 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
438 PublicInboxTestProcess->new($pid, $tail_pid);
441 sub have_xapian_compact () {
442 require PublicInbox::Spawn;
443 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
444 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
447 our ($err_skip, $lei_opt, $lei_out, $lei_err);
448 # favor lei() or lei_ok() over $lei for new code
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)));
463 my $msg = ref($_[-1]) eq 'SCALAR' ? pop(@_) : undef;
464 my $tmpdir = quotemeta(File::Spec->tmpdir);
465 # filter out anything that looks like a path name for consistent logs
466 my @msg = ref($_[0]) eq 'ARRAY' ? @{$_[0]} : @_;
468 s!\A([a-z0-9]+://)[^/]+/!$1\$HOST_PORT/! ||
469 s!$tmpdir\b/(?:[^/]+/)?!\$TMPDIR/!;
471 ok(lei(@_), "lei @msg". ($msg ? " ($$msg)" : '')) or diag $lei_err;
475 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
481 my $test_opt = shift // {};
482 require_git(2.6, 1) or skip('git 2.6+ required for lei test', 2);
483 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
484 require PublicInbox::Config;
486 delete $ENV{XDG_DATA_HOME};
487 delete $ENV{XDG_CONFIG_HOME};
488 $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
489 $ENV{GIT_COMMITTER_NAME} = 'lei user';
490 my (undef, $fn, $lineno) = caller(0);
491 my $t = "$fn:$lineno";
492 require PublicInbox::Spawn;
493 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
494 eval { require Socket::MsgHdr; 1 };
495 # XXX fix and move this inside daemon-only before 1.7 release
496 skip <<'EOM', 1 unless $lei_daemon;
497 Socket::MsgHdr missing or Inline::C is unconfigured/missing
499 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
500 my ($daemon_pid, $for_destroy);
501 my $tmpdir = $test_opt->{tmpdir};
502 ($tmpdir, $for_destroy) = tmpdir unless $tmpdir;
504 skip 'TEST_LEI_ONESHOT set', 1 if $ENV{TEST_LEI_ONESHOT};
505 my $home = "$tmpdir/lei-daemon";
506 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
507 local $ENV{HOME} = $home;
508 my $xrd = "$home/xdg_run";
509 mkdir($xrd, 0700) or BAIL_OUT "mkdir: $!";
510 local $ENV{XDG_RUNTIME_DIR} = $xrd;
512 lei_ok(qw(daemon-pid), \"daemon-pid after $t");
513 chomp($daemon_pid = $lei_out);
515 ok(kill(0, $daemon_pid), "daemon running after $t");
516 lei_ok(qw(daemon-kill), \"daemon-kill after $t");
518 fail("daemon not running after $t");
520 }; # SKIP for lei_daemon
521 unless ($test_opt->{daemon_only}) {
522 $ENV{TEST_LEI_DAEMON_ONLY} and
523 skip 'TEST_LEI_DAEMON_ONLY set', 1;
524 require_ok 'PublicInbox::LEI';
525 my $home = "$tmpdir/lei-oneshot";
526 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
527 local $ENV{HOME} = $home;
528 # force sun_path[108] overflow:
529 my $xrd = "$home/1shot-test".('.sun_path' x 108);
530 local $err_skip = qr!\Q$xrd!; # for lei() filtering
531 local $ENV{XDG_RUNTIME_DIR} = $xrd;
536 kill(0, $daemon_pid) or last;
539 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
541 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
544 # returns the pathname to a ~/.public-inbox/config in scalar context,
545 # ($test_home, $pi_config_pathname) in list context
546 sub setup_public_inboxes () {
547 my $test_home = "t/home2";
548 my $pi_config = "$test_home/.public-inbox/config";
549 my $stamp = "$test_home/setup-stamp";
550 my @ret = ($test_home, $pi_config);
551 return @ret if -f $stamp;
553 require PublicInbox::Lock;
554 my $lk = bless { lock_path => "$test_home/setup.lock" },
556 my $end = $lk->lock_for_scope;
557 return @ret if -f $stamp;
559 local $ENV{PI_CONFIG} = $pi_config;
561 run_script([qw(-init), "-V$V", "t$V",
562 '--newsgroup', "t.v$V",
563 "$test_home/t$V", "http://example.com/t$V",
564 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
566 require PublicInbox::Config;
567 require PublicInbox::InboxWritable;
568 my $cfg = PublicInbox::Config->new;
570 $cfg->each_inbox(sub {
572 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
573 my $V = $ibx->version;
574 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
576 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
577 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
582 run_script(['-index', $ibx->{inboxdir}]) or
586 $seen or BAIL_OUT 'no imports';
587 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
591 sub create_inbox ($$;@) {
595 require PublicInbox::Lock;
596 require PublicInbox::InboxWritable;
597 my ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
598 my $dir = "t/data-gen/$base.$ident";
600 mkdir $dir; # may race
601 -d $dir or BAIL_OUT "$dir could not be created: $!";
603 my $lk = bless { lock_path => "$dir/creat.lock" }, 'PublicInbox::Lock';
604 $opt{inboxdir} = File::Spec->rel2abs($dir);
605 $opt{name} //= $ident;
607 my $no_gc = delete $opt{-no_gc};
608 my $tmpdir = delete $opt{tmpdir};
609 my $addr = $opt{address} // [];
610 $opt{-primary_address} //= $addr->[0] // "$ident\@example.com";
611 my $parallel = delete($opt{importer_parallel}) // 0;
612 my $creat_opt = { nproc => delete($opt{nproc}) // 1 };
613 my $ibx = PublicInbox::InboxWritable->new({ %opt }, $creat_opt);
614 my $scope = $lk->lock_for_scope;
615 if (!-f "$dir/creat.stamp") {
616 my $im = $ibx->importer($parallel);
620 my @to_gc = $ibx->version == 1 ? ($ibx->{inboxdir}) :
621 glob("$ibx->{inboxdir}/git/*.git");
622 for my $dir (@to_gc) {
623 xsys_e([ qw(git gc -q) ], { GIT_DIR => $dir });
626 open my $s, '>', "$dir/creat.stamp" or
627 BAIL_OUT "error creating $dir/creat.stamp: $!";
631 xsys([qw(/bin/cp -Rp), $dir, $tmpdir]) == 0 or
632 BAIL_OUT "cp $dir $tmpdir";
633 $opt{inboxdir} = $tmpdir;
634 $ibx = PublicInbox::InboxWritable->new(\%opt);
639 package PublicInboxTestProcess;
642 # prevent new threads from inheriting these objects
646 my ($klass, $pid, $tail_pid) = @_;
647 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
651 my ($self, $sig) = @_;
652 CORE::kill($sig // 'TERM', $self->{pid});
656 my ($self, $sig) = @_;
657 my $pid = delete $self->{pid} or return;
658 CORE::kill($sig, $pid) if defined $sig;
659 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
660 $ret == $pid or die "waitpid($pid) != $ret";
665 return if $self->{owner} != $$;
666 if (my $tail_pid = delete $self->{tail_pid}) {
667 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
668 CORE::kill('TERM', $tail_pid);
673 package PublicInbox::TestCommon::InboxWakeup;
675 sub on_inbox_unlock { ${$_[0]}->($_[1]) }