]> Sergey Matveev's repositories - public-inbox.git/blob - t/common.perl
c56930804fa8c362a214dbf96a931428c680ccb0
[public-inbox.git] / t / common.perl
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>
3
4 use Fcntl qw(FD_CLOEXEC F_SETFD F_GETFD :seek);
5 use POSIX qw(dup2);
6 use strict;
7 use warnings;
8 use IO::Socket::INET;
9
10 sub tcp_server () {
11         IO::Socket::INET->new(
12                 LocalAddr => '127.0.0.1',
13                 ReuseAddr => 1,
14                 Proto => 'tcp',
15                 Type => Socket::SOCK_STREAM(),
16                 Listen => 1024,
17                 Blocking => 0,
18         )
19 }
20
21 sub tcp_connect {
22         my ($dest, %opt) = @_;
23         my $s = IO::Socket::INET->new(
24                 Proto => 'tcp',
25                 Type => Socket::SOCK_STREAM(),
26                 PeerAddr => $dest->sockhost . ':' . $dest->sockport,
27                 %opt,
28         );
29         $s->autoflush(1);
30         $s;
31 }
32
33 sub spawn_listener {
34         my ($env, $cmd, $socks) = @_;
35         my $pid = fork;
36         defined $pid or die "fork failed: $!\n";
37         if ($pid == 0) {
38                 # pretend to be systemd (cf. sd_listen_fds(3))
39                 my $fd = 3; # 3 == SD_LISTEN_FDS_START
40                 foreach my $s (@$socks) {
41                         my $fl = fcntl($s, F_GETFD, 0);
42                         if (($fl & FD_CLOEXEC) != FD_CLOEXEC) {
43                                 warn "got FD:".fileno($s)." w/o CLOEXEC\n";
44                         }
45                         fcntl($s, F_SETFD, $fl &= ~FD_CLOEXEC);
46                         dup2(fileno($s), $fd++) or die "dup2 failed: $!\n";
47                 }
48                 $ENV{LISTEN_PID} = $$;
49                 $ENV{LISTEN_FDS} = scalar @$socks;
50                 %ENV = (%ENV, %$env) if $env;
51                 exec @$cmd;
52                 die "FAIL: ",join(' ', @$cmd), ": $!\n";
53         }
54         $pid;
55 }
56
57 sub require_git ($;$) {
58         my ($req, $maybe) = @_;
59         my ($req_maj, $req_min) = split(/\./, $req);
60         my ($cur_maj, $cur_min) = (`git --version` =~ /version (\d+)\.(\d+)/);
61
62         my $req_int = ($req_maj << 24) | ($req_min << 16);
63         my $cur_int = ($cur_maj << 24) | ($cur_min << 16);
64         if ($cur_int < $req_int) {
65                 return 0 if $maybe;
66                 plan skip_all => "git $req+ required, have $cur_maj.$cur_min";
67         }
68         1;
69 }
70
71 my %cached_scripts;
72 sub key2script ($) {
73         my ($key) = @_;
74         return $key if $key =~ m!\A/!;
75         # n.b. we may have scripts which don't start with "public-inbox" in
76         # the future:
77         $key =~ s/\A([-\.])/public-inbox$1/;
78         'blib/script/'.$key;
79 }
80
81 sub _prepare_redirects ($) {
82         my ($fhref) = @_;
83         my @x = ([ \*STDIN, '<&' ], [ \*STDOUT, '>&' ], [ \*STDERR, '>&' ]);
84         for (my $fd = 0; $fd <= $#x; $fd++) {
85                 my $fh = $fhref->[$fd] or next;
86                 my ($oldfh, $mode) = @{$x[$fd]};
87                 open $oldfh, $mode, $fh or die "$$oldfh $mode redirect: $!";
88         }
89 }
90
91 # $opt->{run_mode} (or $ENV{TEST_RUN_MODE}) allows chosing between
92 # three ways to spawn our own short-lived Perl scripts for testing:
93 #
94 # 0 - (fork|vfork) + execve, the most realistic but slowest
95 # 1 - preloading and running in a forked subprocess (fast)
96 # 2 - preloading and running in current process (slightly faster than 1)
97 #
98 # 2 is not compatible with scripts which use "exit" (which we'll try to
99 # avoid in the future).
100 # The default is 2.
101 our $run_script_exit_code;
102 sub RUN_SCRIPT_EXIT () { "RUN_SCRIPT_EXIT\n" };
103 sub run_script_exit (;$) {
104         $run_script_exit_code = $_[0] // 0;
105         die RUN_SCRIPT_EXIT;
106 }
107
108 sub run_script ($;$$) {
109         my ($cmd, $env, $opt) = @_;
110         my ($key, @argv) = @$cmd;
111         my $run_mode = $ENV{TEST_RUN_MODE} // $opt->{run_mode} // 1;
112         my $sub = $run_mode == 0 ? undef : ($cached_scripts{$key} //= do {
113                 my $f = key2script($key);
114                 open my $fh, '<', $f or die "open $f: $!";
115                 my $str = do { local $/; <$fh> };
116                 my ($fc, $rest) = ($key =~ m/([a-z])([a-z0-9]+)\z/);
117                 $fc = uc($fc);
118                 my $pkg = "PublicInbox::TestScript::$fc$rest";
119                 eval <<EOF;
120 package $pkg;
121 use strict;
122 use subs qw(exit);
123
124 *exit = *::run_script_exit;
125 sub main {
126 $str
127         0;
128 }
129 1;
130 EOF
131                 $pkg->can('main');
132         }); # do
133
134         my $fhref = [];
135         my $spawn_opt = {};
136         for my $fd (0..2) {
137                 my $redir = $opt->{$fd};
138                 next unless ref($redir);
139                 open my $fh, '+>', undef or die "open: $!";
140                 $fhref->[$fd] = $fh;
141                 $spawn_opt->{$fd} = fileno($fh);
142                 next if $fd > 0;
143                 $fh->autoflush(1);
144                 print $fh $$redir or die "print: $!";
145                 seek($fh, 0, SEEK_SET) or die "seek: $!";
146         }
147         if ($run_mode == 0) {
148                 # spawn an independent new process, like real-world use cases:
149                 require PublicInbox::Spawn;
150                 my $cmd = [ key2script($key), @argv ];
151                 my $pid = PublicInbox::Spawn::spawn($cmd, $env, $spawn_opt);
152                 defined($pid) or die "spawn: $!";
153                 if (defined $pid) {
154                         my $r = waitpid($pid, 0);
155                         defined($r) or die "waitpid: $!";
156                         $r == $pid or die "waitpid: expected $pid, got $r";
157                 }
158         } else { # localize and run everything in the same process:
159                 local *STDIN = *STDIN;
160                 local *STDOUT = *STDOUT;
161                 local *STDERR = *STDERR;
162                 local %ENV = $env ? (%ENV, %$env) : %ENV;
163                 local %SIG = %SIG;
164                 _prepare_redirects($fhref);
165                 local @ARGV = @argv;
166                 $run_script_exit_code = undef;
167                 my $exit_code = eval { $sub->(@argv) };
168                 if ($@ eq RUN_SCRIPT_EXIT) {
169                         $@ = '';
170                         $exit_code = $run_script_exit_code;
171                         $? = ($exit_code << 8);
172                 } elsif (defined($exit_code)) {
173                         $? = ($exit_code << 8);
174                 } elsif ($@) { # mimic die() behavior when uncaught
175                         warn "E: eval-ed $key: $@\n";
176                         $? = ($! << 8) if $!;
177                         $? = (255 << 8) if $? == 0;
178                 } else {
179                         die "BUG: eval-ed $key: no exit code or \$@\n";
180                 }
181         }
182
183         # slurp the redirects back into user-supplied strings
184         for my $fd (1..2) {
185                 my $fh = $fhref->[$fd] or next;
186                 seek($fh, 0, SEEK_SET) or die "seek: $!";
187                 my $redir = $opt->{$fd};
188                 local $/;
189                 $$redir = <$fh>;
190         }
191         $? == 0;
192 }
193
194 1;