]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - t/lib/VPIT/TestHelpers.pm
Update VPIT::TestHelpers to f24eb57f
[perl/modules/Variable-Magic.git] / t / lib / VPIT / TestHelpers.pm
1 package VPIT::TestHelpers;
2
3 use strict;
4 use warnings;
5
6 use Config ();
7
8 =head1 NAME
9
10 VPIT::TestHelpers
11
12 =head1 SYNTAX
13
14     use VPIT::TestHelpers (
15      feature1 => \@feature1_args,
16      feature2 => \@feature2_args,
17     );
18
19 =cut
20
21 sub export_to_pkg {
22  my ($subs, $pkg) = @_;
23
24  while (my ($name, $code) = each %$subs) {
25   no strict 'refs';
26   *{$pkg.'::'.$name} = $code;
27  }
28
29  return 1;
30 }
31
32 sub sanitize_prefix {
33  my $prefix = shift;
34
35  if (defined $prefix) {
36   if (length $prefix and $prefix !~ /_$/) {
37    $prefix .= '_';
38   }
39  } else {
40   $prefix = '';
41  }
42
43  return $prefix;
44 }
45
46 my %default_exports = (
47  load_or_skip     => \&load_or_skip,
48  load_or_skip_all => \&load_or_skip_all,
49  skip_all         => \&skip_all,
50 );
51
52 my %features = (
53  threads  => \&init_threads,
54  usleep   => \&init_usleep,
55  run_perl => \&init_run_perl,
56  capture  => \&init_capture,
57 );
58
59 sub import {
60  shift;
61  my @opts = @_;
62
63  my %exports = %default_exports;
64
65  for (my $i = 0; $i <= $#opts; ++$i) {
66   my $feature = $opts[$i];
67   next unless defined $feature;
68
69   my $args;
70   if ($i < $#opts and defined $opts[$i+1] and ref $opts[$i+1] eq 'ARRAY') {
71    ++$i;
72    $args = $opts[$i];
73   } else {
74    $args = [ ];
75   }
76
77   my $handler = $features{$feature};
78   die "Unknown feature '$feature'" unless defined $handler;
79
80   my %syms = $handler->(@$args);
81
82   $exports{$_} = $syms{$_} for sort keys %syms;
83  }
84
85  export_to_pkg \%exports => scalar caller;
86 }
87
88 my $test_sub = sub {
89  my $sub = shift;
90
91  my $stash;
92  if ($INC{'Test/Leaner.pm'}) {
93   $stash = \%Test::Leaner::;
94  } else {
95   require Test::More;
96   $stash = \%Test::More::;
97  }
98
99  my $glob = $stash->{$sub};
100  return $glob ? *$glob{CODE} : undef;
101 };
102
103 sub skip { $test_sub->('skip')->(@_) }
104
105 sub skip_all { $test_sub->('plan')->(skip_all => $_[0]) }
106
107 sub diag {
108  my $diag = $test_sub->('diag');
109  $diag->($_) for @_;
110 }
111
112 our $TODO;
113 local $TODO;
114
115 sub load {
116  my ($pkg, $ver, $imports) = @_;
117
118  my $spec = $ver && $ver !~ /^[0._]*$/ ? "$pkg $ver" : $pkg;
119  my $err;
120
121  local $@;
122  if (eval "use $spec (); 1") {
123   $ver = do { no strict 'refs'; ${"${pkg}::VERSION"} };
124   $ver = 'undef' unless defined $ver;
125
126   if ($imports) {
127    my @imports = @$imports;
128    my $caller  = (caller 1)[0];
129    local $@;
130    my $res = eval <<"IMPORTER";
131 package
132         $caller;
133 BEGIN { \$pkg->import(\@imports) }
134 1;
135 IMPORTER
136    $err = "Could not import '@imports' from $pkg $ver: $@" unless $res;
137   }
138  } else {
139   (my $file = "$pkg.pm") =~ s{::}{/}g;
140   delete $INC{$file};
141   $err = "Could not load $spec";
142  }
143
144  if ($err) {
145   return wantarray ? (0, $err) : 0;
146  } else {
147   diag "Using $pkg $ver";
148   return 1;
149  }
150 }
151
152 sub load_or_skip {
153  my ($pkg, $ver, $imports, $tests) = @_;
154
155  die 'You must specify how many tests to skip' unless defined $tests;
156
157  my ($loaded, $err) = load($pkg, $ver, $imports);
158  skip $err => $tests unless $loaded;
159
160  return $loaded;
161 }
162
163 sub load_or_skip_all {
164  my ($pkg, $ver, $imports) = @_;
165
166  my ($loaded, $err) = load($pkg, $ver, $imports);
167  skip_all $err unless $loaded;
168
169  return $loaded;
170 }
171
172 =head1 FEATURES
173
174 =head2 C<run_perl>
175
176 =over 4
177
178 =item *
179
180 Import :
181
182     use VPIT::TestHelpers run_perl => [ $p ]
183
184 where :
185
186 =over 8
187
188 =item -
189
190 C<$p> is prefixed to the constants exported by this feature (defaults to C<''>).
191
192 =back
193
194 =item *
195
196 Dependencies : none
197
198 =item *
199
200 Exports :
201
202 =over 8
203
204 =item -
205
206 C<run_perl $code>
207
208 =item -
209
210 C<RUN_PERL_FAILED> (possibly prefixed by C<$p>)
211
212 =back
213
214 =back
215
216 =cut
217
218 sub fresh_perl_env (&) {
219  my $handler = shift;
220
221  my ($SystemRoot, $PATH) = @ENV{qw<SystemRoot PATH>};
222  my $ld_name  = $Config::Config{ldlibpthname};
223  my $ldlibpth = $ENV{$ld_name};
224
225  local %ENV;
226  $ENV{$ld_name}   = $ldlibpth   if                      defined $ldlibpth;
227  $ENV{SystemRoot} = $SystemRoot if $^O eq 'MSWin32' and defined $SystemRoot;
228  $ENV{PATH}       = $PATH       if $^O eq 'cygwin'  and defined $PATH;
229
230  my $perl = $^X;
231  unless (-e $perl and -x $perl) {
232   $perl = $Config::Config{perlpath};
233   unless (-e $perl and -x $perl) {
234    return undef;
235   }
236  }
237
238  return $handler->($perl, '-T', map("-I$_", @INC));
239 }
240
241 sub init_run_perl {
242  my $p = sanitize_prefix(shift);
243
244  return (
245   run_perl              => \&run_perl,
246   "${p}RUN_PERL_FAILED" => sub () { 'Could not execute perl subprocess' },
247  );
248 }
249
250 sub run_perl {
251  my $code = shift;
252
253  if ($code =~ /"/) {
254   die 'Double quotes in evaluated code are not portable';
255  }
256
257  fresh_perl_env {
258   my ($perl, @perl_args) = @_;
259   system { $perl } $perl, @perl_args, '-e', $code;
260  };
261 }
262
263 =head2 C<capture>
264
265 =over 4
266
267 =item *
268
269 Import :
270
271     use VPIT::TestHelpers capture => [ $p ];
272
273 where :
274
275 =over 8
276
277 =item -
278
279 C<$p> is prefixed to the constants exported by this feature (defaults to C<''>).
280
281 =back
282
283 =item *
284
285 Dependencies :
286
287 =over 8
288
289 =item -
290
291 Not VMS
292
293 =item -
294
295 L<IO::Handle>, L<IO::Select>, L<IPC::Open3>
296
297 =item -
298
299 On MSWin32 : L<Socket>
300
301 =back
302
303 =item *
304
305 Exports :
306
307 =over 8
308
309 =item -
310
311 C<capture @command>
312
313 =item -
314
315 C<CAPTURE_FAILED $details> (possibly prefixed by C<$p>)
316
317 =item -
318
319 C<capture_perl $code>
320
321 =item -
322
323 C<CAPTURE_PERL_FAILED $details> (possibly prefixed by C<$p>)
324
325 =back
326
327 =back
328
329 =cut
330
331 sub init_capture {
332  my $p = sanitize_prefix(shift);
333
334  skip_all 'Cannot capture output on VMS' if $^O eq 'VMS';
335
336  load_or_skip_all 'IO::Handle', '0', [ ];
337  load_or_skip_all 'IO::Select', '0', [ ];
338  load_or_skip_all 'IPC::Open3', '0', [ ];
339  if ($^O eq 'MSWin32') {
340   load_or_skip_all 'Socket', '0', [ ];
341  }
342
343  return (
344   capture                   => \&capture,
345   "${p}CAPTURE_FAILED"      => \&capture_failed_msg,
346   capture_perl              => \&capture_perl,
347   "${p}CAPTURE_PERL_FAILED" => \&capture_perl_failed_msg,
348  );
349 }
350
351 # Inspired from IPC::Cmd
352
353 sub capture {
354  my @cmd = @_;
355
356  my $want = wantarray;
357
358  my $fail = sub {
359   my $err     = $!;
360   my $ext_err = $^O eq 'MSWin32' ? $^E : undef;
361
362   my $syscall = shift;
363   my $args    = join ', ', @_;
364
365   my $msg = "$syscall($args) failed: ";
366
367   if (defined $err) {
368    no warnings 'numeric';
369    my ($err_code, $err_str) = (int $err, "$err");
370    $msg .= "$err_str ($err_code)";
371   }
372
373   if (defined $ext_err) {
374    no warnings 'numeric';
375    my ($ext_err_code, $ext_err_str) = (int $ext_err, "$ext_err");
376    $msg .= ", $ext_err_str ($ext_err_code)";
377   }
378
379   die "$msg\n";
380  };
381
382  my ($status, $content_out, $content_err);
383
384  local $@;
385  my $ok = eval {
386   my ($pid, $out, $err);
387
388   if ($^O eq 'MSWin32') {
389    my $pipe = sub {
390     socketpair $_[0], $_[1],
391                &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC
392                       or $fail->(qw<socketpair reader writer>);
393     shutdown $_[0], 1 or $fail->(qw<shutdown reader>);
394     shutdown $_[1], 0 or $fail->(qw<shutdown writer>);
395     return 1;
396    };
397    local (*IN_R,  *IN_W);
398    local (*OUT_R, *OUT_W);
399    local (*ERR_R, *ERR_W);
400    $pipe->(*IN_R,  *IN_W);
401    $pipe->(*OUT_R, *OUT_W);
402    $pipe->(*ERR_R, *ERR_W);
403
404    $pid = IPC::Open3::open3('>&IN_R', '<&OUT_W', '<&ERR_W', @cmd);
405
406    close *IN_W or $fail->(qw<close input>);
407    $out = *OUT_R;
408    $err = *ERR_R;
409   } else {
410    my $in = IO::Handle->new;
411    $out   = IO::Handle->new;
412    $out->autoflush(1);
413    $err   = IO::Handle->new;
414    $err->autoflush(1);
415
416    $pid = IPC::Open3::open3($in, $out, $err, @cmd);
417
418    close $in;
419   }
420
421   # Forward signals to the child (except SIGKILL)
422   my %sig_handlers;
423   foreach my $s (keys %SIG) {
424    $sig_handlers{$s} = sub {
425     kill "$s" => $pid;
426     $SIG{$s} = $sig_handlers{$s};
427    };
428   }
429   local $SIG{$_} = $sig_handlers{$_} for keys %SIG;
430
431   unless ($want) {
432    close $out or $fail->(qw<close output>);
433    close $err or $fail->(qw<close error>);
434    waitpid $pid, 0;
435    $status = $?;
436    return 1;
437   }
438
439   my $sel = IO::Select->new();
440   $sel->add($out, $err);
441
442   my $fd_out = fileno $out;
443   my $fd_err = fileno $err;
444
445   my %contents;
446   $contents{$fd_out} = '';
447   $contents{$fd_err} = '';
448
449   while (my @ready = $sel->can_read) {
450    for my $fh (@ready) {
451     my $buf;
452     my $bytes_read = sysread $fh, $buf, 4096;
453     if (not defined $bytes_read) {
454      $fail->('sysread', 'fd(' . fileno($fh) . ')');
455     } elsif ($bytes_read) {
456      $contents{fileno($fh)} .= $buf;
457     } else {
458      $sel->remove($fh);
459      close $fh or $fail->('close', 'fd(' . fileno($fh) . ')');
460      last unless $sel->count;
461     }
462    }
463   }
464
465   waitpid $pid, 0;
466   $status = $?;
467
468   if ($^O eq 'MSWin32') {
469    # Manual CRLF translation that couldn't be done with sysread.
470    s/\x0D\x0A/\n/g for values %contents;
471   }
472
473   $content_out = $contents{$fd_out};
474   $content_err = $contents{$fd_err};
475
476   1;
477  };
478
479  if ($ok) {
480   return ($status, $content_out, $content_err);
481  } else {
482   my $err = $@;
483   chomp $err;
484   return (undef, $err);
485  }
486 }
487
488 sub capture_failed_msg {
489  my $details = shift;
490
491  my $msg = 'Could not capture command output';
492  $msg   .= " ($details)" if defined $details;
493
494  return $msg;
495 }
496
497 sub capture_perl {
498  my $code = shift;
499
500  if ($code =~ /"/) {
501   die 'Double quotes in evaluated code are not portable';
502  }
503
504  fresh_perl_env {
505   my @perl = @_;
506   capture @perl, '-e', $code;
507  };
508 }
509
510 sub capture_perl_failed_msg {
511  my $details = shift;
512
513  my $msg = 'Could not capture perl output';
514  $msg   .= " ($details)" if defined $details;
515
516  return $msg;
517 }
518
519 =head2 C<threads>
520
521 =over 4
522
523 =item *
524
525 Import :
526
527     use VPIT::TestHelpers threads => [
528      $pkg, $is_threadsafe, $force_var
529     ];
530
531 where :
532
533 =over 8
534
535 =item -
536
537 C<$pkg> is the target package name to be used in error messages (defaults to C<'package'>) ;
538
539 =item -
540
541 C<$is_threadsafe> is a boolean telling whether the target module is thread-safe (not tested if C<undef>) ;
542
543 =item -
544
545 C<$force_var> is the name of the environment variable that can be used to force the thread tests (defaults to C<PERL_FORCE_TEST_THREADS>).
546
547 =back
548
549 =item *
550
551 Dependencies :
552
553 =over 8
554
555 =item -
556
557 C<perl> 5.13.4
558
559 =item -
560
561 L<threads> 1.67
562
563 =item -
564
565 L<threads::shared> 1.14
566
567 =item -
568
569 L<Test::Leaner>
570
571 =back
572
573 =item *
574
575 Exports :
576
577 =over 8
578
579 =item -
580
581 C<spawn $coderef>
582
583 =back
584
585 =back
586
587 =cut
588
589 sub init_threads {
590  my ($pkg, $threadsafe, $force_var) = @_;
591
592  skip_all 'This perl wasn\'t built to support threads'
593                                             unless $Config::Config{useithreads};
594
595  $pkg = 'package' unless defined $pkg;
596  skip_all "This $pkg isn't thread safe" if defined $threadsafe and !$threadsafe;
597
598  $force_var = 'PERL_FORCE_TEST_THREADS' unless defined $force_var;
599  my $force  = $ENV{$force_var} ? 1 : !1;
600  skip_all 'perl 5.13.4 required to test thread safety'
601                                              unless $force or "$]" >= 5.013_004;
602
603  if (($INC{'Test/More.pm'} || $INC{'Test/Leaner.pm'}) && !$INC{'threads.pm'}) {
604   die 'Test::More/Test::Leaner was loaded too soon';
605  }
606
607  load_or_skip_all 'threads',         $force ? '0' : '1.67', [ ];
608  load_or_skip_all 'threads::shared', $force ? '0' : '1.14', [ ];
609
610  require Test::Leaner;
611
612  diag "Threads testing forced by \$ENV{$force_var}" if $force;
613
614  return spawn => \&spawn;
615 }
616
617 sub spawn {
618  local $@;
619  my @diag;
620  my $thread = eval {
621   local $SIG{__WARN__} = sub { push @diag, "Thread creation warning: @_" };
622   threads->create(@_);
623  };
624  push @diag, "Thread creation error: $@" if $@;
625  diag @diag;
626  return $thread ? $thread : ();
627 }
628
629 =head2 C<usleep>
630
631 =over 4
632
633 =item *
634
635 Import :
636
637     use VPIT::TestHelpers 'usleep'
638
639 =item *
640
641 Dependencies : none
642
643 =item *
644
645 Exports :
646
647 =over 8
648
649 =item -
650
651 C<usleep $microseconds>
652
653 =back
654
655 =back
656
657 =cut
658
659 sub init_usleep {
660  my $usleep;
661
662  if (do { local $@; eval { require Time::HiRes; 1 } }) {
663   defined and diag "Using usleep() from Time::HiRes $_"
664                                                       for $Time::HiRes::VERSION;
665   $usleep = \&Time::HiRes::usleep;
666  } else {
667   diag 'Using fallback usleep()';
668   $usleep = sub {
669    my $s = int($_[0] / 1e6);
670    sleep $s if $s;
671   };
672  }
673
674  return usleep => $usleep;
675 }
676
677 =head1 CLASSES
678
679 =head2 C<VPIT::TestHelpers::Guard>
680
681 Syntax :
682
683     {
684      my $guard = VPIT::TestHelpers::Guard->new($coderef);
685      ...
686     } # $codref called here
687
688 =cut
689
690 package VPIT::TestHelpers::Guard;
691
692 sub new {
693  my ($class, $code) = @_;
694
695  bless { code => $code }, $class;
696 }
697
698 sub DESTROY { $_[0]->{code}->() }
699
700 =head1 AUTHOR
701
702 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
703
704 =head1 COPYRIGHT & LICENSE
705
706 Copyright 2012,2013,2014,2015 Vincent Pit, all rights reserved.
707
708 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
709
710 =cut
711
712 1;