]> git.vpit.fr Git - perl/modules/VPIT-TestHelpers.git/blob - lib/VPIT/TestHelpers.pm
6a3655e9646aa45649087d5e063ecfd42d71a9a5
[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 fresh_perl_env (&) {
146  my $handler = shift;
147
148  my ($SystemRoot, $PATH) = @ENV{qw<SystemRoot PATH>};
149  my $ld_name  = $Config::Config{ldlibpthname};
150  my $ldlibpth = $ENV{$ld_name};
151
152  local %ENV;
153  $ENV{$ld_name}   = $ldlibpth   if                      defined $ldlibpth;
154  $ENV{SystemRoot} = $SystemRoot if $^O eq 'MSWin32' and defined $SystemRoot;
155  $ENV{PATH}       = $PATH       if $^O eq 'cygwin'  and defined $PATH;
156
157  my $perl = $^X;
158  unless (-e $perl and -x $perl) {
159   $perl = $Config::Config{perlpath};
160   unless (-e $perl and -x $perl) {
161    return undef;
162   }
163  }
164
165  return $handler->($perl, '-T', map("-I$_", @INC));
166 }
167
168 sub run_perl {
169  my $code = shift;
170
171  if ($code =~ /"/) {
172   die 'Double quotes in evaluated code are not portable';
173  }
174
175  fresh_perl_env {
176   my ($perl, @perl_args) = @_;
177   system { $perl } $perl, @perl_args, '-e', $code;
178  };
179 }
180
181 sub init_capture {
182  skip_all 'Cannot capture output on VMS' if $^O eq 'VMS';
183
184  load_or_skip_all 'IO::Handle', '0', [ ];
185  load_or_skip_all 'IO::Select', '0', [ ];
186  load_or_skip_all 'IPC::Open3', '0', [ ];
187  if ($^O eq 'MSWin32') {
188   load_or_skip_all 'Socket', '0', [ ];
189  }
190
191  return (
192   capture      => \&capture,
193   capture_perl => \&capture_perl,
194  );
195 }
196
197 # Inspired from IPC::Cmd
198
199 sub capture {
200  my @cmd = @_;
201
202  my $want = wantarray;
203
204  my $fail = sub {
205   my $err     = $!;
206   my $ext_err = $^O eq 'MSWin32' ? $^E : undef;
207
208   my $syscall = shift;
209   my $args    = join ', ', @_;
210
211   my $msg = "$syscall($args) failed: ";
212
213   if (defined $err) {
214    no warnings 'numeric';
215    my ($err_code, $err_str) = (int $err, "$err");
216    $msg .= "$err_str ($err_code)";
217   }
218
219   if (defined $ext_err) {
220    no warnings 'numeric';
221    my ($ext_err_code, $ext_err_str) = (int $ext_err, "$ext_err");
222    $msg .= ", $ext_err_str ($ext_err_code)";
223   }
224
225   die "$msg\n";
226  };
227
228  my ($status, $content_out, $content_err);
229
230  local $@;
231  my $ok = eval {
232   my ($pid, $out, $err);
233
234   if ($^O eq 'MSWin32') {
235    my $pipe = sub {
236     socketpair $_[0], $_[1],
237                &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC
238                       or $fail->(qw<socketpair reader writer>);
239     shutdown $_[0], 1 or $fail->(qw<shutdown reader>);
240     shutdown $_[1], 0 or $fail->(qw<shutdown writer>);
241     return 1;
242    };
243    local (*IN_R,  *IN_W);
244    local (*OUT_R, *OUT_W);
245    local (*ERR_R, *ERR_W);
246    $pipe->(*IN_R,  *IN_W);
247    $pipe->(*OUT_R, *OUT_W);
248    $pipe->(*ERR_R, *ERR_W);
249
250    $pid = IPC::Open3::open3('>&IN_R', '<&OUT_W', '<&ERR_W', @cmd);
251
252    close *IN_W or $fail->(qw<close input>);
253    $out = *OUT_R;
254    $err = *ERR_R;
255   } else {
256    my $in = IO::Handle->new;
257    $out   = IO::Handle->new;
258    $out->autoflush(1);
259    $err   = IO::Handle->new;
260    $err->autoflush(1);
261
262    $pid = IPC::Open3::open3($in, $out, $err, @cmd);
263
264    close $in;
265   }
266
267   # Forward signals to the child (except SIGKILL)
268   my %sig_handlers;
269   foreach my $s (keys %SIG) {
270    $sig_handlers{$s} = sub {
271     kill "$s" => $pid;
272     $SIG{$s} = $sig_handlers{$s};
273    };
274   }
275   local $SIG{$_} = $sig_handlers{$_} for keys %SIG;
276
277   unless ($want) {
278    close $out or $fail->(qw<close output>);
279    close $err or $fail->(qw<close error>);
280    waitpid $pid, 0;
281    $status = $?;
282    return 1;
283   }
284
285   my $sel = IO::Select->new();
286   $sel->add($out, $err);
287
288   my $fd_out = fileno $out;
289   my $fd_err = fileno $err;
290
291   my %contents;
292   $contents{$fd_out} = '';
293   $contents{$fd_err} = '';
294
295   while (my @ready = $sel->can_read) {
296    for my $fh (@ready) {
297     my $buf;
298     my $bytes_read = sysread $fh, $buf, 4096;
299     if (not defined $bytes_read) {
300      $fail->('sysread', 'fd(' . fileno($fh) . ')');
301     } elsif ($bytes_read) {
302      $contents{fileno($fh)} .= $buf;
303     } else {
304      $sel->remove($fh);
305      close $fh or $fail->('close', 'fd(' . fileno($fh) . ')');
306      last unless $sel->count;
307     }
308    }
309   }
310
311   waitpid $pid, 0;
312   $status = $?;
313
314   if ($^O eq 'MSWin32') {
315    # Manual CRLF translation that couldn't be done with sysread.
316    s/\x0D\x0A/\n/g for values %contents;
317   }
318
319   $content_out = $contents{$fd_out};
320   $content_err = $contents{$fd_err};
321
322   1;
323  };
324
325  if ($ok) {
326   return ($status, $content_out, $content_err);
327  } else {
328   my $err = $@;
329   chomp $err;
330   return (undef, $err);
331  }
332 }
333
334 sub capture_perl {
335  my $code = shift;
336
337  if ($code =~ /"/) {
338   die 'Double quotes in evaluated code are not portable';
339  }
340
341  fresh_perl_env {
342   my @perl = @_;
343   capture @perl, '-e', $code;
344  };
345 }
346
347 sub init_threads {
348  my ($pkg, $threadsafe, $force_var) = @_;
349
350  skip_all 'This perl wasn\'t built to support threads'
351                                             unless $Config::Config{useithreads};
352
353  $pkg = 'package' unless defined $pkg;
354  skip_all "This $pkg isn't thread safe" if defined $threadsafe and !$threadsafe;
355
356  $force_var = 'PERL_FORCE_TEST_THREADS' unless defined $force_var;
357  my $force  = $ENV{$force_var} ? 1 : !1;
358  skip_all 'perl 5.13.4 required to test thread safety'
359                                              unless $force or "$]" >= 5.013_004;
360
361  if (($INC{'Test/More.pm'} || $INC{'Test/Leaner.pm'}) && !$INC{'threads.pm'}) {
362   die 'Test::More/Test::Leaner was loaded too soon';
363  }
364
365  load_or_skip_all 'threads',         $force ? '0' : '1.67', [ ];
366  load_or_skip_all 'threads::shared', $force ? '0' : '1.14', [ ];
367
368  require Test::Leaner;
369
370  diag "Threads testing forced by \$ENV{$force_var}" if $force;
371
372  return spawn => \&spawn;
373 }
374
375 sub init_usleep {
376  my $usleep;
377
378  if (do { local $@; eval { require Time::HiRes; 1 } }) {
379   defined and diag "Using usleep() from Time::HiRes $_"
380                                                       for $Time::HiRes::VERSION;
381   $usleep = \&Time::HiRes::usleep;
382  } else {
383   diag 'Using fallback usleep()';
384   $usleep = sub {
385    my $s = int($_[0] / 2.5e5);
386    sleep $s if $s;
387   };
388  }
389
390  return usleep => $usleep;
391 }
392
393 sub spawn {
394  local $@;
395  my @diag;
396  my $thread = eval {
397   local $SIG{__WARN__} = sub { push @diag, "Thread creation warning: @_" };
398   threads->create(@_);
399  };
400  push @diag, "Thread creation error: $@" if $@;
401  diag @diag;
402  return $thread ? $thread : ();
403 }
404
405 package VPIT::TestHelpers::Guard;
406
407 sub new {
408  my ($class, $code) = @_;
409
410  bless { code => $code }, $class;
411 }
412
413 sub DESTROY { $_[0]->{code}->() }
414
415 1;