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