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) // die "waitpid: $!";
258 $r == $pid or die "waitpid: expected $pid, got $r";
260 } else { # localize and run everything in the same process:
261 # note: "local *STDIN = *STDIN;" and so forth did not work in
262 # old versions of perl
263 local %ENV = $env ? (%ENV, %$env) : %ENV;
265 local $0 = join(' ', @$cmd);
266 my $orig_io = _prepare_redirects($fhref);
267 _run_sub($sub, $key, \@argv);
268 _undo_redirects($orig_io);
272 # slurp the redirects back into user-supplied strings
274 my $fh = $fhref->[$fd] or next;
275 seek($fh, 0, SEEK_SET) or die "seek: $!";
276 my $redir = $opt->{$fd};
284 my $tick = shift // 0.1;
285 select undef, undef, undef, $tick;
289 sub wait_for_tail ($;$) {
290 my ($tail_pid, $want) = @_;
292 if ($^O eq 'linux') { # GNU tail may use inotify
293 state $tail_has_inotify;
294 return tick if $want < 0 && $tail_has_inotify;
295 my $end = time + $wait;
299 readlink($_) =~ /\binotify\b/
300 } glob("/proc/$tail_pid/fd/*");
301 } while (!@ino && time <= $end and tick);
303 $tail_has_inotify = 1;
304 $ino[0] =~ s!/fd/!/fdinfo/!;
307 if (open my $fh, '<', $ino[0]) {
309 @info = grep(/^inotify wd:/, <$fh>);
311 } while (scalar(@info) < $want && time <= $end and tick);
317 # like system() built-in, but uses spawn() for env/rdr + vfork
319 my ($cmd, $env, $rdr) = @_;
327 run_script($cmd, $env, { %$rdr, run_mode => 0 });
331 sub xsys_e { # like "/bin/sh -e"
333 BAIL_OUT (ref $_[0] ? "@{$_[0]}" : "@_"). " failed \$?=$?"
336 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
338 my ($cmd, $env, $rdr) = @_;
340 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
341 wantarray ? split(/^/m, $out) : $out;
345 my ($cmd, $env, $opt) = @_;
346 my ($key, @argv) = @$cmd;
347 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
348 my $sub = $run_mode == 0 ? undef : key2sub($key);
350 if (my $tail_cmd = $ENV{TAIL}) {
353 next unless /\A--std(?:err|out)=(.+)\z/;
358 my $f = $opt->{$_} or next;
361 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
363 my $f = readlink "/proc/$$/fd/$fd";
364 push @paths, $f if -e $f;
369 $tail_pid = fork // die "fork: $!";
370 if ($tail_pid == 0) {
371 # make sure files exist, first
372 open my $fh, '>>', $_ for @paths;
373 open(STDOUT, '>&STDERR') or die "1>&2: $!";
374 exec(split(' ', $tail_cmd), @paths);
375 die "$tail_cmd failed: $!";
377 wait_for_tail($tail_pid, scalar @paths);
380 my $pid = fork // die "fork: $!\n";
382 eval { PublicInbox::DS->Reset };
383 # pretend to be systemd (cf. sd_listen_fds(3))
384 # 3 == SD_LISTEN_FDS_START
386 for ($fd = 0; 1; $fd++) {
388 last if $fd >= 3 && !defined($s);
390 my $fl = fcntl($s, F_GETFD, 0);
391 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
392 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
394 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
395 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
397 %ENV = (%ENV, %$env) if $env;
400 $ENV{LISTEN_PID} = $$;
401 $ENV{LISTEN_FDS} = $fds;
403 $0 = join(' ', @$cmd);
405 eval { PublicInbox::DS->Reset };
406 _run_sub($sub, $key, \@argv);
407 POSIX::_exit($? >> 8);
409 exec(key2script($key), @argv);
410 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
413 PublicInboxTestProcess->new($pid, $tail_pid);
416 sub have_xapian_compact () {
417 require PublicInbox::Spawn;
418 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
419 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
422 package PublicInboxTestProcess;
425 # prevent new threads from inheriting these objects
429 my ($klass, $pid, $tail_pid) = @_;
430 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
434 my ($self, $sig) = @_;
435 CORE::kill($sig // 'TERM', $self->{pid});
439 my ($self, $sig) = @_;
440 my $pid = delete $self->{pid} or return;
441 CORE::kill($sig, $pid) if defined $sig;
442 my $ret = waitpid($pid, 0) // die "waitpid($pid): $!";
443 $ret == $pid or die "waitpid($pid) != $ret";
448 return if $self->{owner} != $$;
449 if (my $tail_pid = delete $self->{tail_pid}) {
450 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
451 CORE::kill('TERM', $tail_pid);
456 package PublicInbox::TestCommon::InboxWakeup;
458 sub on_inbox_unlock { ${$_[0]}->($_[1]) }