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;
33 # This is 'our' to enable harness to account for TODO-ed tests in
34 # overall grade of PASS or FAIL
37 our $Tests_Are_Passing = 1;
39 # Use this instead of print to avoid interference while testing globals.
41 local($\, $", $,) = (undef, ' ', '');
46 local($\, $", $,) = (undef, ' ', '');
54 if ($n eq 'no_plan') {
60 $plan{skip_all} and skip_all($plan{skip_all});
63 _print "1..$n\n" unless $noplan;
68 # Set the plan at the end. See Test::More::done_testing.
81 if (defined $planned && $planned != $ran) {
83 "# Looks like you planned $planned tests but ran $ran.\n";
92 my @mess = _comment(@_);
93 $TODO ? _print(@mess) : _print_stderr(@mess);
96 # Use this instead of "print STDERR" when outputting failure diagnostic
102 # Use this instead of "print" when outputting informational messages
105 _print( _comment(@_) );
109 return !defined &DynaLoader::boot_DynaLoader;
113 # Don’t clobber @INC under miniperl
114 @INC = () unless is_miniperl;
119 return map { /^#/ ? "$_\n" : "# $_\n" }
120 map { split /\n/ } @_;
123 sub _have_dynamic_extension {
124 my $extension = shift;
125 unless (eval {require Config; 1}) {
126 warn "test.pl had problems loading Config: $@";
129 $extension =~ s!::!/!g;
130 return 1 if ($Config::Config{extensions} =~ /\b$extension\b/);
135 _print "1..0 # Skip @_\n";
142 sub skip_all_if_miniperl {
143 skip_all(@_) if is_miniperl();
146 sub skip_all_without_dynamic_extension {
147 my ($extension) = @_;
148 skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
149 return if &_have_dynamic_extension;
150 skip_all("$extension was not built");
153 sub skip_all_without_perlio {
154 skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
157 sub skip_all_without_config {
158 unless (eval {require Config; 1}) {
159 warn "test.pl had problems loading Config: $@";
163 next if $Config::Config{$_};
164 my $key = $_; # Need to copy, before trying to modify.
171 sub skip_all_without_unicode_tables { # (but only under miniperl)
173 skip_all_if_miniperl("Unicode tables not built yet")
174 unless eval 'require "unicore/UCD.pl"';
178 sub find_git_or_skip {
179 my ($source_dir, $reason);
181 if ( $ENV{CONTINUOUS_INTEGRATION} && $ENV{WORKSPACE} ) {
182 $source_dir = $ENV{WORKSPACE};
183 if ( -d "${source_dir}/.git" ) {
184 $ENV{GIT_DIR} = "${source_dir}/.git";
191 } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
192 my $where = readlink 'MANIFEST';
193 die "Can't readlink MANIFEST: $!" unless defined $where;
194 die "Confusing symlink target for MANIFEST, '$where'"
195 unless $where =~ s!/MANIFEST\z!!;
196 if (-d "$where/.git") {
197 # Looks like we are in a symlink tree
198 if (exists $ENV{GIT_DIR}) {
199 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it");
201 note("Found source tree at $where, setting \$ENV{GIT_DIR}");
202 $ENV{GIT_DIR} = "$where/.git";
204 $source_dir = $where;
206 } elsif (exists $ENV{GIT_DIR} || -f '.git') {
207 my $commit = '8d063cd8450e59ea1c611a2f4f5a21059a2804f1';
208 my $out = `git rev-parse --verify --quiet '$commit^{commit}'`;
210 if($out eq $commit) {
214 if ($ENV{'PERL_BUILD_PACKAGING'}) {
215 $reason = 'PERL_BUILD_PACKAGING is set';
216 } elsif ($source_dir) {
217 my $version_string = `git --version`;
218 if (defined $version_string
219 && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
220 return $source_dir if eval "v$1 ge v1.5.0";
221 # If you have earlier than 1.5.0 and it works, change this test
222 $reason = "in git checkout, but git version '$1$2' too old";
224 $reason = "in git checkout, but cannot run git";
227 $reason = 'not being run from a git checkout';
229 skip_all($reason) if $_[0] && $_[0] eq 'all';
235 _print("Bail out! $reason\n");
240 my ($pass, $where, $name, @mess) = @_;
241 # Do not try to microoptimize by factoring out the "not ".
245 # escape out '#' or it will interfere with '# skip' and such
247 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
249 $out = $pass ? "ok $test" : "not ok $test";
253 $out = $out . " # TODO $TODO";
255 $Tests_Are_Passing = 0 unless $pass;
261 note @mess; # Ensure that the message is properly escaped.
264 my $msg = "# Failed test $test - ";
265 $msg.= "$name " if $name;
271 $test = $test + 1; # don't use ++
277 my @caller = caller($Level);
278 return "at $caller[1] line $caller[2]";
281 # DON'T use this for matches. Use like() instead.
283 my ($pass, $name, @mess) = @_;
284 _ok($pass, _where(), $name, @mess);
289 return 'undef' unless defined $x;
298 return defined $x ? '"' . display ($x) . '"' : 'undef';
301 # Support pre-5.10 Perls, for the benefit of CPAN dists that copy this file.
302 # Note that chr(90) exists in both ASCII ("Z") and EBCDIC ("!").
303 my $chars_template = defined(eval { pack "W*", 90 }) ? "W*" : "U*";
304 eval 'sub re::is_regexp { ref($_[0]) eq "Regexp" }'
305 if !defined &re::is_regexp;
307 # keys are the codes \n etc map to, values are 2 char strings such as \n
308 my %backslash_escape;
309 foreach my $x (split //, 'enrtfa\\\'"') {
310 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
312 # A way to display scalars containing control characters and Unicode.
313 # Trying to avoid setting $_, or relying on local $_ to work.
317 if (defined $x and not ref $x) {
319 foreach my $c (unpack($chars_template, $x)) {
321 $y = $y . sprintf "\\x{%x}", $c;
322 } elsif ($backslash_escape{$c}) {
323 $y = $y . $backslash_escape{$c};
324 } elsif ($c < ord " ") {
325 # Use octal for characters with small ordinals that are
326 # traditionally expressed as octal: the controls below
327 # space, which on EBCDIC are almost all the controls, but
328 # on ASCII don't include DEL nor the C1 controls.
329 $y = $y . sprintf "\\%03o", $c;
330 } elsif (chr $c =~ /[[:print:]]/a) {
334 $y = $y . sprintf "\\x%02X", $c;
339 return $x unless wantarray;
346 my ($got, $expected, $name, @mess) = @_;
349 if( !defined $got || !defined $expected ) {
350 # undef only matches undef
351 $pass = !defined $got && !defined $expected;
354 $pass = $got eq $expected;
358 unshift(@mess, "# got "._qq($got)."\n",
359 "# expected "._qq($expected)."\n");
361 _ok($pass, _where(), $name, @mess);
365 my ($got, $isnt, $name, @mess) = @_;
368 if( !defined $got || !defined $isnt ) {
369 # undef only matches undef
370 $pass = defined $got || defined $isnt;
373 $pass = $got ne $isnt;
377 unshift(@mess, "# it should not be "._qq($got)."\n",
380 _ok($pass, _where(), $name, @mess);
384 my($got, $type, $expected, $name, @mess) = @_;
389 local($@,$!); # don't interfere with $@
390 # eval() sometimes resets $!
391 $pass = eval "\$got $type \$expected";
394 # It seems Irix long doubles can have 2147483648 and 2147483648
395 # that stringify to the same thing but are actually numerically
396 # different. Display the numbers if $type isn't a string operator,
397 # and the numbers are stringwise the same.
398 # (all string operators have alphabetic names, so tr/a-z// is true)
399 # This will also show numbers for some unneeded cases, but will
400 # definitely be helpful for things such as == and <= that fail
401 if ($got eq $expected and $type !~ tr/a-z//) {
402 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
404 unshift(@mess, "# got "._qq($got)."\n",
405 "# expected $type "._qq($expected)."\n");
407 _ok($pass, _where(), $name, @mess);
410 # Check that $got is within $range of $expected
411 # if $range is 0, then check it's exact
412 # else if $expected is 0, then $range is an absolute value
413 # otherwise $range is a fractional error.
414 # Here $range must be numeric, >= 0
415 # Non numeric ranges might be a useful future extension. (eg %)
417 my ($got, $expected, $range, $name, @mess) = @_;
419 if (!defined $got or !defined $expected or !defined $range) {
420 # This is a fail, but doesn't need extra diagnostics
421 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
423 unshift @mess, "# got, expected and range must be numeric\n";
424 } elsif ($range < 0) {
425 # This is also a fail
426 unshift @mess, "# range must not be negative\n";
427 } elsif ($range == 0) {
429 $pass = $got == $expected;
430 } elsif ($expected == 0) {
431 # If expected is 0, treat range as absolute
432 $pass = ($got <= $range) && ($got >= - $range);
434 my $diff = $got - $expected;
435 $pass = abs ($diff / $expected) < $range;
438 if ($got eq $expected) {
439 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
441 unshift@mess, "# got "._qq($got)."\n",
442 "# expected "._qq($expected)." (within "._qq($range).")\n";
444 _ok($pass, _where(), $name, @mess);
447 # Note: this isn't quite as fancy as Test::More::like().
449 sub like ($$@) { like_yn (0,@_) }; # 0 for -
450 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
453 my ($flip, undef, $expected, $name, @mess) = @_;
455 # We just accept like(..., qr/.../), not like(..., '...'), and
456 # definitely not like(..., '/.../') like
457 # Test::Builder::maybe_regex() does.
458 unless (re::is_regexp($expected)) {
459 die "PANIC: The value '$expected' isn't a regexp. The like() function needs a qr// pattern, not a string";
463 $pass = $_[1] =~ /$expected/ if !$flip;
464 $pass = $_[1] !~ /$expected/ if $flip;
465 my $display_got = $_[1];
466 $display_got = display($display_got);
467 my $display_expected = $expected;
468 $display_expected = display($display_expected);
470 unshift(@mess, "# got '$display_got'\n",
472 ? "# expected !~ /$display_expected/\n"
473 : "# expected /$display_expected/\n");
475 local $Level = $Level + 1;
476 _ok($pass, _where(), $name, @mess);
484 _ok(0, _where(), @_);
494 $test = $test + 1; # don't use ++
498 # Note: can't pass multipart messages since we try to
499 # be compatible with Test::More::skip().
502 my $n = @_ ? shift : 1;
507 $bad_swap = $why > 0 && $n == 0;
508 $both_zero = $why == 0 && $n == 0;
510 if ($bad_swap || $both_zero || @_) {
511 my $arg = "'$why', '$n'";
513 $arg .= join(", ", '', map { qq['$_'] } @_);
515 die qq[$0: expected skip(why, count), got skip($arg)\n];
518 _print "ok $test # skip $why\n";
525 sub skip_if_miniperl {
526 skip(@_) if is_miniperl();
529 sub skip_without_dynamic_extension {
530 my $extension = shift;
531 skip("no dynamic loading on miniperl, no extension $extension", @_)
533 return if &_have_dynamic_extension($extension);
534 skip("extension $extension was not built", @_);
539 my $n = @_ ? shift : 1;
542 _print "not ok $test # TODO & SKIP $why\n";
551 return 0 unless $#$ra == $#$rb;
552 for my $i (0..$#$ra) {
553 next if !defined $ra->[$i] && !defined $rb->[$i];
554 return 0 if !defined $ra->[$i];
555 return 0 if !defined $rb->[$i];
556 return 0 unless $ra->[$i] eq $rb->[$i];
562 my ($orig, $suspect) = @_;
564 while (my ($key, $value) = each %$suspect) {
565 # Force a hash recompute if this perl's internals can cache the hash key.
567 if (exists $orig->{$key}) {
569 defined $orig->{$key} != defined $value
570 || (defined $value && $orig->{$key} ne $value)
572 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
573 " now ", _qq($value), "\n";
577 _print "# key ", _qq($key), " is ", _qq($value),
578 ", not in original.\n";
582 foreach (keys %$orig) {
583 # Force a hash recompute if this perl's internals can cache the hash key.
585 next if (exists $suspect->{$_});
586 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
592 # We only provide a subset of the Test::More functionality.
595 if ($require =~ tr/[A-Za-z0-9:.]//c) {
596 fail("Invalid character in \"$require\", passed to require_ok");
601 is($@, '', _where(), "require $require");
607 if ($use =~ tr/[A-Za-z0-9:.]//c) {
608 fail("Invalid character in \"$use\", passed to use");
613 is($@, '', _where(), "use $use");
617 # runperl, run_perl - Runs a separate perl interpreter and returns its output.
619 # switches => [ command-line switches ]
620 # nolib => 1 # don't use -I../lib (included by default)
621 # non_portable => Don't warn if a one liner contains quotes
622 # prog => one-liner (avoid quotes)
623 # progs => [ multi-liner (avoid quotes) ]
624 # progfile => perl script
625 # stdin => string to feed the stdin (or undef to redirect from /dev/null)
626 # stderr => If 'devnull' suppresses stderr, if other TRUE value redirect
628 # args => [ command-line arguments to the perl program ]
629 # verbose => print the command line
631 my $is_mswin = $^O eq 'MSWin32';
632 my $is_vms = $^O eq 'VMS';
633 my $is_cygwin = $^O eq 'cygwin';
636 my ($runperl, $args) = @_;
639 # In VMS protect with doublequotes because otherwise
640 # DCL will lowercase -- unless already doublequoted.
641 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
642 $runperl = $runperl . ' ' . $_;
647 sub _create_runperl { # Create the string to qx in runperl().
649 my $runperl = which_perl();
650 if ($runperl =~ m/\s/) {
651 $runperl = qq{"$runperl"};
653 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
654 if ($ENV{PERL_RUNPERL_DEBUG}) {
655 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
657 unless ($args{nolib}) {
658 $runperl = $runperl . ' "-I../lib" "-I." '; # doublequotes because of VMS
660 if ($args{switches}) {
662 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
663 unless ref $args{switches} eq "ARRAY";
664 $runperl = _quote_args($runperl, $args{switches});
666 if (defined $args{prog}) {
667 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
668 if defined $args{progs};
669 $args{progs} = [split /\n/, $args{prog}, -1]
671 if (defined $args{progs}) {
672 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
673 unless ref $args{progs} eq "ARRAY";
674 foreach my $prog (@{$args{progs}}) {
675 if (!$args{non_portable}) {
676 if ($prog =~ tr/'"//) {
677 warn "quotes in prog >>$prog<< are not portable";
679 if ($prog =~ /^([<>|]|2>)/) {
680 warn "Initial $1 in prog >>$prog<< is not portable";
682 if ($prog =~ /&\z/) {
683 warn "Trailing & in prog >>$prog<< is not portable";
686 if ($is_mswin || $is_vms) {
687 $runperl = $runperl . qq ( -e "$prog" );
690 $runperl = $runperl . qq ( -e '$prog' );
693 } elsif (defined $args{progfile}) {
694 $runperl = $runperl . qq( "$args{progfile}");
696 # You probably didn't want to be sucking in from the upstream stdin
697 die "test.pl:runperl(): none of prog, progs, progfile, args, "
698 . " switches or stdin specified"
699 unless defined $args{args} or defined $args{switches}
700 or defined $args{stdin};
702 if (defined $args{stdin}) {
703 # so we don't try to put literal newlines and crs onto the
705 $args{stdin} =~ s/\n/\\n/g;
706 $args{stdin} =~ s/\r/\\r/g;
708 if ($is_mswin || $is_vms) {
709 $runperl = qq{$Perl -e "print qq(} .
710 $args{stdin} . q{)" | } . $runperl;
713 $runperl = qq{$Perl -e 'print qq(} .
714 $args{stdin} . q{)' | } . $runperl;
716 } elsif (exists $args{stdin}) {
717 # Using the pipe construction above can cause fun on systems which use
718 # ksh as /bin/sh, as ksh does pipes differently (with one less process)
719 # With sh, for the command line 'perl -e 'print qq()' | perl -e ...'
720 # the sh process forks two children, which use exec to start the two
721 # perl processes. The parent shell process persists for the duration of
722 # the pipeline, and the second perl process starts with no children.
723 # With ksh (and zsh), the shell saves a process by forking a child for
724 # just the first perl process, and execing itself to start the second.
725 # This means that the second perl process starts with one child which
726 # it didn't create. This causes "fun" when if the tests assume that
727 # wait (or waitpid) will only return information about processes
728 # started within the test.
729 # They also cause fun on VMS, where the pipe implementation returns
730 # the exit code of the process at the front of the pipeline, not the
731 # end. This messes up any test using OPTION FATAL.
732 # Hence it's useful to have a way to make STDIN be at eof without
733 # needing a pipeline, so that the fork tests have a sane environment
734 # without these surprises.
736 # /dev/null appears to be surprisingly portable.
737 $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null');
739 if (defined $args{args}) {
740 $runperl = _quote_args($runperl, $args{args});
742 if (exists $args{stderr} && $args{stderr} eq 'devnull') {
743 $runperl = $runperl . ($is_mswin ? ' 2>nul' : ' 2>/dev/null');
745 elsif ($args{stderr}) {
746 $runperl = $runperl . ' 2>&1';
748 if ($args{verbose}) {
749 my $runperldisplay = $runperl;
750 $runperldisplay =~ s/\n/\n\#/g;
751 _print_stderr "# $runperldisplay\n";
757 # $ENV{PATH} =~ /(.*)/s;
758 # local $ENV{PATH} = untaint_path($1);
763 if (! eval {require Config; 1}) {
764 warn "test.pl had problems loading Config: $@";
767 $sep = $Config::Config{path_sep};
771 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
772 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
773 split quotemeta ($sep), $1;
774 if ($is_cygwin) { # Must have /bin under Cygwin
776 $path = $path . $sep;
778 $path = $path . '/bin';
784 # sub run_perl {} is alias to below
785 # Since this uses backticks to run, it is subject to the rules of the shell.
786 # Locale settings may pose a problem, depending on the program being run.
788 die "test.pl:runperl() does not take a hashref"
789 if ref $_[0] and ref $_[0] eq 'HASH';
790 my $runperl = &_create_runperl;
793 my $tainted = ${^TAINT};
795 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
798 # We will assume that if you're running under -T, you really mean to
799 # run a fresh perl, so we'll brute force launder everything for you
800 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
801 local @ENV{@keys} = ();
802 # Untaint, plus take out . and empty string:
803 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
804 $ENV{PATH} =~ /(.*)/s;
805 local $ENV{PATH} = untaint_path($1);
809 $result = `$runperl`;
811 $result = `$runperl`;
813 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
818 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
821 _print_stderr "# @_\n";
825 # A somewhat safer version of the sometimes wrong $^X.
827 unless (defined $Perl) {
830 # VMS should have 'perl' aliased properly
831 return $Perl if $is_vms;
834 if (! eval {require Config; 1}) {
835 warn "test.pl had problems loading Config: $@";
838 $exe = $Config::Config{_exe};
840 $exe = '' unless defined $exe;
842 # This doesn't absolutize the path: beware of future chdirs().
843 # We could do File::Spec->abs2rel() but that does getcwd()s,
844 # which is a bit heavyweight to do here.
846 if ($Perl =~ /^perl\Q$exe\E$/i) {
847 my $perl = "perl$exe";
848 if (! eval {require File::Spec; 1}) {
849 warn "test.pl had problems loading File::Spec: $@";
852 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
856 # Build up the name of the executable file from the name of
859 if ($Perl !~ /\Q$exe\E$/i) {
860 $Perl = $Perl . $exe;
863 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
865 # For subcommands to use.
866 $ENV{PERLEXE} = $Perl;
873 foreach my $file (@_) {
874 1 while unlink $file;
876 _print_stderr "# Couldn't unlink '$file': $!\n";
878 $count = $count + 1; # don't use ++
884 # _num_to_alpha - Returns a string of letters representing a positive integer.
887 # maximum number of letters
889 # returns undef if the number is negative
890 # returns undef if the number of letters is greater than the maximum wanted
892 # _num_to_alpha( 0) eq 'A';
893 # _num_to_alpha( 1) eq 'B';
894 # _num_to_alpha(25) eq 'Z';
895 # _num_to_alpha(26) eq 'AA';
896 # _num_to_alpha(27) eq 'AB';
898 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);
900 # Avoid ++ -- ranges split negative numbers
902 my($num,$max_char) = @_;
903 return unless $num >= 0;
906 $max_char = 0 if $max_char < 0;
909 $alpha = $letters[ $num % 26 ] . $alpha;
910 $num = int( $num / 26 );
915 next unless $max_char;
916 $char_count = $char_count + 1;
917 return if $char_count == $max_char;
923 END { unlink_all keys %tmpfiles }
925 # A regexp that matches the tempfile names
926 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
928 # Avoid ++, avoid ranges, avoid split //
929 my $tempfile_count = 0;
932 my $try = (-d "t" ? "t/" : "")."tmp$$";
933 my $alpha = _num_to_alpha($tempfile_count,2);
934 last unless defined $alpha;
935 $try = $try . $alpha;
936 $tempfile_count = $tempfile_count + 1;
938 # Need to note all the file names we allocated, as a second request may
939 # come before the first is created.
940 if (!$tmpfiles{$try} && !-e $try) {
946 die "Can't find temporary file name starting \"tmp$$\"";
949 # register_tempfile - Adds a list of files to be removed at the end of the current test file
951 # a list of files to be removed later
953 # returns a count of how many file names were actually added
955 # Reuses %tmpfiles so that tempfile() will also skip any files added here
956 # even if the file doesn't exist yet.
958 sub register_tempfile {
962 _print_stderr "# Temporary file '$_' already added\n";
971 # This is the temporary file for fresh_perl
972 my $tmpfile = tempfile();
975 my($prog, $runperl_args) = @_;
977 # Run 'runperl' with the complete perl program contained in '$prog', and
978 # arguments in the hash referred to by '$runperl_args'. The results are
979 # returned, with $? set to the exit code. Unless overridden, stderr is
980 # redirected to stdout.
982 # Placing the program in a file bypasses various sh vagaries
984 die sprintf "Second argument to fresh_perl_.* must be hashref of args to fresh_perl (or {})"
985 unless !(defined $runperl_args) || ref($runperl_args) eq 'HASH';
987 # Given the choice of the mis-parsable {}
988 # (we want an anon hash, but a borked lexer might think that it's a block)
989 # or relying on taking a reference to a lexical
990 # (\ might be mis-parsed, and the reference counting on the pad may go
992 # it feels like the least-worse thing is to assume that auto-vivification
993 # works. At least, this is only going to be a run-time failure, so won't
994 # affect tests using this file but not this function.
995 $runperl_args->{progfile} ||= $tmpfile;
996 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
998 open TEST, '>', $tmpfile or die "Cannot open $tmpfile: $!";
999 binmode TEST, ':utf8' if $runperl_args->{wide_chars};
1001 close TEST or die "Cannot close $tmpfile: $!";
1003 my $results = runperl(%$runperl_args);
1004 my $status = $?; # Not necessary to save this, but it makes it clear to
1005 # future maintainers.
1007 # Clean up the results into something a bit more predictable.
1008 $results =~ s/\n+$//;
1009 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
1010 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
1012 # bison says 'parse error' instead of 'syntax error',
1013 # various yaccs may or may not capitalize 'syntax'.
1014 $results =~ s/^(syntax|parse) error/syntax error/mig;
1017 # some tests will trigger VMS messages that won't be expected
1018 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1020 # pipes double these sometimes
1021 $results =~ s/\n\n/\n/g;
1030 my($prog, $action, $expect, $runperl_args, $name) = @_;
1032 my $results = fresh_perl($prog, $runperl_args);
1035 # Use the first line of the program as a name if none was given
1037 (my $first_line, $name) = $prog =~ /^((.{1,50}).*)/;
1038 $name = $name . '...' if length $first_line > length $name;
1041 # Historically this was implemented using a closure, but then that means
1042 # that the tests for closures avoid using this code. Given that there
1043 # are exactly two callers, doing exactly two things, the simpler approach
1044 # feels like a better trade off.
1046 if ($action eq 'eq') {
1047 $pass = is($results, $expect, $name);
1048 } elsif ($action eq '=~') {
1049 $pass = like($results, $expect, $name);
1051 die "_fresh_perl can't process action '$action'";
1055 _diag "# PROG: \n$prog\n";
1056 _diag "# STATUS: $status\n";
1065 # Combination of run_perl() and is().
1069 my($prog, $expected, $runperl_args, $name) = @_;
1071 # _fresh_perl() is going to clip the trailing newlines off the result.
1072 # This will make it so the test author doesn't have to know that.
1073 $expected =~ s/\n+$//;
1076 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
1082 # Combination of run_perl() and like().
1085 sub fresh_perl_like {
1086 my($prog, $expected, $runperl_args, $name) = @_;
1088 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
1091 # Many tests use the same format in __DATA__ or external files to specify a
1092 # sequence of (fresh) tests to run, extra files they may temporarily need, and
1093 # what the expected output is. Putting it here allows common code to serve
1094 # these multiple tests.
1096 # Each program is source code to run followed by an "EXPECT" line, followed
1097 # by the expected output.
1099 # The first line of the code to run may be a command line switch such as -wE
1100 # or -0777 (alphanumerics only; only one cluster, beginning with a minus is
1101 # allowed). Later lines may contain (note the '# ' on each):
1102 # # TODO reason for todo
1103 # # SKIP reason for skip
1104 # # SKIP ?code to test if this should be skipped
1105 # # NAME name of the test (as with ok($ok, $name))
1107 # The expected output may contain:
1108 # OPTION list of options
1109 # OPTIONS list of options
1111 # The possible options for OPTION may be:
1112 # regex - the expected output is a regular expression
1113 # random - all lines match but in any order
1114 # fatal - the code will fail fatally (croak, die)
1115 # nonfatal - the code is not expected to fail fatally
1117 # If the actual output contains a line "SKIPPED" the test will be
1120 # If the actual output contains a line "PREFIX", any output starting with that
1121 # line will be ignored when comparing with the expected output
1123 # If the global variable $FATAL is true then OPTION fatal is the
1127 sub _setup_one_file {
1129 # Store the filename as a program that started at line 0.
1130 # Real files count lines starting at line 1.
1131 my @these = (0, shift);
1132 my ($lineno, $current);
1134 if ($_ eq "########\n") {
1135 if (defined $current) {
1136 push @these, $lineno, $current;
1140 if (!defined $current) {
1146 if (defined $current) {
1147 push @these, $lineno, $current;
1149 ((scalar @these) / 2 - 1, @these);
1152 sub setup_multiple_progs {
1154 foreach my $file (@_) {
1155 next if $file =~ /(?:~|\.orig|,v)$/;
1156 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1159 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1163 $found = $found + 1; # don't use ++
1167 # This is an internal error, and should never happen. All bar one of
1168 # the files had an __END__ marker to signal the end of their preamble,
1169 # although for some it wasn't technically necessary as they have no
1170 # tests. It might be possible to process files without an __END__ by
1171 # seeking back to the start and treating the whole file as tests, but
1172 # it's simpler and more reliable just to make the rule that all files
1173 # must have __END__ in. This should never fail - a file without an
1174 # __END__ should not have been checked in, because the regression tests
1175 # would not have passed.
1176 die "Could not find '__END__' in $file"
1179 my ($t, @p) = _setup_one_file($fh, $file);
1184 or die "Cannot close $file: $!\n";
1186 return ($tests, @prgs);
1189 sub run_multiple_progs {
1193 # The tests in lib run in a temporary subdirectory of t, and always
1194 # pass in a list of "programs" to run
1197 # The tests below t run in t and pass in a file handle. In theory we
1198 # can pass (caller)[1] as the second argument to report errors with
1199 # the filename of our caller, as the handle is always DATA. However,
1200 # line numbers in DATA count from the __END__ token, so will be wrong.
1201 # Which is more confusing than not providing line numbers. So, for now,
1202 # don't provide line numbers. No obvious clean solution - one hack
1203 # would be to seek DATA back to the start and read to the __END__ token,
1204 # but that feels almost like we should just open $0 instead.
1206 # Not going to rely on undef in list assignment.
1208 ($dummy, @prgs) = _setup_one_file(shift);
1211 my $tmpfile = tempfile();
1213 my $count_failures = 0;
1216 while (defined ($line = shift @prgs)) {
1220 if (defined $file) {
1221 print "# From $file\n";
1228 if (s/^(\s*-\w+)//) {
1231 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1234 foreach my $what (qw(skip todo)) {
1235 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1236 # If the SKIP reason starts ? then it's taken as a code snippet to
1237 # evaluate. This provides the flexibility to have conditional SKIPs
1238 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1239 my $temp = eval $reason{$what};
1241 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1243 $reason{$what} = $temp;
1248 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1250 } elsif (defined $file) {
1251 $name = "test from $file at line $line";
1254 if ($reason{skip}) {
1257 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1262 if ($prog =~ /--FILE--/) {
1263 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1265 die "Internal error: test $_ didn't split into pairs, got " .
1266 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1268 while (@files > 2) {
1269 my $filename = shift @files;
1270 my $code = shift @files;
1271 push @temps, $filename;
1272 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1274 File::Path::mkpath($1);
1275 push(@temp_path, $1);
1277 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1279 close $fh or die "Cannot close $filename: $!\n";
1282 $prog = shift @files;
1285 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1289 open STDERR, '>&', STDOUT
1290 or die "Can't dup STDOUT->STDERR: $!;";
1293 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1294 print $fh $prog,"\n";
1295 close $fh or die "Cannot close $tmpfile: $!";
1296 my $results = runperl( stderr => 1, progfile => $tmpfile,
1298 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1299 : (switches => [$switch])
1302 $results =~ s/\n+$//;
1303 # allow expected output to be written as if $prog is on STDIN
1304 $results =~ s/$::tempfile_regexp/-/g;
1306 # some tests will trigger VMS messages that won't be expected
1307 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1309 # pipes double these sometimes
1310 $results =~ s/\n\n/\n/g;
1312 # bison says 'parse error' instead of 'syntax error',
1313 # various yaccs may or may not capitalize 'syntax'.
1314 $results =~ s/^(syntax|parse) error/syntax error/mig;
1315 # allow all tests to run when there are leaks
1316 $results =~ s/Scalars leaked: \d+\n//g;
1318 $expected =~ s/\n+$//;
1319 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1320 # any special options? (OPTIONS foo bar zap)
1321 my $option_regex = 0;
1322 my $option_random = 0;
1324 if ($expected =~ s/^OPTIONS? (.+)(?:\n|\Z)//) {
1325 foreach my $option (split(' ', $1)) {
1326 if ($option eq 'regex') { # allow regular expressions
1329 elsif ($option eq 'random') { # all lines match, but in any order
1332 elsif ($option eq 'fatal') { # perl should fail
1335 elsif ($option eq 'nonfatal') {
1336 # used to turn off default fatal
1340 die "$0: Unknown OPTION '$option'\n";
1344 die "$0: can't have OPTION regex and random\n"
1345 if $option_regex + $option_random > 1;
1347 if ($results =~ s/^SKIPPED\n//) {
1348 print "$results\n" ;
1352 if ($option_random) {
1353 my @got = sort split "\n", $results;
1354 my @expected = sort split "\n", $expected;
1356 $ok = "@got" eq "@expected";
1358 elsif ($option_regex) {
1359 $ok = $results =~ /^$expected/;
1362 $ok = $results =~ /^\Q$expected/;
1365 $ok = $results eq $expected;
1368 if ($ok && $fatal && !($status >> 8)) {
1373 local $::TODO = $reason{todo};
1377 $err_line .= "FILE: $file ; line $line\n" if defined $file;
1378 $err_line .= "PROG: $switch\n$prog\n" .
1379 "EXPECTED:\n$expected\n";
1380 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1381 $err_line .= "GOT:\n$results\n";
1382 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1384 $err_line =~ s/^/# /mg;
1385 print $err_line; # Harness can't filter it out from STDERR.
1388 print STDERR $err_line;
1390 die "PERL_TEST_ABORT_FIRST_FAILURE set Test Failure"
1391 if $ENV{PERL_TEST_ABORT_FIRST_FAILURE};
1395 if (defined $file) {
1396 _ok($ok, "at $file line $line", $name);
1398 # We don't have file and line number data for the test, so report
1399 # errors as coming from our caller.
1400 local $Level = $Level + 1;
1407 foreach (@temp_path) {
1408 File::Path::rmtree $_ if -d $_;
1412 if ( $count_failures ) {
1413 print STDERR <<'EOS';
1415 # Note: 'run_multiple_progs' run has one or more failures
1416 # you can consider setting the environment variable
1417 # PERL_TEST_ABORT_FIRST_FAILURE=1 before running the test
1418 # to stop on the first error.
1428 my($proto, @methods) = @_;
1429 my $class = ref $proto || $proto;
1431 unless( @methods ) {
1432 return _ok( 0, _where(), "$class->can(...)" );
1436 foreach my $method (@methods) {
1437 local($!, $@); # don't interfere with caller's $@
1438 # eval sometimes resets $!
1439 eval { $proto->can($method) } || push @nok, $method;
1443 $name = @methods == 1 ? "$class->can('$methods[0]')"
1444 : "$class->can(...)";
1446 _ok( !@nok, _where(), $name );
1450 # Call $class->new( @$args ); and run the result through object_ok.
1451 # See Test::More::new_ok
1453 my($class, $args, $obj_name) = @_;
1455 $obj_name = "The object" unless defined $obj_name;
1457 local $Level = $Level + 1;
1460 my $ok = eval { $obj = $class->new(@$args); 1 };
1464 object_ok($obj, $class, $obj_name);
1467 ok( 0, "new() died" );
1468 diag("Error was: $@");
1477 my($object, $class, $obj_name) = @_;
1480 $obj_name = 'The object' unless defined $obj_name;
1481 my $name = "$obj_name isa $class";
1482 if( !defined $object ) {
1483 $diag = "$obj_name isn't defined";
1486 my $whatami = ref $object ? 'object' : 'class';
1488 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1489 local($@, $!); # eval sometimes resets $!
1490 my $rslt = eval { $object->isa($class) };
1491 my $error = $@; # in case something else blows away $@
1494 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1495 # It's an unblessed reference
1496 $obj_name = 'The reference' unless defined $obj_name;
1497 if( !UNIVERSAL::isa($object, $class) ) {
1498 my $ref = ref $object;
1499 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1502 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1503 # It's something that can't even be a class
1504 $obj_name = 'The thing' unless defined $obj_name;
1505 $diag = "$obj_name isn't a class or reference";
1509 WHOA! I tried to call ->isa on your object and got some weird error.
1510 This should never happen. Please contact the author immediately.
1517 $obj_name = "The $whatami" unless defined $obj_name;
1518 my $ref = ref $object;
1519 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1523 _ok( !$diag, _where(), $name );
1528 my($class, $isa, $class_name) = @_;
1530 # Written so as to count as one test
1531 local $Level = $Level + 1;
1533 ok( 0, "$class is a reference, not a class name" );
1536 isa_ok($class, $isa, $class_name);
1542 my($obj, $isa, $obj_name) = @_;
1544 local $Level = $Level + 1;
1546 ok( 0, "$obj is not a reference" );
1549 isa_ok($obj, $isa, $obj_name);
1554 # Purposefully avoiding a closure.
1556 push @::__capture, join "", @_;
1559 sub capture_warnings {
1563 local $SIG {__WARN__} = \&__capture;
1566 return @::__capture;
1569 # This will generate a variable number of tests.
1570 # Use done_testing() instead of a fixed plan.
1572 my ($code, $expect, $name) = @_;
1573 local $Level = $Level + 1;
1575 my @w = capture_warnings($code);
1577 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1578 foreach my $e (@$expect) {
1580 like(shift @w, $e, $name);
1582 is(shift @w, $e, $name);
1586 diag("Saw these additional warnings:");
1587 diag($_) foreach @w;
1591 sub _fail_excess_warnings {
1592 my($expect, $got, $name) = @_;
1593 local $Level = $Level + 1;
1594 # This will fail, and produce diagnostics
1595 is($expect, scalar @$got, $name);
1596 diag("Saw these warnings:");
1597 diag($_) foreach @$got;
1601 my ($code, $expect, $name) = @_;
1602 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1604 local $Level = $Level + 1;
1605 my @w = capture_warnings($code);
1607 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1609 is($w[0], $expect, $name);
1614 my ($code, $expect, $name) = @_;
1615 die sprintf "Expect must be a regexp object"
1616 unless ref $expect eq 'Regexp';
1617 local $Level = $Level + 1;
1618 my @w = capture_warnings($code);
1620 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1622 like($w[0], $expect, $name);
1626 # Set a watchdog to timeout the entire test file
1627 # NOTE: If the test file uses 'threads', then call the watchdog() function
1628 # _AFTER_ the 'threads' module is loaded.
1631 my $timeout = shift;
1632 my $method = shift || "";
1633 my $timeout_msg = 'Test process timed out - terminating';
1635 # Valgrind slows perl way down so give it more time before dying.
1636 $timeout *= 10 if $ENV{PERL_VALGRIND};
1638 my $pid_to_kill = $$; # PID for this process
1640 if ($method eq "alarm") {
1641 goto WATCHDOG_VIA_ALARM;
1644 # shut up use only once warning
1645 my $threads_on = $threads::threads && $threads::threads;
1647 # Don't use a watchdog process if 'threads' is loaded -
1648 # use a watchdog thread instead
1649 if (!$threads_on || $method eq "process") {
1651 # On Windows and VMS, try launching a watchdog process
1652 # using system(1, ...) (see perlport.pod)
1653 if ($is_mswin || $is_vms) {
1654 # On Windows, try to get the 'real' PID
1656 eval { require Win32; };
1657 if (defined(&Win32::GetCurrentProcessId)) {
1658 $pid_to_kill = Win32::GetCurrentProcessId();
1662 # If we still have a fake PID, we can't use this method at all
1663 return if ($pid_to_kill <= 0);
1665 # Launch watchdog process
1668 local $SIG{'__WARN__'} = sub {
1669 _diag("Watchdog warning: $_[0]");
1671 my $sig = $is_vms ? 'TERM' : 'KILL';
1672 my $prog = "sleep($timeout);" .
1673 "warn qq/# $timeout_msg" . '\n/;' .
1674 "kill(q/$sig/, $pid_to_kill);";
1676 # If we're in taint mode PATH will be tainted
1677 $ENV{PATH} =~ /(.*)/s;
1678 local $ENV{PATH} = untaint_path($1);
1680 # On Windows use the indirect object plus LIST form to guarantee
1681 # that perl is launched directly rather than via the shell (see
1682 # perlfunc.pod), and ensure that the LIST has multiple elements
1683 # since the indirect object plus COMMANDSTRING form seems to
1684 # hang (see perl #121283). Don't do this on VMS, which doesn't
1685 # support the LIST form at all.
1687 my $runperl = which_perl();
1690 if ($runperl =~ m/\s/) {
1691 $runperl = qq{"$runperl"};
1693 $watchdog = system({ $runperl } 1, $runperl, '-e', $prog);
1696 my $cmd = _create_runperl(prog => $prog);
1697 $watchdog = system(1, $cmd);
1700 if ($@ || ($watchdog <= 0)) {
1701 _diag('Failed to start watchdog');
1707 # Add END block to parent to terminate and
1708 # clean up watchdog process
1709 eval("END { local \$! = 0; local \$? = 0;
1710 wait() if kill('KILL', $watchdog); };");
1714 # Try using fork() to generate a watchdog process
1716 eval { $watchdog = fork() };
1717 if (defined($watchdog)) {
1718 if ($watchdog) { # Parent process
1719 # Add END block to parent to terminate and
1720 # clean up watchdog process
1721 eval "END { local \$! = 0; local \$? = 0;
1722 wait() if kill('KILL', $watchdog); };";
1726 ### Watchdog process code
1728 # Load POSIX if available
1729 eval { require POSIX; };
1731 # Execute the timeout
1732 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1735 # Kill test process if still running
1736 if (kill(0, $pid_to_kill)) {
1737 _diag($timeout_msg);
1738 kill('KILL', $pid_to_kill);
1740 # sometimes the above isn't enough on cygwin
1741 sleep 1; # wait a little, it might have worked after all
1742 system("/bin/kill -f $pid_to_kill") if kill(0, $pid_to_kill);
1746 # Don't execute END block (added at beginning of this file)
1749 # Terminate ourself (i.e., the watchdog)
1750 POSIX::_exit(1) if (defined(&POSIX::_exit));
1754 # fork() failed - fall through and try using a thread
1757 # Use a watchdog thread because either 'threads' is loaded,
1759 if (eval {require threads; 1}) {
1760 'threads'->create(sub {
1761 # Load POSIX if available
1762 eval { require POSIX; };
1764 # Execute the timeout
1765 my $time_left = $timeout;
1767 $time_left = $time_left - sleep($time_left);
1768 } while ($time_left > 0);
1770 # Kill the parent (and ourself)
1771 select(STDERR); $| = 1;
1772 _diag($timeout_msg);
1773 POSIX::_exit(1) if (defined(&POSIX::_exit));
1774 my $sig = $is_vms ? 'TERM' : 'KILL';
1775 kill($sig, $pid_to_kill);
1780 # If everything above fails, then just use an alarm timeout
1782 if (eval { alarm($timeout); 1; }) {
1783 # Load POSIX if available
1784 eval { require POSIX; };
1786 # Alarm handler will do the actual 'killing'
1787 $SIG{'ALRM'} = sub {
1788 select(STDERR); $| = 1;
1789 _diag($timeout_msg);
1790 POSIX::_exit(1) if (defined(&POSIX::_exit));
1791 my $sig = $is_vms ? 'TERM' : 'KILL';
1792 kill($sig, $pid_to_kill);
1797 # Orphaned Docker or Linux containers do not necessarily attach to PID 1. They might attach to 0 instead.
1798 sub is_linux_container {
1800 if ($^O eq 'linux' && open my $fh, '<', '/proc/1/cgroup') {
1802 if (m{^\d+:pids:(.*)} && $1 ne '/init.scope') {