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 use PublicInbox::MIME; # temporary
12 our @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
13 run_script start_script key2sub xsys xqx mime_load eml_load);
17 open(my $fh, '<', $path) or die "open $path: $!";
18 # test should've called: require_mods('Email::MIME')
19 require PublicInbox::MIME;
20 PublicInbox::MIME->new(\(do { local $/; <$fh> }));
25 open(my $fh, '<', $path) or die "open $path: $!";
27 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
33 unless (defined $base) {
34 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
36 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
37 ($tmpdir->dirname, $tmpdir);
41 IO::Socket::INET->new(
42 LocalAddr => '127.0.0.1',
45 Type => Socket::SOCK_STREAM(),
52 my ($dest, %opt) = @_;
53 my $s = IO::Socket::INET->new(
55 Type => Socket::SOCK_STREAM(),
56 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
63 sub require_git ($;$) {
64 my ($req, $maybe) = @_;
65 my ($req_maj, $req_min) = split(/\./, $req);
66 my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
68 my $req_int = ($req_maj << 24) | ($req_min << 16);
69 my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
70 if ($cur_int < $req_int) {
72 Test::More::plan(skip_all =>
73 "git $req+ required, have $cur_maj.$cur_min");
80 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
83 if ($mod eq 'Search::Xapian') {
84 if (eval { require PublicInbox::Search } &&
85 PublicInbox::Search::load_xapian()) {
88 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
89 if (eval { require PublicInbox::SearchIdx } &&
90 PublicInbox::SearchIdx::load_xapian_writable()){
96 push @need, $mod if $@;
99 my $m = join(', ', @need)." missing for $0";
100 Test::More::skip($m, $maybe) if $maybe;
101 Test::More::plan(skip_all => $m)
106 return $key if ($key eq 'git' || index($key, '/') >= 0);
107 # n.b. we may have scripts which don't start with "public-inbox" in
109 $key =~ s/\A([-\.])/public-inbox$1/;
113 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
114 [ *STDERR{IO}, '>&' ]);
116 sub _prepare_redirects ($) {
119 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
120 my $fh = $fhref->[$fd] or next;
121 my ($oldfh, $mode) = @{$io_mode[$fd]};
122 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
123 $orig_io->[$fd] = $orig;
124 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
129 sub _undo_redirects ($) {
131 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
132 my $fh = $orig_io->[$fd] or next;
133 my ($oldfh, $mode) = @{$io_mode[$fd]};
134 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
138 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
139 # three ways to spawn our own short-lived Perl scripts for testing:
141 # 0 - (fork|vfork) + execve, the most realistic but slowest
142 # 1 - (not currently implemented)
143 # 2 - preloading and running in current process (slightly faster than 1)
145 # 2 is not compatible with scripts which use "exit" (which we'll try to
146 # avoid in the future).
148 our $run_script_exit_code;
149 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
150 sub run_script_exit (;$) {
151 $run_script_exit_code = $_[0] // 0;
158 $cached_scripts{$key} //= do {
159 my $f = key2script($key);
160 open my $fh, '<', $f or die "open $f: $!";
161 my $str = do { local $/; <$fh> };
162 my $pkg = (split(m!/!, $f))[-1];
163 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
166 $pkg = "PublicInbox::TestScript::$pkg";
172 *exit = *PublicInbox::TestCommon::run_script_exit;
174 # the below "line" directive is a magic comment, see perlsyn(1) manpage
186 my ($sub, $key, $argv) = @_;
187 local @ARGV = @$argv;
188 $run_script_exit_code = undef;
189 my $exit_code = eval { $sub->(@$argv) };
190 if ($@ eq RUN_SCRIPT_EXIT) {
192 $exit_code = $run_script_exit_code;
193 $? = ($exit_code << 8);
194 } elsif (defined($exit_code)) {
195 $? = ($exit_code << 8);
196 } elsif ($@) { # mimic die() behavior when uncaught
197 warn "E: eval-ed $key: $@\n";
198 $? = ($! << 8) if $!;
199 $? = (255 << 8) if $? == 0;
201 die "BUG: eval-ed $key: no exit code or \$@\n";
205 sub run_script ($;$$) {
206 my ($cmd, $env, $opt) = @_;
207 my ($key, @argv) = @$cmd;
208 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
209 my $sub = $run_mode == 0 ? undef : key2sub($key);
213 my $redir = $opt->{$fd};
214 my $ref = ref($redir);
215 if ($ref eq 'SCALAR') {
216 open my $fh, '+>', undef or die "open: $!";
218 $spawn_opt->{$fd} = $fh;
221 print $fh $$redir or die "print: $!";
222 seek($fh, 0, SEEK_SET) or die "seek: $!";
223 } elsif ($ref eq 'GLOB') {
224 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
226 die "unable to deal with $ref $redir";
229 if ($run_mode == 0) {
230 # spawn an independent new process, like real-world use cases:
231 require PublicInbox::Spawn;
232 my $cmd = [ key2script($key), @argv ];
233 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
235 my $r = waitpid($pid, 0);
236 defined($r) or die "waitpid: $!";
237 $r == $pid or die "waitpid: expected $pid, got $r";
239 } else { # localize and run everything in the same process:
240 # note: "local *STDIN = *STDIN;" and so forth did not work in
241 # old versions of perl
242 local %ENV = $env ? (%ENV, %$env) : %ENV;
244 local $0 = join(' ', @$cmd);
245 my $orig_io = _prepare_redirects($fhref);
246 _run_sub($sub, $key, \@argv);
247 _undo_redirects($orig_io);
250 # slurp the redirects back into user-supplied strings
252 my $fh = $fhref->[$fd] or next;
253 seek($fh, 0, SEEK_SET) or die "seek: $!";
254 my $redir = $opt->{$fd};
261 sub wait_for_tail () { sleep(2) }
263 # like system() built-in, but uses spawn() for env/rdr + vfork
265 my ($cmd, $env, $rdr) = @_;
273 run_script($cmd, $env, { %$rdr, run_mode => 0 });
277 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
279 my ($cmd, $env, $rdr) = @_;
281 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
282 wantarray ? split(/^/m, $out) : $out;
286 my ($cmd, $env, $opt) = @_;
287 my ($key, @argv) = @$cmd;
288 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
289 my $sub = $run_mode == 0 ? undef : key2sub($key);
291 if (my $tail_cmd = $ENV{TAIL}) {
294 next unless /\A--std(?:err|out)=(.+)\z/;
298 defined($tail_pid = fork) or die "fork: $!\n";
299 if ($tail_pid == 0) {
300 # make sure files exist, first
301 open my $fh, '>>', $_ for @paths;
302 open(STDOUT, '>&STDERR') or die "1>&2: $!";
303 exec(split(' ', $tail_cmd), @paths);
304 die "$tail_cmd failed: $!";
309 defined(my $pid = fork) or die "fork: $!\n";
311 # pretend to be systemd (cf. sd_listen_fds(3))
312 # 3 == SD_LISTEN_FDS_START
314 for ($fd = 0; 1; $fd++) {
316 last if $fd >= 3 && !defined($s);
318 my $fl = fcntl($s, F_GETFD, 0);
319 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
320 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
322 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
323 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
325 %ENV = (%ENV, %$env) if $env;
328 $ENV{LISTEN_PID} = $$;
329 $ENV{LISTEN_FDS} = $fds;
331 $0 = join(' ', @$cmd);
333 _run_sub($sub, $key, \@argv);
334 POSIX::_exit($? >> 8);
336 exec(key2script($key), @argv);
337 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
340 PublicInboxTestProcess->new($pid, $tail_pid);
343 package PublicInboxTestProcess;
346 # prevent new threads from inheriting these objects
350 my ($klass, $pid, $tail_pid) = @_;
351 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
355 my ($self, $sig) = @_;
356 CORE::kill($sig // 'TERM', $self->{pid});
360 my ($self, $sig) = @_;
361 my $pid = delete $self->{pid} or return;
362 CORE::kill($sig, $pid) if defined $sig;
363 my $ret = waitpid($pid, 0);
364 defined($ret) or die "waitpid($pid): $!";
365 $ret == $pid or die "waitpid($pid) != $ret";
370 return if $self->{owner} != $$;
371 if (my $tail = delete $self->{tail_pid}) {
372 PublicInbox::TestCommon::wait_for_tail();
373 CORE::kill('TERM', $tail);