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(),
44 my ($dest, %opt) = @_;
45 my $s = IO::Socket::INET->new(
47 Type => Socket::SOCK_STREAM(),
48 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
55 sub require_git ($;$) {
56 my ($req, $maybe) = @_;
57 my ($req_maj, $req_min) = split(/\./, $req);
58 my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
60 my $req_int = ($req_maj << 24) | ($req_min << 16);
61 my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
62 if ($cur_int < $req_int) {
64 Test::More::plan(skip_all =>
65 "git $req+ required, have $cur_maj.$cur_min");
72 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
75 if ($mod eq 'Search::Xapian') {
76 if (eval { require PublicInbox::Search } &&
77 PublicInbox::Search::load_xapian()) {
80 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
81 if (eval { require PublicInbox::SearchIdx } &&
82 PublicInbox::SearchIdx::load_xapian_writable()){
88 push @need, $mod if $@;
91 my $m = join(', ', @need)." missing for $0";
92 Test::More::skip($m, $maybe) if $maybe;
93 Test::More::plan(skip_all => $m)
98 return $key if ($key eq 'git' || index($key, '/') >= 0);
99 # n.b. we may have scripts which don't start with "public-inbox" in
101 $key =~ s/\A([-\.])/public-inbox$1/;
105 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
106 [ *STDERR{IO}, '>&' ]);
108 sub _prepare_redirects ($) {
111 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
112 my $fh = $fhref->[$fd] or next;
113 my ($oldfh, $mode) = @{$io_mode[$fd]};
114 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
115 $orig_io->[$fd] = $orig;
116 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
121 sub _undo_redirects ($) {
123 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
124 my $fh = $orig_io->[$fd] or next;
125 my ($oldfh, $mode) = @{$io_mode[$fd]};
126 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
130 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
131 # three ways to spawn our own short-lived Perl scripts for testing:
133 # 0 - (fork|vfork) + execve, the most realistic but slowest
134 # 1 - (not currently implemented)
135 # 2 - preloading and running in current process (slightly faster than 1)
137 # 2 is not compatible with scripts which use "exit" (which we'll try to
138 # avoid in the future).
140 our $run_script_exit_code;
141 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
142 sub run_script_exit (;$) {
143 $run_script_exit_code = $_[0] // 0;
150 $cached_scripts{$key} //= do {
151 my $f = key2script($key);
152 open my $fh, '<', $f or die "open $f: $!";
153 my $str = do { local $/; <$fh> };
154 my $pkg = (split(m!/!, $f))[-1];
155 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
158 $pkg = "PublicInbox::TestScript::$pkg";
164 *exit = *PublicInbox::TestCommon::run_script_exit;
166 # the below "line" directive is a magic comment, see perlsyn(1) manpage
178 my ($sub, $key, $argv) = @_;
179 local @ARGV = @$argv;
180 $run_script_exit_code = undef;
181 my $exit_code = eval { $sub->(@$argv) };
182 if ($@ eq RUN_SCRIPT_EXIT) {
184 $exit_code = $run_script_exit_code;
185 $? = ($exit_code << 8);
186 } elsif (defined($exit_code)) {
187 $? = ($exit_code << 8);
188 } elsif ($@) { # mimic die() behavior when uncaught
189 warn "E: eval-ed $key: $@\n";
190 $? = ($! << 8) if $!;
191 $? = (255 << 8) if $? == 0;
193 die "BUG: eval-ed $key: no exit code or \$@\n";
197 sub run_script ($;$$) {
198 my ($cmd, $env, $opt) = @_;
199 my ($key, @argv) = @$cmd;
200 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
201 my $sub = $run_mode == 0 ? undef : key2sub($key);
205 my $redir = $opt->{$fd};
206 my $ref = ref($redir);
207 if ($ref eq 'SCALAR') {
208 open my $fh, '+>', undef or die "open: $!";
210 $spawn_opt->{$fd} = $fh;
213 print $fh $$redir or die "print: $!";
214 seek($fh, 0, SEEK_SET) or die "seek: $!";
215 } elsif ($ref eq 'GLOB') {
216 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
218 die "unable to deal with $ref $redir";
221 if ($run_mode == 0) {
222 # spawn an independent new process, like real-world use cases:
223 require PublicInbox::Spawn;
224 my $cmd = [ key2script($key), @argv ];
225 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
227 my $r = waitpid($pid, 0);
228 defined($r) or die "waitpid: $!";
229 $r == $pid or die "waitpid: expected $pid, got $r";
231 } else { # localize and run everything in the same process:
232 # note: "local *STDIN = *STDIN;" and so forth did not work in
233 # old versions of perl
234 local %ENV = $env ? (%ENV, %$env) : %ENV;
236 local $0 = join(' ', @$cmd);
237 my $orig_io = _prepare_redirects($fhref);
238 _run_sub($sub, $key, \@argv);
239 _undo_redirects($orig_io);
242 # slurp the redirects back into user-supplied strings
244 my $fh = $fhref->[$fd] or next;
245 seek($fh, 0, SEEK_SET) or die "seek: $!";
246 my $redir = $opt->{$fd};
254 my $tick = shift // 0.1;
255 select undef, undef, undef, $tick;
259 sub wait_for_tail ($;$) {
260 my ($tail_pid, $stop) = @_;
262 if ($^O eq 'linux') { # GNU tail may use inotify
263 state $tail_has_inotify;
264 return tick if $stop && $tail_has_inotify;
265 my $end = time + $wait;
269 readlink($_) =~ /\binotify\b/
270 } glob("/proc/$tail_pid/fd/*");
271 } while (!@ino && time <= $end and tick);
273 $tail_has_inotify = 1;
274 $ino[0] =~ s!/fd/!/fdinfo/!;
277 if (open my $fh, '<', $ino[0]) {
279 @info = grep(/^inotify wd:/, <$fh>);
281 } while (scalar(@info) < 2 && time <= $end and tick);
287 # like system() built-in, but uses spawn() for env/rdr + vfork
289 my ($cmd, $env, $rdr) = @_;
297 run_script($cmd, $env, { %$rdr, run_mode => 0 });
301 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
303 my ($cmd, $env, $rdr) = @_;
305 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
306 wantarray ? split(/^/m, $out) : $out;
310 my ($cmd, $env, $opt) = @_;
311 my ($key, @argv) = @$cmd;
312 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
313 my $sub = $run_mode == 0 ? undef : key2sub($key);
315 if (my $tail_cmd = $ENV{TAIL}) {
318 next unless /\A--std(?:err|out)=(.+)\z/;
322 defined($tail_pid = fork) or die "fork: $!\n";
323 if ($tail_pid == 0) {
324 # make sure files exist, first
325 open my $fh, '>>', $_ for @paths;
326 open(STDOUT, '>&STDERR') or die "1>&2: $!";
327 exec(split(' ', $tail_cmd), @paths);
328 die "$tail_cmd failed: $!";
330 wait_for_tail($tail_pid);
333 defined(my $pid = fork) or die "fork: $!\n";
335 # pretend to be systemd (cf. sd_listen_fds(3))
336 # 3 == SD_LISTEN_FDS_START
338 for ($fd = 0; 1; $fd++) {
340 last if $fd >= 3 && !defined($s);
342 my $fl = fcntl($s, F_GETFD, 0);
343 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
344 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
346 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
347 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
349 %ENV = (%ENV, %$env) if $env;
352 $ENV{LISTEN_PID} = $$;
353 $ENV{LISTEN_FDS} = $fds;
355 $0 = join(' ', @$cmd);
357 _run_sub($sub, $key, \@argv);
358 POSIX::_exit($? >> 8);
360 exec(key2script($key), @argv);
361 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
364 PublicInboxTestProcess->new($pid, $tail_pid);
367 package PublicInboxTestProcess;
370 # prevent new threads from inheriting these objects
374 my ($klass, $pid, $tail_pid) = @_;
375 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
379 my ($self, $sig) = @_;
380 CORE::kill($sig // 'TERM', $self->{pid});
384 my ($self, $sig) = @_;
385 my $pid = delete $self->{pid} or return;
386 CORE::kill($sig, $pid) if defined $sig;
387 my $ret = waitpid($pid, 0);
388 defined($ret) or die "waitpid($pid): $!";
389 $ret == $pid or die "waitpid($pid) != $ret";
394 return if $self->{owner} != $$;
395 if (my $tail_pid = delete $self->{tail_pid}) {
396 PublicInbox::TestCommon::wait_for_tail($tail_pid, 1);
397 CORE::kill('TERM', $tail_pid);