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);
12 our @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
13 run_script start_script key2sub xsys xsys_e xqx eml_load tick
17 *BAIL_OUT = \&Test::More::BAIL_OUT;
18 *plan = \&Test::More::plan;
19 *skip = \&Test::More::skip;
24 open(my $fh, '<', $path) or die "open $path: $!";
25 require PublicInbox::Eml;
26 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
32 unless (defined $base) {
33 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
35 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
36 ($tmpdir->dirname, $tmpdir);
40 IO::Socket::INET->new(
41 LocalAddr => '127.0.0.1',
44 Type => Socket::SOCK_STREAM(),
47 ) or BAIL_OUT "failed to create TCP server: $!";
51 my ($dest, %opt) = @_;
52 my $addr = $dest->sockhost . ':' . $dest->sockport;
53 my $s = IO::Socket::INET->new(
55 Type => Socket::SOCK_STREAM(),
58 ) or BAIL_OUT "failed to connect to $addr: $!";
63 sub require_git ($;$) {
64 my ($req, $maybe) = @_;
65 my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
66 my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
67 =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
69 my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
70 my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
71 if ($cur_int < $req_int) {
74 "git $req+ required, have $cur_maj.$cur_min.$cur_sub";
81 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
83 while (my $mod = shift(@mods)) {
85 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||'.
88 if ($mod eq 'Search::Xapian') {
89 if (eval { require PublicInbox::Search } &&
90 PublicInbox::Search::load_xapian()) {
93 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
94 if (eval { require PublicInbox::SearchIdx } &&
95 PublicInbox::SearchIdx::load_xapian_writable()){
98 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
100 for my $m (split(/\Q||\E/, $mod)) {
112 } elsif ($mod eq 'IO::Socket::SSL' &&
113 # old versions of IO::Socket::SSL aren't supported
114 # by libnet, at least:
115 # https://rt.cpan.org/Ticket/Display.html?id=100529
116 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
121 my $m = join(', ', @need)." missing for $0";
122 skip($m, $maybe) if $maybe;
128 return $key if ($key eq 'git' || index($key, '/') >= 0);
129 # n.b. we may have scripts which don't start with "public-inbox" in
131 $key =~ s/\A([-\.])/public-inbox$1/;
135 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
136 [ *STDERR{IO}, '>&' ]);
138 sub _prepare_redirects ($) {
141 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
142 my $fh = $fhref->[$fd] or next;
143 my ($oldfh, $mode) = @{$io_mode[$fd]};
144 open my $orig, $mode, $oldfh or die "$oldfh $mode stash: $!";
145 $orig_io->[$fd] = $orig;
146 open $oldfh, $mode, $fh or die "$oldfh $mode redirect: $!";
151 sub _undo_redirects ($) {
153 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
154 my $fh = $orig_io->[$fd] or next;
155 my ($oldfh, $mode) = @{$io_mode[$fd]};
156 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
160 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
161 # three ways to spawn our own short-lived Perl scripts for testing:
163 # 0 - (fork|vfork) + execve, the most realistic but slowest
164 # 1 - (not currently implemented)
165 # 2 - preloading and running in current process (slightly faster than 1)
167 # 2 is not compatible with scripts which use "exit" (which we'll try to
168 # avoid in the future).
170 our $run_script_exit_code;
171 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
172 sub run_script_exit {
173 $run_script_exit_code = $_[0] // 0;
180 $cached_scripts{$key} //= do {
181 my $f = key2script($key);
182 open my $fh, '<', $f or die "open $f: $!";
183 my $str = do { local $/; <$fh> };
184 my $pkg = (split(m!/!, $f))[-1];
185 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
188 $pkg = "PublicInbox::TestScript::$pkg";
194 *exit = \\&PublicInbox::TestCommon::run_script_exit;
196 # the below "line" directive is a magic comment, see perlsyn(1) manpage
208 my ($sub, $key, $argv) = @_;
209 local @ARGV = @$argv;
210 $run_script_exit_code = undef;
211 my $exit_code = eval { $sub->(@$argv) };
212 if ($@ eq RUN_SCRIPT_EXIT) {
214 $exit_code = $run_script_exit_code;
215 $? = ($exit_code << 8);
216 } elsif (defined($exit_code)) {
217 $? = ($exit_code << 8);
218 } elsif ($@) { # mimic die() behavior when uncaught
219 warn "E: eval-ed $key: $@\n";
220 $? = ($! << 8) if $!;
221 $? = (255 << 8) if $? == 0;
223 die "BUG: eval-ed $key: no exit code or \$@\n";
227 sub run_script ($;$$) {
228 my ($cmd, $env, $opt) = @_;
229 my ($key, @argv) = @$cmd;
230 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
231 my $sub = $run_mode == 0 ? undef : key2sub($key);
235 my $redir = $opt->{$fd};
236 my $ref = ref($redir);
237 if ($ref eq 'SCALAR') {
238 open my $fh, '+>', undef or die "open: $!";
240 $spawn_opt->{$fd} = $fh;
243 print $fh $$redir or die "print: $!";
244 seek($fh, 0, SEEK_SET) or die "seek: $!";
245 } elsif ($ref eq 'GLOB') {
246 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
248 die "unable to deal with $ref $redir";
251 if ($run_mode == 0) {
252 # spawn an independent new process, like real-world use cases:
253 require PublicInbox::Spawn;
254 my $cmd = [ key2script($key), @argv ];
255 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
257 my $r = waitpid($pid, 0);
258 defined($r) or die "waitpid: $!";
259 $r == $pid or die "waitpid: expected $pid, got $r";
261 } else { # localize and run everything in the same process:
262 # note: "local *STDIN = *STDIN;" and so forth did not work in
263 # old versions of perl
264 local %ENV = $env ? (%ENV, %$env) : %ENV;
266 local $0 = join(' ', @$cmd);
267 my $orig_io = _prepare_redirects($fhref);
268 _run_sub($sub, $key, \@argv);
269 _undo_redirects($orig_io);
273 # slurp the redirects back into user-supplied strings
275 my $fh = $fhref->[$fd] or next;
276 seek($fh, 0, SEEK_SET) or die "seek: $!";
277 my $redir = $opt->{$fd};
285 my $tick = shift // 0.1;
286 select undef, undef, undef, $tick;
290 sub wait_for_tail ($;$) {
291 my ($tail_pid, $want) = @_;
293 if ($^O eq 'linux') { # GNU tail may use inotify
294 state $tail_has_inotify;
295 return tick if $want < 0 && $tail_has_inotify;
296 my $end = time + $wait;
300 readlink($_) =~ /\binotify\b/
301 } glob("/proc/$tail_pid/fd/*");
302 } while (!@ino && time <= $end and tick);
304 $tail_has_inotify = 1;
305 $ino[0] =~ s!/fd/!/fdinfo/!;
308 if (open my $fh, '<', $ino[0]) {
310 @info = grep(/^inotify wd:/, <$fh>);
312 } while (scalar(@info) < $want && time <= $end and tick);
318 # like system() built-in, but uses spawn() for env/rdr + vfork
320 my ($cmd, $env, $rdr) = @_;
328 run_script($cmd, $env, { %$rdr, run_mode => 0 });
332 sub xsys_e { # like "/bin/sh -e"
334 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
337 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
339 my ($cmd, $env, $rdr) = @_;
341 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
342 wantarray ? split(/^/m, $out) : $out;
346 my ($cmd, $env, $opt) = @_;
347 my ($key, @argv) = @$cmd;
348 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
349 my $sub = $run_mode == 0 ? undef : key2sub($key);
351 if (my $tail_cmd = $ENV{TAIL}) {
354 next unless /\A--std(?:err|out)=(.+)\z/;
359 my $f = $opt->{$_} or next;
362 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
364 my $f = readlink "/proc/$$/fd/$fd";
365 push @paths, $f if -e $f;
370 defined($tail_pid = fork) or die "fork: $!\n";
371 if ($tail_pid == 0) {
372 # make sure files exist, first
373 open my $fh, '>>', $_ for @paths;
374 open(STDOUT, '>&STDERR') or die "1>&2: $!";
375 exec(split(' ', $tail_cmd), @paths);
376 die "$tail_cmd failed: $!";
378 wait_for_tail($tail_pid, scalar @paths);
381 defined(my $pid = fork) or die "fork: $!\n";
383 eval { PublicInbox::DS->Reset };
384 # pretend to be systemd (cf. sd_listen_fds(3))
385 # 3 == SD_LISTEN_FDS_START
387 for ($fd = 0; 1; $fd++) {
389 last if $fd >= 3 && !defined($s);
391 my $fl = fcntl($s, F_GETFD, 0);
392 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
393 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
395 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
396 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
398 %ENV = (%ENV, %$env) if $env;
401 $ENV{LISTEN_PID} = $$;
402 $ENV{LISTEN_FDS} = $fds;
404 $0 = join(' ', @$cmd);
406 eval { PublicInbox::DS->Reset };
407 _run_sub($sub, $key, \@argv);
408 POSIX::_exit($? >> 8);
410 exec(key2script($key), @argv);
411 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
414 PublicInboxTestProcess->new($pid, $tail_pid);
417 sub have_xapian_compact () {
418 require PublicInbox::Spawn;
419 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
420 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
423 package PublicInboxTestProcess;
426 # prevent new threads from inheriting these objects
430 my ($klass, $pid, $tail_pid) = @_;
431 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
435 my ($self, $sig) = @_;
436 CORE::kill($sig // 'TERM', $self->{pid});
440 my ($self, $sig) = @_;
441 my $pid = delete $self->{pid} or return;
442 CORE::kill($sig, $pid) if defined $sig;
443 my $ret = waitpid($pid, 0);
444 defined($ret) or die "waitpid($pid): $!";
445 $ret == $pid or die "waitpid($pid) != $ret";
450 return if $self->{owner} != $$;
451 if (my $tail_pid = delete $self->{tail_pid}) {
452 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
453 CORE::kill('TERM', $tail_pid);
458 package PublicInbox::TestCommon::InboxWakeup;
460 sub on_inbox_unlock { ${$_[0]}->($_[1]) }