1 package VPIT::TestHelpers;
14 use VPIT::TestHelpers (
15 feature1 => \@feature1_args,
16 feature2 => \@feature2_args,
22 my ($subs, $pkg) = @_;
24 while (my ($name, $code) = each %$subs) {
26 *{$pkg.'::'.$name} = $code;
35 if (defined $prefix) {
36 if (length $prefix and $prefix !~ /_$/) {
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,
53 threads => \&init_threads,
54 usleep => \&init_usleep,
55 run_perl => \&init_run_perl,
56 capture => \&init_capture,
63 my %exports = %default_exports;
65 for (my $i = 0; $i <= $#opts; ++$i) {
66 my $feature = $opts[$i];
67 next unless defined $feature;
70 if ($i < $#opts and defined $opts[$i+1] and ref $opts[$i+1] eq 'ARRAY') {
77 my $handler = $features{$feature};
78 die "Unknown feature '$feature'" unless defined $handler;
80 my %syms = $handler->(@$args);
82 $exports{$_} = $syms{$_} for sort keys %syms;
85 export_to_pkg \%exports => scalar caller;
92 if ($INC{'Test/Leaner.pm'}) {
93 $stash = \%Test::Leaner::;
96 $stash = \%Test::More::;
99 my $glob = $stash->{$sub};
100 return $glob ? *$glob{CODE} : undef;
103 sub skip { $test_sub->('skip')->(@_) }
105 sub skip_all { $test_sub->('plan')->(skip_all => $_[0]) }
108 my $diag = $test_sub->('diag');
116 my ($pkg, $ver, $imports) = @_;
118 my $spec = $ver && $ver !~ /^[0._]*$/ ? "$pkg $ver" : $pkg;
122 if (eval "use $spec (); 1") {
123 $ver = do { no strict 'refs'; ${"${pkg}::VERSION"} };
124 $ver = 'undef' unless defined $ver;
127 my @imports = @$imports;
128 my $caller = (caller 1)[0];
130 my $res = eval <<"IMPORTER";
133 BEGIN { \$pkg->import(\@imports) }
136 $err = "Could not import '@imports' from $pkg $ver: $@" unless $res;
139 (my $file = "$pkg.pm") =~ s{::}{/}g;
141 $err = "Could not load $spec";
145 return wantarray ? (0, $err) : 0;
147 diag "Using $pkg $ver";
153 my ($pkg, $ver, $imports, $tests) = @_;
155 die 'You must specify how many tests to skip' unless defined $tests;
157 my ($loaded, $err) = load($pkg, $ver, $imports);
158 skip $err => $tests unless $loaded;
163 sub load_or_skip_all {
164 my ($pkg, $ver, $imports) = @_;
166 my ($loaded, $err) = load($pkg, $ver, $imports);
167 skip_all $err unless $loaded;
182 use VPIT::TestHelpers run_perl => [ $p ]
190 C<$p> is prefixed to the constants exported by this feature (defaults to C<''>).
210 C<RUN_PERL_FAILED> (possibly prefixed by C<$p>)
218 sub fresh_perl_env (&) {
221 my ($SystemRoot, $PATH) = @ENV{qw<SystemRoot PATH>};
222 my $ld_name = $Config::Config{ldlibpthname};
223 my $ldlibpth = $ENV{$ld_name};
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;
231 unless (-e $perl and -x $perl) {
232 $perl = $Config::Config{perlpath};
233 unless (-e $perl and -x $perl) {
238 return $handler->($perl, '-T', map("-I$_", @INC));
242 my $p = sanitize_prefix(shift);
245 run_perl => \&run_perl,
246 "${p}RUN_PERL_FAILED" => sub () { 'Could not execute perl subprocess' },
254 die 'Double quotes in evaluated code are not portable';
258 my ($perl, @perl_args) = @_;
259 system { $perl } $perl, @perl_args, '-e', $code;
271 use VPIT::TestHelpers capture => [ $p ];
279 C<$p> is prefixed to the constants exported by this feature (defaults to C<''>).
295 L<IO::Handle>, L<IO::Select>, L<IPC::Open3>
299 On MSWin32 : L<Socket>
315 C<CAPTURE_FAILED $details> (possibly prefixed by C<$p>)
319 C<capture_perl $code>
323 C<CAPTURE_PERL_FAILED $details> (possibly prefixed by C<$p>)
332 my $p = sanitize_prefix(shift);
334 skip_all 'Cannot capture output on VMS' if $^O eq 'VMS';
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', [ ];
344 capture => \&capture,
345 "${p}CAPTURE_FAILED" => \&capture_failed_msg,
346 capture_perl => \&capture_perl,
347 "${p}CAPTURE_PERL_FAILED" => \&capture_perl_failed_msg,
351 # Inspired from IPC::Cmd
356 my $want = wantarray;
360 my $ext_err = $^O eq 'MSWin32' ? $^E : undef;
363 my $args = join ', ', @_;
365 my $msg = "$syscall($args) failed: ";
368 no warnings 'numeric';
369 my ($err_code, $err_str) = (int $err, "$err");
370 $msg .= "$err_str ($err_code)";
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)";
382 my ($status, $content_out, $content_err);
386 my ($pid, $out, $err);
388 if ($^O eq 'MSWin32') {
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>);
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);
404 $pid = IPC::Open3::open3('>&IN_R', '<&OUT_W', '<&ERR_W', @cmd);
406 close *IN_W or $fail->(qw<close input>);
410 my $in = IO::Handle->new;
411 $out = IO::Handle->new;
413 $err = IO::Handle->new;
416 $pid = IPC::Open3::open3($in, $out, $err, @cmd);
421 # Forward signals to the child (except SIGKILL)
423 foreach my $s (keys %SIG) {
424 $sig_handlers{$s} = sub {
426 $SIG{$s} = $sig_handlers{$s};
429 local $SIG{$_} = $sig_handlers{$_} for keys %SIG;
432 close $out or $fail->(qw<close output>);
433 close $err or $fail->(qw<close error>);
439 my $sel = IO::Select->new();
440 $sel->add($out, $err);
442 my $fd_out = fileno $out;
443 my $fd_err = fileno $err;
446 $contents{$fd_out} = '';
447 $contents{$fd_err} = '';
449 while (my @ready = $sel->can_read) {
450 for my $fh (@ready) {
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;
459 close $fh or $fail->('close', 'fd(' . fileno($fh) . ')');
460 last unless $sel->count;
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;
473 $content_out = $contents{$fd_out};
474 $content_err = $contents{$fd_err};
480 return ($status, $content_out, $content_err);
484 return (undef, $err);
488 sub capture_failed_msg {
491 my $msg = 'Could not capture command output';
492 $msg .= " ($details)" if defined $details;
501 die 'Double quotes in evaluated code are not portable';
506 capture @perl, '-e', $code;
510 sub capture_perl_failed_msg {
513 my $msg = 'Could not capture perl output';
514 $msg .= " ($details)" if defined $details;
527 use VPIT::TestHelpers threads => [
528 $pkg, $threadsafe_var, $force_var
537 C<$pkg> is the target package name that will be exercised by this test ;
541 C<$threadsafe_var> is the name of an optional variable in C<$pkg> that evaluates to true if and only if the module claims to be thread safe (not checked if either C<$threadsafe_var> or C<$pkg> is C<undef>) ;
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>).
569 L<threads::shared> 1.14
590 my ($pkg, $threadsafe_var, $force_var) = @_;
592 skip_all 'This perl wasn\'t built to support threads'
593 unless $Config::Config{useithreads};
595 if (defined $pkg and defined $threadsafe_var) {
597 my $stat = run_perl("require POSIX; require $pkg; exit($threadsafe_var ? POSIX::EXIT_SUCCESS() : POSIX::EXIT_FAILURE())");
600 my $res = $stat >> 8;
601 if ($res == POSIX::EXIT_SUCCESS()) {
603 } elsif ($res == POSIX::EXIT_FAILURE()) {
607 if (not defined $threadsafe) {
608 skip_all "Could not detect if $pkg is thread safe or not";
609 } elsif (not $threadsafe) {
610 skip_all "This $pkg is not thread safe";
614 $force_var = 'PERL_FORCE_TEST_THREADS' unless defined $force_var;
615 my $force = $ENV{$force_var} ? 1 : !1;
616 skip_all 'perl 5.13.4 required to test thread safety'
617 unless $force or "$]" >= 5.013_004;
619 unless ($INC{'threads.pm'}) {
621 if ($INC{'Test/Leaner.pm'}) {
622 $test_module = 'Test::Leaner';
623 } elsif ($INC{'Test/More.pm'}) {
624 $test_module = 'Test::More';
626 die "$test_module was loaded too soon" if defined $test_module;
629 load_or_skip_all 'threads', $force ? '0' : '1.67', [ ];
630 load_or_skip_all 'threads::shared', $force ? '0' : '1.14', [ ];
632 diag "Threads testing forced by \$ENV{$force_var}" if $force;
634 return spawn => \&spawn;
641 local $SIG{__WARN__} = sub { push @diag, "Thread creation warning: @_" };
644 push @diag, "Thread creation error: $@" if $@;
646 return $thread ? $thread : ();
657 use VPIT::TestHelpers 'usleep'
671 C<usleep $microseconds>
682 if (do { local $@; eval { require Time::HiRes; 1 } }) {
683 defined and diag "Using usleep() from Time::HiRes $_"
684 for $Time::HiRes::VERSION;
685 $usleep = \&Time::HiRes::usleep;
687 diag 'Using fallback usleep()';
689 my $s = int($_[0] / 1e6);
694 return usleep => $usleep;
699 =head2 C<VPIT::TestHelpers::Guard>
704 my $guard = VPIT::TestHelpers::Guard->new($coderef);
706 } # $codref called here
710 package VPIT::TestHelpers::Guard;
713 my ($class, $code) = @_;
715 bless { code => $code }, $class;
718 sub DESTROY { $_[0]->{code}->() }
722 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
724 =head1 COPYRIGHT & LICENSE
726 Copyright 2012,2013,2014,2015 Vincent Pit, all rights reserved.
728 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.