]> git.vpit.fr Git - perl/modules/VPIT-TestHelpers.git/blob - lib/VPIT/TestHelpers.pm
Add capture feature
[perl/modules/VPIT-TestHelpers.git] / lib / VPIT / TestHelpers.pm
1 package VPIT::TestHelpers;
2
3 use strict;
4 use warnings;
5
6 use Config ();
7
8 sub export_to_pkg {
9  my ($subs, $pkg) = @_;
10
11  while (my ($name, $code) = each %$subs) {
12   no strict 'refs';
13   *{$pkg.'::'.$name} = $code;
14  }
15
16  return 1;
17 }
18
19 my %default_exports = (
20  load_or_skip     => \&load_or_skip,
21  load_or_skip_all => \&load_or_skip_all,
22  run_perl         => \&run_perl,
23  skip_all         => \&skip_all,
24 );
25
26 my %features = (
27  threads => \&init_threads,
28  usleep  => \&init_usleep,
29  capture => \&init_capture,
30 );
31
32 sub import {
33  shift;
34  my @opts = @_;
35
36  my %exports = %default_exports;
37
38  for (my $i = 0; $i <= $#opts; ++$i) {
39   my $feature = $opts[$i];
40   next unless defined $feature;
41
42   my $args;
43   if ($i < $#opts and defined $opts[$i+1] and ref $opts[$i+1] eq 'ARRAY') {
44    ++$i;
45    $args = $opts[$i];
46   } else {
47    $args = [ ];
48   }
49
50   my $handler = $features{$feature};
51   die "Unknown feature '$feature'" unless defined $handler;
52
53   my %syms = $handler->(@$args);
54
55   $exports{$_} = $syms{$_} for sort keys %syms;
56  }
57
58  export_to_pkg \%exports => scalar caller;
59 }
60
61 my $test_sub = sub {
62  my $sub = shift;
63
64  my $stash;
65  if ($INC{'Test/Leaner.pm'}) {
66   $stash = \%Test::Leaner::;
67  } else {
68   require Test::More;
69   $stash = \%Test::More::;
70  }
71
72  my $glob = $stash->{$sub};
73  return $glob ? *$glob{CODE} : undef;
74 };
75
76 sub skip { $test_sub->('skip')->(@_) }
77
78 sub skip_all { $test_sub->('plan')->(skip_all => $_[0]) }
79
80 sub diag {
81  my $diag = $test_sub->('diag');
82  $diag->($_) for @_;
83 }
84
85 our $TODO;
86 local $TODO;
87
88 sub load {
89  my ($pkg, $ver, $imports) = @_;
90
91  my $spec = $ver && $ver !~ /^[0._]*$/ ? "$pkg $ver" : $pkg;
92  my $err;
93
94  local $@;
95  if (eval "use $spec (); 1") {
96   $ver = do { no strict 'refs'; ${"${pkg}::VERSION"} };
97   $ver = 'undef' unless defined $ver;
98
99   if ($imports) {
100    my @imports = @$imports;
101    my $caller  = (caller 1)[0];
102    local $@;
103    my $res = eval <<"IMPORTER";
104 package
105         $caller;
106 BEGIN { \$pkg->import(\@imports) }
107 1;
108 IMPORTER
109    $err = "Could not import '@imports' from $pkg $ver: $@" unless $res;
110   }
111  } else {
112   (my $file = "$pkg.pm") =~ s{::}{/}g;
113   delete $INC{$file};
114   $err = "Could not load $spec";
115  }
116
117  if ($err) {
118   return wantarray ? (0, $err) : 0;
119  } else {
120   diag "Using $pkg $ver";
121   return 1;
122  }
123 }
124
125 sub load_or_skip {
126  my ($pkg, $ver, $imports, $tests) = @_;
127
128  die 'You must specify how many tests to skip' unless defined $tests;
129
130  my ($loaded, $err) = load($pkg, $ver, $imports);
131  skip $err => $tests unless $loaded;
132
133  return $loaded;
134 }
135
136 sub load_or_skip_all {
137  my ($pkg, $ver, $imports) = @_;
138
139  my ($loaded, $err) = load($pkg, $ver, $imports);
140  skip_all $err unless $loaded;
141
142  return $loaded;
143 }
144
145 sub run_perl {
146  my $code = shift;
147
148  if ($code =~ /"/) {
149   die 'Double quotes in evaluated code are not portable';
150  }
151
152  my ($SystemRoot, $PATH) = @ENV{qw<SystemRoot PATH>};
153  my $ld_name  = $Config::Config{ldlibpthname};
154  my $ldlibpth = $ENV{$ld_name};
155
156  local %ENV;
157  $ENV{$ld_name}   = $ldlibpth   if                      defined $ldlibpth;
158  $ENV{SystemRoot} = $SystemRoot if $^O eq 'MSWin32' and defined $SystemRoot;
159  $ENV{PATH}       = $PATH       if $^O eq 'cygwin'  and defined $PATH;
160
161  my $perl = $^X;
162  unless (-e $perl and -x $perl) {
163   $perl = $Config::Config{perlpath};
164   unless (-e $perl and -x $perl) {
165    return undef;
166   }
167  }
168
169  system { $perl } $perl, '-T', map("-I$_", @INC), '-e', $code;
170 }
171
172 sub init_capture {
173  skip_all 'Cannot capture output on VMS' if $^O eq 'VMS';
174
175  load_or_skip_all 'IO::Handle', '0', [ ];
176  load_or_skip_all 'IO::Select', '0', [ ];
177  load_or_skip_all 'IPC::Open3', '0', [ ];
178  if ($^O eq 'MSWin32') {
179   load_or_skip_all 'Socket', '0', [ ];
180  }
181
182  return capture => \&capture;
183 }
184
185 # Inspired from IPC::Cmd
186
187 sub capture {
188  my @cmd = @_;
189
190  my $want = wantarray;
191
192  my $fail = sub {
193   my $err     = $!;
194   my $ext_err = $^O eq 'MSWin32' ? $^E : undef;
195
196   my $syscall = shift;
197   my $args    = join ', ', @_;
198
199   my $msg = "$syscall($args) failed: ";
200
201   if (defined $err) {
202    no warnings 'numeric';
203    my ($err_code, $err_str) = (int $err, "$err");
204    $msg .= "$err_str ($err_code)";
205   }
206
207   if (defined $ext_err) {
208    no warnings 'numeric';
209    my ($ext_err_code, $ext_err_str) = (int $ext_err, "$ext_err");
210    $msg .= ", $ext_err_str ($ext_err_code)";
211   }
212
213   die "$msg\n";
214  };
215
216  my ($status, $content_out, $content_err);
217
218  local $@;
219  my $ok = eval {
220   my ($pid, $out, $err);
221
222   if ($^O eq 'MSWin32') {
223    my $pipe = sub {
224     socketpair $_[0], $_[1],
225                &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC
226                       or $fail->(qw<socketpair reader writer>);
227     shutdown $_[0], 1 or $fail->(qw<shutdown reader>);
228     shutdown $_[1], 0 or $fail->(qw<shutdown writer>);
229     return 1;
230    };
231    local (*IN_R,  *IN_W);
232    local (*OUT_R, *OUT_W);
233    local (*ERR_R, *ERR_W);
234    $pipe->(*IN_R,  *IN_W);
235    $pipe->(*OUT_R, *OUT_W);
236    $pipe->(*ERR_R, *ERR_W);
237
238    $pid = IPC::Open3::open3('>&IN_R', '<&OUT_W', '<&ERR_W', @cmd);
239
240    close *IN_W or $fail->(qw<close input>);
241    $out = *OUT_R;
242    $err = *ERR_R;
243   } else {
244    my $in = IO::Handle->new;
245    $out   = IO::Handle->new;
246    $out->autoflush(1);
247    $err   = IO::Handle->new;
248    $err->autoflush(1);
249
250    $pid = IPC::Open3::open3($in, $out, $err, @cmd);
251
252    close $in;
253   }
254
255   # Forward signals to the child (except SIGKILL)
256   my %sig_handlers;
257   foreach my $s (keys %SIG) {
258    $sig_handlers{$s} = sub {
259     kill "$s" => $pid;
260     $SIG{$s} = $sig_handlers{$s};
261    };
262   }
263   local $SIG{$_} = $sig_handlers{$_} for keys %SIG;
264
265   unless ($want) {
266    close $out or $fail->(qw<close output>);
267    close $err or $fail->(qw<close error>);
268    waitpid $pid, 0;
269    $status = $?;
270    return 1;
271   }
272
273   my $sel = IO::Select->new();
274   $sel->add($out, $err);
275
276   my $fd_out = fileno $out;
277   my $fd_err = fileno $err;
278
279   my %contents;
280   $contents{$fd_out} = '';
281   $contents{$fd_err} = '';
282
283   while (my @ready = $sel->can_read) {
284    for my $fh (@ready) {
285     my $buf;
286     my $bytes_read = sysread $fh, $buf, 4096;
287     if (not defined $bytes_read) {
288      $fail->('sysread', 'fd(' . fileno($fh) . ')');
289     } elsif ($bytes_read) {
290      $contents{fileno($fh)} .= $buf;
291     } else {
292      $sel->remove($fh);
293      close $fh or $fail->('close', 'fd(' . fileno($fh) . ')');
294      last unless $sel->count;
295     }
296    }
297   }
298
299   waitpid $pid, 0;
300   $status = $?;
301
302   if ($^O eq 'MSWin32') {
303    # Manual CRLF translation that couldn't be done with sysread.
304    s/\x0D\x0A/\n/g for values %contents;
305   }
306
307   $content_out = $contents{$fd_out};
308   $content_err = $contents{$fd_err};
309
310   1;
311  };
312
313  if ($ok) {
314   return ($status, $content_out, $content_err);
315  } else {
316   my $err = $@;
317   chomp $err;
318   return (undef, $err);
319  }
320 }
321
322 sub init_threads {
323  my ($pkg, $threadsafe, $force_var) = @_;
324
325  skip_all 'This perl wasn\'t built to support threads'
326                                             unless $Config::Config{useithreads};
327
328  $pkg = 'package' unless defined $pkg;
329  skip_all "This $pkg isn't thread safe" if defined $threadsafe and !$threadsafe;
330
331  $force_var = 'PERL_FORCE_TEST_THREADS' unless defined $force_var;
332  my $force  = $ENV{$force_var} ? 1 : !1;
333  skip_all 'perl 5.13.4 required to test thread safety'
334                                              unless $force or "$]" >= 5.013_004;
335
336  if (($INC{'Test/More.pm'} || $INC{'Test/Leaner.pm'}) && !$INC{'threads.pm'}) {
337   die 'Test::More/Test::Leaner was loaded too soon';
338  }
339
340  load_or_skip_all 'threads',         $force ? '0' : '1.67', [ ];
341  load_or_skip_all 'threads::shared', $force ? '0' : '1.14', [ ];
342
343  require Test::Leaner;
344
345  diag "Threads testing forced by \$ENV{$force_var}" if $force;
346
347  return spawn => \&spawn;
348 }
349
350 sub init_usleep {
351  my $usleep;
352
353  if (do { local $@; eval { require Time::HiRes; 1 } }) {
354   defined and diag "Using usleep() from Time::HiRes $_"
355                                                       for $Time::HiRes::VERSION;
356   $usleep = \&Time::HiRes::usleep;
357  } else {
358   diag 'Using fallback usleep()';
359   $usleep = sub {
360    my $s = int($_[0] / 2.5e5);
361    sleep $s if $s;
362   };
363  }
364
365  return usleep => $usleep;
366 }
367
368 sub spawn {
369  local $@;
370  my @diag;
371  my $thread = eval {
372   local $SIG{__WARN__} = sub { push @diag, "Thread creation warning: @_" };
373   threads->create(@_);
374  };
375  push @diag, "Thread creation error: $@" if $@;
376  diag @diag;
377  return $thread ? $thread : ();
378 }
379
380 package VPIT::TestHelpers::Guard;
381
382 sub new {
383  my ($class, $code) = @_;
384
385  bless { code => $code }, $class;
386 }
387
388 sub DESTROY { $_[0]->{code}->() }
389
390 1;