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 $key =~ m!\A/!;
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 ($fc, $rest) = ($key =~ m/([a-z])([a-z0-9]+)\z/);
106 my $pkg = "PublicInbox::TestScript::$fc$rest";
112 *exit = *PublicInbox::TestCommon::run_script_exit;
124 my ($sub, $key, $argv) = @_;
125 local @ARGV = @$argv;
126 $run_script_exit_code = undef;
127 my $exit_code = eval { $sub->(@$argv) };
128 if ($@ eq RUN_SCRIPT_EXIT) {
130 $exit_code = $run_script_exit_code;
131 $? = ($exit_code << 8);
132 } elsif (defined($exit_code)) {
133 $? = ($exit_code << 8);
134 } elsif ($@) { # mimic die() behavior when uncaught
135 warn "E: eval-ed $key: $@\n";
136 $? = ($! << 8) if $!;
137 $? = (255 << 8) if $? == 0;
139 die "BUG: eval-ed $key: no exit code or \$@\n";
143 sub run_script ($;$$) {
144 my ($cmd, $env, $opt) = @_;
145 my ($key, @argv) = @$cmd;
146 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
147 my $sub = $run_mode == 0 ? undef : key2sub($key);
151 my $redir = $opt->{$fd};
152 next unless ref($redir);
153 open my $fh, '+>', undef or die "open: $!";
155 $spawn_opt->{$fd} = fileno($fh);
158 print $fh $$redir or die "print: $!";
159 seek($fh, 0, SEEK_SET) or die "seek: $!";
161 if ($run_mode == 0) {
162 # spawn an independent new process, like real-world use cases:
163 require PublicInbox::Spawn;
164 my $cmd = [ key2script($key), @argv ];
165 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
166 defined($pid) or die "spawn: $!";
168 my $r = waitpid($pid, 0);
169 defined($r) or die "waitpid: $!";
170 $r == $pid or die "waitpid: expected $pid, got $r";
172 } else { # localize and run everything in the same process:
173 local *STDIN = *STDIN;
174 local *STDOUT = *STDOUT;
175 local *STDERR = *STDERR;
176 local %ENV = $env ? (%ENV, %$env) : %ENV;
178 local $0 = join(' ', @$cmd);
179 _prepare_redirects($fhref);
180 _run_sub($sub, $key, \@argv);
183 # slurp the redirects back into user-supplied strings
185 my $fh = $fhref->[$fd] or next;
186 seek($fh, 0, SEEK_SET) or die "seek: $!";
187 my $redir = $opt->{$fd};
194 sub wait_for_tail () { sleep(2) }
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);
202 if (my $tail_cmd = $ENV{TAIL}) {
205 next unless /\A--std(?:err|out)=(.+)\z/;
209 defined($tail_pid = fork) or die "fork: $!\n";
210 if ($tail_pid == 0) {
211 # make sure files exist, first
212 open my $fh, '>>', $_ for @paths;
213 open(STDOUT, '>&STDERR') or die "1>&2: $!";
214 exec(split(' ', $tail_cmd), @paths);
215 die "$tail_cmd failed: $!";
220 defined(my $pid = fork) or die "fork: $!\n";
222 # pretend to be systemd (cf. sd_listen_fds(3))
223 # 3 == SD_LISTEN_FDS_START
225 for ($fd = 0; 1; $fd++) {
227 last if $fd >= 3 && !defined($s);
229 my $fl = fcntl($s, F_GETFD, 0);
230 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
231 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
233 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
234 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
236 %ENV = (%ENV, %$env) if $env;
239 $ENV{LISTEN_PID} = $$;
240 $ENV{LISTEN_FDS} = $fds;
242 $0 = join(' ', @$cmd);
244 _run_sub($sub, $key, \@argv);
245 POSIX::_exit($? >> 8);
247 exec(key2script($key), @argv);
248 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
251 PublicInboxTestProcess->new($pid, $tail_pid);
254 package PublicInboxTestProcess;
257 # prevent new threads from inheriting these objects
261 my ($klass, $pid, $tail_pid) = @_;
262 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
266 my ($self, $sig) = @_;
267 CORE::kill($sig // 'TERM', $self->{pid});
272 my $pid = delete $self->{pid} or return;
273 my $ret = waitpid($pid, 0);
274 defined($ret) or die "waitpid($pid): $!";
275 $ret == $pid or die "waitpid($pid) != $ret";
280 return if $self->{owner} != $$;
281 if (my $tail = delete $self->{tail_pid}) {
282 PublicInbox::TestCommon::wait_for_tail();
283 CORE::kill('TERM', $tail);
285 my $pid = delete $self->{pid} or return;
286 CORE::kill('TERM', $pid);