2 # t/test.pl - most of Test::More functionality without the fuss
7 # Do not rely on features found only in more modern Perls here, as some CPAN
8 # distributions copy this file and must operate on older Perls. Similarly, keep
9 # things, simple as this may be run under fairly broken circumstances. For
10 # example, increment ($x++) has a certain amount of cleverness for things like
13 # $x++; # $x eq 'aaa';
15 # This stands more chance of breaking than just a simple
19 # In this file, we use the latter "Baby Perl" approach, and increment
20 # will be worked over by t/op/inc.t
27 my $Perl; # Safer version of $^X set by which_perl()
29 # This defines ASCII/UTF-8 vs EBCDIC/UTF-EBCDIC
30 $::IS_ASCII = ord 'A' == 65;
31 $::IS_EBCDIC = ord 'A' == 193;
35 $Tests_Are_Passing = 1;
37 # Use this instead of print to avoid interference while testing globals.
39 local($\, $", $,) = (undef, ' ', '');
44 local($\, $", $,) = (undef, ' ', '');
52 if ($n eq 'no_plan') {
58 $plan{skip_all} and skip_all($plan{skip_all});
61 _print "1..$n\n" unless $noplan;
66 # Set the plan at the end. See Test::More::done_testing.
79 if (defined $planned && $planned != $ran) {
81 "# Looks like you planned $planned tests but ran $ran.\n";
90 my @mess = _comment(@_);
91 $TODO ? _print(@mess) : _print_stderr(@mess);
94 # Use this instead of "print STDERR" when outputting failure diagnostic
100 # Use this instead of "print" when outputting informational messages
103 _print( _comment(@_) );
107 return !defined &DynaLoader::boot_DynaLoader;
111 # Don’t clobber @INC under miniperl
112 @INC = () unless is_miniperl;
117 return map { /^#/ ? "$_\n" : "# $_\n" }
118 map { split /\n/ } @_;
121 sub _have_dynamic_extension {
122 my $extension = shift;
123 unless (eval {require Config; 1}) {
124 warn "test.pl had problems loading Config: $@";
127 $extension =~ s!::!/!g;
128 return 1 if ($Config::Config{extensions} =~ /\b$extension\b/);
133 _print "1..0 # Skip @_\n";
140 sub skip_all_if_miniperl {
141 skip_all(@_) if is_miniperl();
144 sub skip_all_without_dynamic_extension {
145 my ($extension) = @_;
146 skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
147 return if &_have_dynamic_extension;
148 skip_all("$extension was not built");
151 sub skip_all_without_perlio {
152 skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
155 sub skip_all_without_config {
156 unless (eval {require Config; 1}) {
157 warn "test.pl had problems loading Config: $@";
161 next if $Config::Config{$_};
162 my $key = $_; # Need to copy, before trying to modify.
169 sub skip_all_without_unicode_tables { # (but only under miniperl)
171 skip_all_if_miniperl("Unicode tables not built yet")
172 unless eval 'require "unicore/UCD.pl"';
176 sub find_git_or_skip {
177 my ($source_dir, $reason);
180 } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
181 my $where = readlink 'MANIFEST';
182 die "Can't readling MANIFEST: $!" unless defined $where;
183 die "Confusing symlink target for MANIFEST, '$where'"
184 unless $where =~ s!/MANIFEST\z!!;
185 if (-d "$where/.git") {
186 # Looks like we are in a symlink tree
187 if (exists $ENV{GIT_DIR}) {
188 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it");
190 note("Found source tree at $where, setting \$ENV{GIT_DIR}");
191 $ENV{GIT_DIR} = "$where/.git";
193 $source_dir = $where;
195 } elsif (exists $ENV{GIT_DIR}) {
196 my $commit = '8d063cd8450e59ea1c611a2f4f5a21059a2804f1';
197 my $out = `git rev-parse --verify --quiet '$commit^{commit}'`;
199 if($out eq $commit) {
203 if ($ENV{'PERL_BUILD_PACKAGING'}) {
204 $reason = 'PERL_BUILD_PACKAGING is set';
205 } elsif ($source_dir) {
206 my $version_string = `git --version`;
207 if (defined $version_string
208 && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
209 return $source_dir if eval "v$1 ge v1.5.0";
210 # If you have earlier than 1.5.0 and it works, change this test
211 $reason = "in git checkout, but git version '$1$2' too old";
213 $reason = "in git checkout, but cannot run git";
216 $reason = 'not being run from a git checkout';
218 skip_all($reason) if $_[0] && $_[0] eq 'all';
224 _print("Bail out! $reason\n");
229 my ($pass, $where, $name, @mess) = @_;
230 # Do not try to microoptimize by factoring out the "not ".
234 # escape out '#' or it will interfere with '# skip' and such
236 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
238 $out = $pass ? "ok $test" : "not ok $test";
242 $out = $out . " # TODO $TODO";
244 $Tests_Are_Passing = 0 unless $pass;
250 note @mess; # Ensure that the message is properly escaped.
253 my $msg = "# Failed test $test - ";
254 $msg.= "$name " if $name;
260 $test = $test + 1; # don't use ++
266 my @caller = caller($Level);
267 return "at $caller[1] line $caller[2]";
270 # DON'T use this for matches. Use like() instead.
272 my ($pass, $name, @mess) = @_;
273 _ok($pass, _where(), $name, @mess);
278 return 'undef' unless defined $x;
287 return defined $x ? '"' . display ($x) . '"' : 'undef';
290 # Support pre-5.10 Perls, for the benefit of CPAN dists that copy this file.
291 # Note that chr(90) exists in both ASCII ("Z") and EBCDIC ("!").
292 my $chars_template = defined(eval { pack "W*", 90 }) ? "W*" : "U*";
293 eval 'sub re::is_regexp { ref($_[0]) eq "Regexp" }'
294 if !defined &re::is_regexp;
296 # keys are the codes \n etc map to, values are 2 char strings such as \n
297 my %backslash_escape;
298 foreach my $x (split //, 'nrtfa\\\'"') {
299 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
301 # A way to display scalars containing control characters and Unicode.
302 # Trying to avoid setting $_, or relying on local $_ to work.
306 if (defined $x and not ref $x) {
308 foreach my $c (unpack($chars_template, $x)) {
310 $y = $y . sprintf "\\x{%x}", $c;
311 } elsif ($backslash_escape{$c}) {
312 $y = $y . $backslash_escape{$c};
313 } elsif ($c < ord " ") {
314 # Use octal for characters with small ordinals that are
315 # traditionally expressed as octal: the controls below
316 # space, which on EBCDIC are almost all the controls, but
317 # on ASCII don't include DEL nor the C1 controls.
318 $y = $y . sprintf "\\%03o", $c;
319 } elsif (chr $c =~ /[[:print:]]/a) {
323 $y = $y . sprintf "\\x%02X", $c;
328 return $x unless wantarray;
335 my ($got, $expected, $name, @mess) = @_;
338 if( !defined $got || !defined $expected ) {
339 # undef only matches undef
340 $pass = !defined $got && !defined $expected;
343 $pass = $got eq $expected;
347 unshift(@mess, "# got "._qq($got)."\n",
348 "# expected "._qq($expected)."\n");
350 _ok($pass, _where(), $name, @mess);
354 my ($got, $isnt, $name, @mess) = @_;
357 if( !defined $got || !defined $isnt ) {
358 # undef only matches undef
359 $pass = defined $got || defined $isnt;
362 $pass = $got ne $isnt;
366 unshift(@mess, "# it should not be "._qq($got)."\n",
369 _ok($pass, _where(), $name, @mess);
373 my($got, $type, $expected, $name, @mess) = @_;
378 local($@,$!); # don't interfere with $@
379 # eval() sometimes resets $!
380 $pass = eval "\$got $type \$expected";
383 # It seems Irix long doubles can have 2147483648 and 2147483648
384 # that stringify to the same thing but are actually numerically
385 # different. Display the numbers if $type isn't a string operator,
386 # and the numbers are stringwise the same.
387 # (all string operators have alphabetic names, so tr/a-z// is true)
388 # This will also show numbers for some unneeded cases, but will
389 # definitely be helpful for things such as == and <= that fail
390 if ($got eq $expected and $type !~ tr/a-z//) {
391 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
393 unshift(@mess, "# got "._qq($got)."\n",
394 "# expected $type "._qq($expected)."\n");
396 _ok($pass, _where(), $name, @mess);
399 # Check that $got is within $range of $expected
400 # if $range is 0, then check it's exact
401 # else if $expected is 0, then $range is an absolute value
402 # otherwise $range is a fractional error.
403 # Here $range must be numeric, >= 0
404 # Non numeric ranges might be a useful future extension. (eg %)
406 my ($got, $expected, $range, $name, @mess) = @_;
408 if (!defined $got or !defined $expected or !defined $range) {
409 # This is a fail, but doesn't need extra diagnostics
410 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
412 unshift @mess, "# got, expected and range must be numeric\n";
413 } elsif ($range < 0) {
414 # This is also a fail
415 unshift @mess, "# range must not be negative\n";
416 } elsif ($range == 0) {
418 $pass = $got == $expected;
419 } elsif ($expected == 0) {
420 # If expected is 0, treat range as absolute
421 $pass = ($got <= $range) && ($got >= - $range);
423 my $diff = $got - $expected;
424 $pass = abs ($diff / $expected) < $range;
427 if ($got eq $expected) {
428 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
430 unshift@mess, "# got "._qq($got)."\n",
431 "# expected "._qq($expected)." (within "._qq($range).")\n";
433 _ok($pass, _where(), $name, @mess);
436 # Note: this isn't quite as fancy as Test::More::like().
438 sub like ($$@) { like_yn (0,@_) }; # 0 for -
439 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
442 my ($flip, undef, $expected, $name, @mess) = @_;
444 # We just accept like(..., qr/.../), not like(..., '...'), and
445 # definitely not like(..., '/.../') like
446 # Test::Builder::maybe_regex() does.
447 unless (re::is_regexp($expected)) {
448 die "PANIC: The value '$expected' isn't a regexp. The like() function needs a qr// pattern, not a string";
452 $pass = $_[1] =~ /$expected/ if !$flip;
453 $pass = $_[1] !~ /$expected/ if $flip;
454 my $display_got = $_[1];
455 $display_got = display($display_got);
456 my $display_expected = $expected;
457 $display_expected = display($display_expected);
459 unshift(@mess, "# got '$display_got'\n",
461 ? "# expected !~ /$display_expected/\n"
462 : "# expected /$display_expected/\n");
464 local $Level = $Level + 1;
465 _ok($pass, _where(), $name, @mess);
473 _ok(0, _where(), @_);
483 $test = $test + 1; # don't use ++
487 # Note: can't pass multipart messages since we try to
488 # be compatible with Test::More::skip().
491 my $n = @_ ? shift : 1;
496 $bad_swap = $why > 0 && $n == 0;
497 $both_zero = $why == 0 && $n == 0;
499 if ($bad_swap || $both_zero || @_) {
500 my $arg = "'$why', '$n'";
502 $arg .= join(", ", '', map { qq['$_'] } @_);
504 die qq[$0: expected skip(why, count), got skip($arg)\n];
507 _print "ok $test # skip $why\n";
514 sub skip_if_miniperl {
515 skip(@_) if is_miniperl();
518 sub skip_without_dynamic_extension {
519 my $extension = shift;
520 skip("no dynamic loading on miniperl, no extension $extension", @_)
522 return if &_have_dynamic_extension($extension);
523 skip("extension $extension was not built", @_);
528 my $n = @_ ? shift : 1;
531 _print "not ok $test # TODO & SKIP $why\n";
540 return 0 unless $#$ra == $#$rb;
541 for my $i (0..$#$ra) {
542 next if !defined $ra->[$i] && !defined $rb->[$i];
543 return 0 if !defined $ra->[$i];
544 return 0 if !defined $rb->[$i];
545 return 0 unless $ra->[$i] eq $rb->[$i];
551 my ($orig, $suspect) = @_;
553 while (my ($key, $value) = each %$suspect) {
554 # Force a hash recompute if this perl's internals can cache the hash key.
556 if (exists $orig->{$key}) {
558 defined $orig->{$key} != defined $value
559 || (defined $value && $orig->{$key} ne $value)
561 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
562 " now ", _qq($value), "\n";
566 _print "# key ", _qq($key), " is ", _qq($value),
567 ", not in original.\n";
571 foreach (keys %$orig) {
572 # Force a hash recompute if this perl's internals can cache the hash key.
574 next if (exists $suspect->{$_});
575 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
581 # We only provide a subset of the Test::More functionality.
584 if ($require =~ tr/[A-Za-z0-9:.]//c) {
585 fail("Invalid character in \"$require\", passed to require_ok");
590 is($@, '', _where(), "require $require");
596 if ($use =~ tr/[A-Za-z0-9:.]//c) {
597 fail("Invalid character in \"$use\", passed to use");
602 is($@, '', _where(), "use $use");
606 # runperl - Runs a separate perl interpreter and returns its output.
608 # switches => [ command-line switches ]
609 # nolib => 1 # don't use -I../lib (included by default)
610 # non_portable => Don't warn if a one liner contains quotes
611 # prog => one-liner (avoid quotes)
612 # progs => [ multi-liner (avoid quotes) ]
613 # progfile => perl script
614 # stdin => string to feed the stdin (or undef to redirect from /dev/null)
615 # stderr => If 'devnull' suppresses stderr, if other TRUE value redirect
617 # args => [ command-line arguments to the perl program ]
618 # verbose => print the command line
620 my $is_mswin = $^O eq 'MSWin32';
621 my $is_netware = $^O eq 'NetWare';
622 my $is_vms = $^O eq 'VMS';
623 my $is_cygwin = $^O eq 'cygwin';
626 my ($runperl, $args) = @_;
629 # In VMS protect with doublequotes because otherwise
630 # DCL will lowercase -- unless already doublequoted.
631 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
632 $runperl = $runperl . ' ' . $_;
637 sub _create_runperl { # Create the string to qx in runperl().
639 my $runperl = which_perl();
640 if ($runperl =~ m/\s/) {
641 $runperl = qq{"$runperl"};
643 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
644 if ($ENV{PERL_RUNPERL_DEBUG}) {
645 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
647 unless ($args{nolib}) {
648 $runperl = $runperl . ' "-I../lib" "-I." '; # doublequotes because of VMS
650 if ($args{switches}) {
652 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
653 unless ref $args{switches} eq "ARRAY";
654 $runperl = _quote_args($runperl, $args{switches});
656 if (defined $args{prog}) {
657 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
658 if defined $args{progs};
659 $args{progs} = [split /\n/, $args{prog}, -1]
661 if (defined $args{progs}) {
662 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
663 unless ref $args{progs} eq "ARRAY";
664 foreach my $prog (@{$args{progs}}) {
665 if (!$args{non_portable}) {
666 if ($prog =~ tr/'"//) {
667 warn "quotes in prog >>$prog<< are not portable";
669 if ($prog =~ /^([<>|]|2>)/) {
670 warn "Initial $1 in prog >>$prog<< is not portable";
672 if ($prog =~ /&\z/) {
673 warn "Trailing & in prog >>$prog<< is not portable";
676 if ($is_mswin || $is_netware || $is_vms) {
677 $runperl = $runperl . qq ( -e "$prog" );
680 $runperl = $runperl . qq ( -e '$prog' );
683 } elsif (defined $args{progfile}) {
684 $runperl = $runperl . qq( "$args{progfile}");
686 # You probably didn't want to be sucking in from the upstream stdin
687 die "test.pl:runperl(): none of prog, progs, progfile, args, "
688 . " switches or stdin specified"
689 unless defined $args{args} or defined $args{switches}
690 or defined $args{stdin};
692 if (defined $args{stdin}) {
693 # so we don't try to put literal newlines and crs onto the
695 $args{stdin} =~ s/\n/\\n/g;
696 $args{stdin} =~ s/\r/\\r/g;
698 if ($is_mswin || $is_netware || $is_vms) {
699 $runperl = qq{$Perl -e "print qq(} .
700 $args{stdin} . q{)" | } . $runperl;
703 $runperl = qq{$Perl -e 'print qq(} .
704 $args{stdin} . q{)' | } . $runperl;
706 } elsif (exists $args{stdin}) {
707 # Using the pipe construction above can cause fun on systems which use
708 # ksh as /bin/sh, as ksh does pipes differently (with one less process)
709 # With sh, for the command line 'perl -e 'print qq()' | perl -e ...'
710 # the sh process forks two children, which use exec to start the two
711 # perl processes. The parent shell process persists for the duration of
712 # the pipeline, and the second perl process starts with no children.
713 # With ksh (and zsh), the shell saves a process by forking a child for
714 # just the first perl process, and execing itself to start the second.
715 # This means that the second perl process starts with one child which
716 # it didn't create. This causes "fun" when if the tests assume that
717 # wait (or waitpid) will only return information about processes
718 # started within the test.
719 # They also cause fun on VMS, where the pipe implementation returns
720 # the exit code of the process at the front of the pipeline, not the
721 # end. This messes up any test using OPTION FATAL.
722 # Hence it's useful to have a way to make STDIN be at eof without
723 # needing a pipeline, so that the fork tests have a sane environment
724 # without these surprises.
726 # /dev/null appears to be surprisingly portable.
727 $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null');
729 if (defined $args{args}) {
730 $runperl = _quote_args($runperl, $args{args});
732 if (exists $args{stderr} && $args{stderr} eq 'devnull') {
733 $runperl = $runperl . ($is_mswin ? ' 2>nul' : ' 2>/dev/null');
735 elsif ($args{stderr}) {
736 $runperl = $runperl . ' 2>&1';
738 if ($args{verbose}) {
739 my $runperldisplay = $runperl;
740 $runperldisplay =~ s/\n/\n\#/g;
741 _print_stderr "# $runperldisplay\n";
746 # sub run_perl {} is alias to below
748 die "test.pl:runperl() does not take a hashref"
749 if ref $_[0] and ref $_[0] eq 'HASH';
750 my $runperl = &_create_runperl;
753 my $tainted = ${^TAINT};
755 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
758 # We will assume that if you're running under -T, you really mean to
759 # run a fresh perl, so we'll brute force launder everything for you
762 if (! eval {require Config; 1}) {
763 warn "test.pl had problems loading Config: $@";
766 $sep = $Config::Config{path_sep};
769 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
770 local @ENV{@keys} = ();
771 # Untaint, plus take out . and empty string:
772 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
773 $ENV{PATH} =~ /(.*)/s;
775 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
776 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
777 split quotemeta ($sep), $1;
778 if ($is_cygwin) { # Must have /bin under Cygwin
779 if (length $ENV{PATH}) {
780 $ENV{PATH} = $ENV{PATH} . $sep;
782 $ENV{PATH} = $ENV{PATH} . '/bin';
787 $result = `$runperl`;
789 $result = `$runperl`;
791 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
796 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
799 _print_stderr "# @_\n";
803 # A somewhat safer version of the sometimes wrong $^X.
805 unless (defined $Perl) {
808 # VMS should have 'perl' aliased properly
809 return $Perl if $is_vms;
812 if (! eval {require Config; 1}) {
813 warn "test.pl had problems loading Config: $@";
816 $exe = $Config::Config{_exe};
818 $exe = '' unless defined $exe;
820 # This doesn't absolutize the path: beware of future chdirs().
821 # We could do File::Spec->abs2rel() but that does getcwd()s,
822 # which is a bit heavyweight to do here.
824 if ($Perl =~ /^perl\Q$exe\E$/i) {
825 my $perl = "perl$exe";
826 if (! eval {require File::Spec; 1}) {
827 warn "test.pl had problems loading File::Spec: $@";
830 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
834 # Build up the name of the executable file from the name of
837 if ($Perl !~ /\Q$exe\E$/i) {
838 $Perl = $Perl . $exe;
841 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
843 # For subcommands to use.
844 $ENV{PERLEXE} = $Perl;
851 foreach my $file (@_) {
852 1 while unlink $file;
854 _print_stderr "# Couldn't unlink '$file': $!\n";
856 $count = $count + 1; # don't use ++
862 # _num_to_alpha - Returns a string of letters representing a positive integer.
865 # maximum number of letters
867 # returns undef if the number is negative
868 # returns undef if the number of letters is greater than the maximum wanted
870 # _num_to_alpha( 0) eq 'A';
871 # _num_to_alpha( 1) eq 'B';
872 # _num_to_alpha(25) eq 'Z';
873 # _num_to_alpha(26) eq 'AA';
874 # _num_to_alpha(27) eq 'AB';
876 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);
878 # Avoid ++ -- ranges split negative numbers
880 my($num,$max_char) = @_;
881 return unless $num >= 0;
884 $max_char = 0 if $max_char < 0;
887 $alpha = $letters[ $num % 26 ] . $alpha;
888 $num = int( $num / 26 );
893 next unless $max_char;
894 $char_count = $char_count + 1;
895 return if $char_count == $max_char;
901 END { unlink_all keys %tmpfiles }
903 # A regexp that matches the tempfile names
904 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
906 # Avoid ++, avoid ranges, avoid split //
907 my $tempfile_count = 0;
910 my $try = (-d "t" ? "t/" : "")."tmp$$";
911 my $alpha = _num_to_alpha($tempfile_count,2);
912 last unless defined $alpha;
913 $try = $try . $alpha;
914 $tempfile_count = $tempfile_count + 1;
916 # Need to note all the file names we allocated, as a second request may
917 # come before the first is created.
918 if (!$tmpfiles{$try} && !-e $try) {
924 die "Can't find temporary file name starting \"tmp$$\"";
927 # register_tempfile - Adds a list of files to be removed at the end of the current test file
929 # a list of files to be removed later
931 # returns a count of how many file names were actually added
933 # Reuses %tmpfiles so that tempfile() will also skip any files added here
934 # even if the file doesn't exist yet.
936 sub register_tempfile {
940 _print_stderr "# Temporary file '$_' already added\n";
949 # This is the temporary file for fresh_perl
950 my $tmpfile = tempfile();
953 my($prog, $runperl_args) = @_;
955 # Run 'runperl' with the complete perl program contained in '$prog', and
956 # arguments in the hash referred to by '$runperl_args'. The results are
957 # returned, with $? set to the exit code. Unless overridden, stderr is
958 # redirected to stdout.
960 die sprintf "Third argument to fresh_perl_.* must be hashref of args to fresh_perl (or {})"
961 unless !(defined $runperl_args) || ref($runperl_args) eq 'HASH';
963 # Given the choice of the mis-parsable {}
964 # (we want an anon hash, but a borked lexer might think that it's a block)
965 # or relying on taking a reference to a lexical
966 # (\ might be mis-parsed, and the reference counting on the pad may go
968 # it feels like the least-worse thing is to assume that auto-vivification
969 # works. At least, this is only going to be a run-time failure, so won't
970 # affect tests using this file but not this function.
971 $runperl_args->{progfile} ||= $tmpfile;
972 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
974 open TEST, '>', $tmpfile or die "Cannot open $tmpfile: $!";
975 binmode TEST, ':utf8' if $runperl_args->{wide_chars};
977 close TEST or die "Cannot close $tmpfile: $!";
979 my $results = runperl(%$runperl_args);
980 my $status = $?; # Not necessary to save this, but it makes it clear to
981 # future maintainers.
983 # Clean up the results into something a bit more predictable.
984 $results =~ s/\n+$//;
985 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
986 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
988 # bison says 'parse error' instead of 'syntax error',
989 # various yaccs may or may not capitalize 'syntax'.
990 $results =~ s/^(syntax|parse) error/syntax error/mig;
993 # some tests will trigger VMS messages that won't be expected
994 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
996 # pipes double these sometimes
997 $results =~ s/\n\n/\n/g;
1006 my($prog, $action, $expect, $runperl_args, $name) = @_;
1008 my $results = fresh_perl($prog, $runperl_args);
1011 # Use the first line of the program as a name if none was given
1013 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
1014 $name = $name . '...' if length $first_line > length $name;
1017 # Historically this was implemented using a closure, but then that means
1018 # that the tests for closures avoid using this code. Given that there
1019 # are exactly two callers, doing exactly two things, the simpler approach
1020 # feels like a better trade off.
1022 if ($action eq 'eq') {
1023 $pass = is($results, $expect, $name);
1024 } elsif ($action eq '=~') {
1025 $pass = like($results, $expect, $name);
1027 die "_fresh_perl can't process action '$action'";
1031 _diag "# PROG: \n$prog\n";
1032 _diag "# STATUS: $status\n";
1041 # Combination of run_perl() and is().
1045 my($prog, $expected, $runperl_args, $name) = @_;
1047 # _fresh_perl() is going to clip the trailing newlines off the result.
1048 # This will make it so the test author doesn't have to know that.
1049 $expected =~ s/\n+$//;
1052 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
1058 # Combination of run_perl() and like().
1061 sub fresh_perl_like {
1062 my($prog, $expected, $runperl_args, $name) = @_;
1064 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
1067 # Many tests use the same format in __DATA__ or external files to specify a
1068 # sequence of (fresh) tests to run, extra files they may temporarily need, and
1069 # what the expected output is. Putting it here allows common code to serve
1070 # these multiple tests.
1072 # Each program is source code to run followed by an "EXPECT" line, followed
1073 # by the expected output.
1075 # The first line of the code to run may be a command line switch such as -wE
1076 # or -0777 (alphanumerics only; only one cluster, beginning with a minus is
1077 # allowed). Later lines may contain (note the '# ' on each):
1078 # # TODO reason for todo
1079 # # SKIP reason for skip
1080 # # SKIP ?code to test if this should be skipped
1081 # # NAME name of the test (as with ok($ok, $name))
1083 # The expected output may contain:
1084 # OPTION list of options
1085 # OPTIONS list of options
1087 # The possible options for OPTION may be:
1088 # regex - the expected output is a regular expression
1089 # random - all lines match but in any order
1090 # fatal - the code will fail fatally (croak, die)
1092 # If the actual output contains a line "SKIPPED" the test will be
1095 # If the actual output contains a line "PREFIX", any output starting with that
1096 # line will be ignored when comparing with the expected output
1098 # If the global variable $FATAL is true then OPTION fatal is the
1101 sub _setup_one_file {
1103 # Store the filename as a program that started at line 0.
1104 # Real files count lines starting at line 1.
1105 my @these = (0, shift);
1106 my ($lineno, $current);
1108 if ($_ eq "########\n") {
1109 if (defined $current) {
1110 push @these, $lineno, $current;
1114 if (!defined $current) {
1120 if (defined $current) {
1121 push @these, $lineno, $current;
1123 ((scalar @these) / 2 - 1, @these);
1126 sub setup_multiple_progs {
1128 foreach my $file (@_) {
1129 next if $file =~ /(?:~|\.orig|,v)$/;
1130 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1133 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1137 $found = $found + 1; # don't use ++
1141 # This is an internal error, and should never happen. All bar one of
1142 # the files had an __END__ marker to signal the end of their preamble,
1143 # although for some it wasn't technically necessary as they have no
1144 # tests. It might be possible to process files without an __END__ by
1145 # seeking back to the start and treating the whole file as tests, but
1146 # it's simpler and more reliable just to make the rule that all files
1147 # must have __END__ in. This should never fail - a file without an
1148 # __END__ should not have been checked in, because the regression tests
1149 # would not have passed.
1150 die "Could not find '__END__' in $file"
1153 my ($t, @p) = _setup_one_file($fh, $file);
1158 or die "Cannot close $file: $!\n";
1160 return ($tests, @prgs);
1163 sub run_multiple_progs {
1167 # The tests in lib run in a temporary subdirectory of t, and always
1168 # pass in a list of "programs" to run
1171 # The tests below t run in t and pass in a file handle. In theory we
1172 # can pass (caller)[1] as the second argument to report errors with
1173 # the filename of our caller, as the handle is always DATA. However,
1174 # line numbers in DATA count from the __END__ token, so will be wrong.
1175 # Which is more confusing than not providing line numbers. So, for now,
1176 # don't provide line numbers. No obvious clean solution - one hack
1177 # would be to seek DATA back to the start and read to the __END__ token,
1178 # but that feels almost like we should just open $0 instead.
1180 # Not going to rely on undef in list assignment.
1182 ($dummy, @prgs) = _setup_one_file(shift);
1185 my $tmpfile = tempfile();
1189 while (defined ($line = shift @prgs)) {
1193 if (defined $file) {
1194 print "# From $file\n";
1201 if (s/^(\s*-\w+)//) {
1204 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1207 foreach my $what (qw(skip todo)) {
1208 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1209 # If the SKIP reason starts ? then it's taken as a code snippet to
1210 # evaluate. This provides the flexibility to have conditional SKIPs
1211 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1212 my $temp = eval $reason{$what};
1214 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1216 $reason{$what} = $temp;
1221 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1225 if ($reason{skip}) {
1228 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1233 if ($prog =~ /--FILE--/) {
1234 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1236 die "Internal error: test $_ didn't split into pairs, got " .
1237 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1239 while (@files > 2) {
1240 my $filename = shift @files;
1241 my $code = shift @files;
1242 push @temps, $filename;
1243 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1245 File::Path::mkpath($1);
1246 push(@temp_path, $1);
1248 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1250 close $fh or die "Cannot close $filename: $!\n";
1253 $prog = shift @files;
1256 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1260 open STDERR, '>&', STDOUT
1261 or die "Can't dup STDOUT->STDERR: $!;";
1264 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1265 print $fh $prog,"\n";
1266 close $fh or die "Cannot close $tmpfile: $!";
1267 my $results = runperl( stderr => 1, progfile => $tmpfile,
1269 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1270 : (switches => [$switch])
1273 $results =~ s/\n+$//;
1274 # allow expected output to be written as if $prog is on STDIN
1275 $results =~ s/$::tempfile_regexp/-/g;
1277 # some tests will trigger VMS messages that won't be expected
1278 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1280 # pipes double these sometimes
1281 $results =~ s/\n\n/\n/g;
1283 # bison says 'parse error' instead of 'syntax error',
1284 # various yaccs may or may not capitalize 'syntax'.
1285 $results =~ s/^(syntax|parse) error/syntax error/mig;
1286 # allow all tests to run when there are leaks
1287 $results =~ s/Scalars leaked: \d+\n//g;
1289 $expected =~ s/\n+$//;
1290 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1291 # any special options? (OPTIONS foo bar zap)
1292 my $option_regex = 0;
1293 my $option_random = 0;
1295 if ($expected =~ s/^OPTIONS? (.+)\n//) {
1296 foreach my $option (split(' ', $1)) {
1297 if ($option eq 'regex') { # allow regular expressions
1300 elsif ($option eq 'random') { # all lines match, but in any order
1303 elsif ($option eq 'fatal') { # perl should fail
1307 die "$0: Unknown OPTION '$option'\n";
1311 die "$0: can't have OPTION regex and random\n"
1312 if $option_regex + $option_random > 1;
1314 if ($results =~ s/^SKIPPED\n//) {
1315 print "$results\n" ;
1319 if ($option_random) {
1320 my @got = sort split "\n", $results;
1321 my @expected = sort split "\n", $expected;
1323 $ok = "@got" eq "@expected";
1325 elsif ($option_regex) {
1326 $ok = $results =~ /^$expected/;
1329 $ok = $results =~ /^\Q$expected/;
1332 $ok = $results eq $expected;
1335 if ($ok && $fatal && !($status >> 8)) {
1340 local $::TODO = $reason{todo};
1343 my $err_line = "PROG: $switch\n$prog\n" .
1344 "EXPECTED:\n$expected\n";
1345 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1346 $err_line .= "GOT:\n$results\n";
1347 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1349 $err_line =~ s/^/# /mg;
1350 print $err_line; # Harness can't filter it out from STDERR.
1353 print STDERR $err_line;
1357 if (defined $file) {
1358 _ok($ok, "at $file line $line", $name);
1360 # We don't have file and line number data for the test, so report
1361 # errors as coming from our caller.
1362 local $Level = $Level + 1;
1369 foreach (@temp_path) {
1370 File::Path::rmtree $_ if -d $_;
1376 my($proto, @methods) = @_;
1377 my $class = ref $proto || $proto;
1379 unless( @methods ) {
1380 return _ok( 0, _where(), "$class->can(...)" );
1384 foreach my $method (@methods) {
1385 local($!, $@); # don't interfere with caller's $@
1386 # eval sometimes resets $!
1387 eval { $proto->can($method) } || push @nok, $method;
1391 $name = @methods == 1 ? "$class->can('$methods[0]')"
1392 : "$class->can(...)";
1394 _ok( !@nok, _where(), $name );
1398 # Call $class->new( @$args ); and run the result through object_ok.
1399 # See Test::More::new_ok
1401 my($class, $args, $obj_name) = @_;
1403 $object_name = "The object" unless defined $obj_name;
1405 local $Level = $Level + 1;
1408 my $ok = eval { $obj = $class->new(@$args); 1 };
1412 object_ok($obj, $class, $object_name);
1415 ok( 0, "new() died" );
1416 diag("Error was: $@");
1425 my($object, $class, $obj_name) = @_;
1428 $obj_name = 'The object' unless defined $obj_name;
1429 my $name = "$obj_name isa $class";
1430 if( !defined $object ) {
1431 $diag = "$obj_name isn't defined";
1434 my $whatami = ref $object ? 'object' : 'class';
1436 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1437 local($@, $!); # eval sometimes resets $!
1438 my $rslt = eval { $object->isa($class) };
1439 my $error = $@; # in case something else blows away $@
1442 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1443 # It's an unblessed reference
1444 $obj_name = 'The reference' unless defined $obj_name;
1445 if( !UNIVERSAL::isa($object, $class) ) {
1446 my $ref = ref $object;
1447 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1450 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1451 # It's something that can't even be a class
1452 $obj_name = 'The thing' unless defined $obj_name;
1453 $diag = "$obj_name isn't a class or reference";
1457 WHOA! I tried to call ->isa on your object and got some weird error.
1458 This should never happen. Please contact the author immediately.
1465 $obj_name = "The $whatami" unless defined $obj_name;
1466 my $ref = ref $object;
1467 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1471 _ok( !$diag, _where(), $name );
1476 my($class, $isa, $class_name) = @_;
1478 # Written so as to count as one test
1479 local $Level = $Level + 1;
1481 ok( 0, "$class is a reference, not a class name" );
1484 isa_ok($class, $isa, $class_name);
1490 my($obj, $isa, $obj_name) = @_;
1492 local $Level = $Level + 1;
1494 ok( 0, "$obj is not a reference" );
1497 isa_ok($obj, $isa, $obj_name);
1502 # Purposefully avoiding a closure.
1504 push @::__capture, join "", @_;
1507 sub capture_warnings {
1511 local $SIG {__WARN__} = \&__capture;
1514 return @::__capture;
1517 # This will generate a variable number of tests.
1518 # Use done_testing() instead of a fixed plan.
1520 my ($code, $expect, $name) = @_;
1521 local $Level = $Level + 1;
1523 my @w = capture_warnings($code);
1525 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1526 foreach my $e (@$expect) {
1528 like(shift @w, $e, $name);
1530 is(shift @w, $e, $name);
1534 diag("Saw these additional warnings:");
1535 diag($_) foreach @w;
1539 sub _fail_excess_warnings {
1540 my($expect, $got, $name) = @_;
1541 local $Level = $Level + 1;
1542 # This will fail, and produce diagnostics
1543 is($expect, scalar @$got, $name);
1544 diag("Saw these warnings:");
1545 diag($_) foreach @$got;
1549 my ($code, $expect, $name) = @_;
1550 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1552 local $Level = $Level + 1;
1553 my @w = capture_warnings($code);
1555 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1557 is($w[0], $expect, $name);
1562 my ($code, $expect, $name) = @_;
1563 die sprintf "Expect must be a regexp object"
1564 unless ref $expect eq 'Regexp';
1565 local $Level = $Level + 1;
1566 my @w = capture_warnings($code);
1568 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1570 like($w[0], $expect, $name);
1574 # Set a watchdog to timeout the entire test file
1575 # NOTE: If the test file uses 'threads', then call the watchdog() function
1576 # _AFTER_ the 'threads' module is loaded.
1579 my $timeout = shift;
1580 my $method = shift || "";
1581 my $timeout_msg = 'Test process timed out - terminating';
1583 # Valgrind slows perl way down so give it more time before dying.
1584 $timeout *= 10 if $ENV{PERL_VALGRIND};
1586 my $pid_to_kill = $$; # PID for this process
1588 if ($method eq "alarm") {
1589 goto WATCHDOG_VIA_ALARM;
1592 # shut up use only once warning
1593 my $threads_on = $threads::threads && $threads::threads;
1595 # Don't use a watchdog process if 'threads' is loaded -
1596 # use a watchdog thread instead
1597 if (!$threads_on || $method eq "process") {
1599 # On Windows and VMS, try launching a watchdog process
1600 # using system(1, ...) (see perlport.pod)
1601 if ($is_mswin || $is_vms) {
1602 # On Windows, try to get the 'real' PID
1604 eval { require Win32; };
1605 if (defined(&Win32::GetCurrentProcessId)) {
1606 $pid_to_kill = Win32::GetCurrentProcessId();
1610 # If we still have a fake PID, we can't use this method at all
1611 return if ($pid_to_kill <= 0);
1613 # Launch watchdog process
1616 local $SIG{'__WARN__'} = sub {
1617 _diag("Watchdog warning: $_[0]");
1619 my $sig = $is_vms ? 'TERM' : 'KILL';
1620 my $prog = "sleep($timeout);" .
1621 "warn qq/# $timeout_msg" . '\n/;' .
1622 "kill(q/$sig/, $pid_to_kill);";
1624 # On Windows use the indirect object plus LIST form to guarantee
1625 # that perl is launched directly rather than via the shell (see
1626 # perlfunc.pod), and ensure that the LIST has multiple elements
1627 # since the indirect object plus COMMANDSTRING form seems to
1628 # hang (see perl #121283). Don't do this on VMS, which doesn't
1629 # support the LIST form at all.
1631 my $runperl = which_perl();
1632 if ($runperl =~ m/\s/) {
1633 $runperl = qq{"$runperl"};
1635 $watchdog = system({ $runperl } 1, $runperl, '-e', $prog);
1638 my $cmd = _create_runperl(prog => $prog);
1639 $watchdog = system(1, $cmd);
1642 if ($@ || ($watchdog <= 0)) {
1643 _diag('Failed to start watchdog');
1649 # Add END block to parent to terminate and
1650 # clean up watchdog process
1651 eval("END { local \$! = 0; local \$? = 0;
1652 wait() if kill('KILL', $watchdog); };");
1656 # Try using fork() to generate a watchdog process
1658 eval { $watchdog = fork() };
1659 if (defined($watchdog)) {
1660 if ($watchdog) { # Parent process
1661 # Add END block to parent to terminate and
1662 # clean up watchdog process
1663 eval "END { local \$! = 0; local \$? = 0;
1664 wait() if kill('KILL', $watchdog); };";
1668 ### Watchdog process code
1670 # Load POSIX if available
1671 eval { require POSIX; };
1673 # Execute the timeout
1674 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1677 # Kill test process if still running
1678 if (kill(0, $pid_to_kill)) {
1679 _diag($timeout_msg);
1680 kill('KILL', $pid_to_kill);
1682 # sometimes the above isn't enough on cygwin
1683 sleep 1; # wait a little, it might have worked after all
1684 system("/bin/kill -f $pid_to_kill");
1688 # Don't execute END block (added at beginning of this file)
1691 # Terminate ourself (i.e., the watchdog)
1692 POSIX::_exit(1) if (defined(&POSIX::_exit));
1696 # fork() failed - fall through and try using a thread
1699 # Use a watchdog thread because either 'threads' is loaded,
1701 if (eval {require threads; 1}) {
1702 'threads'->create(sub {
1703 # Load POSIX if available
1704 eval { require POSIX; };
1706 # Execute the timeout
1707 my $time_left = $timeout;
1709 $time_left = $time_left - sleep($time_left);
1710 } while ($time_left > 0);
1712 # Kill the parent (and ourself)
1713 select(STDERR); $| = 1;
1714 _diag($timeout_msg);
1715 POSIX::_exit(1) if (defined(&POSIX::_exit));
1716 my $sig = $is_vms ? 'TERM' : 'KILL';
1717 kill($sig, $pid_to_kill);
1722 # If everything above fails, then just use an alarm timeout
1724 if (eval { alarm($timeout); 1; }) {
1725 # Load POSIX if available
1726 eval { require POSIX; };
1728 # Alarm handler will do the actual 'killing'
1729 $SIG{'ALRM'} = sub {
1730 select(STDERR); $| = 1;
1731 _diag($timeout_msg);
1732 POSIX::_exit(1) if (defined(&POSIX::_exit));
1733 my $sig = $is_vms ? 'TERM' : 'KILL';
1734 kill($sig, $pid_to_kill);
1739 # Orphaned Docker or Linux containers do not necessarily attach to PID 1. They might attach to 0 instead.
1740 sub is_linux_container {
1742 if ($^O eq 'linux' && open my $fh, '<', '/proc/1/cgroup') {
1744 if (m{^\d+:pids:(.*)} && $1 ne '/init.scope') {