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') {
58 _print "1..$n\n" unless $noplan;
63 # Set the plan at the end. See Test::More::done_testing.
76 if (defined $planned && $planned != $ran) {
78 "# Looks like you planned $planned tests but ran $ran.\n";
87 my @mess = _comment(@_);
88 $TODO ? _print(@mess) : _print_stderr(@mess);
91 # Use this instead of "print STDERR" when outputting failure diagnostic
97 # Use this instead of "print" when outputting informational messages
100 _print( _comment(@_) );
104 return !defined &DynaLoader::boot_DynaLoader;
108 return map { /^#/ ? "$_\n" : "# $_\n" }
109 map { split /\n/ } @_;
112 sub _have_dynamic_extension {
113 my $extension = shift;
114 unless (eval {require Config; 1}) {
115 warn "test.pl had problems loading Config: $@";
118 $extension =~ s!::!/!g;
119 return 1 if ($Config::Config{extensions} =~ /\b$extension\b/);
124 _print "1..0 # Skip @_\n";
131 sub skip_all_if_miniperl {
132 skip_all(@_) if is_miniperl();
135 sub skip_all_without_dynamic_extension {
136 my ($extension) = @_;
137 skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
138 return if &_have_dynamic_extension;
139 skip_all("$extension was not built");
142 sub skip_all_without_perlio {
143 skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
146 sub skip_all_without_config {
147 unless (eval {require Config; 1}) {
148 warn "test.pl had problems loading Config: $@";
152 next if $Config::Config{$_};
153 my $key = $_; # Need to copy, before trying to modify.
160 sub find_git_or_skip {
161 my ($source_dir, $reason);
164 } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
165 my $where = readlink 'MANIFEST';
166 die "Can't readling MANIFEST: $!" unless defined $where;
167 die "Confusing symlink target for MANIFEST, '$where'"
168 unless $where =~ s!/MANIFEST\z!!;
169 if (-d "$where/.git") {
170 # Looks like we are in a symlink tree
171 if (exists $ENV{GIT_DIR}) {
172 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it");
174 note("Found source tree at $where, setting \$ENV{GIT_DIR}");
175 $ENV{GIT_DIR} = "$where/.git";
177 $source_dir = $where;
181 my $version_string = `git --version`;
182 if (defined $version_string
183 && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
184 return $source_dir if eval "v$1 ge v1.5.0";
185 # If you have earlier than 1.5.0 and it works, change this test
186 $reason = "in git checkout, but git version '$1$2' too old";
188 $reason = "in git checkout, but cannot run git";
191 $reason = 'not being run from a git checkout';
193 skip_all($reason) if $_[0] && $_[0] eq 'all';
199 _print("Bail out! $reason\n");
204 my ($pass, $where, $name, @mess) = @_;
205 # Do not try to microoptimize by factoring out the "not ".
209 # escape out '#' or it will interfere with '# skip' and such
211 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
213 $out = $pass ? "ok $test" : "not ok $test";
217 $out = $out . " # TODO $TODO";
219 $Tests_Are_Passing = 0 unless $pass;
225 note @mess; # Ensure that the message is properly escaped.
228 my $msg = "# Failed test $test - ";
229 $msg.= "$name " if $name;
235 $test = $test + 1; # don't use ++
241 my @caller = caller($Level);
242 return "at $caller[1] line $caller[2]";
245 # DON'T use this for matches. Use like() instead.
247 my ($pass, $name, @mess) = @_;
248 _ok($pass, _where(), $name, @mess);
253 return 'undef' unless defined $x;
262 return defined $x ? '"' . display ($x) . '"' : 'undef';
265 # keys are the codes \n etc map to, values are 2 char strings such as \n
266 my %backslash_escape;
267 foreach my $x (split //, 'nrtfa\\\'"') {
268 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
270 # A way to display scalars containing control characters and Unicode.
271 # Trying to avoid setting $_, or relying on local $_ to work.
275 if (defined $x and not ref $x) {
277 foreach my $c (unpack("U*", $x)) {
279 $y = $y . sprintf "\\x{%x}", $c;
280 } elsif ($backslash_escape{$c}) {
281 $y = $y . $backslash_escape{$c};
283 my $z = chr $c; # Maybe we can get away with a literal...
284 if ($z =~ /[[:^print:]]/) {
286 # Use octal for characters traditionally expressed as
287 # such: the low controls, which on EBCDIC aren't
288 # necessarily the same ones as on ASCII platforms, but
289 # are small ordinals, nonetheless
291 $z = sprintf "\\%03o", $c;
293 $z = sprintf "\\x{%x}", $c;
301 return $x unless wantarray;
308 my ($got, $expected, $name, @mess) = @_;
311 if( !defined $got || !defined $expected ) {
312 # undef only matches undef
313 $pass = !defined $got && !defined $expected;
316 $pass = $got eq $expected;
320 unshift(@mess, "# got "._qq($got)."\n",
321 "# expected "._qq($expected)."\n");
323 _ok($pass, _where(), $name, @mess);
327 my ($got, $isnt, $name, @mess) = @_;
330 if( !defined $got || !defined $isnt ) {
331 # undef only matches undef
332 $pass = defined $got || defined $isnt;
335 $pass = $got ne $isnt;
339 unshift(@mess, "# it should not be "._qq($got)."\n",
342 _ok($pass, _where(), $name, @mess);
346 my($got, $type, $expected, $name, @mess) = @_;
351 local($@,$!); # don't interfere with $@
352 # eval() sometimes resets $!
353 $pass = eval "\$got $type \$expected";
356 # It seems Irix long doubles can have 2147483648 and 2147483648
357 # that stringify to the same thing but are actually numerically
358 # different. Display the numbers if $type isn't a string operator,
359 # and the numbers are stringwise the same.
360 # (all string operators have alphabetic names, so tr/a-z// is true)
361 # This will also show numbers for some unneeded cases, but will
362 # definitely be helpful for things such as == and <= that fail
363 if ($got eq $expected and $type !~ tr/a-z//) {
364 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
366 unshift(@mess, "# got "._qq($got)."\n",
367 "# expected $type "._qq($expected)."\n");
369 _ok($pass, _where(), $name, @mess);
372 # Check that $got is within $range of $expected
373 # if $range is 0, then check it's exact
374 # else if $expected is 0, then $range is an absolute value
375 # otherwise $range is a fractional error.
376 # Here $range must be numeric, >= 0
377 # Non numeric ranges might be a useful future extension. (eg %)
379 my ($got, $expected, $range, $name, @mess) = @_;
381 if (!defined $got or !defined $expected or !defined $range) {
382 # This is a fail, but doesn't need extra diagnostics
383 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
385 unshift @mess, "# got, expected and range must be numeric\n";
386 } elsif ($range < 0) {
387 # This is also a fail
388 unshift @mess, "# range must not be negative\n";
389 } elsif ($range == 0) {
391 $pass = $got == $expected;
392 } elsif ($expected == 0) {
393 # If expected is 0, treat range as absolute
394 $pass = ($got <= $range) && ($got >= - $range);
396 my $diff = $got - $expected;
397 $pass = abs ($diff / $expected) < $range;
400 if ($got eq $expected) {
401 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
403 unshift@mess, "# got "._qq($got)."\n",
404 "# expected "._qq($expected)." (within "._qq($range).")\n";
406 _ok($pass, _where(), $name, @mess);
409 # Note: this isn't quite as fancy as Test::More::like().
411 sub like ($$@) { like_yn (0,@_) }; # 0 for -
412 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
415 my ($flip, undef, $expected, $name, @mess) = @_;
417 $pass = $_[1] =~ /$expected/ if !$flip;
418 $pass = $_[1] !~ /$expected/ if $flip;
420 unshift(@mess, "# got '$_[1]'\n",
422 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
424 local $Level = $Level + 1;
425 _ok($pass, _where(), $name, @mess);
433 _ok(0, _where(), @_);
443 $test = $test + 1; # don't use ++
447 # Note: can't pass multipart messages since we try to
448 # be compatible with Test::More::skip().
451 my $n = @_ ? shift : 1;
453 _print "ok $test # skip $why\n";
460 sub skip_if_miniperl {
461 skip(@_) if is_miniperl();
464 sub skip_without_dynamic_extension {
465 my ($extension) = @_;
466 skip("no dynamic loading on miniperl, no $extension") if is_miniperl();
467 return if &_have_dynamic_extension;
468 skip("$extension was not built");
473 my $n = @_ ? shift : 1;
476 _print "not ok $test # TODO & SKIP $why\n";
485 return 0 unless $#$ra == $#$rb;
486 for my $i (0..$#$ra) {
487 next if !defined $ra->[$i] && !defined $rb->[$i];
488 return 0 if !defined $ra->[$i];
489 return 0 if !defined $rb->[$i];
490 return 0 unless $ra->[$i] eq $rb->[$i];
496 my ($orig, $suspect) = @_;
498 while (my ($key, $value) = each %$suspect) {
499 # Force a hash recompute if this perl's internals can cache the hash key.
501 if (exists $orig->{$key}) {
503 defined $orig->{$key} != defined $value
504 || (defined $value && $orig->{$key} ne $value)
506 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
507 " now ", _qq($value), "\n";
511 _print "# key ", _qq($key), " is ", _qq($value),
512 ", not in original.\n";
516 foreach (keys %$orig) {
517 # Force a hash recompute if this perl's internals can cache the hash key.
519 next if (exists $suspect->{$_});
520 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
526 # We only provide a subset of the Test::More functionality.
529 if ($require =~ tr/[A-Za-z0-9:.]//c) {
530 fail("Invalid character in \"$require\", passed to require_ok");
535 is($@, '', _where(), "require $require");
541 if ($use =~ tr/[A-Za-z0-9:.]//c) {
542 fail("Invalid character in \"$use\", passed to use");
547 is($@, '', _where(), "use $use");
551 # runperl - Runs a separate perl interpreter.
553 # switches => [ command-line switches ]
554 # nolib => 1 # don't use -I../lib (included by default)
555 # non_portable => Don't warn if a one liner contains quotes
556 # prog => one-liner (avoid quotes)
557 # progs => [ multi-liner (avoid quotes) ]
558 # progfile => perl script
559 # stdin => string to feed the stdin (or undef to redirect from /dev/null)
560 # stderr => redirect stderr to stdout
561 # args => [ command-line arguments to the perl program ]
562 # verbose => print the command line
564 my $is_mswin = $^O eq 'MSWin32';
565 my $is_netware = $^O eq 'NetWare';
566 my $is_vms = $^O eq 'VMS';
567 my $is_cygwin = $^O eq 'cygwin';
570 my ($runperl, $args) = @_;
573 # In VMS protect with doublequotes because otherwise
574 # DCL will lowercase -- unless already doublequoted.
575 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
576 $runperl = $runperl . ' ' . $_;
581 sub _create_runperl { # Create the string to qx in runperl().
583 my $runperl = which_perl();
584 if ($runperl =~ m/\s/) {
585 $runperl = qq{"$runperl"};
587 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
588 if ($ENV{PERL_RUNPERL_DEBUG}) {
589 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
591 unless ($args{nolib}) {
592 $runperl = $runperl . ' "-I../lib"'; # doublequotes because of VMS
594 if ($args{switches}) {
596 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
597 unless ref $args{switches} eq "ARRAY";
598 $runperl = _quote_args($runperl, $args{switches});
600 if (defined $args{prog}) {
601 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
602 if defined $args{progs};
603 $args{progs} = [$args{prog}]
605 if (defined $args{progs}) {
606 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
607 unless ref $args{progs} eq "ARRAY";
608 foreach my $prog (@{$args{progs}}) {
609 if ($prog =~ tr/'"// && !$args{non_portable}) {
610 warn "quotes in prog >>$prog<< are not portable";
612 if ($is_mswin || $is_netware || $is_vms) {
613 $runperl = $runperl . qq ( -e "$prog" );
616 $runperl = $runperl . qq ( -e '$prog' );
619 } elsif (defined $args{progfile}) {
620 $runperl = $runperl . qq( "$args{progfile}");
622 # You probably didn't want to be sucking in from the upstream stdin
623 die "test.pl:runperl(): none of prog, progs, progfile, args, "
624 . " switches or stdin specified"
625 unless defined $args{args} or defined $args{switches}
626 or defined $args{stdin};
628 if (defined $args{stdin}) {
629 # so we don't try to put literal newlines and crs onto the
631 $args{stdin} =~ s/\n/\\n/g;
632 $args{stdin} =~ s/\r/\\r/g;
634 if ($is_mswin || $is_netware || $is_vms) {
635 $runperl = qq{$Perl -e "print qq(} .
636 $args{stdin} . q{)" | } . $runperl;
639 $runperl = qq{$Perl -e 'print qq(} .
640 $args{stdin} . q{)' | } . $runperl;
642 } elsif (exists $args{stdin}) {
643 # Using the pipe construction above can cause fun on systems which use
644 # ksh as /bin/sh, as ksh does pipes differently (with one less process)
645 # With sh, for the command line 'perl -e 'print qq()' | perl -e ...'
646 # the sh process forks two children, which use exec to start the two
647 # perl processes. The parent shell process persists for the duration of
648 # the pipeline, and the second perl process starts with no children.
649 # With ksh (and zsh), the shell saves a process by forking a child for
650 # just the first perl process, and execing itself to start the second.
651 # This means that the second perl process starts with one child which
652 # it didn't create. This causes "fun" when if the tests assume that
653 # wait (or waitpid) will only return information about processes
654 # started within the test.
655 # They also cause fun on VMS, where the pipe implementation returns
656 # the exit code of the process at the front of the pipeline, not the
657 # end. This messes up any test using OPTION FATAL.
658 # Hence it's useful to have a way to make STDIN be at eof without
659 # needing a pipeline, so that the fork tests have a sane environment
660 # without these surprises.
662 # /dev/null appears to be surprisingly portable.
663 $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null');
665 if (defined $args{args}) {
666 $runperl = _quote_args($runperl, $args{args});
668 $runperl = $runperl . ' 2>&1' if $args{stderr};
669 if ($args{verbose}) {
670 my $runperldisplay = $runperl;
671 $runperldisplay =~ s/\n/\n\#/g;
672 _print_stderr "# $runperldisplay\n";
678 die "test.pl:runperl() does not take a hashref"
679 if ref $_[0] and ref $_[0] eq 'HASH';
680 my $runperl = &_create_runperl;
683 my $tainted = ${^TAINT};
685 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
688 # We will assume that if you're running under -T, you really mean to
689 # run a fresh perl, so we'll brute force launder everything for you
692 if (! eval {require Config; 1}) {
693 warn "test.pl had problems loading Config: $@";
696 $sep = $Config::Config{path_sep};
699 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
700 local @ENV{@keys} = ();
701 # Untaint, plus take out . and empty string:
702 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
703 $ENV{PATH} =~ /(.*)/s;
705 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
706 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
707 split quotemeta ($sep), $1;
708 if ($is_cygwin) { # Must have /bin under Cygwin
709 if (length $ENV{PATH}) {
710 $ENV{PATH} = $ENV{PATH} . $sep;
712 $ENV{PATH} = $ENV{PATH} . '/bin';
717 $result = `$runperl`;
719 $result = `$runperl`;
721 $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
726 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
729 _print_stderr "# @_\n";
733 # A somewhat safer version of the sometimes wrong $^X.
735 unless (defined $Perl) {
738 # VMS should have 'perl' aliased properly
739 return $Perl if $is_vms;
742 if (! eval {require Config; 1}) {
743 warn "test.pl had problems loading Config: $@";
746 $exe = $Config::Config{_exe};
748 $exe = '' unless defined $exe;
750 # This doesn't absolutize the path: beware of future chdirs().
751 # We could do File::Spec->abs2rel() but that does getcwd()s,
752 # which is a bit heavyweight to do here.
754 if ($Perl =~ /^perl\Q$exe\E$/i) {
755 my $perl = "perl$exe";
756 if (! eval {require File::Spec; 1}) {
757 warn "test.pl had problems loading File::Spec: $@";
760 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
764 # Build up the name of the executable file from the name of
767 if ($Perl !~ /\Q$exe\E$/i) {
768 $Perl = $Perl . $exe;
771 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
773 # For subcommands to use.
774 $ENV{PERLEXE} = $Perl;
781 foreach my $file (@_) {
782 1 while unlink $file;
784 _print_stderr "# Couldn't unlink '$file': $!\n";
792 # _num_to_alpha - Returns a string of letters representing a positive integer.
795 # maximum number of letters
797 # returns undef if the number is negative
798 # returns undef if the number of letters is greater than the maximum wanted
800 # _num_to_alpha( 0) eq 'A';
801 # _num_to_alpha( 1) eq 'B';
802 # _num_to_alpha(25) eq 'Z';
803 # _num_to_alpha(26) eq 'AA';
804 # _num_to_alpha(27) eq 'AB';
806 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);
808 # Avoid ++ -- ranges split negative numbers
810 my($num,$max_char) = @_;
811 return unless $num >= 0;
814 $max_char = 0 if $max_char < 0;
817 $alpha = $letters[ $num % 26 ] . $alpha;
818 $num = int( $num / 26 );
823 next unless $max_char;
824 $char_count = $char_count + 1;
825 return if $char_count == $max_char;
831 END { unlink_all keys %tmpfiles }
833 # A regexp that matches the tempfile names
834 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
836 # Avoid ++, avoid ranges, avoid split //
837 my $tempfile_count = 0;
841 my $alpha = _num_to_alpha($tempfile_count,2);
842 last unless defined $alpha;
843 $try = $try . $alpha;
844 $tempfile_count = $tempfile_count + 1;
846 # Need to note all the file names we allocated, as a second request may
847 # come before the first is created.
848 if (!$tmpfiles{$try} && !-e $try) {
854 die "Can't find temporary file name starting \"tmp$$\"";
857 # This is the temporary file for _fresh_perl
858 my $tmpfile = tempfile();
861 my($prog, $action, $expect, $runperl_args, $name) = @_;
863 # Given the choice of the mis-parsable {}
864 # (we want an anon hash, but a borked lexer might think that it's a block)
865 # or relying on taking a reference to a lexical
866 # (\ might be mis-parsed, and the reference counting on the pad may go
868 # it feels like the least-worse thing is to assume that auto-vivification
869 # works. At least, this is only going to be a run-time failure, so won't
870 # affect tests using this file but not this function.
871 $runperl_args->{progfile} ||= $tmpfile;
872 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
874 open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
876 close TEST or die "Cannot close $tmpfile: $!";
878 my $results = runperl(%$runperl_args);
881 # Clean up the results into something a bit more predictable.
882 $results =~ s/\n+$//;
883 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
884 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
886 # bison says 'parse error' instead of 'syntax error',
887 # various yaccs may or may not capitalize 'syntax'.
888 $results =~ s/^(syntax|parse) error/syntax error/mig;
891 # some tests will trigger VMS messages that won't be expected
892 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
894 # pipes double these sometimes
895 $results =~ s/\n\n/\n/g;
898 # Use the first line of the program as a name if none was given
900 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
901 $name = $name . '...' if length $first_line > length $name;
904 # Historically this was implemented using a closure, but then that means
905 # that the tests for closures avoid using this code. Given that there
906 # are exactly two callers, doing exactly two things, the simpler approach
907 # feels like a better trade off.
909 if ($action eq 'eq') {
910 $pass = is($results, $expect, $name);
911 } elsif ($action eq '=~') {
912 $pass = like($results, $expect, $name);
914 die "_fresh_perl can't process action '$action'";
918 _diag "# PROG: \n$prog\n";
919 _diag "# STATUS: $status\n";
928 # Combination of run_perl() and is().
932 my($prog, $expected, $runperl_args, $name) = @_;
934 # _fresh_perl() is going to clip the trailing newlines off the result.
935 # This will make it so the test author doesn't have to know that.
936 $expected =~ s/\n+$//;
939 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
945 # Combination of run_perl() and like().
948 sub fresh_perl_like {
949 my($prog, $expected, $runperl_args, $name) = @_;
951 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
954 # Many tests use the same format in __DATA__ or external files to specify a
955 # sequence of (fresh) tests to run, extra files they may temporarily need, and
956 # what the expected output is. So have excatly one copy of the code to run that
958 # Each program is source code to run followed by an "EXPECT" line, followed
959 # by the expected output.
961 # The code to run may begin with a command line switch such as -w or -0777
962 # (alphanumerics only), and may contain (note the '# ' on each):
963 # # TODO reason for todo
964 # # SKIP reason for skip
965 # # SKIP ?code to test if this should be skipped
966 # # NAME name of the test (as with ok($ok, $name))
968 # The expected output may contain:
969 # OPTION list of options
970 # OPTIONS list of options
972 # The possible options for OPTION may be:
973 # regex - the expected output is a regular expression
974 # random - all lines match but in any order
975 # fatal - the code will fail fatally (croak, die)
977 # If the actual output contains a line "SKIPPED" the test will be
980 # If the actual output contains a line "PREFIX", any output starting with that
981 # line will be ignored when comparing with the expected output
983 # If the global variable $FATAL is true then OPTION fatal is the
986 sub _setup_one_file {
988 # Store the filename as a program that started at line 0.
989 # Real files count lines starting at line 1.
990 my @these = (0, shift);
991 my ($lineno, $current);
993 if ($_ eq "########\n") {
994 if (defined $current) {
995 push @these, $lineno, $current;
999 if (!defined $current) {
1005 if (defined $current) {
1006 push @these, $lineno, $current;
1008 ((scalar @these) / 2 - 1, @these);
1011 sub setup_multiple_progs {
1013 foreach my $file (@_) {
1014 next if $file =~ /(?:~|\.orig|,v)$/;
1015 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1018 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1026 # This is an internal error, and should never happen. All bar one of
1027 # the files had an __END__ marker to signal the end of their preamble,
1028 # although for some it wasn't technically necessary as they have no
1029 # tests. It might be possible to process files without an __END__ by
1030 # seeking back to the start and treating the whole file as tests, but
1031 # it's simpler and more reliable just to make the rule that all files
1032 # must have __END__ in. This should never fail - a file without an
1033 # __END__ should not have been checked in, because the regression tests
1034 # would not have passed.
1035 die "Could not find '__END__' in $file"
1038 my ($t, @p) = _setup_one_file($fh, $file);
1043 or die "Cannot close $file: $!\n";
1045 return ($tests, @prgs);
1048 sub run_multiple_progs {
1052 # The tests in lib run in a temporary subdirectory of t, and always
1053 # pass in a list of "programs" to run
1056 # The tests below t run in t and pass in a file handle. In theory we
1057 # can pass (caller)[1] as the second argument to report errors with
1058 # the filename of our caller, as the handle is always DATA. However,
1059 # line numbers in DATA count from the __END__ token, so will be wrong.
1060 # Which is more confusing than not providing line numbers. So, for now,
1061 # don't provide line numbers. No obvious clean solution - one hack
1062 # would be to seek DATA back to the start and read to the __END__ token,
1063 # but that feels almost like we should just open $0 instead.
1065 # Not going to rely on undef in list assignment.
1067 ($dummy, @prgs) = _setup_one_file(shift);
1070 my $tmpfile = tempfile();
1074 while (defined ($line = shift @prgs)) {
1078 if (defined $file) {
1079 print "# From $file\n";
1086 if (s/^(\s*-\w+)//) {
1089 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1092 foreach my $what (qw(skip todo)) {
1093 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1094 # If the SKIP reason starts ? then it's taken as a code snippet to
1095 # evaluate. This provides the flexibility to have conditional SKIPs
1096 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1097 my $temp = eval $reason{$what};
1099 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1101 $reason{$what} = $temp;
1106 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1110 if ($reason{skip}) {
1113 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1118 if ($prog =~ /--FILE--/) {
1119 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1121 die "Internal error: test $_ didn't split into pairs, got " .
1122 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1124 while (@files > 2) {
1125 my $filename = shift @files;
1126 my $code = shift @files;
1127 push @temps, $filename;
1128 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1130 File::Path::mkpath($1);
1131 push(@temp_path, $1);
1133 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1135 close $fh or die "Cannot close $filename: $!\n";
1138 $prog = shift @files;
1141 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1144 open STDERR, '>&', STDOUT
1145 or die "Can't dup STDOUT->STDERR: $!;";
1148 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1149 print $fh $prog,"\n";
1150 close $fh or die "Cannot close $tmpfile: $!";
1151 my $results = runperl( stderr => 1, progfile => $tmpfile,
1153 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1154 : (switches => [$switch])
1157 $results =~ s/\n+$//;
1158 # allow expected output to be written as if $prog is on STDIN
1159 $results =~ s/$::tempfile_regexp/-/g;
1161 # some tests will trigger VMS messages that won't be expected
1162 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1164 # pipes double these sometimes
1165 $results =~ s/\n\n/\n/g;
1167 # bison says 'parse error' instead of 'syntax error',
1168 # various yaccs may or may not capitalize 'syntax'.
1169 $results =~ s/^(syntax|parse) error/syntax error/mig;
1170 # allow all tests to run when there are leaks
1171 $results =~ s/Scalars leaked: \d+\n//g;
1173 $expected =~ s/\n+$//;
1174 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1175 # any special options? (OPTIONS foo bar zap)
1176 my $option_regex = 0;
1177 my $option_random = 0;
1179 if ($expected =~ s/^OPTIONS? (.+)\n//) {
1180 foreach my $option (split(' ', $1)) {
1181 if ($option eq 'regex') { # allow regular expressions
1184 elsif ($option eq 'random') { # all lines match, but in any order
1187 elsif ($option eq 'fatal') { # perl should fail
1191 die "$0: Unknown OPTION '$option'\n";
1195 die "$0: can't have OPTION regex and random\n"
1196 if $option_regex + $option_random > 1;
1198 if ($results =~ s/^SKIPPED\n//) {
1199 print "$results\n" ;
1203 if ($option_random) {
1204 my @got = sort split "\n", $results;
1205 my @expected = sort split "\n", $expected;
1207 $ok = "@got" eq "@expected";
1209 elsif ($option_regex) {
1210 $ok = $results =~ /^$expected/;
1213 $ok = $results =~ /^\Q$expected/;
1216 $ok = $results eq $expected;
1219 if ($ok && $fatal && !($status >> 8)) {
1224 local $::TODO = $reason{todo};
1227 my $err_line = "PROG: $switch\n$prog\n" .
1228 "EXPECTED:\n$expected\n";
1229 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1230 $err_line .= "GOT:\n$results\n";
1231 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1233 $err_line =~ s/^/# /mg;
1234 print $err_line; # Harness can't filter it out from STDERR.
1237 print STDERR $err_line;
1241 if (defined $file) {
1242 _ok($ok, "at $file line $line", $name);
1244 # We don't have file and line number data for the test, so report
1245 # errors as coming from our caller.
1246 local $Level = $Level + 1;
1253 foreach (@temp_path) {
1254 File::Path::rmtree $_ if -d $_;
1260 my($proto, @methods) = @_;
1261 my $class = ref $proto || $proto;
1263 unless( @methods ) {
1264 return _ok( 0, _where(), "$class->can(...)" );
1268 foreach my $method (@methods) {
1269 local($!, $@); # don't interfere with caller's $@
1270 # eval sometimes resets $!
1271 eval { $proto->can($method) } || push @nok, $method;
1275 $name = @methods == 1 ? "$class->can('$methods[0]')"
1276 : "$class->can(...)";
1278 _ok( !@nok, _where(), $name );
1282 # Call $class->new( @$args ); and run the result through object_ok.
1283 # See Test::More::new_ok
1285 my($class, $args, $obj_name) = @_;
1287 $object_name = "The object" unless defined $obj_name;
1289 local $Level = $Level + 1;
1292 my $ok = eval { $obj = $class->new(@$args); 1 };
1296 object_ok($obj, $class, $object_name);
1299 ok( 0, "new() died" );
1300 diag("Error was: $@");
1309 my($object, $class, $obj_name) = @_;
1312 $obj_name = 'The object' unless defined $obj_name;
1313 my $name = "$obj_name isa $class";
1314 if( !defined $object ) {
1315 $diag = "$obj_name isn't defined";
1318 my $whatami = ref $object ? 'object' : 'class';
1320 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1321 local($@, $!); # eval sometimes resets $!
1322 my $rslt = eval { $object->isa($class) };
1323 my $error = $@; # in case something else blows away $@
1326 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1327 # It's an unblessed reference
1328 $obj_name = 'The reference' unless defined $obj_name;
1329 if( !UNIVERSAL::isa($object, $class) ) {
1330 my $ref = ref $object;
1331 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1334 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1335 # It's something that can't even be a class
1336 $obj_name = 'The thing' unless defined $obj_name;
1337 $diag = "$obj_name isn't a class or reference";
1341 WHOA! I tried to call ->isa on your object and got some weird error.
1342 This should never happen. Please contact the author immediately.
1349 $obj_name = "The $whatami" unless defined $obj_name;
1350 my $ref = ref $object;
1351 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1355 _ok( !$diag, _where(), $name );
1360 my($class, $isa, $class_name) = @_;
1362 # Written so as to count as one test
1363 local $Level = $Level + 1;
1365 ok( 0, "$class is a refrence, not a class name" );
1368 isa_ok($class, $isa, $class_name);
1374 my($obj, $isa, $obj_name) = @_;
1376 local $Level = $Level + 1;
1378 ok( 0, "$obj is not a reference" );
1381 isa_ok($obj, $isa, $obj_name);
1386 # Purposefully avoiding a closure.
1388 push @::__capture, join "", @_;
1391 sub capture_warnings {
1395 local $SIG {__WARN__} = \&__capture;
1397 return @::__capture;
1400 # This will generate a variable number of tests.
1401 # Use done_testing() instead of a fixed plan.
1403 my ($code, $expect, $name) = @_;
1404 local $Level = $Level + 1;
1406 my @w = capture_warnings($code);
1408 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1409 foreach my $e (@$expect) {
1411 like(shift @w, $e, $name);
1413 is(shift @w, $e, $name);
1417 diag("Saw these additional warnings:");
1418 diag($_) foreach @w;
1422 sub _fail_excess_warnings {
1423 my($expect, $got, $name) = @_;
1424 local $Level = $Level + 1;
1425 # This will fail, and produce diagnostics
1426 is($expect, scalar @$got, $name);
1427 diag("Saw these warnings:");
1428 diag($_) foreach @$got;
1432 my ($code, $expect, $name) = @_;
1433 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1435 local $Level = $Level + 1;
1436 my @w = capture_warnings($code);
1438 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1440 is($w[0], $expect, $name);
1445 my ($code, $expect, $name) = @_;
1446 die sprintf "Expect must be a regexp object"
1447 unless ref $expect eq 'Regexp';
1448 local $Level = $Level + 1;
1449 my @w = capture_warnings($code);
1451 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1453 like($w[0], $expect, $name);
1457 # Set a watchdog to timeout the entire test file
1458 # NOTE: If the test file uses 'threads', then call the watchdog() function
1459 # _AFTER_ the 'threads' module is loaded.
1462 my $timeout = shift;
1463 my $method = shift || "";
1464 my $timeout_msg = 'Test process timed out - terminating';
1466 # Valgrind slows perl way down so give it more time before dying.
1467 $timeout *= 10 if $ENV{PERL_VALGRIND};
1469 my $pid_to_kill = $$; # PID for this process
1471 if ($method eq "alarm") {
1472 goto WATCHDOG_VIA_ALARM;
1475 # shut up use only once warning
1476 my $threads_on = $threads::threads && $threads::threads;
1478 # Don't use a watchdog process if 'threads' is loaded -
1479 # use a watchdog thread instead
1480 if (!$threads_on || $method eq "process") {
1482 # On Windows and VMS, try launching a watchdog process
1483 # using system(1, ...) (see perlport.pod)
1484 if ($is_mswin || $is_vms) {
1485 # On Windows, try to get the 'real' PID
1487 eval { require Win32; };
1488 if (defined(&Win32::GetCurrentProcessId)) {
1489 $pid_to_kill = Win32::GetCurrentProcessId();
1493 # If we still have a fake PID, we can't use this method at all
1494 return if ($pid_to_kill <= 0);
1496 # Launch watchdog process
1499 local $SIG{'__WARN__'} = sub {
1500 _diag("Watchdog warning: $_[0]");
1502 my $sig = $is_vms ? 'TERM' : 'KILL';
1503 my $cmd = _create_runperl( prog => "sleep($timeout);" .
1504 "warn qq/# $timeout_msg" . '\n/;' .
1505 "kill($sig, $pid_to_kill);");
1506 $watchdog = system(1, $cmd);
1508 if ($@ || ($watchdog <= 0)) {
1509 _diag('Failed to start watchdog');
1515 # Add END block to parent to terminate and
1516 # clean up watchdog process
1517 eval "END { local \$! = 0; local \$? = 0;
1518 wait() if kill('KILL', $watchdog); };";
1522 # Try using fork() to generate a watchdog process
1524 eval { $watchdog = fork() };
1525 if (defined($watchdog)) {
1526 if ($watchdog) { # Parent process
1527 # Add END block to parent to terminate and
1528 # clean up watchdog process
1529 eval "END { local \$! = 0; local \$? = 0;
1530 wait() if kill('KILL', $watchdog); };";
1534 ### Watchdog process code
1536 # Load POSIX if available
1537 eval { require POSIX; };
1539 # Execute the timeout
1540 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1543 # Kill test process if still running
1544 if (kill(0, $pid_to_kill)) {
1545 _diag($timeout_msg);
1546 kill('KILL', $pid_to_kill);
1548 # sometimes the above isn't enough on cygwin
1549 sleep 1; # wait a little, it might have worked after all
1550 system("/bin/kill -f $pid_to_kill");
1554 # Don't execute END block (added at beginning of this file)
1557 # Terminate ourself (i.e., the watchdog)
1558 POSIX::_exit(1) if (defined(&POSIX::_exit));
1562 # fork() failed - fall through and try using a thread
1565 # Use a watchdog thread because either 'threads' is loaded,
1567 if (eval {require threads; 1}) {
1568 'threads'->create(sub {
1569 # Load POSIX if available
1570 eval { require POSIX; };
1572 # Execute the timeout
1573 my $time_left = $timeout;
1575 $time_left = $time_left - sleep($time_left);
1576 } while ($time_left > 0);
1578 # Kill the parent (and ourself)
1579 select(STDERR); $| = 1;
1580 _diag($timeout_msg);
1581 POSIX::_exit(1) if (defined(&POSIX::_exit));
1582 my $sig = $is_vms ? 'TERM' : 'KILL';
1583 kill($sig, $pid_to_kill);
1588 # If everything above fails, then just use an alarm timeout
1590 if (eval { alarm($timeout); 1; }) {
1591 # Load POSIX if available
1592 eval { require POSIX; };
1594 # Alarm handler will do the actual 'killing'
1595 $SIG{'ALRM'} = sub {
1596 select(STDERR); $| = 1;
1597 _diag($timeout_msg);
1598 POSIX::_exit(1) if (defined(&POSIX::_exit));
1599 my $sig = $is_vms ? 'TERM' : 'KILL';
1600 kill($sig, $pid_to_kill);
1605 # The following 2 functions allow tests to work on both EBCDIC and
1606 # ASCII-ish platforms. They convert string scalars between the native
1607 # character set and the set of 256 characters which is usually called
1610 sub native_to_latin1($) {
1613 return $string if ord('^') == 94; # ASCII, Latin1
1615 for my $i (0 .. length($string) - 1) {
1616 $output .= chr(ord_native_to_latin1(ord(substr($string, $i, 1))));
1618 # Preserve utf8ness of input onto the output, even if it didn't need to be
1620 utf8::upgrade($output) if utf8::is_utf8($string);
1625 sub latin1_to_native($) {
1628 return $string if ord('^') == 94; # ASCII, Latin1
1630 for my $i (0 .. length($string) - 1) {
1631 $output .= chr(ord_latin1_to_native(ord(substr($string, $i, 1))));
1633 # Preserve utf8ness of input onto the output, even if it didn't need to be
1635 utf8::upgrade($output) if utf8::is_utf8($string);
1640 sub ord_latin1_to_native {
1641 # given an input code point, return the platform's native
1642 # equivalent value. Anything above latin1 is itself.
1645 return $ord if ord('^') == 94; # ASCII, Latin1
1646 return utf8::unicode_to_native($ord);
1649 sub ord_native_to_latin1 {
1650 # given an input platform code point, return the latin1 equivalent value.
1651 # Anything above latin1 is itself.
1654 return $ord if ord('^') == 94; # ASCII, Latin1
1655 return utf8::native_to_unicode($ord);