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 # Don’t clobber @INC under miniperl
110 @INC = () unless is_miniperl;
115 return map { /^#/ ? "$_\n" : "# $_\n" }
116 map { split /\n/ } @_;
119 sub _have_dynamic_extension {
120 my $extension = shift;
121 unless (eval {require Config; 1}) {
122 warn "test.pl had problems loading Config: $@";
125 $extension =~ s!::!/!g;
126 return 1 if ($Config::Config{extensions} =~ /\b$extension\b/);
131 _print "1..0 # Skip @_\n";
138 sub skip_all_if_miniperl {
139 skip_all(@_) if is_miniperl();
142 sub skip_all_without_dynamic_extension {
143 my ($extension) = @_;
144 skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
145 return if &_have_dynamic_extension;
146 skip_all("$extension was not built");
149 sub skip_all_without_perlio {
150 skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
153 sub skip_all_without_config {
154 unless (eval {require Config; 1}) {
155 warn "test.pl had problems loading Config: $@";
159 next if $Config::Config{$_};
160 my $key = $_; # Need to copy, before trying to modify.
167 sub skip_all_without_unicode_tables { # (but only under miniperl)
169 skip_all_if_miniperl("Unicode tables not built yet")
170 unless eval 'require "unicore/Heavy.pl"';
174 sub find_git_or_skip {
175 my ($source_dir, $reason);
178 } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
179 my $where = readlink 'MANIFEST';
180 die "Can't readling MANIFEST: $!" unless defined $where;
181 die "Confusing symlink target for MANIFEST, '$where'"
182 unless $where =~ s!/MANIFEST\z!!;
183 if (-d "$where/.git") {
184 # Looks like we are in a symlink tree
185 if (exists $ENV{GIT_DIR}) {
186 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it");
188 note("Found source tree at $where, setting \$ENV{GIT_DIR}");
189 $ENV{GIT_DIR} = "$where/.git";
191 $source_dir = $where;
193 } elsif (exists $ENV{GIT_DIR}) {
194 my $commit = '8d063cd8450e59ea1c611a2f4f5a21059a2804f1';
195 my $out = `git rev-parse --verify --quiet '$commit^{commit}'`;
197 if($out eq $commit) {
202 my $version_string = `git --version`;
203 if (defined $version_string
204 && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
205 return $source_dir if eval "v$1 ge v1.5.0";
206 # If you have earlier than 1.5.0 and it works, change this test
207 $reason = "in git checkout, but git version '$1$2' too old";
209 $reason = "in git checkout, but cannot run git";
212 $reason = 'not being run from a git checkout';
214 skip_all($reason) if $_[0] && $_[0] eq 'all';
220 _print("Bail out! $reason\n");
225 my ($pass, $where, $name, @mess) = @_;
226 # Do not try to microoptimize by factoring out the "not ".
230 # escape out '#' or it will interfere with '# skip' and such
232 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
234 $out = $pass ? "ok $test" : "not ok $test";
238 $out = $out . " # TODO $TODO";
240 $Tests_Are_Passing = 0 unless $pass;
246 note @mess; # Ensure that the message is properly escaped.
249 my $msg = "# Failed test $test - ";
250 $msg.= "$name " if $name;
256 $test = $test + 1; # don't use ++
262 my @caller = caller($Level);
263 return "at $caller[1] line $caller[2]";
266 # DON'T use this for matches. Use like() instead.
268 my ($pass, $name, @mess) = @_;
269 _ok($pass, _where(), $name, @mess);
274 return 'undef' unless defined $x;
283 return defined $x ? '"' . display ($x) . '"' : 'undef';
286 # keys are the codes \n etc map to, values are 2 char strings such as \n
287 my %backslash_escape;
288 foreach my $x (split //, 'nrtfa\\\'"') {
289 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
291 # A way to display scalars containing control characters and Unicode.
292 # Trying to avoid setting $_, or relying on local $_ to work.
296 if (defined $x and not ref $x) {
298 foreach my $c (unpack("W*", $x)) {
300 $y = $y . sprintf "\\x{%x}", $c;
301 } elsif ($backslash_escape{$c}) {
302 $y = $y . $backslash_escape{$c};
304 my $z = chr $c; # Maybe we can get away with a literal...
305 if ($z =~ /[[:^print:]]/) {
307 # Use octal for characters traditionally expressed as
308 # such: the low controls, which on EBCDIC aren't
309 # necessarily the same ones as on ASCII platforms, but
310 # are small ordinals, nonetheless
312 $z = sprintf "\\%03o", $c;
314 $z = sprintf "\\x{%x}", $c;
322 return $x unless wantarray;
329 my ($got, $expected, $name, @mess) = @_;
332 if( !defined $got || !defined $expected ) {
333 # undef only matches undef
334 $pass = !defined $got && !defined $expected;
337 $pass = $got eq $expected;
341 unshift(@mess, "# got "._qq($got)."\n",
342 "# expected "._qq($expected)."\n");
344 _ok($pass, _where(), $name, @mess);
348 my ($got, $isnt, $name, @mess) = @_;
351 if( !defined $got || !defined $isnt ) {
352 # undef only matches undef
353 $pass = defined $got || defined $isnt;
356 $pass = $got ne $isnt;
360 unshift(@mess, "# it should not be "._qq($got)."\n",
363 _ok($pass, _where(), $name, @mess);
367 my($got, $type, $expected, $name, @mess) = @_;
372 local($@,$!); # don't interfere with $@
373 # eval() sometimes resets $!
374 $pass = eval "\$got $type \$expected";
377 # It seems Irix long doubles can have 2147483648 and 2147483648
378 # that stringify to the same thing but are actually numerically
379 # different. Display the numbers if $type isn't a string operator,
380 # and the numbers are stringwise the same.
381 # (all string operators have alphabetic names, so tr/a-z// is true)
382 # This will also show numbers for some unneeded cases, but will
383 # definitely be helpful for things such as == and <= that fail
384 if ($got eq $expected and $type !~ tr/a-z//) {
385 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
387 unshift(@mess, "# got "._qq($got)."\n",
388 "# expected $type "._qq($expected)."\n");
390 _ok($pass, _where(), $name, @mess);
393 # Check that $got is within $range of $expected
394 # if $range is 0, then check it's exact
395 # else if $expected is 0, then $range is an absolute value
396 # otherwise $range is a fractional error.
397 # Here $range must be numeric, >= 0
398 # Non numeric ranges might be a useful future extension. (eg %)
400 my ($got, $expected, $range, $name, @mess) = @_;
402 if (!defined $got or !defined $expected or !defined $range) {
403 # This is a fail, but doesn't need extra diagnostics
404 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
406 unshift @mess, "# got, expected and range must be numeric\n";
407 } elsif ($range < 0) {
408 # This is also a fail
409 unshift @mess, "# range must not be negative\n";
410 } elsif ($range == 0) {
412 $pass = $got == $expected;
413 } elsif ($expected == 0) {
414 # If expected is 0, treat range as absolute
415 $pass = ($got <= $range) && ($got >= - $range);
417 my $diff = $got - $expected;
418 $pass = abs ($diff / $expected) < $range;
421 if ($got eq $expected) {
422 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
424 unshift@mess, "# got "._qq($got)."\n",
425 "# expected "._qq($expected)." (within "._qq($range).")\n";
427 _ok($pass, _where(), $name, @mess);
430 # Note: this isn't quite as fancy as Test::More::like().
432 sub like ($$@) { like_yn (0,@_) }; # 0 for -
433 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
436 my ($flip, undef, $expected, $name, @mess) = @_;
438 # We just accept like(..., qr/.../), not like(..., '...'), and
439 # definitely not like(..., '/.../') like
440 # Test::Builder::maybe_regex() does.
441 unless (re::is_regexp($expected)) {
442 die "PANIC: The value '$expected' isn't a regexp. The like() function needs a qr// pattern, not a string";
446 $pass = $_[1] =~ /$expected/ if !$flip;
447 $pass = $_[1] !~ /$expected/ if $flip;
449 unshift(@mess, "# got '$_[1]'\n",
451 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
453 local $Level = $Level + 1;
454 _ok($pass, _where(), $name, @mess);
462 _ok(0, _where(), @_);
472 $test = $test + 1; # don't use ++
476 # Note: can't pass multipart messages since we try to
477 # be compatible with Test::More::skip().
480 my $n = @_ ? shift : 1;
485 $bad_swap = $why > 0 && $n == 0;
486 $both_zero = $why == 0 && $n == 0;
488 if ($bad_swap || $both_zero || @_) {
489 my $arg = "'$why', '$n'";
491 $arg .= join(", ", '', map { qq['$_'] } @_);
493 die qq[$0: expected skip(why, count), got skip($arg)\n];
496 _print "ok $test # skip $why\n";
503 sub skip_if_miniperl {
504 skip(@_) if is_miniperl();
507 sub skip_without_dynamic_extension {
508 my $extension = shift;
509 skip("no dynamic loading on miniperl, no extension $extension", @_)
511 return if &_have_dynamic_extension($extension);
512 skip("extension $extension was not built", @_);
517 my $n = @_ ? shift : 1;
520 _print "not ok $test # TODO & SKIP $why\n";
529 return 0 unless $#$ra == $#$rb;
530 for my $i (0..$#$ra) {
531 next if !defined $ra->[$i] && !defined $rb->[$i];
532 return 0 if !defined $ra->[$i];
533 return 0 if !defined $rb->[$i];
534 return 0 unless $ra->[$i] eq $rb->[$i];
540 my ($orig, $suspect) = @_;
542 while (my ($key, $value) = each %$suspect) {
543 # Force a hash recompute if this perl's internals can cache the hash key.
545 if (exists $orig->{$key}) {
547 defined $orig->{$key} != defined $value
548 || (defined $value && $orig->{$key} ne $value)
550 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
551 " now ", _qq($value), "\n";
555 _print "# key ", _qq($key), " is ", _qq($value),
556 ", not in original.\n";
560 foreach (keys %$orig) {
561 # Force a hash recompute if this perl's internals can cache the hash key.
563 next if (exists $suspect->{$_});
564 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
570 # We only provide a subset of the Test::More functionality.
573 if ($require =~ tr/[A-Za-z0-9:.]//c) {
574 fail("Invalid character in \"$require\", passed to require_ok");
579 is($@, '', _where(), "require $require");
585 if ($use =~ tr/[A-Za-z0-9:.]//c) {
586 fail("Invalid character in \"$use\", passed to use");
591 is($@, '', _where(), "use $use");
595 # runperl - Runs a separate perl interpreter and returns its output.
597 # switches => [ command-line switches ]
598 # nolib => 1 # don't use -I../lib (included by default)
599 # non_portable => Don't warn if a one liner contains quotes
600 # prog => one-liner (avoid quotes)
601 # progs => [ multi-liner (avoid quotes) ]
602 # progfile => perl script
603 # stdin => string to feed the stdin (or undef to redirect from /dev/null)
604 # stderr => If 'devnull' suppresses stderr, if other TRUE value redirect
606 # args => [ command-line arguments to the perl program ]
607 # verbose => print the command line
609 my $is_mswin = $^O eq 'MSWin32';
610 my $is_netware = $^O eq 'NetWare';
611 my $is_vms = $^O eq 'VMS';
612 my $is_cygwin = $^O eq 'cygwin';
615 my ($runperl, $args) = @_;
618 # In VMS protect with doublequotes because otherwise
619 # DCL will lowercase -- unless already doublequoted.
620 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
621 $runperl = $runperl . ' ' . $_;
626 sub _create_runperl { # Create the string to qx in runperl().
628 my $runperl = which_perl();
629 if ($runperl =~ m/\s/) {
630 $runperl = qq{"$runperl"};
632 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
633 if ($ENV{PERL_RUNPERL_DEBUG}) {
634 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
636 unless ($args{nolib}) {
637 $runperl = $runperl . ' "-I../lib"'; # doublequotes because of VMS
639 if ($args{switches}) {
641 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
642 unless ref $args{switches} eq "ARRAY";
643 $runperl = _quote_args($runperl, $args{switches});
645 if (defined $args{prog}) {
646 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
647 if defined $args{progs};
648 $args{progs} = [split /\n/, $args{prog}, -1]
650 if (defined $args{progs}) {
651 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
652 unless ref $args{progs} eq "ARRAY";
653 foreach my $prog (@{$args{progs}}) {
654 if (!$args{non_portable}) {
655 if ($prog =~ tr/'"//) {
656 warn "quotes in prog >>$prog<< are not portable";
658 if ($prog =~ /^([<>|]|2>)/) {
659 warn "Initial $1 in prog >>$prog<< is not portable";
661 if ($prog =~ /&\z/) {
662 warn "Trailing & in prog >>$prog<< is not portable";
665 if ($is_mswin || $is_netware || $is_vms) {
666 $runperl = $runperl . qq ( -e "$prog" );
669 $runperl = $runperl . qq ( -e '$prog' );
672 } elsif (defined $args{progfile}) {
673 $runperl = $runperl . qq( "$args{progfile}");
675 # You probably didn't want to be sucking in from the upstream stdin
676 die "test.pl:runperl(): none of prog, progs, progfile, args, "
677 . " switches or stdin specified"
678 unless defined $args{args} or defined $args{switches}
679 or defined $args{stdin};
681 if (defined $args{stdin}) {
682 # so we don't try to put literal newlines and crs onto the
684 $args{stdin} =~ s/\n/\\n/g;
685 $args{stdin} =~ s/\r/\\r/g;
687 if ($is_mswin || $is_netware || $is_vms) {
688 $runperl = qq{$Perl -e "print qq(} .
689 $args{stdin} . q{)" | } . $runperl;
692 $runperl = qq{$Perl -e 'print qq(} .
693 $args{stdin} . q{)' | } . $runperl;
695 } elsif (exists $args{stdin}) {
696 # Using the pipe construction above can cause fun on systems which use
697 # ksh as /bin/sh, as ksh does pipes differently (with one less process)
698 # With sh, for the command line 'perl -e 'print qq()' | perl -e ...'
699 # the sh process forks two children, which use exec to start the two
700 # perl processes. The parent shell process persists for the duration of
701 # the pipeline, and the second perl process starts with no children.
702 # With ksh (and zsh), the shell saves a process by forking a child for
703 # just the first perl process, and execing itself to start the second.
704 # This means that the second perl process starts with one child which
705 # it didn't create. This causes "fun" when if the tests assume that
706 # wait (or waitpid) will only return information about processes
707 # started within the test.
708 # They also cause fun on VMS, where the pipe implementation returns
709 # the exit code of the process at the front of the pipeline, not the
710 # end. This messes up any test using OPTION FATAL.
711 # Hence it's useful to have a way to make STDIN be at eof without
712 # needing a pipeline, so that the fork tests have a sane environment
713 # without these surprises.
715 # /dev/null appears to be surprisingly portable.
716 $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null');
718 if (defined $args{args}) {
719 $runperl = _quote_args($runperl, $args{args});
721 if (exists $args{stderr} && $args{stderr} eq 'devnull') {
722 $runperl = $runperl . ($is_mswin ? ' 2>nul' : ' 2>/dev/null');
724 elsif ($args{stderr}) {
725 $runperl = $runperl . ' 2>&1';
727 if ($args{verbose}) {
728 my $runperldisplay = $runperl;
729 $runperldisplay =~ s/\n/\n\#/g;
730 _print_stderr "# $runperldisplay\n";
736 die "test.pl:runperl() does not take a hashref"
737 if ref $_[0] and ref $_[0] eq 'HASH';
738 my $runperl = &_create_runperl;
741 my $tainted = ${^TAINT};
743 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
746 # We will assume that if you're running under -T, you really mean to
747 # run a fresh perl, so we'll brute force launder everything for you
750 if (! eval {require Config; 1}) {
751 warn "test.pl had problems loading Config: $@";
754 $sep = $Config::Config{path_sep};
757 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
758 local @ENV{@keys} = ();
759 # Untaint, plus take out . and empty string:
760 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
761 $ENV{PATH} =~ /(.*)/s;
763 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
764 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
765 split quotemeta ($sep), $1;
766 if ($is_cygwin) { # Must have /bin under Cygwin
767 if (length $ENV{PATH}) {
768 $ENV{PATH} = $ENV{PATH} . $sep;
770 $ENV{PATH} = $ENV{PATH} . '/bin';
775 $result = `$runperl`;
777 $result = `$runperl`;
779 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
784 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
787 _print_stderr "# @_\n";
791 # A somewhat safer version of the sometimes wrong $^X.
793 unless (defined $Perl) {
796 # VMS should have 'perl' aliased properly
797 return $Perl if $is_vms;
800 if (! eval {require Config; 1}) {
801 warn "test.pl had problems loading Config: $@";
804 $exe = $Config::Config{_exe};
806 $exe = '' unless defined $exe;
808 # This doesn't absolutize the path: beware of future chdirs().
809 # We could do File::Spec->abs2rel() but that does getcwd()s,
810 # which is a bit heavyweight to do here.
812 if ($Perl =~ /^perl\Q$exe\E$/i) {
813 my $perl = "perl$exe";
814 if (! eval {require File::Spec; 1}) {
815 warn "test.pl had problems loading File::Spec: $@";
818 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
822 # Build up the name of the executable file from the name of
825 if ($Perl !~ /\Q$exe\E$/i) {
826 $Perl = $Perl . $exe;
829 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
831 # For subcommands to use.
832 $ENV{PERLEXE} = $Perl;
839 foreach my $file (@_) {
840 1 while unlink $file;
842 _print_stderr "# Couldn't unlink '$file': $!\n";
850 # _num_to_alpha - Returns a string of letters representing a positive integer.
853 # maximum number of letters
855 # returns undef if the number is negative
856 # returns undef if the number of letters is greater than the maximum wanted
858 # _num_to_alpha( 0) eq 'A';
859 # _num_to_alpha( 1) eq 'B';
860 # _num_to_alpha(25) eq 'Z';
861 # _num_to_alpha(26) eq 'AA';
862 # _num_to_alpha(27) eq 'AB';
864 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);
866 # Avoid ++ -- ranges split negative numbers
868 my($num,$max_char) = @_;
869 return unless $num >= 0;
872 $max_char = 0 if $max_char < 0;
875 $alpha = $letters[ $num % 26 ] . $alpha;
876 $num = int( $num / 26 );
881 next unless $max_char;
882 $char_count = $char_count + 1;
883 return if $char_count == $max_char;
889 END { unlink_all keys %tmpfiles }
891 # A regexp that matches the tempfile names
892 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
894 # Avoid ++, avoid ranges, avoid split //
895 my $tempfile_count = 0;
899 my $alpha = _num_to_alpha($tempfile_count,2);
900 last unless defined $alpha;
901 $try = $try . $alpha;
902 $tempfile_count = $tempfile_count + 1;
904 # Need to note all the file names we allocated, as a second request may
905 # come before the first is created.
906 if (!$tmpfiles{$try} && !-e $try) {
912 die "Can't find temporary file name starting \"tmp$$\"";
915 # register_tempfile - Adds a list of files to be removed at the end of the current test file
917 # a list of files to be removed later
919 # returns a count of how many file names were actually added
921 # Reuses %tmpfiles so that tempfile() will also skip any files added here
922 # even if the file doesn't exist yet.
924 sub register_tempfile {
928 _print_stderr "# Temporary file '$_' already added\n";
937 # This is the temporary file for _fresh_perl
938 my $tmpfile = tempfile();
941 my($prog, $action, $expect, $runperl_args, $name) = @_;
943 # Given the choice of the mis-parsable {}
944 # (we want an anon hash, but a borked lexer might think that it's a block)
945 # or relying on taking a reference to a lexical
946 # (\ might be mis-parsed, and the reference counting on the pad may go
948 # it feels like the least-worse thing is to assume that auto-vivification
949 # works. At least, this is only going to be a run-time failure, so won't
950 # affect tests using this file but not this function.
951 $runperl_args->{progfile} ||= $tmpfile;
952 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
954 open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
956 close TEST or die "Cannot close $tmpfile: $!";
958 my $results = runperl(%$runperl_args);
961 # Clean up the results into something a bit more predictable.
962 $results =~ s/\n+$//;
963 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
964 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
966 # bison says 'parse error' instead of 'syntax error',
967 # various yaccs may or may not capitalize 'syntax'.
968 $results =~ s/^(syntax|parse) error/syntax error/mig;
971 # some tests will trigger VMS messages that won't be expected
972 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
974 # pipes double these sometimes
975 $results =~ s/\n\n/\n/g;
978 # Use the first line of the program as a name if none was given
980 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
981 $name = $name . '...' if length $first_line > length $name;
984 # Historically this was implemented using a closure, but then that means
985 # that the tests for closures avoid using this code. Given that there
986 # are exactly two callers, doing exactly two things, the simpler approach
987 # feels like a better trade off.
989 if ($action eq 'eq') {
990 $pass = is($results, $expect, $name);
991 } elsif ($action eq '=~') {
992 $pass = like($results, $expect, $name);
994 die "_fresh_perl can't process action '$action'";
998 _diag "# PROG: \n$prog\n";
999 _diag "# STATUS: $status\n";
1008 # Combination of run_perl() and is().
1012 my($prog, $expected, $runperl_args, $name) = @_;
1014 # _fresh_perl() is going to clip the trailing newlines off the result.
1015 # This will make it so the test author doesn't have to know that.
1016 $expected =~ s/\n+$//;
1019 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
1025 # Combination of run_perl() and like().
1028 sub fresh_perl_like {
1029 my($prog, $expected, $runperl_args, $name) = @_;
1031 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
1034 # Many tests use the same format in __DATA__ or external files to specify a
1035 # sequence of (fresh) tests to run, extra files they may temporarily need, and
1036 # what the expected output is. Putting it here allows common code to serve
1037 # these multiple tests.
1039 # Each program is source code to run followed by an "EXPECT" line, followed
1040 # by the expected output.
1042 # The code to run may begin with a command line switch such as -w or -0777
1043 # (alphanumerics only), and may contain (note the '# ' on each):
1044 # # TODO reason for todo
1045 # # SKIP reason for skip
1046 # # SKIP ?code to test if this should be skipped
1047 # # NAME name of the test (as with ok($ok, $name))
1049 # The expected output may contain:
1050 # OPTION list of options
1051 # OPTIONS list of options
1053 # The possible options for OPTION may be:
1054 # regex - the expected output is a regular expression
1055 # random - all lines match but in any order
1056 # fatal - the code will fail fatally (croak, die)
1058 # If the actual output contains a line "SKIPPED" the test will be
1061 # If the actual output contains a line "PREFIX", any output starting with that
1062 # line will be ignored when comparing with the expected output
1064 # If the global variable $FATAL is true then OPTION fatal is the
1067 sub _setup_one_file {
1069 # Store the filename as a program that started at line 0.
1070 # Real files count lines starting at line 1.
1071 my @these = (0, shift);
1072 my ($lineno, $current);
1074 if ($_ eq "########\n") {
1075 if (defined $current) {
1076 push @these, $lineno, $current;
1080 if (!defined $current) {
1086 if (defined $current) {
1087 push @these, $lineno, $current;
1089 ((scalar @these) / 2 - 1, @these);
1092 sub setup_multiple_progs {
1094 foreach my $file (@_) {
1095 next if $file =~ /(?:~|\.orig|,v)$/;
1096 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1099 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1107 # This is an internal error, and should never happen. All bar one of
1108 # the files had an __END__ marker to signal the end of their preamble,
1109 # although for some it wasn't technically necessary as they have no
1110 # tests. It might be possible to process files without an __END__ by
1111 # seeking back to the start and treating the whole file as tests, but
1112 # it's simpler and more reliable just to make the rule that all files
1113 # must have __END__ in. This should never fail - a file without an
1114 # __END__ should not have been checked in, because the regression tests
1115 # would not have passed.
1116 die "Could not find '__END__' in $file"
1119 my ($t, @p) = _setup_one_file($fh, $file);
1124 or die "Cannot close $file: $!\n";
1126 return ($tests, @prgs);
1129 sub run_multiple_progs {
1133 # The tests in lib run in a temporary subdirectory of t, and always
1134 # pass in a list of "programs" to run
1137 # The tests below t run in t and pass in a file handle. In theory we
1138 # can pass (caller)[1] as the second argument to report errors with
1139 # the filename of our caller, as the handle is always DATA. However,
1140 # line numbers in DATA count from the __END__ token, so will be wrong.
1141 # Which is more confusing than not providing line numbers. So, for now,
1142 # don't provide line numbers. No obvious clean solution - one hack
1143 # would be to seek DATA back to the start and read to the __END__ token,
1144 # but that feels almost like we should just open $0 instead.
1146 # Not going to rely on undef in list assignment.
1148 ($dummy, @prgs) = _setup_one_file(shift);
1151 my $tmpfile = tempfile();
1155 while (defined ($line = shift @prgs)) {
1159 if (defined $file) {
1160 print "# From $file\n";
1167 if (s/^(\s*-\w+)//) {
1170 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1173 foreach my $what (qw(skip todo)) {
1174 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1175 # If the SKIP reason starts ? then it's taken as a code snippet to
1176 # evaluate. This provides the flexibility to have conditional SKIPs
1177 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1178 my $temp = eval $reason{$what};
1180 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1182 $reason{$what} = $temp;
1187 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1191 if ($reason{skip}) {
1194 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1199 if ($prog =~ /--FILE--/) {
1200 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1202 die "Internal error: test $_ didn't split into pairs, got " .
1203 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1205 while (@files > 2) {
1206 my $filename = shift @files;
1207 my $code = shift @files;
1208 push @temps, $filename;
1209 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1211 File::Path::mkpath($1);
1212 push(@temp_path, $1);
1214 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1216 close $fh or die "Cannot close $filename: $!\n";
1219 $prog = shift @files;
1222 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1225 open STDERR, '>&', STDOUT
1226 or die "Can't dup STDOUT->STDERR: $!;";
1229 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1230 print $fh $prog,"\n";
1231 close $fh or die "Cannot close $tmpfile: $!";
1232 my $results = runperl( stderr => 1, progfile => $tmpfile,
1234 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1235 : (switches => [$switch])
1238 $results =~ s/\n+$//;
1239 # allow expected output to be written as if $prog is on STDIN
1240 $results =~ s/$::tempfile_regexp/-/g;
1242 # some tests will trigger VMS messages that won't be expected
1243 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1245 # pipes double these sometimes
1246 $results =~ s/\n\n/\n/g;
1248 # bison says 'parse error' instead of 'syntax error',
1249 # various yaccs may or may not capitalize 'syntax'.
1250 $results =~ s/^(syntax|parse) error/syntax error/mig;
1251 # allow all tests to run when there are leaks
1252 $results =~ s/Scalars leaked: \d+\n//g;
1254 $expected =~ s/\n+$//;
1255 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1256 # any special options? (OPTIONS foo bar zap)
1257 my $option_regex = 0;
1258 my $option_random = 0;
1260 if ($expected =~ s/^OPTIONS? (.+)\n//) {
1261 foreach my $option (split(' ', $1)) {
1262 if ($option eq 'regex') { # allow regular expressions
1265 elsif ($option eq 'random') { # all lines match, but in any order
1268 elsif ($option eq 'fatal') { # perl should fail
1272 die "$0: Unknown OPTION '$option'\n";
1276 die "$0: can't have OPTION regex and random\n"
1277 if $option_regex + $option_random > 1;
1279 if ($results =~ s/^SKIPPED\n//) {
1280 print "$results\n" ;
1284 if ($option_random) {
1285 my @got = sort split "\n", $results;
1286 my @expected = sort split "\n", $expected;
1288 $ok = "@got" eq "@expected";
1290 elsif ($option_regex) {
1291 $ok = $results =~ /^$expected/;
1294 $ok = $results =~ /^\Q$expected/;
1297 $ok = $results eq $expected;
1300 if ($ok && $fatal && !($status >> 8)) {
1305 local $::TODO = $reason{todo};
1308 my $err_line = "PROG: $switch\n$prog\n" .
1309 "EXPECTED:\n$expected\n";
1310 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1311 $err_line .= "GOT:\n$results\n";
1312 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1314 $err_line =~ s/^/# /mg;
1315 print $err_line; # Harness can't filter it out from STDERR.
1318 print STDERR $err_line;
1322 if (defined $file) {
1323 _ok($ok, "at $file line $line", $name);
1325 # We don't have file and line number data for the test, so report
1326 # errors as coming from our caller.
1327 local $Level = $Level + 1;
1334 foreach (@temp_path) {
1335 File::Path::rmtree $_ if -d $_;
1341 my($proto, @methods) = @_;
1342 my $class = ref $proto || $proto;
1344 unless( @methods ) {
1345 return _ok( 0, _where(), "$class->can(...)" );
1349 foreach my $method (@methods) {
1350 local($!, $@); # don't interfere with caller's $@
1351 # eval sometimes resets $!
1352 eval { $proto->can($method) } || push @nok, $method;
1356 $name = @methods == 1 ? "$class->can('$methods[0]')"
1357 : "$class->can(...)";
1359 _ok( !@nok, _where(), $name );
1363 # Call $class->new( @$args ); and run the result through object_ok.
1364 # See Test::More::new_ok
1366 my($class, $args, $obj_name) = @_;
1368 $object_name = "The object" unless defined $obj_name;
1370 local $Level = $Level + 1;
1373 my $ok = eval { $obj = $class->new(@$args); 1 };
1377 object_ok($obj, $class, $object_name);
1380 ok( 0, "new() died" );
1381 diag("Error was: $@");
1390 my($object, $class, $obj_name) = @_;
1393 $obj_name = 'The object' unless defined $obj_name;
1394 my $name = "$obj_name isa $class";
1395 if( !defined $object ) {
1396 $diag = "$obj_name isn't defined";
1399 my $whatami = ref $object ? 'object' : 'class';
1401 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1402 local($@, $!); # eval sometimes resets $!
1403 my $rslt = eval { $object->isa($class) };
1404 my $error = $@; # in case something else blows away $@
1407 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1408 # It's an unblessed reference
1409 $obj_name = 'The reference' unless defined $obj_name;
1410 if( !UNIVERSAL::isa($object, $class) ) {
1411 my $ref = ref $object;
1412 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1415 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1416 # It's something that can't even be a class
1417 $obj_name = 'The thing' unless defined $obj_name;
1418 $diag = "$obj_name isn't a class or reference";
1422 WHOA! I tried to call ->isa on your object and got some weird error.
1423 This should never happen. Please contact the author immediately.
1430 $obj_name = "The $whatami" unless defined $obj_name;
1431 my $ref = ref $object;
1432 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1436 _ok( !$diag, _where(), $name );
1441 my($class, $isa, $class_name) = @_;
1443 # Written so as to count as one test
1444 local $Level = $Level + 1;
1446 ok( 0, "$class is a refrence, not a class name" );
1449 isa_ok($class, $isa, $class_name);
1455 my($obj, $isa, $obj_name) = @_;
1457 local $Level = $Level + 1;
1459 ok( 0, "$obj is not a reference" );
1462 isa_ok($obj, $isa, $obj_name);
1467 # Purposefully avoiding a closure.
1469 push @::__capture, join "", @_;
1472 sub capture_warnings {
1476 local $SIG {__WARN__} = \&__capture;
1478 return @::__capture;
1481 # This will generate a variable number of tests.
1482 # Use done_testing() instead of a fixed plan.
1484 my ($code, $expect, $name) = @_;
1485 local $Level = $Level + 1;
1487 my @w = capture_warnings($code);
1489 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1490 foreach my $e (@$expect) {
1492 like(shift @w, $e, $name);
1494 is(shift @w, $e, $name);
1498 diag("Saw these additional warnings:");
1499 diag($_) foreach @w;
1503 sub _fail_excess_warnings {
1504 my($expect, $got, $name) = @_;
1505 local $Level = $Level + 1;
1506 # This will fail, and produce diagnostics
1507 is($expect, scalar @$got, $name);
1508 diag("Saw these warnings:");
1509 diag($_) foreach @$got;
1513 my ($code, $expect, $name) = @_;
1514 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1516 local $Level = $Level + 1;
1517 my @w = capture_warnings($code);
1519 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1521 is($w[0], $expect, $name);
1526 my ($code, $expect, $name) = @_;
1527 die sprintf "Expect must be a regexp object"
1528 unless ref $expect eq 'Regexp';
1529 local $Level = $Level + 1;
1530 my @w = capture_warnings($code);
1532 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1534 like($w[0], $expect, $name);
1538 # Set a watchdog to timeout the entire test file
1539 # NOTE: If the test file uses 'threads', then call the watchdog() function
1540 # _AFTER_ the 'threads' module is loaded.
1543 my $timeout = shift;
1544 my $method = shift || "";
1545 my $timeout_msg = 'Test process timed out - terminating';
1547 # Valgrind slows perl way down so give it more time before dying.
1548 $timeout *= 10 if $ENV{PERL_VALGRIND};
1550 my $pid_to_kill = $$; # PID for this process
1552 if ($method eq "alarm") {
1553 goto WATCHDOG_VIA_ALARM;
1556 # shut up use only once warning
1557 my $threads_on = $threads::threads && $threads::threads;
1559 # Don't use a watchdog process if 'threads' is loaded -
1560 # use a watchdog thread instead
1561 if (!$threads_on || $method eq "process") {
1563 # On Windows and VMS, try launching a watchdog process
1564 # using system(1, ...) (see perlport.pod)
1565 if ($is_mswin || $is_vms) {
1566 # On Windows, try to get the 'real' PID
1568 eval { require Win32; };
1569 if (defined(&Win32::GetCurrentProcessId)) {
1570 $pid_to_kill = Win32::GetCurrentProcessId();
1574 # If we still have a fake PID, we can't use this method at all
1575 return if ($pid_to_kill <= 0);
1577 # Launch watchdog process
1580 local $SIG{'__WARN__'} = sub {
1581 _diag("Watchdog warning: $_[0]");
1583 my $sig = $is_vms ? 'TERM' : 'KILL';
1584 my $cmd = _create_runperl( prog => "sleep($timeout);" .
1585 "warn qq/# $timeout_msg" . '\n/;' .
1586 "kill($sig, $pid_to_kill);");
1587 $watchdog = system(1, $cmd);
1589 if ($@ || ($watchdog <= 0)) {
1590 _diag('Failed to start watchdog');
1596 # Add END block to parent to terminate and
1597 # clean up watchdog process
1598 # Win32 watchdog is launched by cmd.exe shell, so use process group
1599 # kill, otherwise the watchdog is never killed and harness waits
1600 # every time for the timeout, #121395
1602 "END { local \$! = 0; local \$? = 0;
1603 wait() if kill('-KILL', $watchdog); };"
1604 : "END { local \$! = 0; local \$? = 0;
1605 wait() if kill('KILL', $watchdog); };");
1609 # Try using fork() to generate a watchdog process
1611 eval { $watchdog = fork() };
1612 if (defined($watchdog)) {
1613 if ($watchdog) { # Parent process
1614 # Add END block to parent to terminate and
1615 # clean up watchdog process
1616 eval "END { local \$! = 0; local \$? = 0;
1617 wait() if kill('KILL', $watchdog); };";
1621 ### Watchdog process code
1623 # Load POSIX if available
1624 eval { require POSIX; };
1626 # Execute the timeout
1627 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1630 # Kill test process if still running
1631 if (kill(0, $pid_to_kill)) {
1632 _diag($timeout_msg);
1633 kill('KILL', $pid_to_kill);
1635 # sometimes the above isn't enough on cygwin
1636 sleep 1; # wait a little, it might have worked after all
1637 system("/bin/kill -f $pid_to_kill");
1641 # Don't execute END block (added at beginning of this file)
1644 # Terminate ourself (i.e., the watchdog)
1645 POSIX::_exit(1) if (defined(&POSIX::_exit));
1649 # fork() failed - fall through and try using a thread
1652 # Use a watchdog thread because either 'threads' is loaded,
1654 if (eval {require threads; 1}) {
1655 'threads'->create(sub {
1656 # Load POSIX if available
1657 eval { require POSIX; };
1659 # Execute the timeout
1660 my $time_left = $timeout;
1662 $time_left = $time_left - sleep($time_left);
1663 } while ($time_left > 0);
1665 # Kill the parent (and ourself)
1666 select(STDERR); $| = 1;
1667 _diag($timeout_msg);
1668 POSIX::_exit(1) if (defined(&POSIX::_exit));
1669 my $sig = $is_vms ? 'TERM' : 'KILL';
1670 kill($sig, $pid_to_kill);
1675 # If everything above fails, then just use an alarm timeout
1677 if (eval { alarm($timeout); 1; }) {
1678 # Load POSIX if available
1679 eval { require POSIX; };
1681 # Alarm handler will do the actual 'killing'
1682 $SIG{'ALRM'} = sub {
1683 select(STDERR); $| = 1;
1684 _diag($timeout_msg);
1685 POSIX::_exit(1) if (defined(&POSIX::_exit));
1686 my $sig = $is_vms ? 'TERM' : 'KILL';
1687 kill($sig, $pid_to_kill);