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
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 plan(skip_all => "git $req+ required, have $cur_maj.$cur_min");
63 return $key if (index($key, '/') >= 0);
64 # n.b. we may have scripts which don't start with "public-inbox" in
66 $key =~ s/\A([-\.])/public-inbox$1/;
70 sub _prepare_redirects ($) {
72 my @x = ([ \*STDIN, '<&' ], [ \*STDOUT, '>&' ], [ \*STDERR, '>&' ]);
73 for (my $fd = 0; $fd <= $#x; $fd++) {
74 my $fh = $fhref->[$fd] or next;
75 my ($oldfh, $mode) = @{$x[$fd]};
76 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
80 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows chosing between
81 # three ways to spawn our own short-lived Perl scripts for testing:
83 # 0 - (fork|vfork) + execve, the most realistic but slowest
84 # 1 - preloading and running in a forked subprocess (fast)
85 # 2 - preloading and running in current process (slightly faster than 1)
87 # 2 is not compatible with scripts which use "exit" (which we'll try to
88 # avoid in the future).
90 our $run_script_exit_code;
91 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
92 sub run_script_exit (;$) {
93 $run_script_exit_code = $_[0] // 0;
100 $cached_scripts{$key} //= do {
101 my $f = key2script($key);
102 open my $fh, '<', $f or die "open $f: $!";
103 my $str = do { local $/; <$fh> };
104 my $pkg = (split(m!/!, $f))[-1];
105 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
108 $pkg = "PublicInbox::TestScript::$pkg";
114 *exit = *PublicInbox::TestCommon::run_script_exit;
116 # the below "line" directive is a magic comment, see perlsyn(1) manpage
128 my ($sub, $key, $argv) = @_;
129 local @ARGV = @$argv;
130 $run_script_exit_code = undef;
131 my $exit_code = eval { $sub->(@$argv) };
132 if ($@ eq RUN_SCRIPT_EXIT) {
134 $exit_code = $run_script_exit_code;
135 $? = ($exit_code << 8);
136 } elsif (defined($exit_code)) {
137 $? = ($exit_code << 8);
138 } elsif ($@) { # mimic die() behavior when uncaught
139 warn "E: eval-ed $key: $@\n";
140 $? = ($! << 8) if $!;
141 $? = (255 << 8) if $? == 0;
143 die "BUG: eval-ed $key: no exit code or \$@\n";
147 sub run_script ($;$$) {
148 my ($cmd, $env, $opt) = @_;
149 my ($key, @argv) = @$cmd;
150 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
151 my $sub = $run_mode == 0 ? undef : key2sub($key);
155 my $redir = $opt->{$fd};
156 next unless ref($redir);
157 open my $fh, '+>', undef or die "open: $!";
159 $spawn_opt->{$fd} = fileno($fh);
162 print $fh $$redir or die "print: $!";
163 seek($fh, 0, SEEK_SET) or die "seek: $!";
165 if ($run_mode == 0) {
166 # spawn an independent new process, like real-world use cases:
167 require PublicInbox::Spawn;
168 my $cmd = [ key2script($key), @argv ];
169 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
170 defined($pid) or die "spawn: $!";
172 my $r = waitpid($pid, 0);
173 defined($r) or die "waitpid: $!";
174 $r == $pid or die "waitpid: expected $pid, got $r";
176 } else { # localize and run everything in the same process:
177 local *STDIN = *STDIN;
178 local *STDOUT = *STDOUT;
179 local *STDERR = *STDERR;
180 local %ENV = $env ? (%ENV, %$env) : %ENV;
182 local $0 = join(' ', @$cmd);
183 _prepare_redirects($fhref);
184 _run_sub($sub, $key, \@argv);
187 # slurp the redirects back into user-supplied strings
189 my $fh = $fhref->[$fd] or next;
190 seek($fh, 0, SEEK_SET) or die "seek: $!";
191 my $redir = $opt->{$fd};
198 sub wait_for_tail () { sleep(2) }
201 my ($cmd, $env, $opt) = @_;
202 my ($key, @argv) = @$cmd;
203 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
204 my $sub = $run_mode == 0 ? undef : key2sub($key);
206 if (my $tail_cmd = $ENV{TAIL}) {
209 next unless /\A--std(?:err|out)=(.+)\z/;
213 defined($tail_pid = fork) or die "fork: $!\n";
214 if ($tail_pid == 0) {
215 # make sure files exist, first
216 open my $fh, '>>', $_ for @paths;
217 open(STDOUT, '>&STDERR') or die "1>&2: $!";
218 exec(split(' ', $tail_cmd), @paths);
219 die "$tail_cmd failed: $!";
224 defined(my $pid = fork) or die "fork: $!\n";
226 # pretend to be systemd (cf. sd_listen_fds(3))
227 # 3 == SD_LISTEN_FDS_START
229 for ($fd = 0; 1; $fd++) {
231 last if $fd >= 3 && !defined($s);
233 my $fl = fcntl($s, F_GETFD, 0);
234 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
235 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
237 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
238 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
240 %ENV = (%ENV, %$env) if $env;
243 $ENV{LISTEN_PID} = $$;
244 $ENV{LISTEN_FDS} = $fds;
246 $0 = join(' ', @$cmd);
248 _run_sub($sub, $key, \@argv);
249 POSIX::_exit($? >> 8);
251 exec(key2script($key), @argv);
252 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
255 PublicInboxTestProcess->new($pid, $tail_pid);
258 package PublicInboxTestProcess;
261 # prevent new threads from inheriting these objects
265 my ($klass, $pid, $tail_pid) = @_;
266 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
270 my ($self, $sig) = @_;
271 CORE::kill($sig // 'TERM', $self->{pid});
276 my $pid = delete $self->{pid} or return;
277 my $ret = waitpid($pid, 0);
278 defined($ret) or die "waitpid($pid): $!";
279 $ret == $pid or die "waitpid($pid) != $ret";
284 return if $self->{owner} != $$;
285 if (my $tail = delete $self->{tail_pid}) {
286 PublicInbox::TestCommon::wait_for_tail();
287 CORE::kill('TERM', $tail);
289 my $pid = delete $self->{pid} or return;
290 CORE::kill('TERM', $pid);