]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/TestCommon.pm
testcommon: introduce mime_load sub
[public-inbox.git] / lib / PublicInbox / TestCommon.pm
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>
3
4 # internal APIs used only for tests
5 package PublicInbox::TestCommon;
6 use strict;
7 use parent qw(Exporter);
8 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
9 use POSIX qw(dup2);
10 use IO::Socket::INET;
11 our @EXPORT = qw(tmpdir tcp_server tcp_connect require_git require_mods
12         run_script start_script key2sub xsys xqx mime_load);
13
14 sub mime_load ($;&) {
15         my ($path, $cb) = @_;
16         if (open(my $fh, '<', $path)) {
17                 PublicInbox::MIME->new(\(do { local $/; <$fh> }));
18         } elsif ($cb) {
19                 require File::Temp;
20
21                 my $mime = $cb->();
22                 my ($dir) = ($path =~ m!(.+)/(?:[^/]+)\z!);
23                 -d $dir or die "BUG: dir=$dir is not the dir of $path";
24                 my $fh = File::Temp->new(DIR => $dir);
25                 $fh->autoflush(1);
26                 print $fh $mime->as_string or die "print: $!";
27                 my $fn = $fh->filename;
28                 rename($fn, $path) or die "link $fn => $path: $!";
29                 $fh->unlink_on_destroy(0);
30                 pop @_; # retry via tail recursion
31                 goto &mime_load;
32         } else {
33                 die "open $path: $!";
34         }
35 }
36
37 sub tmpdir (;$) {
38         my ($base) = @_;
39         require File::Temp;
40         unless (defined $base) {
41                 ($base) = ($0 =~ m!\b([^/]+)\.[^\.]+\z!);
42         }
43         my $tmpdir = File::Temp->newdir("pi-$base-$$-XXXXXX", TMPDIR => 1);
44         ($tmpdir->dirname, $tmpdir);
45 }
46
47 sub tcp_server () {
48         IO::Socket::INET->new(
49                 LocalAddr => '127.0.0.1',
50                 ReuseAddr => 1,
51                 Proto => 'tcp',
52                 Type => Socket::SOCK_STREAM(),
53                 Listen => 1024,
54                 Blocking => 0,
55         )
56 }
57
58 sub tcp_connect {
59         my ($dest, %opt) = @_;
60         my $s = IO::Socket::INET->new(
61                 Proto => 'tcp',
62                 Type => Socket::SOCK_STREAM(),
63                 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
64                 %opt,
65         );
66         $s->autoflush(1);
67         $s;
68 }
69
70 sub require_git ($;$) {
71         my ($req, $maybe) = @_;
72         my ($req_maj, $req_min) = split(/\./, $req);
73         my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
74
75         my $req_int = ($req_maj << 24) | ($req_min << 16);
76         my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
77         if ($cur_int < $req_int) {
78                 return 0 if $maybe;
79                 Test::More::plan(skip_all =>
80                                 "git $req+ required, have $cur_maj.$cur_min");
81         }
82         1;
83 }
84
85 sub require_mods {
86         my @mods = @_;
87         my $maybe = pop @mods if $mods[-1] =~ /\A[0-9]+\z/;
88         my @need;
89         for my $mod (@mods) {
90                 if ($mod eq 'Search::Xapian') {
91                         if (eval { require PublicInbox::Search } &&
92                                 PublicInbox::Search::load_xapian()) {
93                                 next;
94                         }
95                 } elsif ($mod eq 'Search::Xapian::WritableDatabase') {
96                         if (eval { require PublicInbox::SearchIdx } &&
97                                 PublicInbox::SearchIdx::load_xapian_writable()){
98                                         next;
99                         }
100                 } else {
101                         eval "require $mod";
102                 }
103                 push @need, $mod if $@;
104         }
105         return unless @need;
106         my $m = join(', ', @need)." missing for $0";
107         Test::More::skip($m, $maybe) if $maybe;
108         Test::More::plan(skip_all => $m)
109 }
110
111 sub key2script ($) {
112         my ($key) = @_;
113         return $key if ($key eq 'git' || index($key, '/') >= 0);
114         # n.b. we may have scripts which don't start with "public-inbox" in
115         # the future:
116         $key =~ s/\A([-\.])/public-inbox$1/;
117         'blib/script/'.$key;
118 }
119
120 my @io_mode = ([ *STDIN{IO}, '<&' ], [ *STDOUT{IO}, '>&' ],
121                 [ *STDERR{IO}, '>&' ]);
122
123 sub _prepare_redirects ($) {
124         my ($fhref) = @_;
125         my $orig_io = [];
126         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
127                 my $fh = $fhref->[$fd] or next;
128                 my ($oldfh, $mode) = @{$io_mode[$fd]};
129                 open my $orig, $mode, $oldfh or die "$$oldfh $mode stash: $!";
130                 $orig_io->[$fd] = $orig;
131                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
132         }
133         $orig_io;
134 }
135
136 sub _undo_redirects ($) {
137         my ($orig_io) = @_;
138         for (my $fd = 0; $fd <= $#io_mode; $fd++) {
139                 my $fh = $orig_io->[$fd] or next;
140                 my ($oldfh, $mode) = @{$io_mode[$fd]};
141                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
142         }
143 }
144
145 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows choosing between
146 # three ways to spawn our own short-lived Perl scripts for testing:
147 #
148 # 0 - (fork|vfork) + execve, the most realistic but slowest
149 # 1 - (not currently implemented)
150 # 2 - preloading and running in current process (slightly faster than 1)
151 #
152 # 2 is not compatible with scripts which use "exit" (which we'll try to
153 # avoid in the future).
154 # The default is 2.
155 our $run_script_exit_code;
156 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
157 sub run_script_exit (;$) {
158         $run_script_exit_code = $_[0] // 0;
159         die RUN_SCRIPT_EXIT;
160 }
161
162 my %cached_scripts;
163 sub key2sub ($) {
164         my ($key) = @_;
165         $cached_scripts{$key} //= do {
166                 my $f = key2script($key);
167                 open my $fh, '<', $f or die "open $f: $!";
168                 my $str = do { local $/; <$fh> };
169                 my $pkg = (split(m!/!, $f))[-1];
170                 $pkg =~ s/([a-z])([a-z0-9]+)(\.t)?\z/\U$1\E$2/;
171                 $pkg .= "_T" if $3;
172                 $pkg =~ tr/-.//d;
173                 $pkg = "PublicInbox::TestScript::$pkg";
174                 eval <<EOF;
175 package $pkg;
176 use strict;
177 use subs qw(exit);
178
179 *exit = *PublicInbox::TestCommon::run_script_exit;
180 sub main {
181 # the below "line" directive is a magic comment, see perlsyn(1) manpage
182 # line 1 "$f"
183 $str
184         0;
185 }
186 1;
187 EOF
188                 $pkg->can('main');
189         }
190 }
191
192 sub _run_sub ($$$) {
193         my ($sub, $key, $argv) = @_;
194         local @ARGV = @$argv;
195         $run_script_exit_code = undef;
196         my $exit_code = eval { $sub->(@$argv) };
197         if ($@ eq RUN_SCRIPT_EXIT) {
198                 $@ = '';
199                 $exit_code = $run_script_exit_code;
200                 $? = ($exit_code << 8);
201         } elsif (defined($exit_code)) {
202                 $? = ($exit_code << 8);
203         } elsif ($@) { # mimic die() behavior when uncaught
204                 warn "E: eval-ed $key: $@\n";
205                 $? = ($! << 8) if $!;
206                 $? = (255 << 8) if $? == 0;
207         } else {
208                 die "BUG: eval-ed $key: no exit code or \$@\n";
209         }
210 }
211
212 sub run_script ($;$$) {
213         my ($cmd, $env, $opt) = @_;
214         my ($key, @argv) = @$cmd;
215         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
216         my $sub = $run_mode == 0 ? undef : key2sub($key);
217         my $fhref = [];
218         my $spawn_opt = {};
219         for my $fd (0..2) {
220                 my $redir = $opt->{$fd};
221                 my $ref = ref($redir);
222                 if ($ref eq 'SCALAR') {
223                         open my $fh, '+>', undef or die "open: $!";
224                         $fhref->[$fd] = $fh;
225                         $spawn_opt->{$fd} = $fh;
226                         next if $fd > 0;
227                         $fh->autoflush(1);
228                         print $fh $$redir or die "print: $!";
229                         seek($fh, 0, SEEK_SET) or die "seek: $!";
230                 } elsif ($ref eq 'GLOB') {
231                         $spawn_opt->{$fd} = $fhref->[$fd] = $redir;
232                 } elsif ($ref) {
233                         die "unable to deal with $ref $redir";
234                 }
235         }
236         if ($run_mode == 0) {
237                 # spawn an independent new process, like real-world use cases:
238                 require PublicInbox::Spawn;
239                 my $cmd = [ key2script($key), @argv ];
240                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
241                 if (defined $pid) {
242                         my $r = waitpid($pid, 0);
243                         defined($r) or die "waitpid: $!";
244                         $r == $pid or die "waitpid: expected $pid, got $r";
245                 }
246         } else { # localize and run everything in the same process:
247                 # note: "local *STDIN = *STDIN;" and so forth did not work in
248                 # old versions of perl
249                 local %ENV = $env ? (%ENV, %$env) : %ENV;
250                 local %SIG = %SIG;
251                 local $0 = join(' ', @$cmd);
252                 my $orig_io = _prepare_redirects($fhref);
253                 _run_sub($sub, $key, \@argv);
254                 _undo_redirects($orig_io);
255         }
256
257         # slurp the redirects back into user-supplied strings
258         for my $fd (1..2) {
259                 my $fh = $fhref->[$fd] or next;
260                 seek($fh, 0, SEEK_SET) or die "seek: $!";
261                 my $redir = $opt->{$fd};
262                 local $/;
263                 $$redir = <$fh>;
264         }
265         $? == 0;
266 }
267
268 sub wait_for_tail () { sleep(2) }
269
270 # like system() built-in, but uses spawn() for env/rdr + vfork
271 sub xsys {
272         my ($cmd, $env, $rdr) = @_;
273         if (ref($cmd)) {
274                 $rdr ||= {};
275         } else {
276                 $cmd = [ @_ ];
277                 $env = undef;
278                 $rdr = {};
279         }
280         run_script($cmd, $env, { %$rdr, run_mode => 0 });
281         $? >> 8
282 }
283
284 # like `backtick` or qx{} op, but uses spawn() for env/rdr + vfork
285 sub xqx {
286         my ($cmd, $env, $rdr) = @_;
287         $rdr //= {};
288         run_script($cmd, $env, { %$rdr, run_mode => 0, 1 => \(my $out) });
289         wantarray ? split(/^/m, $out) : $out;
290 }
291
292 sub start_script {
293         my ($cmd, $env, $opt) = @_;
294         my ($key, @argv) = @$cmd;
295         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 2;
296         my $sub = $run_mode == 0 ? undef : key2sub($key);
297         my $tail_pid;
298         if (my $tail_cmd = $ENV{TAIL}) {
299                 my @paths;
300                 for (@argv) {
301                         next unless /\A--std(?:err|out)=(.+)\z/;
302                         push @paths, $1;
303                 }
304                 if (@paths) {
305                         defined($tail_pid = fork) or die "fork: $!\n";
306                         if ($tail_pid == 0) {
307                                 # make sure files exist, first
308                                 open my $fh, '>>', $_ for @paths;
309                                 open(STDOUT, '>&STDERR') or die "1>&2: $!";
310                                 exec(split(' ', $tail_cmd), @paths);
311                                 die "$tail_cmd failed: $!";
312                         }
313                         wait_for_tail();
314                 }
315         }
316         defined(my $pid = fork) or die "fork: $!\n";
317         if ($pid == 0) {
318                 # pretend to be systemd (cf. sd_listen_fds(3))
319                 # 3 == SD_LISTEN_FDS_START
320                 my $fd;
321                 for ($fd = 0; 1; $fd++) {
322                         my $s = $opt->{$fd};
323                         last if $fd >= 3 && !defined($s);
324                         next unless $s;
325                         my $fl = fcntl($s, F_GETFD, 0);
326                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
327                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
328                         }
329                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
330                         dup2(fileno($s), $fd) or die "dup2 failed: $!\n";
331                 }
332                 %ENV = (%ENV, %$env) if $env;
333                 my $fds = $fd - 3;
334                 if ($fds > 0) {
335                         $ENV{LISTEN_PID} = $$;
336                         $ENV{LISTEN_FDS} = $fds;
337                 }
338                 $0 = join(' ', @$cmd);
339                 if ($sub) {
340                         _run_sub($sub, $key, \@argv);
341                         POSIX::_exit($? >> 8);
342                 } else {
343                         exec(key2script($key), @argv);
344                         die "FAIL: ",join(' ', $key, @argv), ": $!\n";
345                 }
346         }
347         PublicInboxTestProcess->new($pid, $tail_pid);
348 }
349
350 package PublicInboxTestProcess;
351 use strict;
352
353 # prevent new threads from inheriting these objects
354 sub CLONE_SKIP { 1 }
355
356 sub new {
357         my ($klass, $pid, $tail_pid) = @_;
358         bless { pid => $pid, tail_pid => $tail_pid, owner => $$ }, $klass;
359 }
360
361 sub kill {
362         my ($self, $sig) = @_;
363         CORE::kill($sig // 'TERM', $self->{pid});
364 }
365
366 sub join {
367         my ($self, $sig) = @_;
368         my $pid = delete $self->{pid} or return;
369         CORE::kill($sig, $pid) if defined $sig;
370         my $ret = waitpid($pid, 0);
371         defined($ret) or die "waitpid($pid): $!";
372         $ret == $pid or die "waitpid($pid) != $ret";
373 }
374
375 sub DESTROY {
376         my ($self) = @_;
377         return if $self->{owner} != $$;
378         if (my $tail = delete $self->{tail_pid}) {
379                 PublicInbox::TestCommon::wait_for_tail();
380                 CORE::kill('TERM', $tail);
381         }
382         $self->join('TERM');
383 }
384
385 1;