1 # Copyright (C) 2015-2019 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);
17 unless (defined $base) {
18 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
20 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
21 ($tmpdir->dirname, $tmpdir);
25 IO::Socket::INET->new(
26 LocalAddr => '127.0.0.1',
29 Type => Socket::SOCK_STREAM(),
36 my ($dest, %opt) = @_;
37 my $s = IO::Socket::INET->new(
39 Type => Socket::SOCK_STREAM(),
40 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
47 sub require_git ($;$) {
48 my ($req, $maybe) = @_;
49 my ($req_maj, $req_min) = split(/\./, $req);
50 my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
52 my $req_int = ($req_maj << 24) | ($req_min << 16);
53 my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
54 if ($cur_int < $req_int) {
56 Test::More::plan(skip_all =>
57 "git $req+ required, have $cur_maj.$cur_min");
64 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
67 if ($mod eq 'Search::Xapian') {
68 require PublicInbox::Search;
69 PublicInbox::Search::load_xapian() and next;
70 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
71 require PublicInbox::SearchIdx;
72 PublicInbox::SearchIdx::load_xapian_writable() and next;
76 push @need, $mod if $@;
79 my $m = join(', ', @need)." missing for $0";
80 Test::More::skip($m, $maybe) if $maybe;
81 Test::More::plan(skip_all => $m)
86 return $key if (index($key, '/') >= 0);
87 # n.b. we may have scripts which don't start with "public-inbox" in
89 $key =~ s/\A([-\.])/public-inbox$1/;
93 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
94 [ *STDERR{IO}, '>&' ]);
96 sub _prepare_redirects ($) {
99 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
100 my $fh = $fhref->[$fd] or next;
101 my ($oldfh, $mode) = @{$io_mode[$fd]};
102 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
103 $orig_io->[$fd] = $orig;
104 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
109 sub _undo_redirects ($) {
111 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
112 my $fh = $orig_io->[$fd] or next;
113 my ($oldfh, $mode) = @{$io_mode[$fd]};
114 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
118 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows chosing between
119 # three ways to spawn our own short-lived Perl scripts for testing:
121 # 0 - (fork|vfork) + execve, the most realistic but slowest
122 # 1 - preloading and running in a forked subprocess (fast)
123 # 2 - preloading and running in current process (slightly faster than 1)
125 # 2 is not compatible with scripts which use "exit" (which we'll try to
126 # avoid in the future).
128 our $run_script_exit_code;
129 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
130 sub run_script_exit (;$) {
131 $run_script_exit_code = $_[0] // 0;
138 $cached_scripts{$key} //= do {
139 my $f = key2script($key);
140 open my $fh, '<', $f or die "open $f: $!";
141 my $str = do { local $/; <$fh> };
142 my $pkg = (split(m!/!, $f))[-1];
143 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
146 $pkg = "PublicInbox::TestScript::$pkg";
152 *exit = *PublicInbox::TestCommon::run_script_exit;
154 # the below "line" directive is a magic comment, see perlsyn(1) manpage
166 my ($sub, $key, $argv) = @_;
167 local @ARGV = @$argv;
168 $run_script_exit_code = undef;
169 my $exit_code = eval { $sub->(@$argv) };
170 if ($@ eq RUN_SCRIPT_EXIT) {
172 $exit_code = $run_script_exit_code;
173 $? = ($exit_code << 8);
174 } elsif (defined($exit_code)) {
175 $? = ($exit_code << 8);
176 } elsif ($@) { # mimic die() behavior when uncaught
177 warn "E: eval-ed $key: $@\n";
178 $? = ($! << 8) if $!;
179 $? = (255 << 8) if $? == 0;
181 die "BUG: eval-ed $key: no exit code or \$@\n";
185 sub run_script ($;$$) {
186 my ($cmd, $env, $opt) = @_;
187 my ($key, @argv) = @$cmd;
188 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
189 my $sub = $run_mode == 0 ? undef : key2sub($key);
193 my $redir = $opt->{$fd};
194 next unless ref($redir);
195 open my $fh, '+>', undef or die "open: $!";
197 $spawn_opt->{$fd} = $fh;
200 print $fh $$redir or die "print: $!";
201 seek($fh, 0, SEEK_SET) or die "seek: $!";
203 if ($run_mode == 0) {
204 # spawn an independent new process, like real-world use cases:
205 require PublicInbox::Spawn;
206 my $cmd = [ key2script($key), @argv ];
207 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
208 defined($pid) or die "spawn: $!";
210 my $r = waitpid($pid, 0);
211 defined($r) or die "waitpid: $!";
212 $r == $pid or die "waitpid: expected $pid, got $r";
214 } else { # localize and run everything in the same process:
215 # note: "local *STDIN = *STDIN;" and so forth did not work in
216 # old versions of perl
217 local %ENV = $env ? (%ENV, %$env) : %ENV;
219 local $0 = join(' ', @$cmd);
220 my $orig_io = _prepare_redirects($fhref);
221 _run_sub($sub, $key, \@argv);
222 _undo_redirects($orig_io);
225 # slurp the redirects back into user-supplied strings
227 my $fh = $fhref->[$fd] or next;
228 seek($fh, 0, SEEK_SET) or die "seek: $!";
229 my $redir = $opt->{$fd};
236 sub wait_for_tail () { sleep(2) }
239 my ($cmd, $env, $opt) = @_;
240 my ($key, @argv) = @$cmd;
241 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
242 my $sub = $run_mode == 0 ? undef : key2sub($key);
244 if (my $tail_cmd = $ENV{TAIL}) {
247 next unless /\A--std(?:err|out)=(.+)\z/;
251 defined($tail_pid = fork) or die "fork: $!\n";
252 if ($tail_pid == 0) {
253 # make sure files exist, first
254 open my $fh, '>>', $_ for @paths;
255 open(STDOUT, '>&STDERR') or die "1>&2: $!";
256 exec(split(' ', $tail_cmd), @paths);
257 die "$tail_cmd failed: $!";
262 defined(my $pid = fork) or die "fork: $!\n";
264 # pretend to be systemd (cf. sd_listen_fds(3))
265 # 3 == SD_LISTEN_FDS_START
267 for ($fd = 0; 1; $fd++) {
269 last if $fd >= 3 && !defined($s);
271 my $fl = fcntl($s, F_GETFD, 0);
272 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
273 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
275 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
276 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
278 %ENV = (%ENV, %$env) if $env;
281 $ENV{LISTEN_PID} = $$;
282 $ENV{LISTEN_FDS} = $fds;
284 $0 = join(' ', @$cmd);
286 _run_sub($sub, $key, \@argv);
287 POSIX::_exit($? >> 8);
289 exec(key2script($key), @argv);
290 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
293 PublicInboxTestProcess->new($pid, $tail_pid);
296 package PublicInboxTestProcess;
299 # prevent new threads from inheriting these objects
303 my ($klass, $pid, $tail_pid) = @_;
304 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
308 my ($self, $sig) = @_;
309 CORE::kill($sig // 'TERM', $self->{pid});
314 my $pid = delete $self->{pid} or return;
315 my $ret = waitpid($pid, 0);
316 defined($ret) or die "waitpid($pid): $!";
317 $ret == $pid or die "waitpid($pid) != $ret";
322 return if $self->{owner} != $$;
323 if (my $tail = delete $self->{tail_pid}) {
324 PublicInbox::TestCommon::wait_for_tail();
325 CORE::kill('TERM', $tail);
327 my $pid = delete $self->{pid} or return;
328 CORE::kill('TERM', $pid);