2 # t/test.pl - most of Test::More functionality without the fuss
7 # Increment ($x++) has a certain amount of cleverness for things like
10 # $x++; # $x eq 'aaa';
12 # stands more chance of breaking than just a simple
16 # In this file, we use the latter "Baby Perl" approach, and increment
17 # will be worked over by t/op/inc.t
23 my $Perl; # Safer version of $^X set by which_perl()
25 # This defines ASCII/UTF-8 vs EBCDIC/UTF-EBCDIC
26 $::IS_ASCII = ord 'A' == 65;
27 $::IS_EBCDIC = ord 'A' == 193;
31 $Tests_Are_Passing = 1;
33 # Use this instead of print to avoid interference while testing globals.
35 local($\, $", $,) = (undef, ' ', '');
40 local($\, $", $,) = (undef, ' ', '');
48 if ($n eq 'no_plan') {
54 $plan{skip_all} and skip_all($plan{skip_all});
57 _print "1..$n\n" unless $noplan;
62 # Set the plan at the end. See Test::More::done_testing.
75 if (defined $planned && $planned != $ran) {
77 "# Looks like you planned $planned tests but ran $ran.\n";
86 my @mess = _comment(@_);
87 $TODO ? _print(@mess) : _print_stderr(@mess);
90 # Use this instead of "print STDERR" when outputting failure diagnostic
96 # Use this instead of "print" when outputting informational messages
99 _print( _comment(@_) );
103 return !defined &DynaLoader::boot_DynaLoader;
107 # Don’t clobber @INC under miniperl
108 @INC = () unless is_miniperl;
113 return map { /^#/ ? "$_\n" : "# $_\n" }
114 map { split /\n/ } @_;
117 sub _have_dynamic_extension {
118 my $extension = shift;
119 unless (eval {require Config; 1}) {
120 warn "test.pl had problems loading Config: $@";
123 $extension =~ s!::!/!g;
124 return 1 if ($Config::Config{extensions} =~ /\b$extension\b/);
129 _print "1..0 # Skip @_\n";
136 sub skip_all_if_miniperl {
137 skip_all(@_) if is_miniperl();
140 sub skip_all_without_dynamic_extension {
141 my ($extension) = @_;
142 skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
143 return if &_have_dynamic_extension;
144 skip_all("$extension was not built");
147 sub skip_all_without_perlio {
148 skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
151 sub skip_all_without_config {
152 unless (eval {require Config; 1}) {
153 warn "test.pl had problems loading Config: $@";
157 next if $Config::Config{$_};
158 my $key = $_; # Need to copy, before trying to modify.
165 sub skip_all_without_unicode_tables { # (but only under miniperl)
167 skip_all_if_miniperl("Unicode tables not built yet")
168 unless eval 'require "unicore/Heavy.pl"';
172 sub find_git_or_skip {
173 my ($source_dir, $reason);
176 } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
177 my $where = readlink 'MANIFEST';
178 die "Can't readling MANIFEST: $!" unless defined $where;
179 die "Confusing symlink target for MANIFEST, '$where'"
180 unless $where =~ s!/MANIFEST\z!!;
181 if (-d "$where/.git") {
182 # Looks like we are in a symlink tree
183 if (exists $ENV{GIT_DIR}) {
184 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it");
186 note("Found source tree at $where, setting \$ENV{GIT_DIR}");
187 $ENV{GIT_DIR} = "$where/.git";
189 $source_dir = $where;
191 } elsif (exists $ENV{GIT_DIR}) {
192 my $commit = '8d063cd8450e59ea1c611a2f4f5a21059a2804f1';
193 my $out = `git rev-parse --verify --quiet '$commit^{commit}'`;
195 if($out eq $commit) {
200 my $version_string = `git --version`;
201 if (defined $version_string
202 && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
203 return $source_dir if eval "v$1 ge v1.5.0";
204 # If you have earlier than 1.5.0 and it works, change this test
205 $reason = "in git checkout, but git version '$1$2' too old";
207 $reason = "in git checkout, but cannot run git";
210 $reason = 'not being run from a git checkout';
212 skip_all($reason) if $_[0] && $_[0] eq 'all';
218 _print("Bail out! $reason\n");
223 my ($pass, $where, $name, @mess) = @_;
224 # Do not try to microoptimize by factoring out the "not ".
228 # escape out '#' or it will interfere with '# skip' and such
230 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
232 $out = $pass ? "ok $test" : "not ok $test";
236 $out = $out . " # TODO $TODO";
238 $Tests_Are_Passing = 0 unless $pass;
244 note @mess; # Ensure that the message is properly escaped.
247 my $msg = "# Failed test $test - ";
248 $msg.= "$name " if $name;
254 $test = $test + 1; # don't use ++
260 my @caller = caller($Level);
261 return "at $caller[1] line $caller[2]";
264 # DON'T use this for matches. Use like() instead.
266 my ($pass, $name, @mess) = @_;
267 _ok($pass, _where(), $name, @mess);
272 return 'undef' unless defined $x;
281 return defined $x ? '"' . display ($x) . '"' : 'undef';
284 # keys are the codes \n etc map to, values are 2 char strings such as \n
285 my %backslash_escape;
286 foreach my $x (split //, 'nrtfa\\\'"') {
287 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
289 # A way to display scalars containing control characters and Unicode.
290 # Trying to avoid setting $_, or relying on local $_ to work.
294 if (defined $x and not ref $x) {
296 foreach my $c (unpack("W*", $x)) {
298 $y = $y . sprintf "\\x{%x}", $c;
299 } elsif ($backslash_escape{$c}) {
300 $y = $y . $backslash_escape{$c};
302 my $z = chr $c; # Maybe we can get away with a literal...
303 if ($z =~ /[[:^print:]]/) {
305 # Use octal for characters traditionally expressed as
306 # such: the low controls, which on EBCDIC aren't
307 # necessarily the same ones as on ASCII platforms, but
308 # are small ordinals, nonetheless
310 $z = sprintf "\\%03o", $c;
312 $z = sprintf "\\x{%x}", $c;
320 return $x unless wantarray;
327 my ($got, $expected, $name, @mess) = @_;
330 if( !defined $got || !defined $expected ) {
331 # undef only matches undef
332 $pass = !defined $got && !defined $expected;
335 $pass = $got eq $expected;
339 unshift(@mess, "# got "._qq($got)."\n",
340 "# expected "._qq($expected)."\n");
342 _ok($pass, _where(), $name, @mess);
346 my ($got, $isnt, $name, @mess) = @_;
349 if( !defined $got || !defined $isnt ) {
350 # undef only matches undef
351 $pass = defined $got || defined $isnt;
354 $pass = $got ne $isnt;
358 unshift(@mess, "# it should not be "._qq($got)."\n",
361 _ok($pass, _where(), $name, @mess);
365 my($got, $type, $expected, $name, @mess) = @_;
370 local($@,$!); # don't interfere with $@
371 # eval() sometimes resets $!
372 $pass = eval "\$got $type \$expected";
375 # It seems Irix long doubles can have 2147483648 and 2147483648
376 # that stringify to the same thing but are actually numerically
377 # different. Display the numbers if $type isn't a string operator,
378 # and the numbers are stringwise the same.
379 # (all string operators have alphabetic names, so tr/a-z// is true)
380 # This will also show numbers for some unneeded cases, but will
381 # definitely be helpful for things such as == and <= that fail
382 if ($got eq $expected and $type !~ tr/a-z//) {
383 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
385 unshift(@mess, "# got "._qq($got)."\n",
386 "# expected $type "._qq($expected)."\n");
388 _ok($pass, _where(), $name, @mess);
391 # Check that $got is within $range of $expected
392 # if $range is 0, then check it's exact
393 # else if $expected is 0, then $range is an absolute value
394 # otherwise $range is a fractional error.
395 # Here $range must be numeric, >= 0
396 # Non numeric ranges might be a useful future extension. (eg %)
398 my ($got, $expected, $range, $name, @mess) = @_;
400 if (!defined $got or !defined $expected or !defined $range) {
401 # This is a fail, but doesn't need extra diagnostics
402 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
404 unshift @mess, "# got, expected and range must be numeric\n";
405 } elsif ($range < 0) {
406 # This is also a fail
407 unshift @mess, "# range must not be negative\n";
408 } elsif ($range == 0) {
410 $pass = $got == $expected;
411 } elsif ($expected == 0) {
412 # If expected is 0, treat range as absolute
413 $pass = ($got <= $range) && ($got >= - $range);
415 my $diff = $got - $expected;
416 $pass = abs ($diff / $expected) < $range;
419 if ($got eq $expected) {
420 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
422 unshift@mess, "# got "._qq($got)."\n",
423 "# expected "._qq($expected)." (within "._qq($range).")\n";
425 _ok($pass, _where(), $name, @mess);
428 # Note: this isn't quite as fancy as Test::More::like().
430 sub like ($$@) { like_yn (0,@_) }; # 0 for -
431 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
434 my ($flip, undef, $expected, $name, @mess) = @_;
436 # We just accept like(..., qr/.../), not like(..., '...'), and
437 # definitely not like(..., '/.../') like
438 # Test::Builder::maybe_regex() does.
439 unless (re::is_regexp($expected)) {
440 die "PANIC: The value '$expected' isn't a regexp. The like() function needs a qr// pattern, not a string";
444 $pass = $_[1] =~ /$expected/ if !$flip;
445 $pass = $_[1] !~ /$expected/ if $flip;
447 unshift(@mess, "# got '$_[1]'\n",
449 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
451 local $Level = $Level + 1;
452 _ok($pass, _where(), $name, @mess);
460 _ok(0, _where(), @_);
470 $test = $test + 1; # don't use ++
474 # Note: can't pass multipart messages since we try to
475 # be compatible with Test::More::skip().
478 my $n = @_ ? shift : 1;
483 $bad_swap = $why > 0 && $n == 0;
484 $both_zero = $why == 0 && $n == 0;
486 if ($bad_swap || $both_zero || @_) {
487 my $arg = "'$why', '$n'";
489 $arg .= join(", ", '', map { qq['$_'] } @_);
491 die qq[$0: expected skip(why, count), got skip($arg)\n];
494 _print "ok $test # skip $why\n";
501 sub skip_if_miniperl {
502 skip(@_) if is_miniperl();
505 sub skip_without_dynamic_extension {
506 my $extension = shift;
507 skip("no dynamic loading on miniperl, no extension $extension", @_)
509 return if &_have_dynamic_extension($extension);
510 skip("extension $extension was not built", @_);
515 my $n = @_ ? shift : 1;
518 _print "not ok $test # TODO & SKIP $why\n";
527 return 0 unless $#$ra == $#$rb;
528 for my $i (0..$#$ra) {
529 next if !defined $ra->[$i] && !defined $rb->[$i];
530 return 0 if !defined $ra->[$i];
531 return 0 if !defined $rb->[$i];
532 return 0 unless $ra->[$i] eq $rb->[$i];
538 my ($orig, $suspect) = @_;
540 while (my ($key, $value) = each %$suspect) {
541 # Force a hash recompute if this perl's internals can cache the hash key.
543 if (exists $orig->{$key}) {
545 defined $orig->{$key} != defined $value
546 || (defined $value && $orig->{$key} ne $value)
548 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
549 " now ", _qq($value), "\n";
553 _print "# key ", _qq($key), " is ", _qq($value),
554 ", not in original.\n";
558 foreach (keys %$orig) {
559 # Force a hash recompute if this perl's internals can cache the hash key.
561 next if (exists $suspect->{$_});
562 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
568 # We only provide a subset of the Test::More functionality.
571 if ($require =~ tr/[A-Za-z0-9:.]//c) {
572 fail("Invalid character in \"$require\", passed to require_ok");
577 is($@, '', _where(), "require $require");
583 if ($use =~ tr/[A-Za-z0-9:.]//c) {
584 fail("Invalid character in \"$use\", passed to use");
589 is($@, '', _where(), "use $use");
593 # runperl - Runs a separate perl interpreter and returns its output.
595 # switches => [ command-line switches ]
596 # nolib => 1 # don't use -I../lib (included by default)
597 # non_portable => Don't warn if a one liner contains quotes
598 # prog => one-liner (avoid quotes)
599 # progs => [ multi-liner (avoid quotes) ]
600 # progfile => perl script
601 # stdin => string to feed the stdin (or undef to redirect from /dev/null)
602 # stderr => If 'devnull' suppresses stderr, if other TRUE value redirect
604 # args => [ command-line arguments to the perl program ]
605 # verbose => print the command line
607 my $is_mswin = $^O eq 'MSWin32';
608 my $is_netware = $^O eq 'NetWare';
609 my $is_vms = $^O eq 'VMS';
610 my $is_cygwin = $^O eq 'cygwin';
613 my ($runperl, $args) = @_;
616 # In VMS protect with doublequotes because otherwise
617 # DCL will lowercase -- unless already doublequoted.
618 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
619 $runperl = $runperl . ' ' . $_;
624 sub _create_runperl { # Create the string to qx in runperl().
626 my $runperl = which_perl();
627 if ($runperl =~ m/\s/) {
628 $runperl = qq{"$runperl"};
630 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
631 if ($ENV{PERL_RUNPERL_DEBUG}) {
632 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
634 unless ($args{nolib}) {
635 $runperl = $runperl . ' "-I../lib"'; # doublequotes because of VMS
637 if ($args{switches}) {
639 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
640 unless ref $args{switches} eq "ARRAY";
641 $runperl = _quote_args($runperl, $args{switches});
643 if (defined $args{prog}) {
644 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
645 if defined $args{progs};
646 $args{progs} = [split /\n/, $args{prog}, -1]
648 if (defined $args{progs}) {
649 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
650 unless ref $args{progs} eq "ARRAY";
651 foreach my $prog (@{$args{progs}}) {
652 if (!$args{non_portable}) {
653 if ($prog =~ tr/'"//) {
654 warn "quotes in prog >>$prog<< are not portable";
656 if ($prog =~ /^([<>|]|2>)/) {
657 warn "Initial $1 in prog >>$prog<< is not portable";
659 if ($prog =~ /&\z/) {
660 warn "Trailing & in prog >>$prog<< is not portable";
663 if ($is_mswin || $is_netware || $is_vms) {
664 $runperl = $runperl . qq ( -e "$prog" );
667 $runperl = $runperl . qq ( -e '$prog' );
670 } elsif (defined $args{progfile}) {
671 $runperl = $runperl . qq( "$args{progfile}");
673 # You probably didn't want to be sucking in from the upstream stdin
674 die "test.pl:runperl(): none of prog, progs, progfile, args, "
675 . " switches or stdin specified"
676 unless defined $args{args} or defined $args{switches}
677 or defined $args{stdin};
679 if (defined $args{stdin}) {
680 # so we don't try to put literal newlines and crs onto the
682 $args{stdin} =~ s/\n/\\n/g;
683 $args{stdin} =~ s/\r/\\r/g;
685 if ($is_mswin || $is_netware || $is_vms) {
686 $runperl = qq{$Perl -e "print qq(} .
687 $args{stdin} . q{)" | } . $runperl;
690 $runperl = qq{$Perl -e 'print qq(} .
691 $args{stdin} . q{)' | } . $runperl;
693 } elsif (exists $args{stdin}) {
694 # Using the pipe construction above can cause fun on systems which use
695 # ksh as /bin/sh, as ksh does pipes differently (with one less process)
696 # With sh, for the command line 'perl -e 'print qq()' | perl -e ...'
697 # the sh process forks two children, which use exec to start the two
698 # perl processes. The parent shell process persists for the duration of
699 # the pipeline, and the second perl process starts with no children.
700 # With ksh (and zsh), the shell saves a process by forking a child for
701 # just the first perl process, and execing itself to start the second.
702 # This means that the second perl process starts with one child which
703 # it didn't create. This causes "fun" when if the tests assume that
704 # wait (or waitpid) will only return information about processes
705 # started within the test.
706 # They also cause fun on VMS, where the pipe implementation returns
707 # the exit code of the process at the front of the pipeline, not the
708 # end. This messes up any test using OPTION FATAL.
709 # Hence it's useful to have a way to make STDIN be at eof without
710 # needing a pipeline, so that the fork tests have a sane environment
711 # without these surprises.
713 # /dev/null appears to be surprisingly portable.
714 $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null');
716 if (defined $args{args}) {
717 $runperl = _quote_args($runperl, $args{args});
719 if (exists $args{stderr} && $args{stderr} eq 'devnull') {
720 $runperl = $runperl . ($is_mswin ? ' 2>nul' : ' 2>/dev/null');
722 elsif ($args{stderr}) {
723 $runperl = $runperl . ' 2>&1';
725 if ($args{verbose}) {
726 my $runperldisplay = $runperl;
727 $runperldisplay =~ s/\n/\n\#/g;
728 _print_stderr "# $runperldisplay\n";
733 # sub run_perl {} is alias to below
735 die "test.pl:runperl() does not take a hashref"
736 if ref $_[0] and ref $_[0] eq 'HASH';
737 my $runperl = &_create_runperl;
740 my $tainted = ${^TAINT};
742 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
745 # We will assume that if you're running under -T, you really mean to
746 # run a fresh perl, so we'll brute force launder everything for you
749 if (! eval {require Config; 1}) {
750 warn "test.pl had problems loading Config: $@";
753 $sep = $Config::Config{path_sep};
756 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
757 local @ENV{@keys} = ();
758 # Untaint, plus take out . and empty string:
759 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
760 $ENV{PATH} =~ /(.*)/s;
762 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
763 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
764 split quotemeta ($sep), $1;
765 if ($is_cygwin) { # Must have /bin under Cygwin
766 if (length $ENV{PATH}) {
767 $ENV{PATH} = $ENV{PATH} . $sep;
769 $ENV{PATH} = $ENV{PATH} . '/bin';
774 $result = `$runperl`;
776 $result = `$runperl`;
778 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
783 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
786 _print_stderr "# @_\n";
790 # A somewhat safer version of the sometimes wrong $^X.
792 unless (defined $Perl) {
795 # VMS should have 'perl' aliased properly
796 return $Perl if $is_vms;
799 if (! eval {require Config; 1}) {
800 warn "test.pl had problems loading Config: $@";
803 $exe = $Config::Config{_exe};
805 $exe = '' unless defined $exe;
807 # This doesn't absolutize the path: beware of future chdirs().
808 # We could do File::Spec->abs2rel() but that does getcwd()s,
809 # which is a bit heavyweight to do here.
811 if ($Perl =~ /^perl\Q$exe\E$/i) {
812 my $perl = "perl$exe";
813 if (! eval {require File::Spec; 1}) {
814 warn "test.pl had problems loading File::Spec: $@";
817 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
821 # Build up the name of the executable file from the name of
824 if ($Perl !~ /\Q$exe\E$/i) {
825 $Perl = $Perl . $exe;
828 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
830 # For subcommands to use.
831 $ENV{PERLEXE} = $Perl;
838 foreach my $file (@_) {
839 1 while unlink $file;
841 _print_stderr "# Couldn't unlink '$file': $!\n";
849 # _num_to_alpha - Returns a string of letters representing a positive integer.
852 # maximum number of letters
854 # returns undef if the number is negative
855 # returns undef if the number of letters is greater than the maximum wanted
857 # _num_to_alpha( 0) eq 'A';
858 # _num_to_alpha( 1) eq 'B';
859 # _num_to_alpha(25) eq 'Z';
860 # _num_to_alpha(26) eq 'AA';
861 # _num_to_alpha(27) eq 'AB';
863 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);
865 # Avoid ++ -- ranges split negative numbers
867 my($num,$max_char) = @_;
868 return unless $num >= 0;
871 $max_char = 0 if $max_char < 0;
874 $alpha = $letters[ $num % 26 ] . $alpha;
875 $num = int( $num / 26 );
880 next unless $max_char;
881 $char_count = $char_count + 1;
882 return if $char_count == $max_char;
888 END { unlink_all keys %tmpfiles }
890 # A regexp that matches the tempfile names
891 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
893 # Avoid ++, avoid ranges, avoid split //
894 my $tempfile_count = 0;
898 my $alpha = _num_to_alpha($tempfile_count,2);
899 last unless defined $alpha;
900 $try = $try . $alpha;
901 $tempfile_count = $tempfile_count + 1;
903 # Need to note all the file names we allocated, as a second request may
904 # come before the first is created.
905 if (!$tmpfiles{$try} && !-e $try) {
911 die "Can't find temporary file name starting \"tmp$$\"";
914 # register_tempfile - Adds a list of files to be removed at the end of the current test file
916 # a list of files to be removed later
918 # returns a count of how many file names were actually added
920 # Reuses %tmpfiles so that tempfile() will also skip any files added here
921 # even if the file doesn't exist yet.
923 sub register_tempfile {
927 _print_stderr "# Temporary file '$_' already added\n";
936 # This is the temporary file for _fresh_perl
937 my $tmpfile = tempfile();
940 my($prog, $action, $expect, $runperl_args, $name) = @_;
942 # Given the choice of the mis-parsable {}
943 # (we want an anon hash, but a borked lexer might think that it's a block)
944 # or relying on taking a reference to a lexical
945 # (\ might be mis-parsed, and the reference counting on the pad may go
947 # it feels like the least-worse thing is to assume that auto-vivification
948 # works. At least, this is only going to be a run-time failure, so won't
949 # affect tests using this file but not this function.
950 $runperl_args->{progfile} ||= $tmpfile;
951 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
953 open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
955 close TEST or die "Cannot close $tmpfile: $!";
957 my $results = runperl(%$runperl_args);
960 # Clean up the results into something a bit more predictable.
961 $results =~ s/\n+$//;
962 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
963 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
965 # bison says 'parse error' instead of 'syntax error',
966 # various yaccs may or may not capitalize 'syntax'.
967 $results =~ s/^(syntax|parse) error/syntax error/mig;
970 # some tests will trigger VMS messages that won't be expected
971 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
973 # pipes double these sometimes
974 $results =~ s/\n\n/\n/g;
977 # Use the first line of the program as a name if none was given
979 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
980 $name = $name . '...' if length $first_line > length $name;
983 # Historically this was implemented using a closure, but then that means
984 # that the tests for closures avoid using this code. Given that there
985 # are exactly two callers, doing exactly two things, the simpler approach
986 # feels like a better trade off.
988 if ($action eq 'eq') {
989 $pass = is($results, $expect, $name);
990 } elsif ($action eq '=~') {
991 $pass = like($results, $expect, $name);
993 die "_fresh_perl can't process action '$action'";
997 _diag "# PROG: \n$prog\n";
998 _diag "# STATUS: $status\n";
1007 # Combination of run_perl() and is().
1011 my($prog, $expected, $runperl_args, $name) = @_;
1013 # _fresh_perl() is going to clip the trailing newlines off the result.
1014 # This will make it so the test author doesn't have to know that.
1015 $expected =~ s/\n+$//;
1018 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
1024 # Combination of run_perl() and like().
1027 sub fresh_perl_like {
1028 my($prog, $expected, $runperl_args, $name) = @_;
1030 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
1033 # Many tests use the same format in __DATA__ or external files to specify a
1034 # sequence of (fresh) tests to run, extra files they may temporarily need, and
1035 # what the expected output is. Putting it here allows common code to serve
1036 # these multiple tests.
1038 # Each program is source code to run followed by an "EXPECT" line, followed
1039 # by the expected output.
1041 # The code to run may begin with a command line switch such as -w or -0777
1042 # (alphanumerics only), and may contain (note the '# ' on each):
1043 # # TODO reason for todo
1044 # # SKIP reason for skip
1045 # # SKIP ?code to test if this should be skipped
1046 # # NAME name of the test (as with ok($ok, $name))
1048 # The expected output may contain:
1049 # OPTION list of options
1050 # OPTIONS list of options
1052 # The possible options for OPTION may be:
1053 # regex - the expected output is a regular expression
1054 # random - all lines match but in any order
1055 # fatal - the code will fail fatally (croak, die)
1057 # If the actual output contains a line "SKIPPED" the test will be
1060 # If the actual output contains a line "PREFIX", any output starting with that
1061 # line will be ignored when comparing with the expected output
1063 # If the global variable $FATAL is true then OPTION fatal is the
1066 sub _setup_one_file {
1068 # Store the filename as a program that started at line 0.
1069 # Real files count lines starting at line 1.
1070 my @these = (0, shift);
1071 my ($lineno, $current);
1073 if ($_ eq "########\n") {
1074 if (defined $current) {
1075 push @these, $lineno, $current;
1079 if (!defined $current) {
1085 if (defined $current) {
1086 push @these, $lineno, $current;
1088 ((scalar @these) / 2 - 1, @these);
1091 sub setup_multiple_progs {
1093 foreach my $file (@_) {
1094 next if $file =~ /(?:~|\.orig|,v)$/;
1095 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1098 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1106 # This is an internal error, and should never happen. All bar one of
1107 # the files had an __END__ marker to signal the end of their preamble,
1108 # although for some it wasn't technically necessary as they have no
1109 # tests. It might be possible to process files without an __END__ by
1110 # seeking back to the start and treating the whole file as tests, but
1111 # it's simpler and more reliable just to make the rule that all files
1112 # must have __END__ in. This should never fail - a file without an
1113 # __END__ should not have been checked in, because the regression tests
1114 # would not have passed.
1115 die "Could not find '__END__' in $file"
1118 my ($t, @p) = _setup_one_file($fh, $file);
1123 or die "Cannot close $file: $!\n";
1125 return ($tests, @prgs);
1128 sub run_multiple_progs {
1132 # The tests in lib run in a temporary subdirectory of t, and always
1133 # pass in a list of "programs" to run
1136 # The tests below t run in t and pass in a file handle. In theory we
1137 # can pass (caller)[1] as the second argument to report errors with
1138 # the filename of our caller, as the handle is always DATA. However,
1139 # line numbers in DATA count from the __END__ token, so will be wrong.
1140 # Which is more confusing than not providing line numbers. So, for now,
1141 # don't provide line numbers. No obvious clean solution - one hack
1142 # would be to seek DATA back to the start and read to the __END__ token,
1143 # but that feels almost like we should just open $0 instead.
1145 # Not going to rely on undef in list assignment.
1147 ($dummy, @prgs) = _setup_one_file(shift);
1150 my $tmpfile = tempfile();
1154 while (defined ($line = shift @prgs)) {
1158 if (defined $file) {
1159 print "# From $file\n";
1166 if (s/^(\s*-\w+)//) {
1169 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1172 foreach my $what (qw(skip todo)) {
1173 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1174 # If the SKIP reason starts ? then it's taken as a code snippet to
1175 # evaluate. This provides the flexibility to have conditional SKIPs
1176 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1177 my $temp = eval $reason{$what};
1179 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1181 $reason{$what} = $temp;
1186 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1190 if ($reason{skip}) {
1193 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1198 if ($prog =~ /--FILE--/) {
1199 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1201 die "Internal error: test $_ didn't split into pairs, got " .
1202 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1204 while (@files > 2) {
1205 my $filename = shift @files;
1206 my $code = shift @files;
1207 push @temps, $filename;
1208 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1210 File::Path::mkpath($1);
1211 push(@temp_path, $1);
1213 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1215 close $fh or die "Cannot close $filename: $!\n";
1218 $prog = shift @files;
1221 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1224 open STDERR, '>&', STDOUT
1225 or die "Can't dup STDOUT->STDERR: $!;";
1228 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1229 print $fh $prog,"\n";
1230 close $fh or die "Cannot close $tmpfile: $!";
1231 my $results = runperl( stderr => 1, progfile => $tmpfile,
1233 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1234 : (switches => [$switch])
1237 $results =~ s/\n+$//;
1238 # allow expected output to be written as if $prog is on STDIN
1239 $results =~ s/$::tempfile_regexp/-/g;
1241 # some tests will trigger VMS messages that won't be expected
1242 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1244 # pipes double these sometimes
1245 $results =~ s/\n\n/\n/g;
1247 # bison says 'parse error' instead of 'syntax error',
1248 # various yaccs may or may not capitalize 'syntax'.
1249 $results =~ s/^(syntax|parse) error/syntax error/mig;
1250 # allow all tests to run when there are leaks
1251 $results =~ s/Scalars leaked: \d+\n//g;
1253 $expected =~ s/\n+$//;
1254 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1255 # any special options? (OPTIONS foo bar zap)
1256 my $option_regex = 0;
1257 my $option_random = 0;
1259 if ($expected =~ s/^OPTIONS? (.+)\n//) {
1260 foreach my $option (split(' ', $1)) {
1261 if ($option eq 'regex') { # allow regular expressions
1264 elsif ($option eq 'random') { # all lines match, but in any order
1267 elsif ($option eq 'fatal') { # perl should fail
1271 die "$0: Unknown OPTION '$option'\n";
1275 die "$0: can't have OPTION regex and random\n"
1276 if $option_regex + $option_random > 1;
1278 if ($results =~ s/^SKIPPED\n//) {
1279 print "$results\n" ;
1283 if ($option_random) {
1284 my @got = sort split "\n", $results;
1285 my @expected = sort split "\n", $expected;
1287 $ok = "@got" eq "@expected";
1289 elsif ($option_regex) {
1290 $ok = $results =~ /^$expected/;
1293 $ok = $results =~ /^\Q$expected/;
1296 $ok = $results eq $expected;
1299 if ($ok && $fatal && !($status >> 8)) {
1304 local $::TODO = $reason{todo};
1307 my $err_line = "PROG: $switch\n$prog\n" .
1308 "EXPECTED:\n$expected\n";
1309 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1310 $err_line .= "GOT:\n$results\n";
1311 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1313 $err_line =~ s/^/# /mg;
1314 print $err_line; # Harness can't filter it out from STDERR.
1317 print STDERR $err_line;
1321 if (defined $file) {
1322 _ok($ok, "at $file line $line", $name);
1324 # We don't have file and line number data for the test, so report
1325 # errors as coming from our caller.
1326 local $Level = $Level + 1;
1333 foreach (@temp_path) {
1334 File::Path::rmtree $_ if -d $_;
1340 my($proto, @methods) = @_;
1341 my $class = ref $proto || $proto;
1343 unless( @methods ) {
1344 return _ok( 0, _where(), "$class->can(...)" );
1348 foreach my $method (@methods) {
1349 local($!, $@); # don't interfere with caller's $@
1350 # eval sometimes resets $!
1351 eval { $proto->can($method) } || push @nok, $method;
1355 $name = @methods == 1 ? "$class->can('$methods[0]')"
1356 : "$class->can(...)";
1358 _ok( !@nok, _where(), $name );
1362 # Call $class->new( @$args ); and run the result through object_ok.
1363 # See Test::More::new_ok
1365 my($class, $args, $obj_name) = @_;
1367 $object_name = "The object" unless defined $obj_name;
1369 local $Level = $Level + 1;
1372 my $ok = eval { $obj = $class->new(@$args); 1 };
1376 object_ok($obj, $class, $object_name);
1379 ok( 0, "new() died" );
1380 diag("Error was: $@");
1389 my($object, $class, $obj_name) = @_;
1392 $obj_name = 'The object' unless defined $obj_name;
1393 my $name = "$obj_name isa $class";
1394 if( !defined $object ) {
1395 $diag = "$obj_name isn't defined";
1398 my $whatami = ref $object ? 'object' : 'class';
1400 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1401 local($@, $!); # eval sometimes resets $!
1402 my $rslt = eval { $object->isa($class) };
1403 my $error = $@; # in case something else blows away $@
1406 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1407 # It's an unblessed reference
1408 $obj_name = 'The reference' unless defined $obj_name;
1409 if( !UNIVERSAL::isa($object, $class) ) {
1410 my $ref = ref $object;
1411 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1414 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1415 # It's something that can't even be a class
1416 $obj_name = 'The thing' unless defined $obj_name;
1417 $diag = "$obj_name isn't a class or reference";
1421 WHOA! I tried to call ->isa on your object and got some weird error.
1422 This should never happen. Please contact the author immediately.
1429 $obj_name = "The $whatami" unless defined $obj_name;
1430 my $ref = ref $object;
1431 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1435 _ok( !$diag, _where(), $name );
1440 my($class, $isa, $class_name) = @_;
1442 # Written so as to count as one test
1443 local $Level = $Level + 1;
1445 ok( 0, "$class is a reference, not a class name" );
1448 isa_ok($class, $isa, $class_name);
1454 my($obj, $isa, $obj_name) = @_;
1456 local $Level = $Level + 1;
1458 ok( 0, "$obj is not a reference" );
1461 isa_ok($obj, $isa, $obj_name);
1466 # Purposefully avoiding a closure.
1468 push @::__capture, join "", @_;
1471 sub capture_warnings {
1475 local $SIG {__WARN__} = \&__capture;
1477 return @::__capture;
1480 # This will generate a variable number of tests.
1481 # Use done_testing() instead of a fixed plan.
1483 my ($code, $expect, $name) = @_;
1484 local $Level = $Level + 1;
1486 my @w = capture_warnings($code);
1488 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1489 foreach my $e (@$expect) {
1491 like(shift @w, $e, $name);
1493 is(shift @w, $e, $name);
1497 diag("Saw these additional warnings:");
1498 diag($_) foreach @w;
1502 sub _fail_excess_warnings {
1503 my($expect, $got, $name) = @_;
1504 local $Level = $Level + 1;
1505 # This will fail, and produce diagnostics
1506 is($expect, scalar @$got, $name);
1507 diag("Saw these warnings:");
1508 diag($_) foreach @$got;
1512 my ($code, $expect, $name) = @_;
1513 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1515 local $Level = $Level + 1;
1516 my @w = capture_warnings($code);
1518 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1520 is($w[0], $expect, $name);
1525 my ($code, $expect, $name) = @_;
1526 die sprintf "Expect must be a regexp object"
1527 unless ref $expect eq 'Regexp';
1528 local $Level = $Level + 1;
1529 my @w = capture_warnings($code);
1531 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1533 like($w[0], $expect, $name);
1537 # Set a watchdog to timeout the entire test file
1538 # NOTE: If the test file uses 'threads', then call the watchdog() function
1539 # _AFTER_ the 'threads' module is loaded.
1542 my $timeout = shift;
1543 my $method = shift || "";
1544 my $timeout_msg = 'Test process timed out - terminating';
1546 # Valgrind slows perl way down so give it more time before dying.
1547 $timeout *= 10 if $ENV{PERL_VALGRIND};
1549 my $pid_to_kill = $$; # PID for this process
1551 if ($method eq "alarm") {
1552 goto WATCHDOG_VIA_ALARM;
1555 # shut up use only once warning
1556 my $threads_on = $threads::threads && $threads::threads;
1558 # Don't use a watchdog process if 'threads' is loaded -
1559 # use a watchdog thread instead
1560 if (!$threads_on || $method eq "process") {
1562 # On Windows and VMS, try launching a watchdog process
1563 # using system(1, ...) (see perlport.pod)
1564 if ($is_mswin || $is_vms) {
1565 # On Windows, try to get the 'real' PID
1567 eval { require Win32; };
1568 if (defined(&Win32::GetCurrentProcessId)) {
1569 $pid_to_kill = Win32::GetCurrentProcessId();
1573 # If we still have a fake PID, we can't use this method at all
1574 return if ($pid_to_kill <= 0);
1576 # Launch watchdog process
1579 local $SIG{'__WARN__'} = sub {
1580 _diag("Watchdog warning: $_[0]");
1582 my $sig = $is_vms ? 'TERM' : 'KILL';
1583 my $cmd = _create_runperl( prog => "sleep($timeout);" .
1584 "warn qq/# $timeout_msg" . '\n/;' .
1585 "kill($sig, $pid_to_kill);");
1586 $watchdog = system(1, $cmd);
1588 if ($@ || ($watchdog <= 0)) {
1589 _diag('Failed to start watchdog');
1595 # Add END block to parent to terminate and
1596 # clean up watchdog process
1597 # Win32 watchdog is launched by cmd.exe shell, so use process group
1598 # kill, otherwise the watchdog is never killed and harness waits
1599 # every time for the timeout, #121395
1601 "END { local \$! = 0; local \$? = 0;
1602 wait() if kill('-KILL', $watchdog); };"
1603 : "END { local \$! = 0; local \$? = 0;
1604 wait() if kill('KILL', $watchdog); };");
1608 # Try using fork() to generate a watchdog process
1610 eval { $watchdog = fork() };
1611 if (defined($watchdog)) {
1612 if ($watchdog) { # Parent process
1613 # Add END block to parent to terminate and
1614 # clean up watchdog process
1615 eval "END { local \$! = 0; local \$? = 0;
1616 wait() if kill('KILL', $watchdog); };";
1620 ### Watchdog process code
1622 # Load POSIX if available
1623 eval { require POSIX; };
1625 # Execute the timeout
1626 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1629 # Kill test process if still running
1630 if (kill(0, $pid_to_kill)) {
1631 _diag($timeout_msg);
1632 kill('KILL', $pid_to_kill);
1634 # sometimes the above isn't enough on cygwin
1635 sleep 1; # wait a little, it might have worked after all
1636 system("/bin/kill -f $pid_to_kill");
1640 # Don't execute END block (added at beginning of this file)
1643 # Terminate ourself (i.e., the watchdog)
1644 POSIX::_exit(1) if (defined(&POSIX::_exit));
1648 # fork() failed - fall through and try using a thread
1651 # Use a watchdog thread because either 'threads' is loaded,
1653 if (eval {require threads; 1}) {
1654 'threads'->create(sub {
1655 # Load POSIX if available
1656 eval { require POSIX; };
1658 # Execute the timeout
1659 my $time_left = $timeout;
1661 $time_left = $time_left - sleep($time_left);
1662 } while ($time_left > 0);
1664 # Kill the parent (and ourself)
1665 select(STDERR); $| = 1;
1666 _diag($timeout_msg);
1667 POSIX::_exit(1) if (defined(&POSIX::_exit));
1668 my $sig = $is_vms ? 'TERM' : 'KILL';
1669 kill($sig, $pid_to_kill);
1674 # If everything above fails, then just use an alarm timeout
1676 if (eval { alarm($timeout); 1; }) {
1677 # Load POSIX if available
1678 eval { require POSIX; };
1680 # Alarm handler will do the actual 'killing'
1681 $SIG{'ALRM'} = sub {
1682 select(STDERR); $| = 1;
1683 _diag($timeout_msg);
1684 POSIX::_exit(1) if (defined(&POSIX::_exit));
1685 my $sig = $is_vms ? 'TERM' : 'KILL';
1686 kill($sig, $pid_to_kill);