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 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);
43 IO::Socket::INET->new(
44 LocalAddr => '127.0.0.1',
47 Type => Socket::SOCK_STREAM(),
50 ) or BAIL_OUT "failed to create TCP server: $!";
54 my ($dest, %opt) = @_;
55 my $addr = $dest->sockhost . ':' . $dest->sockport;
56 my $s = IO::Socket::INET->new(
58 Type => Socket::SOCK_STREAM(),
61 ) or BAIL_OUT "failed to connect to $addr: $!";
66 sub require_git ($;$) {
67 my ($req, $maybe) = @_;
68 my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
69 my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
70 =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
72 my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
73 my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
74 if ($cur_int < $req_int) {
77 "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
84 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
86 while (my $mod = shift(@mods)) {
88 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||'.
91 if ($mod eq 'Search::Xapian') {
92 if (eval { require PublicInbox::Search } &&
93 PublicInbox::Search::load_xapian()) {
96 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
97 if (eval { require PublicInbox::SearchIdx } &&
98 PublicInbox::SearchIdx::load_xapian_writable()){
101 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
103 for my $m (split(/\Q||\E/, $mod)) {
115 } elsif ($mod eq 'IO::Socket::SSL' &&
116 # old versions of IO::Socket::SSL aren't supported
117 # by libnet, at least:
118 # https://rt.cpan.org/Ticket/Display.html?id=100529
119 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
124 my $m = join(', ', @need)." missing for $0";
125 skip($m, $maybe) if $maybe;
131 return $key if ($key eq 'git' || index($key, '/') >= 0);
132 # n.b. we may have scripts which don't start with "public-inbox" in
134 $key =~ s/\A([-\.])/public-inbox$1/;
138 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
139 [ *STDERR{IO}, '>&' ]);
141 sub _prepare_redirects ($) {
144 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
145 my $fh = $fhref->[$fd] or next;
146 my ($oldfh, $mode) = @{$io_mode[$fd]};
147 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
148 $orig_io->[$fd] = $orig;
149 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
154 sub _undo_redirects ($) {
156 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
157 my $fh = $orig_io->[$fd] or next;
158 my ($oldfh, $mode) = @{$io_mode[$fd]};
159 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
163 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
164 # three ways to spawn our own short-lived Perl scripts for testing:
166 # 0 - (fork|vfork) + execve, the most realistic but slowest
167 # 1 - (not currently implemented)
168 # 2 - preloading and running in current process (slightly faster than 1)
170 # 2 is not compatible with scripts which use "exit" (which we'll try to
171 # avoid in the future).
173 our $run_script_exit_code;
174 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
175 sub run_script_exit {
176 $run_script_exit_code = $_[0] // 0;
183 $cached_scripts{$key} //= do {
184 my $f = key2script($key);
185 open my $fh, '<', $f or die "open $f: $!";
186 my $str = do { local $/; <$fh> };
187 my $pkg = (split(m!/!, $f))[-1];
188 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
191 $pkg = "PublicInbox::TestScript::$pkg";
197 *exit = \\&PublicInbox::TestCommon::run_script_exit;
199 # the below "line" directive is a magic comment, see perlsyn(1) manpage
211 my ($sub, $key, $argv) = @_;
212 local @ARGV = @$argv;
213 $run_script_exit_code = undef;
214 my $exit_code = eval { $sub->(@$argv) };
215 if ($@ eq RUN_SCRIPT_EXIT) {
217 $exit_code = $run_script_exit_code;
218 $? = ($exit_code << 8);
219 } elsif (defined($exit_code)) {
220 $? = ($exit_code << 8);
221 } elsif ($@) { # mimic die() behavior when uncaught
222 warn "E: eval-ed $key: $@\n";
223 $? = ($! << 8) if $!;
224 $? = (255 << 8) if $? == 0;
226 die "BUG: eval-ed $key: no exit code or \$@\n";
230 sub run_script ($;$$) {
231 my ($cmd, $env, $opt) = @_;
232 my ($key, @argv) = @$cmd;
233 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
234 my $sub = $run_mode == 0 ? undef : key2sub($key);
238 my $redir = $opt->{$fd};
239 my $ref = ref($redir);
240 if ($ref eq 'SCALAR') {
241 open my $fh, '+>', undef or die "open: $!";
243 $spawn_opt->{$fd} = $fh;
246 print $fh $$redir or die "print: $!";
247 seek($fh, 0, SEEK_SET) or die "seek: $!";
248 } elsif ($ref eq 'GLOB') {
249 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
251 die "unable to deal with $ref $redir";
254 if ($run_mode == 0) {
255 # spawn an independent new process, like real-world use cases:
256 require PublicInbox::Spawn;
257 my $cmd = [ key2script($key), @argv ];
258 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
260 my $r = waitpid($pid, 0) // die "waitpid: $!";
261 $r == $pid or die "waitpid: expected $pid, got $r";
263 } else { # localize and run everything in the same process:
264 # note: "local *STDIN = *STDIN;" and so forth did not work in
265 # old versions of perl
266 local %ENV = $env ? (%ENV, %$env) : %ENV;
268 local $0 = join(' ', @$cmd);
269 my $orig_io = _prepare_redirects($fhref);
270 _run_sub($sub, $key, \@argv);
271 _undo_redirects($orig_io);
275 # slurp the redirects back into user-supplied strings
277 my $fh = $fhref->[$fd] or next;
278 seek($fh, 0, SEEK_SET) or die "seek: $!";
279 my $redir = $opt->{$fd};
287 my $tick = shift // 0.1;
288 select undef, undef, undef, $tick;
292 sub wait_for_tail ($;$) {
293 my ($tail_pid, $want) = @_;
295 if ($^O eq 'linux') { # GNU tail may use inotify
296 state $tail_has_inotify;
297 return tick if $want < 0 && $tail_has_inotify;
298 my $end = time + $wait;
302 readlink($_) =~ /\binotify\b/
303 } glob("/proc/$tail_pid/fd/*");
304 } while (!@ino && time <= $end and tick);
306 $tail_has_inotify = 1;
307 $ino[0] =~ s!/fd/!/fdinfo/!;
310 if (open my $fh, '<', $ino[0]) {
312 @info = grep(/^inotify wd:/, <$fh>);
314 } while (scalar(@info) < $want && time <= $end and tick);
320 # like system() built-in, but uses spawn() for env/rdr + vfork
322 my ($cmd, $env, $rdr) = @_;
330 run_script($cmd, $env, { %$rdr, run_mode => 0 });
334 sub xsys_e { # like "/bin/sh -e"
336 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
339 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
341 my ($cmd, $env, $rdr) = @_;
343 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
344 wantarray ? split(/^/m, $out) : $out;
348 my ($cmd, $env, $opt) = @_;
349 my ($key, @argv) = @$cmd;
350 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
351 my $sub = $run_mode == 0 ? undef : key2sub($key);
353 if (my $tail_cmd = $ENV{TAIL}) {
356 next unless /\A--std(?:err|out)=(.+)\z/;
361 my $f = $opt->{$_} or next;
364 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
366 my $f = readlink "/proc/$$/fd/$fd";
367 push @paths, $f if -e $f;
372 $tail_pid = fork // die "fork: $!";
373 if ($tail_pid == 0) {
374 # make sure files exist, first
375 open my $fh, '>>', $_ for @paths;
376 open(STDOUT, '>&STDERR') or die "1>&2: $!";
377 exec(split(' ', $tail_cmd), @paths);
378 die "$tail_cmd failed: $!";
380 wait_for_tail($tail_pid, scalar @paths);
383 my $pid = fork // die "fork: $!\n";
385 eval { PublicInbox::DS->Reset };
386 # pretend to be systemd (cf. sd_listen_fds(3))
387 # 3 == SD_LISTEN_FDS_START
389 for ($fd = 0; 1; $fd++) {
391 last if $fd >= 3 && !defined($s);
393 my $fl = fcntl($s, F_GETFD, 0);
394 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
395 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
397 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
398 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
400 %ENV = (%ENV, %$env) if $env;
403 $ENV{LISTEN_PID} = $$;
404 $ENV{LISTEN_FDS} = $fds;
406 $0 = join(' ', @$cmd);
408 eval { PublicInbox::DS->Reset };
409 _run_sub($sub, $key, \@argv);
410 POSIX::_exit($? >> 8);
412 exec(key2script($key), @argv);
413 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
416 PublicInboxTestProcess->new($pid, $tail_pid);
419 sub have_xapian_compact () {
420 require PublicInbox::Spawn;
421 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
422 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
425 our ($err_skip, $lei_opt, $lei_out, $lei_err);
427 my ($cmd, $env, $xopt) = @_;
428 $lei_out = $lei_err = '';
430 ($env, $xopt) = grep { (!defined) || ref } @_;
431 $cmd = [ grep { defined && !ref } @_ ];
433 my $res = run_script(['lei', @$cmd], $env, $xopt // $lei_opt);
435 $lei_err = join('', grep(!/$err_skip/, split(/^/m, $lei_err)));
440 state $x = ref(PublicInbox::Config->json)->new->utf8->canonical;
446 my $test_opt = shift // {};
447 require_git(2.6) or skip('git 2.6+ required for lei test', 2);
448 require_mods(qw(json DBD::SQLite Search::Xapian), 2);
449 require PublicInbox::Config;
450 delete local $ENV{XDG_DATA_HOME};
451 delete local $ENV{XDG_CONFIG_HOME};
452 local $ENV{GIT_COMMITTER_EMAIL} = 'lei@example.com';
453 local $ENV{GIT_COMMITTER_NAME} = 'lei user';
454 my (undef, $fn, $lineno) = caller(0);
455 my $t = "$fn:$lineno";
456 require PublicInbox::Spawn;
457 state $lei_daemon = PublicInbox::Spawn->can('send_cmd4') ||
458 eval { require Socket::MsgHdr; 1 };
459 $lei_opt = { 1 => \$lei_out, 2 => \$lei_err };
461 my ($tmpdir, $for_destroy) = tmpdir();
463 skip <<'EOM', 1 unless $lei_daemon;
464 Socket::MsgHdr missing or Inline::C is unconfigured/missing
466 my $home = "$tmpdir/lei-daemon";
467 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
468 local $ENV{HOME} = $home;
469 my $xrd = "$home/xdg_run";
470 mkdir($xrd, 0700) or BAIL_OUT "mkdir: $!";
471 local $ENV{XDG_RUNTIME_DIR} = $xrd;
473 ok($lei->(qw(daemon-pid)), "daemon-pid after $t");
474 chomp($daemon_pid = $lei_out);
476 ok(kill(0, $daemon_pid), "daemon running after $t");
477 ok($lei->(qw(daemon-kill)), "daemon-kill after $t");
479 fail("daemon not running after $t");
481 }; # SKIP for lei_daemon
482 unless ($test_opt->{daemon_only}) {
483 require_ok 'PublicInbox::LEI';
484 my $home = "$tmpdir/lei-oneshot";
485 mkdir($home, 0700) or BAIL_OUT "mkdir: $!";
486 local $ENV{HOME} = $home;
487 # force sun_path[108] overflow:
488 my $xrd = "$home/1shot-test".('.sun_path' x 108);
489 local $err_skip = qr!\Q$xrd!; # for $lei->() filtering
490 local $ENV{XDG_RUNTIME_DIR} = $xrd;
495 kill(0, $daemon_pid) or last;
498 ok(!kill(0, $daemon_pid), "$t daemon stopped after oneshot");
500 }; # SKIP if missing git 2.6+ || Xapian || SQLite || json
503 # returns the pathname to a ~/.public-inbox/config in scalar context,
504 # ($test_home, $pi_config_pathname) in list context
505 sub setup_public_inboxes () {
506 my $test_home = "t/home1";
507 my $pi_config = "$test_home/.public-inbox/config";
508 my $stamp = "$test_home/setup-stamp";
509 my @ret = ($test_home, $pi_config);
510 return @ret if -f $stamp;
512 require PublicInbox::Lock;
513 my $lk = bless { lock_path => "$test_home/setup.lock" },
515 my $end = $lk->lock_for_scope;
516 return @ret if -f $stamp;
518 require PublicInbox::InboxWritable;
519 local $ENV{PI_CONFIG} = $pi_config;
521 run_script([qw(-init), "-V$V", "t$V",
522 '--newsgroup', "t.$V",
523 "$test_home/t$V", "http://example.com/t$V",
524 "t$V\@example.com" ]) or BAIL_OUT "init v$V";
526 my $cfg = PublicInbox::Config->new;
528 $cfg->each_inbox(sub {
530 my $im = PublicInbox::InboxWritable->new($ibx)->importer(0);
531 my $V = $ibx->version;
532 my @eml = (glob('t/*.eml'), 't/data/0001.patch');
534 next if $_ eq 't/psgi_v2-old.eml'; # dup mid
535 $im->add(eml_load($_)) or BAIL_OUT "v$V add $_";
540 run_script(['-index', $ibx->{inboxdir}]) or
544 $seen or BAIL_OUT 'no imports';
545 open my $fh, '>', $stamp or BAIL_OUT "open $stamp: $!";
549 package PublicInboxTestProcess;
552 # prevent new threads from inheriting these objects
556 my ($klass, $pid, $tail_pid) = @_;
557 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
561 my ($self, $sig) = @_;
562 CORE::kill($sig // 'TERM', $self->{pid});
566 my ($self, $sig) = @_;
567 my $pid = delete $self->{pid} or return;
568 CORE::kill($sig, $pid) if defined $sig;
569 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
570 $ret == $pid or die "waitpid($pid) != $ret";
575 return if $self->{owner} != $$;
576 if (my $tail_pid = delete $self->{tail_pid}) {
577 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
578 CORE::kill('TERM', $tail_pid);
583 package PublicInbox::TestCommon::InboxWakeup;
585 sub on_inbox_unlock { ${$_[0]}->($_[1]) }