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);
9 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
12 our @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
13 run_script start_script key2sub xsys xqx eml_load tick
18 open(my $fh, '<', $path) or die "open $path: $!";
19 require PublicInbox::Eml;
20 PublicInbox::Eml->new(\(do { local $/; <$fh> }));
26 unless (defined $base) {
27 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
29 my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
30 ($tmpdir->dirname, $tmpdir);
34 IO::Socket::INET->new(
35 LocalAddr => '127.0.0.1',
38 Type => Socket::SOCK_STREAM(),
41 ) or Test::More::BAIL_OUT("failed to create TCP server: $!");
45 my ($dest, %opt) = @_;
46 my $addr = $dest->sockhost . ':' . $dest->sockport;
47 my $s = IO::Socket::INET->new(
49 Type => Socket::SOCK_STREAM(),
52 ) or Test::More::BAIL_OUT("failed to connect to $addr: $!");
57 sub require_git ($;$) {
58 my ($req, $maybe) = @_;
59 my ($req_maj, $req_min, $req_sub) = split(/\./, $req);
60 my ($cur_maj, $cur_min, $cur_sub) = (xqx([qw(git --version)])
61 =~ /version (\d+)\.(\d+)(?:\.(\d+))?/);
63 my $req_int = ($req_maj << 24) | ($req_min << 16) | ($req_sub // 0);
64 my $cur_int = ($cur_maj << 24) | ($cur_min << 16) | ($cur_sub // 0);
65 if ($cur_int < $req_int) {
67 Test::More::plan(skip_all =>
68 "git $req+ required, have $cur_maj.$cur_min.$cur_sub");
75 my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
77 while (my $mod = shift(@mods)) {
78 if ($mod eq 'Search::Xapian') {
79 if (eval { require PublicInbox::Search } &&
80 PublicInbox::Search::load_xapian()) {
83 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
84 if (eval { require PublicInbox::SearchIdx } &&
85 PublicInbox::SearchIdx::load_xapian_writable()){
88 } elsif (index($mod, '||') >= 0) { # "Foo||Bar"
90 for my $m (split(/\Q||\E/, $mod)) {
102 } elsif ($mod eq 'IO::Socket::SSL' &&
103 # old versions of IO::Socket::SSL aren't supported
104 # by libnet, at least:
105 # https://rt.cpan.org/Ticket/Display.html?id=100529
106 !eval{ IO::Socket::SSL->VERSION(2.007); 1 }) {
111 my $m = join(', ', @need)." missing for $0";
112 Test::More::skip($m, $maybe) if $maybe;
113 Test::More::plan(skip_all => $m)
118 return $key if ($key eq 'git' || index($key, '/') >= 0);
119 # n.b. we may have scripts which don't start with "public-inbox" in
121 $key =~ s/\A([-\.])/public-inbox$1/;
125 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
126 [ *STDERR{IO}, '>&' ]);
128 sub _prepare_redirects ($) {
131 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
132 my $fh = $fhref->[$fd] or next;
133 my ($oldfh, $mode) = @{$io_mode[$fd]};
134 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
135 $orig_io->[$fd] = $orig;
136 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
141 sub _undo_redirects ($) {
143 for (my $fd = 0; $fd <= $#io_mode; $fd++) {
144 my $fh = $orig_io->[$fd] or next;
145 my ($oldfh, $mode) = @{$io_mode[$fd]};
146 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
150 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
151 # three ways to spawn our own short-lived Perl scripts for testing:
153 # 0 - (fork|vfork) + execve, the most realistic but slowest
154 # 1 - (not currently implemented)
155 # 2 - preloading and running in current process (slightly faster than 1)
157 # 2 is not compatible with scripts which use "exit" (which we'll try to
158 # avoid in the future).
160 our $run_script_exit_code;
161 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
162 sub run_script_exit {
163 $run_script_exit_code = $_[0] // 0;
170 $cached_scripts{$key} //= do {
171 my $f = key2script($key);
172 open my $fh, '<', $f or die "open $f: $!";
173 my $str = do { local $/; <$fh> };
174 my $pkg = (split(m!/!, $f))[-1];
175 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
178 $pkg = "PublicInbox::TestScript::$pkg";
184 *exit = \\&PublicInbox::TestCommon::run_script_exit;
186 # the below "line" directive is a magic comment, see perlsyn(1) manpage
198 my ($sub, $key, $argv) = @_;
199 local @ARGV = @$argv;
200 $run_script_exit_code = undef;
201 my $exit_code = eval { $sub->(@$argv) };
202 if ($@ eq RUN_SCRIPT_EXIT) {
204 $exit_code = $run_script_exit_code;
205 $? = ($exit_code << 8);
206 } elsif (defined($exit_code)) {
207 $? = ($exit_code << 8);
208 } elsif ($@) { # mimic die() behavior when uncaught
209 warn "E: eval-ed $key: $@\n";
210 $? = ($! << 8) if $!;
211 $? = (255 << 8) if $? == 0;
213 die "BUG: eval-ed $key: no exit code or \$@\n";
217 sub run_script ($;$$) {
218 my ($cmd, $env, $opt) = @_;
219 my ($key, @argv) = @$cmd;
220 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
221 my $sub = $run_mode == 0 ? undef : key2sub($key);
225 my $redir = $opt->{$fd};
226 my $ref = ref($redir);
227 if ($ref eq 'SCALAR') {
228 open my $fh, '+>', undef or die "open: $!";
230 $spawn_opt->{$fd} = $fh;
233 print $fh $$redir or die "print: $!";
234 seek($fh, 0, SEEK_SET) or die "seek: $!";
235 } elsif ($ref eq 'GLOB') {
236 $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
238 die "unable to deal with $ref $redir";
241 if ($run_mode == 0) {
242 # spawn an independent new process, like real-world use cases:
243 require PublicInbox::Spawn;
244 my $cmd = [ key2script($key), @argv ];
245 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
247 my $r = waitpid($pid, 0);
248 defined($r) or die "waitpid: $!";
249 $r == $pid or die "waitpid: expected $pid, got $r";
251 } else { # localize and run everything in the same process:
252 # note: "local *STDIN = *STDIN;" and so forth did not work in
253 # old versions of perl
254 local %ENV = $env ? (%ENV, %$env) : %ENV;
256 local $0 = join(' ', @$cmd);
257 my $orig_io = _prepare_redirects($fhref);
258 _run_sub($sub, $key, \@argv);
259 _undo_redirects($orig_io);
262 # slurp the redirects back into user-supplied strings
264 my $fh = $fhref->[$fd] or next;
265 seek($fh, 0, SEEK_SET) or die "seek: $!";
266 my $redir = $opt->{$fd};
274 my $tick = shift // 0.1;
275 select undef, undef, undef, $tick;
279 sub wait_for_tail ($;$) {
280 my ($tail_pid, $want) = @_;
282 if ($^O eq 'linux') { # GNU tail may use inotify
283 state $tail_has_inotify;
284 return tick if $want < 0 && $tail_has_inotify;
285 my $end = time + $wait;
289 readlink($_) =~ /\binotify\b/
290 } glob("/proc/$tail_pid/fd/*");
291 } while (!@ino && time <= $end and tick);
293 $tail_has_inotify = 1;
294 $ino[0] =~ s!/fd/!/fdinfo/!;
297 if (open my $fh, '<', $ino[0]) {
299 @info = grep(/^inotify wd:/, <$fh>);
301 } while (scalar(@info) < $want && time <= $end and tick);
307 # like system() built-in, but uses spawn() for env/rdr + vfork
309 my ($cmd, $env, $rdr) = @_;
317 run_script($cmd, $env, { %$rdr, run_mode => 0 });
321 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
323 my ($cmd, $env, $rdr) = @_;
325 run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
326 wantarray ? split(/^/m, $out) : $out;
330 my ($cmd, $env, $opt) = @_;
331 my ($key, @argv) = @$cmd;
332 my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
333 my $sub = $run_mode == 0 ? undef : key2sub($key);
335 if (my $tail_cmd = $ENV{TAIL}) {
338 next unless /\A--std(?:err|out)=(.+)\z/;
343 my $f = $opt->{$_} or next;
346 } elsif (ref($f) eq 'GLOB' && $^O eq 'linux') {
348 my $f = readlink "/proc/$$/fd/$fd";
349 push @paths, $f if -e $f;
354 defined($tail_pid = fork) or die "fork: $!\n";
355 if ($tail_pid == 0) {
356 # make sure files exist, first
357 open my $fh, '>>', $_ for @paths;
358 open(STDOUT, '>&STDERR') or die "1>&2: $!";
359 exec(split(' ', $tail_cmd), @paths);
360 die "$tail_cmd failed: $!";
362 wait_for_tail($tail_pid, scalar @paths);
365 defined(my $pid = fork) or die "fork: $!\n";
367 eval { PublicInbox::DS->Reset };
368 # pretend to be systemd (cf. sd_listen_fds(3))
369 # 3 == SD_LISTEN_FDS_START
371 for ($fd = 0; 1; $fd++) {
373 last if $fd >= 3 && !defined($s);
375 my $fl = fcntl($s, F_GETFD, 0);
376 if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
377 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
379 fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
380 dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
382 %ENV = (%ENV, %$env) if $env;
385 $ENV{LISTEN_PID} = $$;
386 $ENV{LISTEN_FDS} = $fds;
388 $0 = join(' ', @$cmd);
390 eval { PublicInbox::DS->Reset };
391 _run_sub($sub, $key, \@argv);
392 POSIX::_exit($? >> 8);
394 exec(key2script($key), @argv);
395 die "FAIL: ",join(' ', $key, @argv), ": $!\n";
398 PublicInboxTestProcess->new($pid, $tail_pid);
401 sub have_xapian_compact () {
402 require PublicInbox::Spawn;
403 # $ENV{XAPIAN_COMPACT} is used by PublicInbox/Xapcmd.pm, too
404 PublicInbox::Spawn::which($ENV{XAPIAN_COMPACT} || 'xapian-compact');
407 package PublicInboxTestProcess;
410 # prevent new threads from inheriting these objects
414 my ($klass, $pid, $tail_pid) = @_;
415 bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
419 my ($self, $sig) = @_;
420 CORE::kill($sig // 'TERM', $self->{pid});
424 my ($self, $sig) = @_;
425 my $pid = delete $self->{pid} or return;
426 CORE::kill($sig, $pid) if defined $sig;
427 my $ret = waitpid($pid, 0);
428 defined($ret) or die "waitpid($pid): $!";
429 $ret == $pid or die "waitpid($pid) != $ret";
434 return if $self->{owner} != $$;
435 if (my $tail_pid = delete $self->{tail_pid}) {
436 PublicInbox::TestCommon::wait_for_tail($tail_pid, -1);
437 CORE::kill('TERM', $tail_pid);
442 package PublicInbox::TestCommon::InboxWakeup;
444 sub on_inbox_unlock { ${$_[0]}->($_[1]) }