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);
17 open(my $fh, '<', $path) or die "open $path: $!";
18 require PublicInbox::Eml;
19 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
25 unless (defined $base) {
26 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
28 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
29 ($tmpdir->dirname, $tmpdir);
33 IO::Socket::INET->new(
34 LocalAddr => '127.0.0.1',
37 Type => Socket::SOCK_STREAM(),
40 ) or Test::More::BAIL_OUT("failed to create TCP server: $!");
44 my ($dest, %opt) = @_;
45 my $addr = $dest->sockhost . ':' . $dest->sockport;
46 my $s = IO::Socket::INET->new(
48 Type => Socket::SOCK_STREAM(),
51 ) or Test::More::BAIL_OUT("failed to connect to $addr: $!");
56 sub require_git ($;$) {
57 my ($req, $maybe) = @_;
58 my ($req_maj, $req_min) = split(/\./, $req);
59 my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
61 my $req_int = ($req_maj << 24) | ($req_min << 16);
62 my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
63 if ($cur_int < $req_int) {
65 Test::More::plan(skip_all =>
66 "git $req+ required, have $cur_maj.$cur_min");
73 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
75 while (my $mod = shift(@mods)) {
76 if ($mod eq 'Search::Xapian') {
77 if (eval { require PublicInbox::Search } &&
78 PublicInbox::Search::load_xapian()) {
81 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
82 if (eval { require PublicInbox::SearchIdx } &&
83 PublicInbox::SearchIdx::load_xapian_writable()){
86 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
88 for my $m (split(/\Q||\E/, $mod)) {
98 push @need, $mod if $@;
101 my $m = join(', ', @need)." missing for $0";
102 Test::More::skip($m, $maybe) if $maybe;
103 Test::More::plan(skip_all => $m)
108 return $key if ($key eq 'git' || index($key, '/') >= 0);
109 # n.b. we may have scripts which don't start with "public-inbox" in
111 $key =~ s/\A([-\.])/public-inbox$1/;
115 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
116 [ *STDERR{IO}, '>&' ]);
118 sub _prepare_redirects ($) {
121 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
122 my $fh = $fhref->[$fd] or next;
123 my ($oldfh, $mode) = @{$io_mode[$fd]};
124 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
125 $orig_io->[$fd] = $orig;
126 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
131 sub _undo_redirects ($) {
133 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
134 my $fh = $orig_io->[$fd] or next;
135 my ($oldfh, $mode) = @{$io_mode[$fd]};
136 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
140 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
141 # three ways to spawn our own short-lived Perl scripts for testing:
143 # 0 - (fork|vfork) + execve, the most realistic but slowest
144 # 1 - (not currently implemented)
145 # 2 - preloading and running in current process (slightly faster than 1)
147 # 2 is not compatible with scripts which use "exit" (which we'll try to
148 # avoid in the future).
150 our $run_script_exit_code;
151 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
152 sub run_script_exit (;$) {
153 $run_script_exit_code = $_[0] // 0;
160 $cached_scripts{$key} //= do {
161 my $f = key2script($key);
162 open my $fh, '<', $f or die "open $f: $!";
163 my $str = do { local $/; <$fh> };
164 my $pkg = (split(m!/!, $f))[-1];
165 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
168 $pkg = "PublicInbox::TestScript::$pkg";
174 *exit = *PublicInbox::TestCommon::run_script_exit;
176 # the below "line" directive is a magic comment, see perlsyn(1) manpage
188 my ($sub, $key, $argv) = @_;
189 local @ARGV = @$argv;
190 $run_script_exit_code = undef;
191 my $exit_code = eval { $sub->(@$argv) };
192 if ($@ eq RUN_SCRIPT_EXIT) {
194 $exit_code = $run_script_exit_code;
195 $? = ($exit_code << 8);
196 } elsif (defined($exit_code)) {
197 $? = ($exit_code << 8);
198 } elsif ($@) { # mimic die() behavior when uncaught
199 warn "E: eval-ed $key: $@\n";
200 $? = ($! << 8) if $!;
201 $? = (255 << 8) if $? == 0;
203 die "BUG: eval-ed $key: no exit code or \$@\n";
207 sub run_script ($;$$) {
208 my ($cmd, $env, $opt) = @_;
209 my ($key, @argv) = @$cmd;
210 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
211 my $sub = $run_mode == 0 ? undef : key2sub($key);
215 my $redir = $opt->{$fd};
216 my $ref = ref($redir);
217 if ($ref eq 'SCALAR') {
218 open my $fh, '+>', undef or die "open: $!";
220 $spawn_opt->{$fd} = $fh;
223 print $fh $$redir or die "print: $!";
224 seek($fh, 0, SEEK_SET) or die "seek: $!";
225 } elsif ($ref eq 'GLOB') {
226 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
228 die "unable to deal with $ref $redir";
231 if ($run_mode == 0) {
232 # spawn an independent new process, like real-world use cases:
233 require PublicInbox::Spawn;
234 my $cmd = [ key2script($key), @argv ];
235 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
237 my $r = waitpid($pid, 0);
238 defined($r) or die "waitpid: $!";
239 $r == $pid or die "waitpid: expected $pid, got $r";
241 } else { # localize and run everything in the same process:
242 # note: "local *STDIN = *STDIN;" and so forth did not work in
243 # old versions of perl
244 local %ENV = $env ? (%ENV, %$env) : %ENV;
246 local $0 = join(' ', @$cmd);
247 my $orig_io = _prepare_redirects($fhref);
248 _run_sub($sub, $key, \@argv);
249 _undo_redirects($orig_io);
252 # slurp the redirects back into user-supplied strings
254 my $fh = $fhref->[$fd] or next;
255 seek($fh, 0, SEEK_SET) or die "seek: $!";
256 my $redir = $opt->{$fd};
264 my $tick = shift // 0.1;
265 select undef, undef, undef, $tick;
269 sub wait_for_tail ($;$) {
270 my ($tail_pid, $stop) = @_;
272 if ($^O eq 'linux') { # GNU tail may use inotify
273 state $tail_has_inotify;
274 return tick if $stop && $tail_has_inotify;
275 my $end = time + $wait;
279 readlink($_) =~ /\binotify\b/
280 } glob("/proc/$tail_pid/fd/*");
281 } while (!@ino && time <= $end and tick);
283 $tail_has_inotify = 1;
284 $ino[0] =~ s!/fd/!/fdinfo/!;
287 if (open my $fh, '<', $ino[0]) {
289 @info = grep(/^inotify wd:/, <$fh>);
291 } while (scalar(@info) < 2 && time <= $end and tick);
297 # like system() built-in, but uses spawn() for env/rdr + vfork
299 my ($cmd, $env, $rdr) = @_;
307 run_script($cmd, $env, { %$rdr, run_mode => 0 });
311 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
313 my ($cmd, $env, $rdr) = @_;
315 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
316 wantarray ? split(/^/m, $out) : $out;
320 my ($cmd, $env, $opt) = @_;
321 my ($key, @argv) = @$cmd;
322 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
323 my $sub = $run_mode == 0 ? undef : key2sub($key);
325 if (my $tail_cmd = $ENV{TAIL}) {
328 next unless /\A--std(?:err|out)=(.+)\z/;
332 defined($tail_pid = fork) or die "fork: $!\n";
333 if ($tail_pid == 0) {
334 # make sure files exist, first
335 open my $fh, '>>', $_ for @paths;
336 open(STDOUT, '>&STDERR') or die "1>&2: $!";
337 exec(split(' ', $tail_cmd), @paths);
338 die "$tail_cmd failed: $!";
340 wait_for_tail($tail_pid);
343 defined(my $pid = fork) or die "fork: $!\n";
345 # pretend to be systemd (cf. sd_listen_fds(3))
346 # 3 == SD_LISTEN_FDS_START
348 for ($fd = 0; 1; $fd++) {
350 last if $fd >= 3 && !defined($s);
352 my $fl = fcntl($s, F_GETFD, 0);
353 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
354 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
356 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
357 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
359 %ENV = (%ENV, %$env) if $env;
362 $ENV{LISTEN_PID} = $$;
363 $ENV{LISTEN_FDS} = $fds;
365 $0 = join(' ', @$cmd);
367 _run_sub($sub, $key, \@argv);
368 POSIX::_exit($? >> 8);
370 exec(key2script($key), @argv);
371 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
374 PublicInboxTestProcess->new($pid, $tail_pid);
377 package PublicInboxTestProcess;
380 # prevent new threads from inheriting these objects
384 my ($klass, $pid, $tail_pid) = @_;
385 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
389 my ($self, $sig) = @_;
390 CORE::kill($sig // 'TERM', $self->{pid});
394 my ($self, $sig) = @_;
395 my $pid = delete $self->{pid} or return;
396 CORE::kill($sig, $pid) if defined $sig;
397 my $ret = waitpid($pid, 0);
398 defined($ret) or die "waitpid($pid): $!";
399 $ret == $pid or die "waitpid($pid) != $ret";
404 return if $self->{owner} != $$;
405 if (my $tail_pid = delete $self->{tail_pid}) {
406 PublicInbox::TestCommon::wait_for_tail($tail_pid, 1);
407 CORE::kill('TERM', $tail_pid);