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);
8 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
11 our @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
12 run_script start_script key2sub xsys xqx mime_load);
16 open(my $fh, '<', $path) or die "open $path: $!";
17 PublicInbox::MIME->new(\(do { local $/; <$fh> }));
23 unless (defined $base) {
24 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
26 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
27 ($tmpdir->dirname, $tmpdir);
31 IO::Socket::INET->new(
32 LocalAddr => '127.0.0.1',
35 Type => Socket::SOCK_STREAM(),
42 my ($dest, %opt) = @_;
43 my $s = IO::Socket::INET->new(
45 Type => Socket::SOCK_STREAM(),
46 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
53 sub require_git ($;$) {
54 my ($req, $maybe) = @_;
55 my ($req_maj, $req_min) = split(/\./, $req);
56 my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
58 my $req_int = ($req_maj << 24) | ($req_min << 16);
59 my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
60 if ($cur_int < $req_int) {
62 Test::More::plan(skip_all =>
63 "git $req+ required, have $cur_maj.$cur_min");
70 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
73 if ($mod eq 'Search::Xapian') {
74 if (eval { require PublicInbox::Search } &&
75 PublicInbox::Search::load_xapian()) {
78 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
79 if (eval { require PublicInbox::SearchIdx } &&
80 PublicInbox::SearchIdx::load_xapian_writable()){
86 push @need, $mod if $@;
89 my $m = join(', ', @need)." missing for $0";
90 Test::More::skip($m, $maybe) if $maybe;
91 Test::More::plan(skip_all => $m)
96 return $key if ($key eq 'git' || index($key, '/') >= 0);
97 # n.b. we may have scripts which don't start with "public-inbox" in
99 $key =~ s/\A([-\.])/public-inbox$1/;
103 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
104 [ *STDERR{IO}, '>&' ]);
106 sub _prepare_redirects ($) {
109 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
110 my $fh = $fhref->[$fd] or next;
111 my ($oldfh, $mode) = @{$io_mode[$fd]};
112 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
113 $orig_io->[$fd] = $orig;
114 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
119 sub _undo_redirects ($) {
121 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
122 my $fh = $orig_io->[$fd] or next;
123 my ($oldfh, $mode) = @{$io_mode[$fd]};
124 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
128 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
129 # three ways to spawn our own short-lived Perl scripts for testing:
131 # 0 - (fork|vfork) + execve, the most realistic but slowest
132 # 1 - (not currently implemented)
133 # 2 - preloading and running in current process (slightly faster than 1)
135 # 2 is not compatible with scripts which use "exit" (which we'll try to
136 # avoid in the future).
138 our $run_script_exit_code;
139 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
140 sub run_script_exit (;$) {
141 $run_script_exit_code = $_[0] // 0;
148 $cached_scripts{$key} //= do {
149 my $f = key2script($key);
150 open my $fh, '<', $f or die "open $f: $!";
151 my $str = do { local $/; <$fh> };
152 my $pkg = (split(m!/!, $f))[-1];
153 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
156 $pkg = "PublicInbox::TestScript::$pkg";
162 *exit = *PublicInbox::TestCommon::run_script_exit;
164 # the below "line" directive is a magic comment, see perlsyn(1) manpage
176 my ($sub, $key, $argv) = @_;
177 local @ARGV = @$argv;
178 $run_script_exit_code = undef;
179 my $exit_code = eval { $sub->(@$argv) };
180 if ($@ eq RUN_SCRIPT_EXIT) {
182 $exit_code = $run_script_exit_code;
183 $? = ($exit_code << 8);
184 } elsif (defined($exit_code)) {
185 $? = ($exit_code << 8);
186 } elsif ($@) { # mimic die() behavior when uncaught
187 warn "E: eval-ed $key: $@\n";
188 $? = ($! << 8) if $!;
189 $? = (255 << 8) if $? == 0;
191 die "BUG: eval-ed $key: no exit code or \$@\n";
195 sub run_script ($;$$) {
196 my ($cmd, $env, $opt) = @_;
197 my ($key, @argv) = @$cmd;
198 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
199 my $sub = $run_mode == 0 ? undef : key2sub($key);
203 my $redir = $opt->{$fd};
204 my $ref = ref($redir);
205 if ($ref eq 'SCALAR') {
206 open my $fh, '+>', undef or die "open: $!";
208 $spawn_opt->{$fd} = $fh;
211 print $fh $$redir or die "print: $!";
212 seek($fh, 0, SEEK_SET) or die "seek: $!";
213 } elsif ($ref eq 'GLOB') {
214 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
216 die "unable to deal with $ref $redir";
219 if ($run_mode == 0) {
220 # spawn an independent new process, like real-world use cases:
221 require PublicInbox::Spawn;
222 my $cmd = [ key2script($key), @argv ];
223 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
225 my $r = waitpid($pid, 0);
226 defined($r) or die "waitpid: $!";
227 $r == $pid or die "waitpid: expected $pid, got $r";
229 } else { # localize and run everything in the same process:
230 # note: "local *STDIN = *STDIN;" and so forth did not work in
231 # old versions of perl
232 local %ENV = $env ? (%ENV, %$env) : %ENV;
234 local $0 = join(' ', @$cmd);
235 my $orig_io = _prepare_redirects($fhref);
236 _run_sub($sub, $key, \@argv);
237 _undo_redirects($orig_io);
240 # slurp the redirects back into user-supplied strings
242 my $fh = $fhref->[$fd] or next;
243 seek($fh, 0, SEEK_SET) or die "seek: $!";
244 my $redir = $opt->{$fd};
251 sub wait_for_tail () { sleep(2) }
253 # like system() built-in, but uses spawn() for env/rdr + vfork
255 my ($cmd, $env, $rdr) = @_;
263 run_script($cmd, $env, { %$rdr, run_mode => 0 });
267 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
269 my ($cmd, $env, $rdr) = @_;
271 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
272 wantarray ? split(/^/m, $out) : $out;
276 my ($cmd, $env, $opt) = @_;
277 my ($key, @argv) = @$cmd;
278 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
279 my $sub = $run_mode == 0 ? undef : key2sub($key);
281 if (my $tail_cmd = $ENV{TAIL}) {
284 next unless /\A--std(?:err|out)=(.+)\z/;
288 defined($tail_pid = fork) or die "fork: $!\n";
289 if ($tail_pid == 0) {
290 # make sure files exist, first
291 open my $fh, '>>', $_ for @paths;
292 open(STDOUT, '>&STDERR') or die "1>&2: $!";
293 exec(split(' ', $tail_cmd), @paths);
294 die "$tail_cmd failed: $!";
299 defined(my $pid = fork) or die "fork: $!\n";
301 # pretend to be systemd (cf. sd_listen_fds(3))
302 # 3 == SD_LISTEN_FDS_START
304 for ($fd = 0; 1; $fd++) {
306 last if $fd >= 3 && !defined($s);
308 my $fl = fcntl($s, F_GETFD, 0);
309 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
310 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
312 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
313 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
315 %ENV = (%ENV, %$env) if $env;
318 $ENV{LISTEN_PID} = $$;
319 $ENV{LISTEN_FDS} = $fds;
321 $0 = join(' ', @$cmd);
323 _run_sub($sub, $key, \@argv);
324 POSIX::_exit($? >> 8);
326 exec(key2script($key), @argv);
327 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
330 PublicInboxTestProcess->new($pid, $tail_pid);
333 package PublicInboxTestProcess;
336 # prevent new threads from inheriting these objects
340 my ($klass, $pid, $tail_pid) = @_;
341 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
345 my ($self, $sig) = @_;
346 CORE::kill($sig // 'TERM', $self->{pid});
350 my ($self, $sig) = @_;
351 my $pid = delete $self->{pid} or return;
352 CORE::kill($sig, $pid) if defined $sig;
353 my $ret = waitpid($pid, 0);
354 defined($ret) or die "waitpid($pid): $!";
355 $ret == $pid or die "waitpid($pid) != $ret";
360 return if $self->{owner} != $$;
361 if (my $tail = delete $self->{tail_pid}) {
362 PublicInbox::TestCommon::wait_for_tail();
363 CORE::kill('TERM', $tail);