1 # Copyright (C) 2015-2020 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 xqx eml_load tick
18 open(my $fh, '<', $path) or die "open $path: $!";
19 require PublicInbox::Eml;
20 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
26 unless (defined $base) {
27 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
29 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
30 ($tmpdir->dirname, $tmpdir);
34 IO::Socket::INET->new(
35 LocalAddr => '127.0.0.1',
38 Type => Socket::SOCK_STREAM(),
41 ) or Test::More::BAIL_OUT("failed to create TCP server: $!");
45 my ($dest, %opt) = @_;
46 my $addr = $dest->sockhost . ':' . $dest->sockport;
47 my $s = IO::Socket::INET->new(
49 Type => Socket::SOCK_STREAM(),
52 ) or Test::More::BAIL_OUT("failed to connect to $addr: $!");
57 sub require_git ($;$) {
58 my ($req, $maybe) = @_;
59 my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
60 my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
61 =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
63 my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
64 my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
65 if ($cur_int < $req_int) {
67 Test::More::plan(skip_all =>
68 "git $req+ required, have $cur_maj.$cur_min.$cur_sub");
75 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
77 while (my $mod = shift(@mods)) {
79 $mod = 'Cpanel::JSON::XS||JSON::MaybeXS||'.
82 if ($mod eq 'Search::Xapian') {
83 if (eval { require PublicInbox::Search } &&
84 PublicInbox::Search::load_xapian()) {
87 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
88 if (eval { require PublicInbox::SearchIdx } &&
89 PublicInbox::SearchIdx::load_xapian_writable()){
92 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
94 for my $m (split(/\Q||\E/, $mod)) {
106 } elsif ($mod eq 'IO::Socket::SSL' &&
107 # old versions of IO::Socket::SSL aren't supported
108 # by libnet, at least:
109 # https://rt.cpan.org/Ticket/Display.html?id=100529
110 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
115 my $m = join(', ', @need)." missing for $0";
116 Test::More::skip($m, $maybe) if $maybe;
117 Test::More::plan(skip_all => $m)
122 return $key if ($key eq 'git' || index($key, '/') >= 0);
123 # n.b. we may have scripts which don't start with "public-inbox" in
125 $key =~ s/\A([-\.])/public-inbox$1/;
129 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
130 [ *STDERR{IO}, '>&' ]);
132 sub _prepare_redirects ($) {
135 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
136 my $fh = $fhref->[$fd] or next;
137 my ($oldfh, $mode) = @{$io_mode[$fd]};
138 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
139 $orig_io->[$fd] = $orig;
140 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
145 sub _undo_redirects ($) {
147 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
148 my $fh = $orig_io->[$fd] or next;
149 my ($oldfh, $mode) = @{$io_mode[$fd]};
150 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
154 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
155 # three ways to spawn our own short-lived Perl scripts for testing:
157 # 0 - (fork|vfork) + execve, the most realistic but slowest
158 # 1 - (not currently implemented)
159 # 2 - preloading and running in current process (slightly faster than 1)
161 # 2 is not compatible with scripts which use "exit" (which we'll try to
162 # avoid in the future).
164 our $run_script_exit_code;
165 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
166 sub run_script_exit {
167 $run_script_exit_code = $_[0] // 0;
174 $cached_scripts{$key} //= do {
175 my $f = key2script($key);
176 open my $fh, '<', $f or die "open $f: $!";
177 my $str = do { local $/; <$fh> };
178 my $pkg = (split(m!/!, $f))[-1];
179 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
182 $pkg = "PublicInbox::TestScript::$pkg";
188 *exit = \\&PublicInbox::TestCommon::run_script_exit;
190 # the below "line" directive is a magic comment, see perlsyn(1) manpage
202 my ($sub, $key, $argv) = @_;
203 local @ARGV = @$argv;
204 $run_script_exit_code = undef;
205 my $exit_code = eval { $sub->(@$argv) };
206 if ($@ eq RUN_SCRIPT_EXIT) {
208 $exit_code = $run_script_exit_code;
209 $? = ($exit_code << 8);
210 } elsif (defined($exit_code)) {
211 $? = ($exit_code << 8);
212 } elsif ($@) { # mimic die() behavior when uncaught
213 warn "E: eval-ed $key: $@\n";
214 $? = ($! << 8) if $!;
215 $? = (255 << 8) if $? == 0;
217 die "BUG: eval-ed $key: no exit code or \$@\n";
221 sub run_script ($;$$) {
222 my ($cmd, $env, $opt) = @_;
223 my ($key, @argv) = @$cmd;
224 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
225 my $sub = $run_mode == 0 ? undef : key2sub($key);
229 my $redir = $opt->{$fd};
230 my $ref = ref($redir);
231 if ($ref eq 'SCALAR') {
232 open my $fh, '+>', undef or die "open: $!";
234 $spawn_opt->{$fd} = $fh;
237 print $fh $$redir or die "print: $!";
238 seek($fh, 0, SEEK_SET) or die "seek: $!";
239 } elsif ($ref eq 'GLOB') {
240 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
242 die "unable to deal with $ref $redir";
245 if ($run_mode == 0) {
246 # spawn an independent new process, like real-world use cases:
247 require PublicInbox::Spawn;
248 my $cmd = [ key2script($key), @argv ];
249 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
251 my $r = waitpid($pid, 0);
252 defined($r) or die "waitpid: $!";
253 $r == $pid or die "waitpid: expected $pid, got $r";
255 } else { # localize and run everything in the same process:
256 # note: "local *STDIN = *STDIN;" and so forth did not work in
257 # old versions of perl
258 local %ENV = $env ? (%ENV, %$env) : %ENV;
260 local $0 = join(' ', @$cmd);
261 my $orig_io = _prepare_redirects($fhref);
262 _run_sub($sub, $key, \@argv);
263 _undo_redirects($orig_io);
266 # slurp the redirects back into user-supplied strings
268 my $fh = $fhref->[$fd] or next;
269 seek($fh, 0, SEEK_SET) or die "seek: $!";
270 my $redir = $opt->{$fd};
278 my $tick = shift // 0.1;
279 select undef, undef, undef, $tick;
283 sub wait_for_tail ($;$) {
284 my ($tail_pid, $want) = @_;
286 if ($^O eq 'linux') { # GNU tail may use inotify
287 state $tail_has_inotify;
288 return tick if $want < 0 && $tail_has_inotify;
289 my $end = time + $wait;
293 readlink($_) =~ /\binotify\b/
294 } glob("/proc/$tail_pid/fd/*");
295 } while (!@ino && time <= $end and tick);
297 $tail_has_inotify = 1;
298 $ino[0] =~ s!/fd/!/fdinfo/!;
301 if (open my $fh, '<', $ino[0]) {
303 @info = grep(/^inotify wd:/, <$fh>);
305 } while (scalar(@info) < $want && time <= $end and tick);
311 # like system() built-in, but uses spawn() for env/rdr + vfork
313 my ($cmd, $env, $rdr) = @_;
321 run_script($cmd, $env, { %$rdr, run_mode => 0 });
325 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
327 my ($cmd, $env, $rdr) = @_;
329 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
330 wantarray ? split(/^/m, $out) : $out;
334 my ($cmd, $env, $opt) = @_;
335 my ($key, @argv) = @$cmd;
336 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
337 my $sub = $run_mode == 0 ? undef : key2sub($key);
339 if (my $tail_cmd = $ENV{TAIL}) {
342 next unless /\A--std(?:err|out)=(.+)\z/;
347 my $f = $opt->{$_} or next;
350 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
352 my $f = readlink "/proc/$$/fd/$fd";
353 push @paths, $f if -e $f;
358 defined($tail_pid = fork) or die "fork: $!\n";
359 if ($tail_pid == 0) {
360 # make sure files exist, first
361 open my $fh, '>>', $_ for @paths;
362 open(STDOUT, '>&STDERR') or die "1>&2: $!";
363 exec(split(' ', $tail_cmd), @paths);
364 die "$tail_cmd failed: $!";
366 wait_for_tail($tail_pid, scalar @paths);
369 defined(my $pid = fork) or die "fork: $!\n";
371 eval { PublicInbox::DS->Reset };
372 # pretend to be systemd (cf. sd_listen_fds(3))
373 # 3 == SD_LISTEN_FDS_START
375 for ($fd = 0; 1; $fd++) {
377 last if $fd >= 3 && !defined($s);
379 my $fl = fcntl($s, F_GETFD, 0);
380 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
381 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
383 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
384 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
386 %ENV = (%ENV, %$env) if $env;
389 $ENV{LISTEN_PID} = $$;
390 $ENV{LISTEN_FDS} = $fds;
392 $0 = join(' ', @$cmd);
394 eval { PublicInbox::DS->Reset };
395 _run_sub($sub, $key, \@argv);
396 POSIX::_exit($? >> 8);
398 exec(key2script($key), @argv);
399 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
402 PublicInboxTestProcess->new($pid, $tail_pid);
405 sub have_xapian_compact () {
406 require PublicInbox::Spawn;
407 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
408 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
411 package PublicInboxTestProcess;
414 # prevent new threads from inheriting these objects
418 my ($klass, $pid, $tail_pid) = @_;
419 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
423 my ($self, $sig) = @_;
424 CORE::kill($sig // 'TERM', $self->{pid});
428 my ($self, $sig) = @_;
429 my $pid = delete $self->{pid} or return;
430 CORE::kill($sig, $pid) if defined $sig;
431 my $ret = waitpid($pid, 0);
432 defined($ret) or die "waitpid($pid): $!";
433 $ret == $pid or die "waitpid($pid) != $ret";
438 return if $self->{owner} != $$;
439 if (my $tail_pid = delete $self->{tail_pid}) {
440 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
441 CORE::kill('TERM', $tail_pid);
446 package PublicInbox::TestCommon::InboxWakeup;
448 sub on_inbox_unlock { ${$_[0]}->($_[1]) }