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 eml_load);
16 open(my $fh, '<', $path) or die "open $path: $!";
17 require PublicInbox::Eml;
18 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
24 unless (defined $base) {
25 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
27 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
28 ($tmpdir->dirname, $tmpdir);
32 IO::Socket::INET->new(
33 LocalAddr => '127.0.0.1',
36 Type => Socket::SOCK_STREAM(),
43 my ($dest, %opt) = @_;
44 my $s = IO::Socket::INET->new(
46 Type => Socket::SOCK_STREAM(),
47 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
54 sub require_git ($;$) {
55 my ($req, $maybe) = @_;
56 my ($req_maj, $req_min) = split(/\./, $req);
57 my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
59 my $req_int = ($req_maj << 24) | ($req_min << 16);
60 my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
61 if ($cur_int < $req_int) {
63 Test::More::plan(skip_all =>
64 "git $req+ required, have $cur_maj.$cur_min");
71 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
74 if ($mod eq 'Search::Xapian') {
75 if (eval { require PublicInbox::Search } &&
76 PublicInbox::Search::load_xapian()) {
79 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
80 if (eval { require PublicInbox::SearchIdx } &&
81 PublicInbox::SearchIdx::load_xapian_writable()){
87 push @need, $mod if $@;
90 my $m = join(', ', @need)." missing for $0";
91 Test::More::skip($m, $maybe) if $maybe;
92 Test::More::plan(skip_all => $m)
97 return $key if ($key eq 'git' || index($key, '/') >= 0);
98 # n.b. we may have scripts which don't start with "public-inbox" in
100 $key =~ s/\A([-\.])/public-inbox$1/;
104 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
105 [ *STDERR{IO}, '>&' ]);
107 sub _prepare_redirects ($) {
110 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
111 my $fh = $fhref->[$fd] or next;
112 my ($oldfh, $mode) = @{$io_mode[$fd]};
113 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
114 $orig_io->[$fd] = $orig;
115 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
120 sub _undo_redirects ($) {
122 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
123 my $fh = $orig_io->[$fd] or next;
124 my ($oldfh, $mode) = @{$io_mode[$fd]};
125 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
129 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
130 # three ways to spawn our own short-lived Perl scripts for testing:
132 # 0 - (fork|vfork) + execve, the most realistic but slowest
133 # 1 - (not currently implemented)
134 # 2 - preloading and running in current process (slightly faster than 1)
136 # 2 is not compatible with scripts which use "exit" (which we'll try to
137 # avoid in the future).
139 our $run_script_exit_code;
140 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
141 sub run_script_exit (;$) {
142 $run_script_exit_code = $_[0] // 0;
149 $cached_scripts{$key} //= do {
150 my $f = key2script($key);
151 open my $fh, '<', $f or die "open $f: $!";
152 my $str = do { local $/; <$fh> };
153 my $pkg = (split(m!/!, $f))[-1];
154 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
157 $pkg = "PublicInbox::TestScript::$pkg";
163 *exit = *PublicInbox::TestCommon::run_script_exit;
165 # the below "line" directive is a magic comment, see perlsyn(1) manpage
177 my ($sub, $key, $argv) = @_;
178 local @ARGV = @$argv;
179 $run_script_exit_code = undef;
180 my $exit_code = eval { $sub->(@$argv) };
181 if ($@ eq RUN_SCRIPT_EXIT) {
183 $exit_code = $run_script_exit_code;
184 $? = ($exit_code << 8);
185 } elsif (defined($exit_code)) {
186 $? = ($exit_code << 8);
187 } elsif ($@) { # mimic die() behavior when uncaught
188 warn "E: eval-ed $key: $@\n";
189 $? = ($! << 8) if $!;
190 $? = (255 << 8) if $? == 0;
192 die "BUG: eval-ed $key: no exit code or \$@\n";
196 sub run_script ($;$$) {
197 my ($cmd, $env, $opt) = @_;
198 my ($key, @argv) = @$cmd;
199 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
200 my $sub = $run_mode == 0 ? undef : key2sub($key);
204 my $redir = $opt->{$fd};
205 my $ref = ref($redir);
206 if ($ref eq 'SCALAR') {
207 open my $fh, '+>', undef or die "open: $!";
209 $spawn_opt->{$fd} = $fh;
212 print $fh $$redir or die "print: $!";
213 seek($fh, 0, SEEK_SET) or die "seek: $!";
214 } elsif ($ref eq 'GLOB') {
215 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
217 die "unable to deal with $ref $redir";
220 if ($run_mode == 0) {
221 # spawn an independent new process, like real-world use cases:
222 require PublicInbox::Spawn;
223 my $cmd = [ key2script($key), @argv ];
224 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
226 my $r = waitpid($pid, 0);
227 defined($r) or die "waitpid: $!";
228 $r == $pid or die "waitpid: expected $pid, got $r";
230 } else { # localize and run everything in the same process:
231 # note: "local *STDIN = *STDIN;" and so forth did not work in
232 # old versions of perl
233 local %ENV = $env ? (%ENV, %$env) : %ENV;
235 local $0 = join(' ', @$cmd);
236 my $orig_io = _prepare_redirects($fhref);
237 _run_sub($sub, $key, \@argv);
238 _undo_redirects($orig_io);
241 # slurp the redirects back into user-supplied strings
243 my $fh = $fhref->[$fd] or next;
244 seek($fh, 0, SEEK_SET) or die "seek: $!";
245 my $redir = $opt->{$fd};
252 sub wait_for_tail () { sleep(2) }
254 # like system() built-in, but uses spawn() for env/rdr + vfork
256 my ($cmd, $env, $rdr) = @_;
264 run_script($cmd, $env, { %$rdr, run_mode => 0 });
268 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
270 my ($cmd, $env, $rdr) = @_;
272 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
273 wantarray ? split(/^/m, $out) : $out;
277 my ($cmd, $env, $opt) = @_;
278 my ($key, @argv) = @$cmd;
279 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
280 my $sub = $run_mode == 0 ? undef : key2sub($key);
282 if (my $tail_cmd = $ENV{TAIL}) {
285 next unless /\A--std(?:err|out)=(.+)\z/;
289 defined($tail_pid = fork) or die "fork: $!\n";
290 if ($tail_pid == 0) {
291 # make sure files exist, first
292 open my $fh, '>>', $_ for @paths;
293 open(STDOUT, '>&STDERR') or die "1>&2: $!";
294 exec(split(' ', $tail_cmd), @paths);
295 die "$tail_cmd failed: $!";
300 defined(my $pid = fork) or die "fork: $!\n";
302 # pretend to be systemd (cf. sd_listen_fds(3))
303 # 3 == SD_LISTEN_FDS_START
305 for ($fd = 0; 1; $fd++) {
307 last if $fd >= 3 && !defined($s);
309 my $fl = fcntl($s, F_GETFD, 0);
310 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
311 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
313 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
314 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
316 %ENV = (%ENV, %$env) if $env;
319 $ENV{LISTEN_PID} = $$;
320 $ENV{LISTEN_FDS} = $fds;
322 $0 = join(' ', @$cmd);
324 _run_sub($sub, $key, \@argv);
325 POSIX::_exit($? >> 8);
327 exec(key2script($key), @argv);
328 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
331 PublicInboxTestProcess->new($pid, $tail_pid);
334 package PublicInboxTestProcess;
337 # prevent new threads from inheriting these objects
341 my ($klass, $pid, $tail_pid) = @_;
342 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
346 my ($self, $sig) = @_;
347 CORE::kill($sig // 'TERM', $self->{pid});
351 my ($self, $sig) = @_;
352 my $pid = delete $self->{pid} or return;
353 CORE::kill($sig, $pid) if defined $sig;
354 my $ret = waitpid($pid, 0);
355 defined($ret) or die "waitpid($pid): $!";
356 $ret == $pid or die "waitpid($pid) != $ret";
361 return if $self->{owner} != $$;
362 if (my $tail = delete $self->{tail_pid}) {
363 PublicInbox::TestCommon::wait_for_tail();
364 CORE::kill('TERM', $tail);