2 # t/test.pl - most of Test::More functionality without the fuss, plus
3 # has mappings native_to_latin1 and latin1_to_native so that fewer tests
4 # on non ASCII-ish platforms need to be skipped
9 # Increment ($x++) has a certain amount of cleverness for things like
12 # $x++; # $x eq 'aaa';
14 # stands more chance of breaking than just a simple
18 # In this file, we use the latter "Baby Perl" approach, and increment
19 # will be worked over by t/op/inc.t
25 my $Perl; # Safer version of $^X set by which_perl()
27 # This defines ASCII/UTF-8 vs EBCDIC/UTF-EBCDIC
28 $::IS_ASCII = ord 'A' == 65;
29 $::IS_EBCDIC = ord 'A' == 193;
33 $Tests_Are_Passing = 1;
35 # Use this instead of print to avoid interference while testing globals.
37 local($\, $", $,) = (undef, ' ', '');
42 local($\, $", $,) = (undef, ' ', '');
50 if ($n eq 'no_plan') {
56 $plan{skip_all} and skip_all($plan{skip_all});
59 _print "1..$n\n" unless $noplan;
64 # Set the plan at the end. See Test::More::done_testing.
77 if (defined $planned && $planned != $ran) {
79 "# Looks like you planned $planned tests but ran $ran.\n";
88 my @mess = _comment(@_);
89 $TODO ? _print(@mess) : _print_stderr(@mess);
92 # Use this instead of "print STDERR" when outputting failure diagnostic
98 # Use this instead of "print" when outputting informational messages
101 _print( _comment(@_) );
105 return !defined &DynaLoader::boot_DynaLoader;
109 return map { /^#/ ? "$_\n" : "# $_\n" }
110 map { split /\n/ } @_;
113 sub _have_dynamic_extension {
114 my $extension = shift;
115 unless (eval {require Config; 1}) {
116 warn "test.pl had problems loading Config: $@";
119 $extension =~ s!::!/!g;
120 return 1 if ($Config::Config{extensions} =~ /\b$extension\b/);
125 _print "1..0 # Skip @_\n";
132 sub skip_all_if_miniperl {
133 skip_all(@_) if is_miniperl();
136 sub skip_all_without_dynamic_extension {
137 my ($extension) = @_;
138 skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
139 return if &_have_dynamic_extension;
140 skip_all("$extension was not built");
143 sub skip_all_without_perlio {
144 skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
147 sub skip_all_without_config {
148 unless (eval {require Config; 1}) {
149 warn "test.pl had problems loading Config: $@";
153 next if $Config::Config{$_};
154 my $key = $_; # Need to copy, before trying to modify.
161 sub find_git_or_skip {
162 my ($source_dir, $reason);
165 } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
166 my $where = readlink 'MANIFEST';
167 die "Can't readling MANIFEST: $!" unless defined $where;
168 die "Confusing symlink target for MANIFEST, '$where'"
169 unless $where =~ s!/MANIFEST\z!!;
170 if (-d "$where/.git") {
171 # Looks like we are in a symlink tree
172 if (exists $ENV{GIT_DIR}) {
173 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it");
175 note("Found source tree at $where, setting \$ENV{GIT_DIR}");
176 $ENV{GIT_DIR} = "$where/.git";
178 $source_dir = $where;
180 } elsif (exists $ENV{GIT_DIR}) {
181 my $commit = '8d063cd8450e59ea1c611a2f4f5a21059a2804f1';
182 my $out = `git rev-parse --verify --quiet '$commit^{commit}'`;
184 if($out eq $commit) {
189 my $version_string = `git --version`;
190 if (defined $version_string
191 && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
192 return $source_dir if eval "v$1 ge v1.5.0";
193 # If you have earlier than 1.5.0 and it works, change this test
194 $reason = "in git checkout, but git version '$1$2' too old";
196 $reason = "in git checkout, but cannot run git";
199 $reason = 'not being run from a git checkout';
201 skip_all($reason) if $_[0] && $_[0] eq 'all';
207 _print("Bail out! $reason\n");
212 my ($pass, $where, $name, @mess) = @_;
213 # Do not try to microoptimize by factoring out the "not ".
217 # escape out '#' or it will interfere with '# skip' and such
219 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
221 $out = $pass ? "ok $test" : "not ok $test";
225 $out = $out . " # TODO $TODO";
227 $Tests_Are_Passing = 0 unless $pass;
233 note @mess; # Ensure that the message is properly escaped.
236 my $msg = "# Failed test $test - ";
237 $msg.= "$name " if $name;
243 $test = $test + 1; # don't use ++
249 my @caller = caller($Level);
250 return "at $caller[1] line $caller[2]";
253 # DON'T use this for matches. Use like() instead.
255 my ($pass, $name, @mess) = @_;
256 _ok($pass, _where(), $name, @mess);
261 return 'undef' unless defined $x;
270 return defined $x ? '"' . display ($x) . '"' : 'undef';
273 # keys are the codes \n etc map to, values are 2 char strings such as \n
274 my %backslash_escape;
275 foreach my $x (split //, 'nrtfa\\\'"') {
276 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
278 # A way to display scalars containing control characters and Unicode.
279 # Trying to avoid setting $_, or relying on local $_ to work.
283 if (defined $x and not ref $x) {
285 foreach my $c (unpack("U*", $x)) {
287 $y = $y . sprintf "\\x{%x}", $c;
288 } elsif ($backslash_escape{$c}) {
289 $y = $y . $backslash_escape{$c};
291 my $z = chr $c; # Maybe we can get away with a literal...
292 if ($z =~ /[[:^print:]]/) {
294 # Use octal for characters traditionally expressed as
295 # such: the low controls, which on EBCDIC aren't
296 # necessarily the same ones as on ASCII platforms, but
297 # are small ordinals, nonetheless
299 $z = sprintf "\\%03o", $c;
301 $z = sprintf "\\x{%x}", $c;
309 return $x unless wantarray;
316 my ($got, $expected, $name, @mess) = @_;
319 if( !defined $got || !defined $expected ) {
320 # undef only matches undef
321 $pass = !defined $got && !defined $expected;
324 $pass = $got eq $expected;
328 unshift(@mess, "# got "._qq($got)."\n",
329 "# expected "._qq($expected)."\n");
331 _ok($pass, _where(), $name, @mess);
335 my ($got, $isnt, $name, @mess) = @_;
338 if( !defined $got || !defined $isnt ) {
339 # undef only matches undef
340 $pass = defined $got || defined $isnt;
343 $pass = $got ne $isnt;
347 unshift(@mess, "# it should not be "._qq($got)."\n",
350 _ok($pass, _where(), $name, @mess);
354 my($got, $type, $expected, $name, @mess) = @_;
359 local($@,$!); # don't interfere with $@
360 # eval() sometimes resets $!
361 $pass = eval "\$got $type \$expected";
364 # It seems Irix long doubles can have 2147483648 and 2147483648
365 # that stringify to the same thing but are actually numerically
366 # different. Display the numbers if $type isn't a string operator,
367 # and the numbers are stringwise the same.
368 # (all string operators have alphabetic names, so tr/a-z// is true)
369 # This will also show numbers for some unneeded cases, but will
370 # definitely be helpful for things such as == and <= that fail
371 if ($got eq $expected and $type !~ tr/a-z//) {
372 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
374 unshift(@mess, "# got "._qq($got)."\n",
375 "# expected $type "._qq($expected)."\n");
377 _ok($pass, _where(), $name, @mess);
380 # Check that $got is within $range of $expected
381 # if $range is 0, then check it's exact
382 # else if $expected is 0, then $range is an absolute value
383 # otherwise $range is a fractional error.
384 # Here $range must be numeric, >= 0
385 # Non numeric ranges might be a useful future extension. (eg %)
387 my ($got, $expected, $range, $name, @mess) = @_;
389 if (!defined $got or !defined $expected or !defined $range) {
390 # This is a fail, but doesn't need extra diagnostics
391 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
393 unshift @mess, "# got, expected and range must be numeric\n";
394 } elsif ($range < 0) {
395 # This is also a fail
396 unshift @mess, "# range must not be negative\n";
397 } elsif ($range == 0) {
399 $pass = $got == $expected;
400 } elsif ($expected == 0) {
401 # If expected is 0, treat range as absolute
402 $pass = ($got <= $range) && ($got >= - $range);
404 my $diff = $got - $expected;
405 $pass = abs ($diff / $expected) < $range;
408 if ($got eq $expected) {
409 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
411 unshift@mess, "# got "._qq($got)."\n",
412 "# expected "._qq($expected)." (within "._qq($range).")\n";
414 _ok($pass, _where(), $name, @mess);
417 # Note: this isn't quite as fancy as Test::More::like().
419 sub like ($$@) { like_yn (0,@_) }; # 0 for -
420 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
423 my ($flip, undef, $expected, $name, @mess) = @_;
425 # We just accept like(..., qr/.../), not like(..., '...'), and
426 # definitely not like(..., '/.../') like
427 # Test::Builder::maybe_regex() does.
428 unless (re::is_regexp($expected)) {
429 die "PANIC: The value '$expected' isn't a regexp. The like() function needs a qr// pattern, not a string";
433 $pass = $_[1] =~ /$expected/ if !$flip;
434 $pass = $_[1] !~ /$expected/ if $flip;
436 unshift(@mess, "# got '$_[1]'\n",
438 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
440 local $Level = $Level + 1;
441 _ok($pass, _where(), $name, @mess);
449 _ok(0, _where(), @_);
459 $test = $test + 1; # don't use ++
463 # Note: can't pass multipart messages since we try to
464 # be compatible with Test::More::skip().
467 my $n = @_ ? shift : 1;
469 _print "ok $test # skip $why\n";
476 sub skip_if_miniperl {
477 skip(@_) if is_miniperl();
480 sub skip_without_dynamic_extension {
481 my ($extension) = @_;
482 skip("no dynamic loading on miniperl, no $extension") if is_miniperl();
483 return if &_have_dynamic_extension;
484 skip("$extension was not built");
489 my $n = @_ ? shift : 1;
492 _print "not ok $test # TODO & SKIP $why\n";
501 return 0 unless $#$ra == $#$rb;
502 for my $i (0..$#$ra) {
503 next if !defined $ra->[$i] && !defined $rb->[$i];
504 return 0 if !defined $ra->[$i];
505 return 0 if !defined $rb->[$i];
506 return 0 unless $ra->[$i] eq $rb->[$i];
512 my ($orig, $suspect) = @_;
514 while (my ($key, $value) = each %$suspect) {
515 # Force a hash recompute if this perl's internals can cache the hash key.
517 if (exists $orig->{$key}) {
519 defined $orig->{$key} != defined $value
520 || (defined $value && $orig->{$key} ne $value)
522 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
523 " now ", _qq($value), "\n";
527 _print "# key ", _qq($key), " is ", _qq($value),
528 ", not in original.\n";
532 foreach (keys %$orig) {
533 # Force a hash recompute if this perl's internals can cache the hash key.
535 next if (exists $suspect->{$_});
536 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
542 # We only provide a subset of the Test::More functionality.
545 if ($require =~ tr/[A-Za-z0-9:.]//c) {
546 fail("Invalid character in \"$require\", passed to require_ok");
551 is($@, '', _where(), "require $require");
557 if ($use =~ tr/[A-Za-z0-9:.]//c) {
558 fail("Invalid character in \"$use\", passed to use");
563 is($@, '', _where(), "use $use");
567 # runperl - Runs a separate perl interpreter and returns its output.
569 # switches => [ command-line switches ]
570 # nolib => 1 # don't use -I../lib (included by default)
571 # non_portable => Don't warn if a one liner contains quotes
572 # prog => one-liner (avoid quotes)
573 # progs => [ multi-liner (avoid quotes) ]
574 # progfile => perl script
575 # stdin => string to feed the stdin (or undef to redirect from /dev/null)
576 # stderr => If 'devnull' suppresses stderr, if other TRUE value redirect
578 # args => [ command-line arguments to the perl program ]
579 # verbose => print the command line
581 my $is_mswin = $^O eq 'MSWin32';
582 my $is_netware = $^O eq 'NetWare';
583 my $is_vms = $^O eq 'VMS';
584 my $is_cygwin = $^O eq 'cygwin';
587 my ($runperl, $args) = @_;
590 # In VMS protect with doublequotes because otherwise
591 # DCL will lowercase -- unless already doublequoted.
592 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
593 $runperl = $runperl . ' ' . $_;
598 sub _create_runperl { # Create the string to qx in runperl().
600 my $runperl = which_perl();
601 if ($runperl =~ m/\s/) {
602 $runperl = qq{"$runperl"};
604 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
605 if ($ENV{PERL_RUNPERL_DEBUG}) {
606 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
608 unless ($args{nolib}) {
609 $runperl = $runperl . ' "-I../lib"'; # doublequotes because of VMS
611 if ($args{switches}) {
613 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
614 unless ref $args{switches} eq "ARRAY";
615 $runperl = _quote_args($runperl, $args{switches});
617 if (defined $args{prog}) {
618 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
619 if defined $args{progs};
620 $args{progs} = [$args{prog}]
622 if (defined $args{progs}) {
623 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
624 unless ref $args{progs} eq "ARRAY";
625 foreach my $prog (@{$args{progs}}) {
626 if (!$args{non_portable}) {
627 if ($prog =~ tr/'"//) {
628 warn "quotes in prog >>$prog<< are not portable";
630 if ($prog =~ /^([<>|]|2>)/) {
631 warn "Initial $1 in prog >>$prog<< is not portable";
633 if ($prog =~ /&\z/) {
634 warn "Trailing & in prog >>$prog<< is not portable";
637 if ($is_mswin || $is_netware || $is_vms) {
638 $runperl = $runperl . qq ( -e "$prog" );
641 $runperl = $runperl . qq ( -e '$prog' );
644 } elsif (defined $args{progfile}) {
645 $runperl = $runperl . qq( "$args{progfile}");
647 # You probably didn't want to be sucking in from the upstream stdin
648 die "test.pl:runperl(): none of prog, progs, progfile, args, "
649 . " switches or stdin specified"
650 unless defined $args{args} or defined $args{switches}
651 or defined $args{stdin};
653 if (defined $args{stdin}) {
654 # so we don't try to put literal newlines and crs onto the
656 $args{stdin} =~ s/\n/\\n/g;
657 $args{stdin} =~ s/\r/\\r/g;
659 if ($is_mswin || $is_netware || $is_vms) {
660 $runperl = qq{$Perl -e "print qq(} .
661 $args{stdin} . q{)" | } . $runperl;
664 $runperl = qq{$Perl -e 'print qq(} .
665 $args{stdin} . q{)' | } . $runperl;
667 } elsif (exists $args{stdin}) {
668 # Using the pipe construction above can cause fun on systems which use
669 # ksh as /bin/sh, as ksh does pipes differently (with one less process)
670 # With sh, for the command line 'perl -e 'print qq()' | perl -e ...'
671 # the sh process forks two children, which use exec to start the two
672 # perl processes. The parent shell process persists for the duration of
673 # the pipeline, and the second perl process starts with no children.
674 # With ksh (and zsh), the shell saves a process by forking a child for
675 # just the first perl process, and execing itself to start the second.
676 # This means that the second perl process starts with one child which
677 # it didn't create. This causes "fun" when if the tests assume that
678 # wait (or waitpid) will only return information about processes
679 # started within the test.
680 # They also cause fun on VMS, where the pipe implementation returns
681 # the exit code of the process at the front of the pipeline, not the
682 # end. This messes up any test using OPTION FATAL.
683 # Hence it's useful to have a way to make STDIN be at eof without
684 # needing a pipeline, so that the fork tests have a sane environment
685 # without these surprises.
687 # /dev/null appears to be surprisingly portable.
688 $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null');
690 if (defined $args{args}) {
691 $runperl = _quote_args($runperl, $args{args});
693 if (exists $args{stderr} && $args{stderr} eq 'devnull') {
694 $runperl = $runperl . ($is_mswin ? ' 2>nul' : ' 2>/dev/null');
696 elsif ($args{stderr}) {
697 $runperl = $runperl . ' 2>&1';
699 if ($args{verbose}) {
700 my $runperldisplay = $runperl;
701 $runperldisplay =~ s/\n/\n\#/g;
702 _print_stderr "# $runperldisplay\n";
708 die "test.pl:runperl() does not take a hashref"
709 if ref $_[0] and ref $_[0] eq 'HASH';
710 my $runperl = &_create_runperl;
713 my $tainted = ${^TAINT};
715 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
718 # We will assume that if you're running under -T, you really mean to
719 # run a fresh perl, so we'll brute force launder everything for you
722 if (! eval {require Config; 1}) {
723 warn "test.pl had problems loading Config: $@";
726 $sep = $Config::Config{path_sep};
729 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
730 local @ENV{@keys} = ();
731 # Untaint, plus take out . and empty string:
732 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
733 $ENV{PATH} =~ /(.*)/s;
735 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
736 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
737 split quotemeta ($sep), $1;
738 if ($is_cygwin) { # Must have /bin under Cygwin
739 if (length $ENV{PATH}) {
740 $ENV{PATH} = $ENV{PATH} . $sep;
742 $ENV{PATH} = $ENV{PATH} . '/bin';
747 $result = `$runperl`;
749 $result = `$runperl`;
751 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
756 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
759 _print_stderr "# @_\n";
763 # A somewhat safer version of the sometimes wrong $^X.
765 unless (defined $Perl) {
768 # VMS should have 'perl' aliased properly
769 return $Perl if $is_vms;
772 if (! eval {require Config; 1}) {
773 warn "test.pl had problems loading Config: $@";
776 $exe = $Config::Config{_exe};
778 $exe = '' unless defined $exe;
780 # This doesn't absolutize the path: beware of future chdirs().
781 # We could do File::Spec->abs2rel() but that does getcwd()s,
782 # which is a bit heavyweight to do here.
784 if ($Perl =~ /^perl\Q$exe\E$/i) {
785 my $perl = "perl$exe";
786 if (! eval {require File::Spec; 1}) {
787 warn "test.pl had problems loading File::Spec: $@";
790 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
794 # Build up the name of the executable file from the name of
797 if ($Perl !~ /\Q$exe\E$/i) {
798 $Perl = $Perl . $exe;
801 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
803 # For subcommands to use.
804 $ENV{PERLEXE} = $Perl;
811 foreach my $file (@_) {
812 1 while unlink $file;
814 _print_stderr "# Couldn't unlink '$file': $!\n";
822 # _num_to_alpha - Returns a string of letters representing a positive integer.
825 # maximum number of letters
827 # returns undef if the number is negative
828 # returns undef if the number of letters is greater than the maximum wanted
830 # _num_to_alpha( 0) eq 'A';
831 # _num_to_alpha( 1) eq 'B';
832 # _num_to_alpha(25) eq 'Z';
833 # _num_to_alpha(26) eq 'AA';
834 # _num_to_alpha(27) eq 'AB';
836 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);
838 # Avoid ++ -- ranges split negative numbers
840 my($num,$max_char) = @_;
841 return unless $num >= 0;
844 $max_char = 0 if $max_char < 0;
847 $alpha = $letters[ $num % 26 ] . $alpha;
848 $num = int( $num / 26 );
853 next unless $max_char;
854 $char_count = $char_count + 1;
855 return if $char_count == $max_char;
861 END { unlink_all keys %tmpfiles }
863 # A regexp that matches the tempfile names
864 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
866 # Avoid ++, avoid ranges, avoid split //
867 my $tempfile_count = 0;
871 my $alpha = _num_to_alpha($tempfile_count,2);
872 last unless defined $alpha;
873 $try = $try . $alpha;
874 $tempfile_count = $tempfile_count + 1;
876 # Need to note all the file names we allocated, as a second request may
877 # come before the first is created.
878 if (!$tmpfiles{$try} && !-e $try) {
884 die "Can't find temporary file name starting \"tmp$$\"";
887 # register_tempfile - Adds a list of files to be removed at the end of the current test file
889 # a list of files to be removed later
891 # returns a count of how many file names were actually added
893 # Reuses %tmpfiles so that tempfile() will also skip any files added here
894 # even if the file doesn't exist yet.
896 sub register_tempfile {
900 _print_stderr "# Temporary file '$_' already added\n";
909 # This is the temporary file for _fresh_perl
910 my $tmpfile = tempfile();
913 my($prog, $action, $expect, $runperl_args, $name) = @_;
915 # Given the choice of the mis-parsable {}
916 # (we want an anon hash, but a borked lexer might think that it's a block)
917 # or relying on taking a reference to a lexical
918 # (\ might be mis-parsed, and the reference counting on the pad may go
920 # it feels like the least-worse thing is to assume that auto-vivification
921 # works. At least, this is only going to be a run-time failure, so won't
922 # affect tests using this file but not this function.
923 $runperl_args->{progfile} ||= $tmpfile;
924 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
926 open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
928 close TEST or die "Cannot close $tmpfile: $!";
930 my $results = runperl(%$runperl_args);
933 # Clean up the results into something a bit more predictable.
934 $results =~ s/\n+$//;
935 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
936 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
938 # bison says 'parse error' instead of 'syntax error',
939 # various yaccs may or may not capitalize 'syntax'.
940 $results =~ s/^(syntax|parse) error/syntax error/mig;
943 # some tests will trigger VMS messages that won't be expected
944 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
946 # pipes double these sometimes
947 $results =~ s/\n\n/\n/g;
950 # Use the first line of the program as a name if none was given
952 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
953 $name = $name . '...' if length $first_line > length $name;
956 # Historically this was implemented using a closure, but then that means
957 # that the tests for closures avoid using this code. Given that there
958 # are exactly two callers, doing exactly two things, the simpler approach
959 # feels like a better trade off.
961 if ($action eq 'eq') {
962 $pass = is($results, $expect, $name);
963 } elsif ($action eq '=~') {
964 $pass = like($results, $expect, $name);
966 die "_fresh_perl can't process action '$action'";
970 _diag "# PROG: \n$prog\n";
971 _diag "# STATUS: $status\n";
980 # Combination of run_perl() and is().
984 my($prog, $expected, $runperl_args, $name) = @_;
986 # _fresh_perl() is going to clip the trailing newlines off the result.
987 # This will make it so the test author doesn't have to know that.
988 $expected =~ s/\n+$//;
991 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
997 # Combination of run_perl() and like().
1000 sub fresh_perl_like {
1001 my($prog, $expected, $runperl_args, $name) = @_;
1003 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
1006 # Many tests use the same format in __DATA__ or external files to specify a
1007 # sequence of (fresh) tests to run, extra files they may temporarily need, and
1008 # what the expected output is. Putting it here allows common code to serve
1009 # these multiple tests.
1011 # Each program is source code to run followed by an "EXPECT" line, followed
1012 # by the expected output.
1014 # The code to run may begin with a command line switch such as -w or -0777
1015 # (alphanumerics only), and may contain (note the '# ' on each):
1016 # # TODO reason for todo
1017 # # SKIP reason for skip
1018 # # SKIP ?code to test if this should be skipped
1019 # # NAME name of the test (as with ok($ok, $name))
1021 # The expected output may contain:
1022 # OPTION list of options
1023 # OPTIONS list of options
1025 # The possible options for OPTION may be:
1026 # regex - the expected output is a regular expression
1027 # random - all lines match but in any order
1028 # fatal - the code will fail fatally (croak, die)
1030 # If the actual output contains a line "SKIPPED" the test will be
1033 # If the actual output contains a line "PREFIX", any output starting with that
1034 # line will be ignored when comparing with the expected output
1036 # If the global variable $FATAL is true then OPTION fatal is the
1039 sub _setup_one_file {
1041 # Store the filename as a program that started at line 0.
1042 # Real files count lines starting at line 1.
1043 my @these = (0, shift);
1044 my ($lineno, $current);
1046 if ($_ eq "########\n") {
1047 if (defined $current) {
1048 push @these, $lineno, $current;
1052 if (!defined $current) {
1058 if (defined $current) {
1059 push @these, $lineno, $current;
1061 ((scalar @these) / 2 - 1, @these);
1064 sub setup_multiple_progs {
1066 foreach my $file (@_) {
1067 next if $file =~ /(?:~|\.orig|,v)$/;
1068 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1071 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1079 # This is an internal error, and should never happen. All bar one of
1080 # the files had an __END__ marker to signal the end of their preamble,
1081 # although for some it wasn't technically necessary as they have no
1082 # tests. It might be possible to process files without an __END__ by
1083 # seeking back to the start and treating the whole file as tests, but
1084 # it's simpler and more reliable just to make the rule that all files
1085 # must have __END__ in. This should never fail - a file without an
1086 # __END__ should not have been checked in, because the regression tests
1087 # would not have passed.
1088 die "Could not find '__END__' in $file"
1091 my ($t, @p) = _setup_one_file($fh, $file);
1096 or die "Cannot close $file: $!\n";
1098 return ($tests, @prgs);
1101 sub run_multiple_progs {
1105 # The tests in lib run in a temporary subdirectory of t, and always
1106 # pass in a list of "programs" to run
1109 # The tests below t run in t and pass in a file handle. In theory we
1110 # can pass (caller)[1] as the second argument to report errors with
1111 # the filename of our caller, as the handle is always DATA. However,
1112 # line numbers in DATA count from the __END__ token, so will be wrong.
1113 # Which is more confusing than not providing line numbers. So, for now,
1114 # don't provide line numbers. No obvious clean solution - one hack
1115 # would be to seek DATA back to the start and read to the __END__ token,
1116 # but that feels almost like we should just open $0 instead.
1118 # Not going to rely on undef in list assignment.
1120 ($dummy, @prgs) = _setup_one_file(shift);
1123 my $tmpfile = tempfile();
1127 while (defined ($line = shift @prgs)) {
1131 if (defined $file) {
1132 print "# From $file\n";
1139 if (s/^(\s*-\w+)//) {
1142 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1145 foreach my $what (qw(skip todo)) {
1146 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1147 # If the SKIP reason starts ? then it's taken as a code snippet to
1148 # evaluate. This provides the flexibility to have conditional SKIPs
1149 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1150 my $temp = eval $reason{$what};
1152 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1154 $reason{$what} = $temp;
1159 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1163 if ($reason{skip}) {
1166 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1171 if ($prog =~ /--FILE--/) {
1172 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1174 die "Internal error: test $_ didn't split into pairs, got " .
1175 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1177 while (@files > 2) {
1178 my $filename = shift @files;
1179 my $code = shift @files;
1180 push @temps, $filename;
1181 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1183 File::Path::mkpath($1);
1184 push(@temp_path, $1);
1186 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1188 close $fh or die "Cannot close $filename: $!\n";
1191 $prog = shift @files;
1194 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1197 open STDERR, '>&', STDOUT
1198 or die "Can't dup STDOUT->STDERR: $!;";
1201 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1202 print $fh $prog,"\n";
1203 close $fh or die "Cannot close $tmpfile: $!";
1204 my $results = runperl( stderr => 1, progfile => $tmpfile,
1206 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1207 : (switches => [$switch])
1210 $results =~ s/\n+$//;
1211 # allow expected output to be written as if $prog is on STDIN
1212 $results =~ s/$::tempfile_regexp/-/g;
1214 # some tests will trigger VMS messages that won't be expected
1215 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1217 # pipes double these sometimes
1218 $results =~ s/\n\n/\n/g;
1220 # bison says 'parse error' instead of 'syntax error',
1221 # various yaccs may or may not capitalize 'syntax'.
1222 $results =~ s/^(syntax|parse) error/syntax error/mig;
1223 # allow all tests to run when there are leaks
1224 $results =~ s/Scalars leaked: \d+\n//g;
1226 $expected =~ s/\n+$//;
1227 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1228 # any special options? (OPTIONS foo bar zap)
1229 my $option_regex = 0;
1230 my $option_random = 0;
1232 if ($expected =~ s/^OPTIONS? (.+)\n//) {
1233 foreach my $option (split(' ', $1)) {
1234 if ($option eq 'regex') { # allow regular expressions
1237 elsif ($option eq 'random') { # all lines match, but in any order
1240 elsif ($option eq 'fatal') { # perl should fail
1244 die "$0: Unknown OPTION '$option'\n";
1248 die "$0: can't have OPTION regex and random\n"
1249 if $option_regex + $option_random > 1;
1251 if ($results =~ s/^SKIPPED\n//) {
1252 print "$results\n" ;
1256 if ($option_random) {
1257 my @got = sort split "\n", $results;
1258 my @expected = sort split "\n", $expected;
1260 $ok = "@got" eq "@expected";
1262 elsif ($option_regex) {
1263 $ok = $results =~ /^$expected/;
1266 $ok = $results =~ /^\Q$expected/;
1269 $ok = $results eq $expected;
1272 if ($ok && $fatal && !($status >> 8)) {
1277 local $::TODO = $reason{todo};
1280 my $err_line = "PROG: $switch\n$prog\n" .
1281 "EXPECTED:\n$expected\n";
1282 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1283 $err_line .= "GOT:\n$results\n";
1284 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1286 $err_line =~ s/^/# /mg;
1287 print $err_line; # Harness can't filter it out from STDERR.
1290 print STDERR $err_line;
1294 if (defined $file) {
1295 _ok($ok, "at $file line $line", $name);
1297 # We don't have file and line number data for the test, so report
1298 # errors as coming from our caller.
1299 local $Level = $Level + 1;
1306 foreach (@temp_path) {
1307 File::Path::rmtree $_ if -d $_;
1313 my($proto, @methods) = @_;
1314 my $class = ref $proto || $proto;
1316 unless( @methods ) {
1317 return _ok( 0, _where(), "$class->can(...)" );
1321 foreach my $method (@methods) {
1322 local($!, $@); # don't interfere with caller's $@
1323 # eval sometimes resets $!
1324 eval { $proto->can($method) } || push @nok, $method;
1328 $name = @methods == 1 ? "$class->can('$methods[0]')"
1329 : "$class->can(...)";
1331 _ok( !@nok, _where(), $name );
1335 # Call $class->new( @$args ); and run the result through object_ok.
1336 # See Test::More::new_ok
1338 my($class, $args, $obj_name) = @_;
1340 $object_name = "The object" unless defined $obj_name;
1342 local $Level = $Level + 1;
1345 my $ok = eval { $obj = $class->new(@$args); 1 };
1349 object_ok($obj, $class, $object_name);
1352 ok( 0, "new() died" );
1353 diag("Error was: $@");
1362 my($object, $class, $obj_name) = @_;
1365 $obj_name = 'The object' unless defined $obj_name;
1366 my $name = "$obj_name isa $class";
1367 if( !defined $object ) {
1368 $diag = "$obj_name isn't defined";
1371 my $whatami = ref $object ? 'object' : 'class';
1373 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1374 local($@, $!); # eval sometimes resets $!
1375 my $rslt = eval { $object->isa($class) };
1376 my $error = $@; # in case something else blows away $@
1379 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1380 # It's an unblessed reference
1381 $obj_name = 'The reference' unless defined $obj_name;
1382 if( !UNIVERSAL::isa($object, $class) ) {
1383 my $ref = ref $object;
1384 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1387 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1388 # It's something that can't even be a class
1389 $obj_name = 'The thing' unless defined $obj_name;
1390 $diag = "$obj_name isn't a class or reference";
1394 WHOA! I tried to call ->isa on your object and got some weird error.
1395 This should never happen. Please contact the author immediately.
1402 $obj_name = "The $whatami" unless defined $obj_name;
1403 my $ref = ref $object;
1404 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1408 _ok( !$diag, _where(), $name );
1413 my($class, $isa, $class_name) = @_;
1415 # Written so as to count as one test
1416 local $Level = $Level + 1;
1418 ok( 0, "$class is a refrence, not a class name" );
1421 isa_ok($class, $isa, $class_name);
1427 my($obj, $isa, $obj_name) = @_;
1429 local $Level = $Level + 1;
1431 ok( 0, "$obj is not a reference" );
1434 isa_ok($obj, $isa, $obj_name);
1439 # Purposefully avoiding a closure.
1441 push @::__capture, join "", @_;
1444 sub capture_warnings {
1448 local $SIG {__WARN__} = \&__capture;
1450 return @::__capture;
1453 # This will generate a variable number of tests.
1454 # Use done_testing() instead of a fixed plan.
1456 my ($code, $expect, $name) = @_;
1457 local $Level = $Level + 1;
1459 my @w = capture_warnings($code);
1461 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1462 foreach my $e (@$expect) {
1464 like(shift @w, $e, $name);
1466 is(shift @w, $e, $name);
1470 diag("Saw these additional warnings:");
1471 diag($_) foreach @w;
1475 sub _fail_excess_warnings {
1476 my($expect, $got, $name) = @_;
1477 local $Level = $Level + 1;
1478 # This will fail, and produce diagnostics
1479 is($expect, scalar @$got, $name);
1480 diag("Saw these warnings:");
1481 diag($_) foreach @$got;
1485 my ($code, $expect, $name) = @_;
1486 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1488 local $Level = $Level + 1;
1489 my @w = capture_warnings($code);
1491 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1493 is($w[0], $expect, $name);
1498 my ($code, $expect, $name) = @_;
1499 die sprintf "Expect must be a regexp object"
1500 unless ref $expect eq 'Regexp';
1501 local $Level = $Level + 1;
1502 my @w = capture_warnings($code);
1504 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1506 like($w[0], $expect, $name);
1510 # Set a watchdog to timeout the entire test file
1511 # NOTE: If the test file uses 'threads', then call the watchdog() function
1512 # _AFTER_ the 'threads' module is loaded.
1515 my $timeout = shift;
1516 my $method = shift || "";
1517 my $timeout_msg = 'Test process timed out - terminating';
1519 # Valgrind slows perl way down so give it more time before dying.
1520 $timeout *= 10 if $ENV{PERL_VALGRIND};
1522 my $pid_to_kill = $$; # PID for this process
1524 if ($method eq "alarm") {
1525 goto WATCHDOG_VIA_ALARM;
1528 # shut up use only once warning
1529 my $threads_on = $threads::threads && $threads::threads;
1531 # Don't use a watchdog process if 'threads' is loaded -
1532 # use a watchdog thread instead
1533 if (!$threads_on || $method eq "process") {
1535 # On Windows and VMS, try launching a watchdog process
1536 # using system(1, ...) (see perlport.pod)
1537 if ($is_mswin || $is_vms) {
1538 # On Windows, try to get the 'real' PID
1540 eval { require Win32; };
1541 if (defined(&Win32::GetCurrentProcessId)) {
1542 $pid_to_kill = Win32::GetCurrentProcessId();
1546 # If we still have a fake PID, we can't use this method at all
1547 return if ($pid_to_kill <= 0);
1549 # Launch watchdog process
1552 local $SIG{'__WARN__'} = sub {
1553 _diag("Watchdog warning: $_[0]");
1555 my $sig = $is_vms ? 'TERM' : 'KILL';
1556 my $cmd = _create_runperl( prog => "sleep($timeout);" .
1557 "warn qq/# $timeout_msg" . '\n/;' .
1558 "kill($sig, $pid_to_kill);");
1559 $watchdog = system(1, $cmd);
1561 if ($@ || ($watchdog <= 0)) {
1562 _diag('Failed to start watchdog');
1568 # Add END block to parent to terminate and
1569 # clean up watchdog process
1570 # Win32 watchdog is launched by cmd.exe shell, so use process group
1571 # kill, otherwise the watchdog is never killed and harness waits
1572 # every time for the timeout, #121395
1574 "END { local \$! = 0; local \$? = 0;
1575 wait() if kill('-KILL', $watchdog); };"
1576 : "END { local \$! = 0; local \$? = 0;
1577 wait() if kill('KILL', $watchdog); };");
1581 # Try using fork() to generate a watchdog process
1583 eval { $watchdog = fork() };
1584 if (defined($watchdog)) {
1585 if ($watchdog) { # Parent process
1586 # Add END block to parent to terminate and
1587 # clean up watchdog process
1588 eval "END { local \$! = 0; local \$? = 0;
1589 wait() if kill('KILL', $watchdog); };";
1593 ### Watchdog process code
1595 # Load POSIX if available
1596 eval { require POSIX; };
1598 # Execute the timeout
1599 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1602 # Kill test process if still running
1603 if (kill(0, $pid_to_kill)) {
1604 _diag($timeout_msg);
1605 kill('KILL', $pid_to_kill);
1607 # sometimes the above isn't enough on cygwin
1608 sleep 1; # wait a little, it might have worked after all
1609 system("/bin/kill -f $pid_to_kill");
1613 # Don't execute END block (added at beginning of this file)
1616 # Terminate ourself (i.e., the watchdog)
1617 POSIX::_exit(1) if (defined(&POSIX::_exit));
1621 # fork() failed - fall through and try using a thread
1624 # Use a watchdog thread because either 'threads' is loaded,
1626 if (eval {require threads; 1}) {
1627 'threads'->create(sub {
1628 # Load POSIX if available
1629 eval { require POSIX; };
1631 # Execute the timeout
1632 my $time_left = $timeout;
1634 $time_left = $time_left - sleep($time_left);
1635 } while ($time_left > 0);
1637 # Kill the parent (and ourself)
1638 select(STDERR); $| = 1;
1639 _diag($timeout_msg);
1640 POSIX::_exit(1) if (defined(&POSIX::_exit));
1641 my $sig = $is_vms ? 'TERM' : 'KILL';
1642 kill($sig, $pid_to_kill);
1647 # If everything above fails, then just use an alarm timeout
1649 if (eval { alarm($timeout); 1; }) {
1650 # Load POSIX if available
1651 eval { require POSIX; };
1653 # Alarm handler will do the actual 'killing'
1654 $SIG{'ALRM'} = sub {
1655 select(STDERR); $| = 1;
1656 _diag($timeout_msg);
1657 POSIX::_exit(1) if (defined(&POSIX::_exit));
1658 my $sig = $is_vms ? 'TERM' : 'KILL';
1659 kill($sig, $pid_to_kill);