2 # t/test.pl - most of Test::More functionality without the fuss
7 # Do not rely on features found only in more modern Perls here, as some CPAN
8 # distributions copy this file and must operate on older Perls. Similarly, keep
9 # things, simple as this may be run under fairly broken circumstances. For
10 # example, increment ($x++) has a certain amount of cleverness for things like
13 # $x++; # $x eq 'aaa';
15 # This stands more chance of breaking than just a simple
19 # In this file, we use the latter "Baby Perl" approach, and increment
20 # will be worked over by t/op/inc.t
26 my $Perl; # Safer version of $^X set by which_perl()
28 # This defines ASCII/UTF-8 vs EBCDIC/UTF-EBCDIC
29 $::IS_ASCII = ord 'A' == 65;
30 $::IS_EBCDIC = ord 'A' == 193;
34 $Tests_Are_Passing = 1;
36 # Use this instead of print to avoid interference while testing globals.
38 local($\, $", $,) = (undef, ' ', '');
43 local($\, $", $,) = (undef, ' ', '');
51 if ($n eq 'no_plan') {
57 $plan{skip_all} and skip_all($plan{skip_all});
60 _print "1..$n\n" unless $noplan;
65 # Set the plan at the end. See Test::More::done_testing.
78 if (defined $planned && $planned != $ran) {
80 "# Looks like you planned $planned tests but ran $ran.\n";
89 my @mess = _comment(@_);
90 $TODO ? _print(@mess) : _print_stderr(@mess);
93 # Use this instead of "print STDERR" when outputting failure diagnostic
99 # Use this instead of "print" when outputting informational messages
102 _print( _comment(@_) );
106 return !defined &DynaLoader::boot_DynaLoader;
110 # Don’t clobber @INC under miniperl
111 @INC = () unless is_miniperl;
116 return map { /^#/ ? "$_\n" : "# $_\n" }
117 map { split /\n/ } @_;
120 sub _have_dynamic_extension {
121 my $extension = shift;
122 unless (eval {require Config; 1}) {
123 warn "test.pl had problems loading Config: $@";
126 $extension =~ s!::!/!g;
127 return 1 if ($Config::Config{extensions} =~ /\b$extension\b/);
132 _print "1..0 # Skip @_\n";
139 sub skip_all_if_miniperl {
140 skip_all(@_) if is_miniperl();
143 sub skip_all_without_dynamic_extension {
144 my ($extension) = @_;
145 skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
146 return if &_have_dynamic_extension;
147 skip_all("$extension was not built");
150 sub skip_all_without_perlio {
151 skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
154 sub skip_all_without_config {
155 unless (eval {require Config; 1}) {
156 warn "test.pl had problems loading Config: $@";
160 next if $Config::Config{$_};
161 my $key = $_; # Need to copy, before trying to modify.
168 sub skip_all_without_unicode_tables { # (but only under miniperl)
170 skip_all_if_miniperl("Unicode tables not built yet")
171 unless eval 'require "unicore/Heavy.pl"';
175 sub find_git_or_skip {
176 my ($source_dir, $reason);
179 } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
180 my $where = readlink 'MANIFEST';
181 die "Can't readling MANIFEST: $!" unless defined $where;
182 die "Confusing symlink target for MANIFEST, '$where'"
183 unless $where =~ s!/MANIFEST\z!!;
184 if (-d "$where/.git") {
185 # Looks like we are in a symlink tree
186 if (exists $ENV{GIT_DIR}) {
187 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it");
189 note("Found source tree at $where, setting \$ENV{GIT_DIR}");
190 $ENV{GIT_DIR} = "$where/.git";
192 $source_dir = $where;
194 } elsif (exists $ENV{GIT_DIR}) {
195 my $commit = '8d063cd8450e59ea1c611a2f4f5a21059a2804f1';
196 my $out = `git rev-parse --verify --quiet '$commit^{commit}'`;
198 if($out eq $commit) {
203 my $version_string = `git --version`;
204 if (defined $version_string
205 && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
206 return $source_dir if eval "v$1 ge v1.5.0";
207 # If you have earlier than 1.5.0 and it works, change this test
208 $reason = "in git checkout, but git version '$1$2' too old";
210 $reason = "in git checkout, but cannot run git";
213 $reason = 'not being run from a git checkout';
215 skip_all($reason) if $_[0] && $_[0] eq 'all';
221 _print("Bail out! $reason\n");
226 my ($pass, $where, $name, @mess) = @_;
227 # Do not try to microoptimize by factoring out the "not ".
231 # escape out '#' or it will interfere with '# skip' and such
233 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
235 $out = $pass ? "ok $test" : "not ok $test";
239 $out = $out . " # TODO $TODO";
241 $Tests_Are_Passing = 0 unless $pass;
247 note @mess; # Ensure that the message is properly escaped.
250 my $msg = "# Failed test $test - ";
251 $msg.= "$name " if $name;
257 $test = $test + 1; # don't use ++
263 my @caller = caller($Level);
264 return "at $caller[1] line $caller[2]";
267 # DON'T use this for matches. Use like() instead.
269 my ($pass, $name, @mess) = @_;
270 _ok($pass, _where(), $name, @mess);
275 return 'undef' unless defined $x;
284 return defined $x ? '"' . display ($x) . '"' : 'undef';
287 # Support pre-5.10 Perls, for the benefit of CPAN dists that copy this file.
288 # Note that chr(90) exists in both ASCII ("Z") and EBCDIC ("!").
289 my $chars_template = defined(eval { pack "W*", 90 }) ? "W*" : "U*";
290 eval 'sub re::is_regexp { ref($_[0]) eq "Regexp" }'
291 if !defined &re::is_regexp;
293 # keys are the codes \n etc map to, values are 2 char strings such as \n
294 my %backslash_escape;
295 foreach my $x (split //, 'nrtfa\\\'"') {
296 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
298 # A way to display scalars containing control characters and Unicode.
299 # Trying to avoid setting $_, or relying on local $_ to work.
303 if (defined $x and not ref $x) {
305 foreach my $c (unpack($chars_template, $x)) {
307 $y = $y . sprintf "\\x{%x}", $c;
308 } elsif ($backslash_escape{$c}) {
309 $y = $y . $backslash_escape{$c};
311 my $z = chr $c; # Maybe we can get away with a literal...
313 if ($z !~ /[^[:^print:][:^ascii:]]/) {
314 # The pattern above is equivalent (by de Morgan's
316 # $z !~ /(?[ [:print:] & [:ascii:] ])/
317 # or, $z is not an ascii printable character
319 # Use octal for characters with small ordinals that
320 # are traditionally expressed as octal: the controls
321 # below space, which on EBCDIC are almost all the
322 # controls, but on ASCII don't include DEL nor the C1
325 $z = sprintf "\\%03o", $c;
327 $z = sprintf "\\x{%x}", $c;
335 return $x unless wantarray;
342 my ($got, $expected, $name, @mess) = @_;
345 if( !defined $got || !defined $expected ) {
346 # undef only matches undef
347 $pass = !defined $got && !defined $expected;
350 $pass = $got eq $expected;
354 unshift(@mess, "# got "._qq($got)."\n",
355 "# expected "._qq($expected)."\n");
357 _ok($pass, _where(), $name, @mess);
361 my ($got, $isnt, $name, @mess) = @_;
364 if( !defined $got || !defined $isnt ) {
365 # undef only matches undef
366 $pass = defined $got || defined $isnt;
369 $pass = $got ne $isnt;
373 unshift(@mess, "# it should not be "._qq($got)."\n",
376 _ok($pass, _where(), $name, @mess);
380 my($got, $type, $expected, $name, @mess) = @_;
385 local($@,$!); # don't interfere with $@
386 # eval() sometimes resets $!
387 $pass = eval "\$got $type \$expected";
390 # It seems Irix long doubles can have 2147483648 and 2147483648
391 # that stringify to the same thing but are actually numerically
392 # different. Display the numbers if $type isn't a string operator,
393 # and the numbers are stringwise the same.
394 # (all string operators have alphabetic names, so tr/a-z// is true)
395 # This will also show numbers for some unneeded cases, but will
396 # definitely be helpful for things such as == and <= that fail
397 if ($got eq $expected and $type !~ tr/a-z//) {
398 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
400 unshift(@mess, "# got "._qq($got)."\n",
401 "# expected $type "._qq($expected)."\n");
403 _ok($pass, _where(), $name, @mess);
406 # Check that $got is within $range of $expected
407 # if $range is 0, then check it's exact
408 # else if $expected is 0, then $range is an absolute value
409 # otherwise $range is a fractional error.
410 # Here $range must be numeric, >= 0
411 # Non numeric ranges might be a useful future extension. (eg %)
413 my ($got, $expected, $range, $name, @mess) = @_;
415 if (!defined $got or !defined $expected or !defined $range) {
416 # This is a fail, but doesn't need extra diagnostics
417 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
419 unshift @mess, "# got, expected and range must be numeric\n";
420 } elsif ($range < 0) {
421 # This is also a fail
422 unshift @mess, "# range must not be negative\n";
423 } elsif ($range == 0) {
425 $pass = $got == $expected;
426 } elsif ($expected == 0) {
427 # If expected is 0, treat range as absolute
428 $pass = ($got <= $range) && ($got >= - $range);
430 my $diff = $got - $expected;
431 $pass = abs ($diff / $expected) < $range;
434 if ($got eq $expected) {
435 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
437 unshift@mess, "# got "._qq($got)."\n",
438 "# expected "._qq($expected)." (within "._qq($range).")\n";
440 _ok($pass, _where(), $name, @mess);
443 # Note: this isn't quite as fancy as Test::More::like().
445 sub like ($$@) { like_yn (0,@_) }; # 0 for -
446 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
449 my ($flip, undef, $expected, $name, @mess) = @_;
451 # We just accept like(..., qr/.../), not like(..., '...'), and
452 # definitely not like(..., '/.../') like
453 # Test::Builder::maybe_regex() does.
454 unless (re::is_regexp($expected)) {
455 die "PANIC: The value '$expected' isn't a regexp. The like() function needs a qr// pattern, not a string";
459 $pass = $_[1] =~ /$expected/ if !$flip;
460 $pass = $_[1] !~ /$expected/ if $flip;
461 my $display_got = $_[1];
462 $display_got = display($display_got);
463 my $display_expected = $expected;
464 $display_expected = display($display_expected);
466 unshift(@mess, "# got '$display_got'\n",
468 ? "# expected !~ /$display_expected/\n"
469 : "# expected /$display_expected/\n");
471 local $Level = $Level + 1;
472 _ok($pass, _where(), $name, @mess);
480 _ok(0, _where(), @_);
490 $test = $test + 1; # don't use ++
494 # Note: can't pass multipart messages since we try to
495 # be compatible with Test::More::skip().
498 my $n = @_ ? shift : 1;
503 $bad_swap = $why > 0 && $n == 0;
504 $both_zero = $why == 0 && $n == 0;
506 if ($bad_swap || $both_zero || @_) {
507 my $arg = "'$why', '$n'";
509 $arg .= join(", ", '', map { qq['$_'] } @_);
511 die qq[$0: expected skip(why, count), got skip($arg)\n];
514 _print "ok $test # skip $why\n";
521 sub skip_if_miniperl {
522 skip(@_) if is_miniperl();
525 sub skip_without_dynamic_extension {
526 my $extension = shift;
527 skip("no dynamic loading on miniperl, no extension $extension", @_)
529 return if &_have_dynamic_extension($extension);
530 skip("extension $extension was not built", @_);
535 my $n = @_ ? shift : 1;
538 _print "not ok $test # TODO & SKIP $why\n";
547 return 0 unless $#$ra == $#$rb;
548 for my $i (0..$#$ra) {
549 next if !defined $ra->[$i] && !defined $rb->[$i];
550 return 0 if !defined $ra->[$i];
551 return 0 if !defined $rb->[$i];
552 return 0 unless $ra->[$i] eq $rb->[$i];
558 my ($orig, $suspect) = @_;
560 while (my ($key, $value) = each %$suspect) {
561 # Force a hash recompute if this perl's internals can cache the hash key.
563 if (exists $orig->{$key}) {
565 defined $orig->{$key} != defined $value
566 || (defined $value && $orig->{$key} ne $value)
568 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
569 " now ", _qq($value), "\n";
573 _print "# key ", _qq($key), " is ", _qq($value),
574 ", not in original.\n";
578 foreach (keys %$orig) {
579 # Force a hash recompute if this perl's internals can cache the hash key.
581 next if (exists $suspect->{$_});
582 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
588 # We only provide a subset of the Test::More functionality.
591 if ($require =~ tr/[A-Za-z0-9:.]//c) {
592 fail("Invalid character in \"$require\", passed to require_ok");
597 is($@, '', _where(), "require $require");
603 if ($use =~ tr/[A-Za-z0-9:.]//c) {
604 fail("Invalid character in \"$use\", passed to use");
609 is($@, '', _where(), "use $use");
613 # runperl - Runs a separate perl interpreter and returns its output.
615 # switches => [ command-line switches ]
616 # nolib => 1 # don't use -I../lib (included by default)
617 # non_portable => Don't warn if a one liner contains quotes
618 # prog => one-liner (avoid quotes)
619 # progs => [ multi-liner (avoid quotes) ]
620 # progfile => perl script
621 # stdin => string to feed the stdin (or undef to redirect from /dev/null)
622 # stderr => If 'devnull' suppresses stderr, if other TRUE value redirect
624 # args => [ command-line arguments to the perl program ]
625 # verbose => print the command line
627 my $is_mswin = $^O eq 'MSWin32';
628 my $is_netware = $^O eq 'NetWare';
629 my $is_vms = $^O eq 'VMS';
630 my $is_cygwin = $^O eq 'cygwin';
633 my ($runperl, $args) = @_;
636 # In VMS protect with doublequotes because otherwise
637 # DCL will lowercase -- unless already doublequoted.
638 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
639 $runperl = $runperl . ' ' . $_;
644 sub _create_runperl { # Create the string to qx in runperl().
646 my $runperl = which_perl();
647 if ($runperl =~ m/\s/) {
648 $runperl = qq{"$runperl"};
650 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
651 if ($ENV{PERL_RUNPERL_DEBUG}) {
652 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
654 unless ($args{nolib}) {
655 $runperl = $runperl . ' "-I../lib" "-I." '; # doublequotes because of VMS
657 if ($args{switches}) {
659 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
660 unless ref $args{switches} eq "ARRAY";
661 $runperl = _quote_args($runperl, $args{switches});
663 if (defined $args{prog}) {
664 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
665 if defined $args{progs};
666 $args{progs} = [split /\n/, $args{prog}, -1]
668 if (defined $args{progs}) {
669 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
670 unless ref $args{progs} eq "ARRAY";
671 foreach my $prog (@{$args{progs}}) {
672 if (!$args{non_portable}) {
673 if ($prog =~ tr/'"//) {
674 warn "quotes in prog >>$prog<< are not portable";
676 if ($prog =~ /^([<>|]|2>)/) {
677 warn "Initial $1 in prog >>$prog<< is not portable";
679 if ($prog =~ /&\z/) {
680 warn "Trailing & in prog >>$prog<< is not portable";
683 if ($is_mswin || $is_netware || $is_vms) {
684 $runperl = $runperl . qq ( -e "$prog" );
687 $runperl = $runperl . qq ( -e '$prog' );
690 } elsif (defined $args{progfile}) {
691 $runperl = $runperl . qq( "$args{progfile}");
693 # You probably didn't want to be sucking in from the upstream stdin
694 die "test.pl:runperl(): none of prog, progs, progfile, args, "
695 . " switches or stdin specified"
696 unless defined $args{args} or defined $args{switches}
697 or defined $args{stdin};
699 if (defined $args{stdin}) {
700 # so we don't try to put literal newlines and crs onto the
702 $args{stdin} =~ s/\n/\\n/g;
703 $args{stdin} =~ s/\r/\\r/g;
705 if ($is_mswin || $is_netware || $is_vms) {
706 $runperl = qq{$Perl -e "print qq(} .
707 $args{stdin} . q{)" | } . $runperl;
710 $runperl = qq{$Perl -e 'print qq(} .
711 $args{stdin} . q{)' | } . $runperl;
713 } elsif (exists $args{stdin}) {
714 # Using the pipe construction above can cause fun on systems which use
715 # ksh as /bin/sh, as ksh does pipes differently (with one less process)
716 # With sh, for the command line 'perl -e 'print qq()' | perl -e ...'
717 # the sh process forks two children, which use exec to start the two
718 # perl processes. The parent shell process persists for the duration of
719 # the pipeline, and the second perl process starts with no children.
720 # With ksh (and zsh), the shell saves a process by forking a child for
721 # just the first perl process, and execing itself to start the second.
722 # This means that the second perl process starts with one child which
723 # it didn't create. This causes "fun" when if the tests assume that
724 # wait (or waitpid) will only return information about processes
725 # started within the test.
726 # They also cause fun on VMS, where the pipe implementation returns
727 # the exit code of the process at the front of the pipeline, not the
728 # end. This messes up any test using OPTION FATAL.
729 # Hence it's useful to have a way to make STDIN be at eof without
730 # needing a pipeline, so that the fork tests have a sane environment
731 # without these surprises.
733 # /dev/null appears to be surprisingly portable.
734 $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null');
736 if (defined $args{args}) {
737 $runperl = _quote_args($runperl, $args{args});
739 if (exists $args{stderr} && $args{stderr} eq 'devnull') {
740 $runperl = $runperl . ($is_mswin ? ' 2>nul' : ' 2>/dev/null');
742 elsif ($args{stderr}) {
743 $runperl = $runperl . ' 2>&1';
745 if ($args{verbose}) {
746 my $runperldisplay = $runperl;
747 $runperldisplay =~ s/\n/\n\#/g;
748 _print_stderr "# $runperldisplay\n";
753 # sub run_perl {} is alias to below
755 die "test.pl:runperl() does not take a hashref"
756 if ref $_[0] and ref $_[0] eq 'HASH';
757 my $runperl = &_create_runperl;
760 my $tainted = ${^TAINT};
762 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
765 # We will assume that if you're running under -T, you really mean to
766 # run a fresh perl, so we'll brute force launder everything for you
769 if (! eval {require Config; 1}) {
770 warn "test.pl had problems loading Config: $@";
773 $sep = $Config::Config{path_sep};
776 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
777 local @ENV{@keys} = ();
778 # Untaint, plus take out . and empty string:
779 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
780 $ENV{PATH} =~ /(.*)/s;
782 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
783 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
784 split quotemeta ($sep), $1;
785 if ($is_cygwin) { # Must have /bin under Cygwin
786 if (length $ENV{PATH}) {
787 $ENV{PATH} = $ENV{PATH} . $sep;
789 $ENV{PATH} = $ENV{PATH} . '/bin';
794 $result = `$runperl`;
796 $result = `$runperl`;
798 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
803 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
806 _print_stderr "# @_\n";
810 # A somewhat safer version of the sometimes wrong $^X.
812 unless (defined $Perl) {
815 # VMS should have 'perl' aliased properly
816 return $Perl if $is_vms;
819 if (! eval {require Config; 1}) {
820 warn "test.pl had problems loading Config: $@";
823 $exe = $Config::Config{_exe};
825 $exe = '' unless defined $exe;
827 # This doesn't absolutize the path: beware of future chdirs().
828 # We could do File::Spec->abs2rel() but that does getcwd()s,
829 # which is a bit heavyweight to do here.
831 if ($Perl =~ /^perl\Q$exe\E$/i) {
832 my $perl = "perl$exe";
833 if (! eval {require File::Spec; 1}) {
834 warn "test.pl had problems loading File::Spec: $@";
837 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
841 # Build up the name of the executable file from the name of
844 if ($Perl !~ /\Q$exe\E$/i) {
845 $Perl = $Perl . $exe;
848 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
850 # For subcommands to use.
851 $ENV{PERLEXE} = $Perl;
858 foreach my $file (@_) {
859 1 while unlink $file;
861 _print_stderr "# Couldn't unlink '$file': $!\n";
869 # _num_to_alpha - Returns a string of letters representing a positive integer.
872 # maximum number of letters
874 # returns undef if the number is negative
875 # returns undef if the number of letters is greater than the maximum wanted
877 # _num_to_alpha( 0) eq 'A';
878 # _num_to_alpha( 1) eq 'B';
879 # _num_to_alpha(25) eq 'Z';
880 # _num_to_alpha(26) eq 'AA';
881 # _num_to_alpha(27) eq 'AB';
883 my @letters = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);
885 # Avoid ++ -- ranges split negative numbers
887 my($num,$max_char) = @_;
888 return unless $num >= 0;
891 $max_char = 0 if $max_char < 0;
894 $alpha = $letters[ $num % 26 ] . $alpha;
895 $num = int( $num / 26 );
900 next unless $max_char;
901 $char_count = $char_count + 1;
902 return if $char_count == $max_char;
908 END { unlink_all keys %tmpfiles }
910 # A regexp that matches the tempfile names
911 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
913 # Avoid ++, avoid ranges, avoid split //
914 my $tempfile_count = 0;
918 my $alpha = _num_to_alpha($tempfile_count,2);
919 last unless defined $alpha;
920 $try = $try . $alpha;
921 $tempfile_count = $tempfile_count + 1;
923 # Need to note all the file names we allocated, as a second request may
924 # come before the first is created.
925 if (!$tmpfiles{$try} && !-e $try) {
931 die "Can't find temporary file name starting \"tmp$$\"";
934 # register_tempfile - Adds a list of files to be removed at the end of the current test file
936 # a list of files to be removed later
938 # returns a count of how many file names were actually added
940 # Reuses %tmpfiles so that tempfile() will also skip any files added here
941 # even if the file doesn't exist yet.
943 sub register_tempfile {
947 _print_stderr "# Temporary file '$_' already added\n";
956 # This is the temporary file for fresh_perl
957 my $tmpfile = tempfile();
960 my($prog, $runperl_args) = @_;
962 # Run 'runperl' with the complete perl program contained in '$prog', and
963 # arguments in the hash referred to by '$runperl_args'. The results are
964 # returned, with $? set to the exit code. Unless overridden, stderr is
965 # redirected to stdout.
967 die sprintf "Third argument to fresh_perl_.* must be hashref of args to fresh_perl (or {})"
968 unless !(defined $runperl_args) || ref($runperl_args) eq 'HASH';
970 # Given the choice of the mis-parsable {}
971 # (we want an anon hash, but a borked lexer might think that it's a block)
972 # or relying on taking a reference to a lexical
973 # (\ might be mis-parsed, and the reference counting on the pad may go
975 # it feels like the least-worse thing is to assume that auto-vivification
976 # works. At least, this is only going to be a run-time failure, so won't
977 # affect tests using this file but not this function.
978 $runperl_args->{progfile} ||= $tmpfile;
979 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
981 open TEST, '>', $tmpfile or die "Cannot open $tmpfile: $!";
983 close TEST or die "Cannot close $tmpfile: $!";
985 my $results = runperl(%$runperl_args);
986 my $status = $?; # Not necessary to save this, but it makes it clear to
987 # future maintainers.
989 # Clean up the results into something a bit more predictable.
990 $results =~ s/\n+$//;
991 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
992 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
994 # bison says 'parse error' instead of 'syntax error',
995 # various yaccs may or may not capitalize 'syntax'.
996 $results =~ s/^(syntax|parse) error/syntax error/mig;
999 # some tests will trigger VMS messages that won't be expected
1000 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1002 # pipes double these sometimes
1003 $results =~ s/\n\n/\n/g;
1012 my($prog, $action, $expect, $runperl_args, $name) = @_;
1014 my $results = fresh_perl($prog, $runperl_args);
1017 # Use the first line of the program as a name if none was given
1019 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
1020 $name = $name . '...' if length $first_line > length $name;
1023 # Historically this was implemented using a closure, but then that means
1024 # that the tests for closures avoid using this code. Given that there
1025 # are exactly two callers, doing exactly two things, the simpler approach
1026 # feels like a better trade off.
1028 if ($action eq 'eq') {
1029 $pass = is($results, $expect, $name);
1030 } elsif ($action eq '=~') {
1031 $pass = like($results, $expect, $name);
1033 die "_fresh_perl can't process action '$action'";
1037 _diag "# PROG: \n$prog\n";
1038 _diag "# STATUS: $status\n";
1047 # Combination of run_perl() and is().
1051 my($prog, $expected, $runperl_args, $name) = @_;
1053 # _fresh_perl() is going to clip the trailing newlines off the result.
1054 # This will make it so the test author doesn't have to know that.
1055 $expected =~ s/\n+$//;
1058 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
1064 # Combination of run_perl() and like().
1067 sub fresh_perl_like {
1068 my($prog, $expected, $runperl_args, $name) = @_;
1070 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
1073 # Many tests use the same format in __DATA__ or external files to specify a
1074 # sequence of (fresh) tests to run, extra files they may temporarily need, and
1075 # what the expected output is. Putting it here allows common code to serve
1076 # these multiple tests.
1078 # Each program is source code to run followed by an "EXPECT" line, followed
1079 # by the expected output.
1081 # The first line of the code to run may be a command line switch such as -wE
1082 # or -0777 (alphanumerics only; only one cluster, beginning with a minus is
1083 # allowed). Later lines may contain (note the '# ' on each):
1084 # # TODO reason for todo
1085 # # SKIP reason for skip
1086 # # SKIP ?code to test if this should be skipped
1087 # # NAME name of the test (as with ok($ok, $name))
1089 # The expected output may contain:
1090 # OPTION list of options
1091 # OPTIONS list of options
1093 # The possible options for OPTION may be:
1094 # regex - the expected output is a regular expression
1095 # random - all lines match but in any order
1096 # fatal - the code will fail fatally (croak, die)
1098 # If the actual output contains a line "SKIPPED" the test will be
1101 # If the actual output contains a line "PREFIX", any output starting with that
1102 # line will be ignored when comparing with the expected output
1104 # If the global variable $FATAL is true then OPTION fatal is the
1107 sub _setup_one_file {
1109 # Store the filename as a program that started at line 0.
1110 # Real files count lines starting at line 1.
1111 my @these = (0, shift);
1112 my ($lineno, $current);
1114 if ($_ eq "########\n") {
1115 if (defined $current) {
1116 push @these, $lineno, $current;
1120 if (!defined $current) {
1126 if (defined $current) {
1127 push @these, $lineno, $current;
1129 ((scalar @these) / 2 - 1, @these);
1132 sub setup_multiple_progs {
1134 foreach my $file (@_) {
1135 next if $file =~ /(?:~|\.orig|,v)$/;
1136 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1139 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1147 # This is an internal error, and should never happen. All bar one of
1148 # the files had an __END__ marker to signal the end of their preamble,
1149 # although for some it wasn't technically necessary as they have no
1150 # tests. It might be possible to process files without an __END__ by
1151 # seeking back to the start and treating the whole file as tests, but
1152 # it's simpler and more reliable just to make the rule that all files
1153 # must have __END__ in. This should never fail - a file without an
1154 # __END__ should not have been checked in, because the regression tests
1155 # would not have passed.
1156 die "Could not find '__END__' in $file"
1159 my ($t, @p) = _setup_one_file($fh, $file);
1164 or die "Cannot close $file: $!\n";
1166 return ($tests, @prgs);
1169 sub run_multiple_progs {
1173 # The tests in lib run in a temporary subdirectory of t, and always
1174 # pass in a list of "programs" to run
1177 # The tests below t run in t and pass in a file handle. In theory we
1178 # can pass (caller)[1] as the second argument to report errors with
1179 # the filename of our caller, as the handle is always DATA. However,
1180 # line numbers in DATA count from the __END__ token, so will be wrong.
1181 # Which is more confusing than not providing line numbers. So, for now,
1182 # don't provide line numbers. No obvious clean solution - one hack
1183 # would be to seek DATA back to the start and read to the __END__ token,
1184 # but that feels almost like we should just open $0 instead.
1186 # Not going to rely on undef in list assignment.
1188 ($dummy, @prgs) = _setup_one_file(shift);
1191 my $tmpfile = tempfile();
1195 while (defined ($line = shift @prgs)) {
1199 if (defined $file) {
1200 print "# From $file\n";
1207 if (s/^(\s*-\w+)//) {
1210 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1213 foreach my $what (qw(skip todo)) {
1214 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1215 # If the SKIP reason starts ? then it's taken as a code snippet to
1216 # evaluate. This provides the flexibility to have conditional SKIPs
1217 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1218 my $temp = eval $reason{$what};
1220 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1222 $reason{$what} = $temp;
1227 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1231 if ($reason{skip}) {
1234 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1239 if ($prog =~ /--FILE--/) {
1240 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1242 die "Internal error: test $_ didn't split into pairs, got " .
1243 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1245 while (@files > 2) {
1246 my $filename = shift @files;
1247 my $code = shift @files;
1248 push @temps, $filename;
1249 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1251 File::Path::mkpath($1);
1252 push(@temp_path, $1);
1254 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1256 close $fh or die "Cannot close $filename: $!\n";
1259 $prog = shift @files;
1262 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1266 open STDERR, '>&', STDOUT
1267 or die "Can't dup STDOUT->STDERR: $!;";
1270 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1271 print $fh $prog,"\n";
1272 close $fh or die "Cannot close $tmpfile: $!";
1273 my $results = runperl( stderr => 1, progfile => $tmpfile,
1275 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1276 : (switches => [$switch])
1279 $results =~ s/\n+$//;
1280 # allow expected output to be written as if $prog is on STDIN
1281 $results =~ s/$::tempfile_regexp/-/g;
1283 # some tests will trigger VMS messages that won't be expected
1284 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1286 # pipes double these sometimes
1287 $results =~ s/\n\n/\n/g;
1289 # bison says 'parse error' instead of 'syntax error',
1290 # various yaccs may or may not capitalize 'syntax'.
1291 $results =~ s/^(syntax|parse) error/syntax error/mig;
1292 # allow all tests to run when there are leaks
1293 $results =~ s/Scalars leaked: \d+\n//g;
1295 $expected =~ s/\n+$//;
1296 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1297 # any special options? (OPTIONS foo bar zap)
1298 my $option_regex = 0;
1299 my $option_random = 0;
1301 if ($expected =~ s/^OPTIONS? (.+)\n//) {
1302 foreach my $option (split(' ', $1)) {
1303 if ($option eq 'regex') { # allow regular expressions
1306 elsif ($option eq 'random') { # all lines match, but in any order
1309 elsif ($option eq 'fatal') { # perl should fail
1313 die "$0: Unknown OPTION '$option'\n";
1317 die "$0: can't have OPTION regex and random\n"
1318 if $option_regex + $option_random > 1;
1320 if ($results =~ s/^SKIPPED\n//) {
1321 print "$results\n" ;
1325 if ($option_random) {
1326 my @got = sort split "\n", $results;
1327 my @expected = sort split "\n", $expected;
1329 $ok = "@got" eq "@expected";
1331 elsif ($option_regex) {
1332 $ok = $results =~ /^$expected/;
1335 $ok = $results =~ /^\Q$expected/;
1338 $ok = $results eq $expected;
1341 if ($ok && $fatal && !($status >> 8)) {
1346 local $::TODO = $reason{todo};
1349 my $err_line = "PROG: $switch\n$prog\n" .
1350 "EXPECTED:\n$expected\n";
1351 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1352 $err_line .= "GOT:\n$results\n";
1353 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1355 $err_line =~ s/^/# /mg;
1356 print $err_line; # Harness can't filter it out from STDERR.
1359 print STDERR $err_line;
1363 if (defined $file) {
1364 _ok($ok, "at $file line $line", $name);
1366 # We don't have file and line number data for the test, so report
1367 # errors as coming from our caller.
1368 local $Level = $Level + 1;
1375 foreach (@temp_path) {
1376 File::Path::rmtree $_ if -d $_;
1382 my($proto, @methods) = @_;
1383 my $class = ref $proto || $proto;
1385 unless( @methods ) {
1386 return _ok( 0, _where(), "$class->can(...)" );
1390 foreach my $method (@methods) {
1391 local($!, $@); # don't interfere with caller's $@
1392 # eval sometimes resets $!
1393 eval { $proto->can($method) } || push @nok, $method;
1397 $name = @methods == 1 ? "$class->can('$methods[0]')"
1398 : "$class->can(...)";
1400 _ok( !@nok, _where(), $name );
1404 # Call $class->new( @$args ); and run the result through object_ok.
1405 # See Test::More::new_ok
1407 my($class, $args, $obj_name) = @_;
1409 $object_name = "The object" unless defined $obj_name;
1411 local $Level = $Level + 1;
1414 my $ok = eval { $obj = $class->new(@$args); 1 };
1418 object_ok($obj, $class, $object_name);
1421 ok( 0, "new() died" );
1422 diag("Error was: $@");
1431 my($object, $class, $obj_name) = @_;
1434 $obj_name = 'The object' unless defined $obj_name;
1435 my $name = "$obj_name isa $class";
1436 if( !defined $object ) {
1437 $diag = "$obj_name isn't defined";
1440 my $whatami = ref $object ? 'object' : 'class';
1442 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1443 local($@, $!); # eval sometimes resets $!
1444 my $rslt = eval { $object->isa($class) };
1445 my $error = $@; # in case something else blows away $@
1448 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1449 # It's an unblessed reference
1450 $obj_name = 'The reference' unless defined $obj_name;
1451 if( !UNIVERSAL::isa($object, $class) ) {
1452 my $ref = ref $object;
1453 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1456 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1457 # It's something that can't even be a class
1458 $obj_name = 'The thing' unless defined $obj_name;
1459 $diag = "$obj_name isn't a class or reference";
1463 WHOA! I tried to call ->isa on your object and got some weird error.
1464 This should never happen. Please contact the author immediately.
1471 $obj_name = "The $whatami" unless defined $obj_name;
1472 my $ref = ref $object;
1473 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1477 _ok( !$diag, _where(), $name );
1482 my($class, $isa, $class_name) = @_;
1484 # Written so as to count as one test
1485 local $Level = $Level + 1;
1487 ok( 0, "$class is a reference, not a class name" );
1490 isa_ok($class, $isa, $class_name);
1496 my($obj, $isa, $obj_name) = @_;
1498 local $Level = $Level + 1;
1500 ok( 0, "$obj is not a reference" );
1503 isa_ok($obj, $isa, $obj_name);
1508 # Purposefully avoiding a closure.
1510 push @::__capture, join "", @_;
1513 sub capture_warnings {
1517 local $SIG {__WARN__} = \&__capture;
1519 return @::__capture;
1522 # This will generate a variable number of tests.
1523 # Use done_testing() instead of a fixed plan.
1525 my ($code, $expect, $name) = @_;
1526 local $Level = $Level + 1;
1528 my @w = capture_warnings($code);
1530 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1531 foreach my $e (@$expect) {
1533 like(shift @w, $e, $name);
1535 is(shift @w, $e, $name);
1539 diag("Saw these additional warnings:");
1540 diag($_) foreach @w;
1544 sub _fail_excess_warnings {
1545 my($expect, $got, $name) = @_;
1546 local $Level = $Level + 1;
1547 # This will fail, and produce diagnostics
1548 is($expect, scalar @$got, $name);
1549 diag("Saw these warnings:");
1550 diag($_) foreach @$got;
1554 my ($code, $expect, $name) = @_;
1555 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1557 local $Level = $Level + 1;
1558 my @w = capture_warnings($code);
1560 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1562 is($w[0], $expect, $name);
1567 my ($code, $expect, $name) = @_;
1568 die sprintf "Expect must be a regexp object"
1569 unless ref $expect eq 'Regexp';
1570 local $Level = $Level + 1;
1571 my @w = capture_warnings($code);
1573 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1575 like($w[0], $expect, $name);
1579 # Set a watchdog to timeout the entire test file
1580 # NOTE: If the test file uses 'threads', then call the watchdog() function
1581 # _AFTER_ the 'threads' module is loaded.
1584 my $timeout = shift;
1585 my $method = shift || "";
1586 my $timeout_msg = 'Test process timed out - terminating';
1588 # Valgrind slows perl way down so give it more time before dying.
1589 $timeout *= 10 if $ENV{PERL_VALGRIND};
1591 my $pid_to_kill = $$; # PID for this process
1593 if ($method eq "alarm") {
1594 goto WATCHDOG_VIA_ALARM;
1597 # shut up use only once warning
1598 my $threads_on = $threads::threads && $threads::threads;
1600 # Don't use a watchdog process if 'threads' is loaded -
1601 # use a watchdog thread instead
1602 if (!$threads_on || $method eq "process") {
1604 # On Windows and VMS, try launching a watchdog process
1605 # using system(1, ...) (see perlport.pod)
1606 if ($is_mswin || $is_vms) {
1607 # On Windows, try to get the 'real' PID
1609 eval { require Win32; };
1610 if (defined(&Win32::GetCurrentProcessId)) {
1611 $pid_to_kill = Win32::GetCurrentProcessId();
1615 # If we still have a fake PID, we can't use this method at all
1616 return if ($pid_to_kill <= 0);
1618 # Launch watchdog process
1621 local $SIG{'__WARN__'} = sub {
1622 _diag("Watchdog warning: $_[0]");
1624 my $sig = $is_vms ? 'TERM' : 'KILL';
1625 my $prog = "sleep($timeout);" .
1626 "warn qq/# $timeout_msg" . '\n/;' .
1627 "kill(q/$sig/, $pid_to_kill);";
1629 # On Windows use the indirect object plus LIST form to guarantee
1630 # that perl is launched directly rather than via the shell (see
1631 # perlfunc.pod), and ensure that the LIST has multiple elements
1632 # since the indirect object plus COMMANDSTRING form seems to
1633 # hang (see perl #121283). Don't do this on VMS, which doesn't
1634 # support the LIST form at all.
1636 my $runperl = which_perl();
1637 if ($runperl =~ m/\s/) {
1638 $runperl = qq{"$runperl"};
1640 $watchdog = system({ $runperl } 1, $runperl, '-e', $prog);
1643 my $cmd = _create_runperl(prog => $prog);
1644 $watchdog = system(1, $cmd);
1647 if ($@ || ($watchdog <= 0)) {
1648 _diag('Failed to start watchdog');
1654 # Add END block to parent to terminate and
1655 # clean up watchdog process
1656 eval("END { local \$! = 0; local \$? = 0;
1657 wait() if kill('KILL', $watchdog); };");
1661 # Try using fork() to generate a watchdog process
1663 eval { $watchdog = fork() };
1664 if (defined($watchdog)) {
1665 if ($watchdog) { # Parent process
1666 # Add END block to parent to terminate and
1667 # clean up watchdog process
1668 eval "END { local \$! = 0; local \$? = 0;
1669 wait() if kill('KILL', $watchdog); };";
1673 ### Watchdog process code
1675 # Load POSIX if available
1676 eval { require POSIX; };
1678 # Execute the timeout
1679 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1682 # Kill test process if still running
1683 if (kill(0, $pid_to_kill)) {
1684 _diag($timeout_msg);
1685 kill('KILL', $pid_to_kill);
1687 # sometimes the above isn't enough on cygwin
1688 sleep 1; # wait a little, it might have worked after all
1689 system("/bin/kill -f $pid_to_kill");
1693 # Don't execute END block (added at beginning of this file)
1696 # Terminate ourself (i.e., the watchdog)
1697 POSIX::_exit(1) if (defined(&POSIX::_exit));
1701 # fork() failed - fall through and try using a thread
1704 # Use a watchdog thread because either 'threads' is loaded,
1706 if (eval {require threads; 1}) {
1707 'threads'->create(sub {
1708 # Load POSIX if available
1709 eval { require POSIX; };
1711 # Execute the timeout
1712 my $time_left = $timeout;
1714 $time_left = $time_left - sleep($time_left);
1715 } while ($time_left > 0);
1717 # Kill the parent (and ourself)
1718 select(STDERR); $| = 1;
1719 _diag($timeout_msg);
1720 POSIX::_exit(1) if (defined(&POSIX::_exit));
1721 my $sig = $is_vms ? 'TERM' : 'KILL';
1722 kill($sig, $pid_to_kill);
1727 # If everything above fails, then just use an alarm timeout
1729 if (eval { alarm($timeout); 1; }) {
1730 # Load POSIX if available
1731 eval { require POSIX; };
1733 # Alarm handler will do the actual 'killing'
1734 $SIG{'ALRM'} = sub {
1735 select(STDERR); $| = 1;
1736 _diag($timeout_msg);
1737 POSIX::_exit(1) if (defined(&POSIX::_exit));
1738 my $sig = $is_vms ? 'TERM' : 'KILL';
1739 kill($sig, $pid_to_kill);