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/;
68 push @need, $mod if $@;
71 my $m = join(', ', @need)." missing for $0";
72 Test::More::skip($m, $maybe) if $maybe;
73 Test::More::plan(skip_all => $m)
78 return $key if (index($key, '/') >= 0);
79 # n.b. we may have scripts which don't start with "public-inbox" in
81 $key =~ s/\A([-\.])/public-inbox$1/;
85 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
86 [ *STDERR{IO}, '>&' ]);
88 sub _prepare_redirects ($) {
91 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
92 my $fh = $fhref->[$fd] or next;
93 my ($oldfh, $mode) = @{$io_mode[$fd]};
94 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
95 $orig_io->[$fd] = $orig;
96 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
101 sub _undo_redirects ($) {
103 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
104 my $fh = $orig_io->[$fd] or next;
105 my ($oldfh, $mode) = @{$io_mode[$fd]};
106 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
110 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows chosing between
111 # three ways to spawn our own short-lived Perl scripts for testing:
113 # 0 - (fork|vfork) + execve, the most realistic but slowest
114 # 1 - preloading and running in a forked subprocess (fast)
115 # 2 - preloading and running in current process (slightly faster than 1)
117 # 2 is not compatible with scripts which use "exit" (which we'll try to
118 # avoid in the future).
120 our $run_script_exit_code;
121 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
122 sub run_script_exit (;$) {
123 $run_script_exit_code = $_[0] // 0;
130 $cached_scripts{$key} //= do {
131 my $f = key2script($key);
132 open my $fh, '<', $f or die "open $f: $!";
133 my $str = do { local $/; <$fh> };
134 my $pkg = (split(m!/!, $f))[-1];
135 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
138 $pkg = "PublicInbox::TestScript::$pkg";
144 *exit = *PublicInbox::TestCommon::run_script_exit;
146 # the below "line" directive is a magic comment, see perlsyn(1) manpage
158 my ($sub, $key, $argv) = @_;
159 local @ARGV = @$argv;
160 $run_script_exit_code = undef;
161 my $exit_code = eval { $sub->(@$argv) };
162 if ($@ eq RUN_SCRIPT_EXIT) {
164 $exit_code = $run_script_exit_code;
165 $? = ($exit_code << 8);
166 } elsif (defined($exit_code)) {
167 $? = ($exit_code << 8);
168 } elsif ($@) { # mimic die() behavior when uncaught
169 warn "E: eval-ed $key: $@\n";
170 $? = ($! << 8) if $!;
171 $? = (255 << 8) if $? == 0;
173 die "BUG: eval-ed $key: no exit code or \$@\n";
177 sub run_script ($;$$) {
178 my ($cmd, $env, $opt) = @_;
179 my ($key, @argv) = @$cmd;
180 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
181 my $sub = $run_mode == 0 ? undef : key2sub($key);
185 my $redir = $opt->{$fd};
186 next unless ref($redir);
187 open my $fh, '+>', undef or die "open: $!";
189 $spawn_opt->{$fd} = fileno($fh);
192 print $fh $$redir or die "print: $!";
193 seek($fh, 0, SEEK_SET) or die "seek: $!";
195 if ($run_mode == 0) {
196 # spawn an independent new process, like real-world use cases:
197 require PublicInbox::Spawn;
198 my $cmd = [ key2script($key), @argv ];
199 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
200 defined($pid) or die "spawn: $!";
202 my $r = waitpid($pid, 0);
203 defined($r) or die "waitpid: $!";
204 $r == $pid or die "waitpid: expected $pid, got $r";
206 } else { # localize and run everything in the same process:
207 # note: "local *STDIN = *STDIN;" and so forth did not work in
208 # old versions of perl
209 local %ENV = $env ? (%ENV, %$env) : %ENV;
211 local $0 = join(' ', @$cmd);
212 my $orig_io = _prepare_redirects($fhref);
213 _run_sub($sub, $key, \@argv);
214 _undo_redirects($orig_io);
217 # slurp the redirects back into user-supplied strings
219 my $fh = $fhref->[$fd] or next;
220 seek($fh, 0, SEEK_SET) or die "seek: $!";
221 my $redir = $opt->{$fd};
228 sub wait_for_tail () { sleep(2) }
231 my ($cmd, $env, $opt) = @_;
232 my ($key, @argv) = @$cmd;
233 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
234 my $sub = $run_mode == 0 ? undef : key2sub($key);
236 if (my $tail_cmd = $ENV{TAIL}) {
239 next unless /\A--std(?:err|out)=(.+)\z/;
243 defined($tail_pid = fork) or die "fork: $!\n";
244 if ($tail_pid == 0) {
245 # make sure files exist, first
246 open my $fh, '>>', $_ for @paths;
247 open(STDOUT, '>&STDERR') or die "1>&2: $!";
248 exec(split(' ', $tail_cmd), @paths);
249 die "$tail_cmd failed: $!";
254 defined(my $pid = fork) or die "fork: $!\n";
256 # pretend to be systemd (cf. sd_listen_fds(3))
257 # 3 == SD_LISTEN_FDS_START
259 for ($fd = 0; 1; $fd++) {
261 last if $fd >= 3 && !defined($s);
263 my $fl = fcntl($s, F_GETFD, 0);
264 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
265 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
267 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
268 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
270 %ENV = (%ENV, %$env) if $env;
273 $ENV{LISTEN_PID} = $$;
274 $ENV{LISTEN_FDS} = $fds;
276 $0 = join(' ', @$cmd);
278 _run_sub($sub, $key, \@argv);
279 POSIX::_exit($? >> 8);
281 exec(key2script($key), @argv);
282 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
285 PublicInboxTestProcess->new($pid, $tail_pid);
288 package PublicInboxTestProcess;
291 # prevent new threads from inheriting these objects
295 my ($klass, $pid, $tail_pid) = @_;
296 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
300 my ($self, $sig) = @_;
301 CORE::kill($sig // 'TERM', $self->{pid});
306 my $pid = delete $self->{pid} or return;
307 my $ret = waitpid($pid, 0);
308 defined($ret) or die "waitpid($pid): $!";
309 $ret == $pid or die "waitpid($pid) != $ret";
314 return if $self->{owner} != $$;
315 if (my $tail = delete $self->{tail_pid}) {
316 PublicInbox::TestCommon::wait_for_tail();
317 CORE::kill('TERM', $tail);
319 my $pid = delete $self->{pid} or return;
320 CORE::kill('TERM', $pid);