2 # t/test.pl - most of Test::More functionality without the fuss
7 # Increment ($x++) has a certain amount of cleverness for things like
10 # $x++; # $x eq 'aaa';
12 # stands more chance of breaking than just a simple
16 # In this file, we use the latter "Baby Perl" approach, and increment
17 # will be worked over by t/op/inc.t
23 my $Perl; # Safer version of $^X set by which_perl()
28 # Use this instead of print to avoid interference while testing globals.
30 local($\, $", $,) = (undef, ' ', '');
35 local($\, $", $,) = (undef, ' ', '');
43 if ($n eq 'no_plan') {
51 _print "1..$n\n" unless $noplan;
58 if (defined $planned && $planned != $ran) {
60 "# Looks like you planned $planned tests but ran $ran.\n";
67 # Use this instead of "print STDERR" when outputing failure diagnostic
71 my @mess = map { /^#/ ? "$_\n" : "# $_\n" }
72 map { split /\n/ } @_;
73 $TODO ? _print(@mess) : _print_stderr(@mess);
82 _print "1..0 # Skip @_\n";
90 my ($pass, $where, $name, @mess) = @_;
91 # Do not try to microoptimize by factoring out the "not ".
95 # escape out '#' or it will interfere with '# skip' and such
97 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
99 $out = $pass ? "ok $test" : "not ok $test";
102 $out .= " # TODO $TODO" if $TODO;
106 _diag "# Failed $where\n";
109 # Ensure that the message is properly escaped.
112 $test = $test + 1; # don't use ++
118 my @caller = caller($Level);
119 return "at $caller[1] line $caller[2]";
122 # DON'T use this for matches. Use like() instead.
124 my ($pass, $name, @mess) = @_;
125 _ok($pass, _where(), $name, @mess);
130 return 'undef' unless defined $x;
139 return defined $x ? '"' . display ($x) . '"' : 'undef';
142 # keys are the codes \n etc map to, values are 2 char strings such as \n
143 my %backslash_escape;
144 foreach my $x (split //, 'nrtfa\\\'"') {
145 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
147 # A way to display scalars containing control characters and Unicode.
148 # Trying to avoid setting $_, or relying on local $_ to work.
152 if (defined $x and not ref $x) {
154 foreach my $c (unpack("U*", $x)) {
156 $y .= sprintf "\\x{%x}", $c;
157 } elsif ($backslash_escape{$c}) {
158 $y .= $backslash_escape{$c};
160 my $z = chr $c; # Maybe we can get away with a literal...
161 $z = sprintf "\\%03o", $c if $z =~ /[[:^print:]]/;
167 return $x unless wantarray;
174 my ($got, $expected, $name, @mess) = @_;
177 if( !defined $got || !defined $expected ) {
178 # undef only matches undef
179 $pass = !defined $got && !defined $expected;
182 $pass = $got eq $expected;
186 unshift(@mess, "# got "._q($got)."\n",
187 "# expected "._q($expected)."\n");
189 _ok($pass, _where(), $name, @mess);
193 my ($got, $isnt, $name, @mess) = @_;
196 if( !defined $got || !defined $isnt ) {
197 # undef only matches undef
198 $pass = defined $got || defined $isnt;
201 $pass = $got ne $isnt;
205 unshift(@mess, "# it should not be "._q($got)."\n",
208 _ok($pass, _where(), $name, @mess);
212 my($got, $type, $expected, $name, @mess) = @_;
217 local($@,$!); # don't interfere with $@
218 # eval() sometimes resets $!
219 $pass = eval "\$got $type \$expected";
222 # It seems Irix long doubles can have 2147483648 and 2147483648
223 # that stringify to the same thing but are acutally numerically
224 # different. Display the numbers if $type isn't a string operator,
225 # and the numbers are stringwise the same.
226 # (all string operators have alphabetic names, so tr/a-z// is true)
227 # This will also show numbers for some uneeded cases, but will
228 # definately be helpful for things such as == and <= that fail
229 if ($got eq $expected and $type !~ tr/a-z//) {
230 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
232 unshift(@mess, "# got "._q($got)."\n",
233 "# expected $type "._q($expected)."\n");
235 _ok($pass, _where(), $name, @mess);
238 # Check that $got is within $range of $expected
239 # if $range is 0, then check it's exact
240 # else if $expected is 0, then $range is an absolute value
241 # otherwise $range is a fractional error.
242 # Here $range must be numeric, >= 0
243 # Non numeric ranges might be a useful future extension. (eg %)
245 my ($got, $expected, $range, $name, @mess) = @_;
247 if (!defined $got or !defined $expected or !defined $range) {
248 # This is a fail, but doesn't need extra diagnostics
249 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
251 unshift @mess, "# got, expected and range must be numeric\n";
252 } elsif ($range < 0) {
253 # This is also a fail
254 unshift @mess, "# range must not be negative\n";
255 } elsif ($range == 0) {
257 $pass = $got == $expected;
258 } elsif ($expected == 0) {
259 # If expected is 0, treat range as absolute
260 $pass = ($got <= $range) && ($got >= - $range);
262 my $diff = $got - $expected;
263 $pass = abs ($diff / $expected) < $range;
266 if ($got eq $expected) {
267 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
269 unshift@mess, "# got "._q($got)."\n",
270 "# expected "._q($expected)." (within "._q($range).")\n";
272 _ok($pass, _where(), $name, @mess);
275 # Note: this isn't quite as fancy as Test::More::like().
277 sub like ($$@) { like_yn (0,@_) }; # 0 for -
278 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
281 my ($flip, $got, $expected, $name, @mess) = @_;
283 $pass = $got =~ /$expected/ if !$flip;
284 $pass = $got !~ /$expected/ if $flip;
286 unshift(@mess, "# got '$got'\n",
288 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
290 local $Level = $Level + 1;
291 _ok($pass, _where(), $name, @mess);
299 _ok(0, _where(), @_);
309 $test = $test + 1; # don't use ++
313 # Note: can't pass multipart messages since we try to
314 # be compatible with Test::More::skip().
317 my $n = @_ ? shift : 1;
319 _print "ok $test # skip $why\n";
328 my $n = @_ ? shift : 1;
331 _print "not ok $test # TODO & SKIP $why\n";
340 return 0 unless $#$ra == $#$rb;
341 for my $i (0..$#$ra) {
342 next if !defined $ra->[$i] && !defined $rb->[$i];
343 return 0 if !defined $ra->[$i];
344 return 0 if !defined $rb->[$i];
345 return 0 unless $ra->[$i] eq $rb->[$i];
351 my ($orig, $suspect) = @_;
353 while (my ($key, $value) = each %$suspect) {
354 # Force a hash recompute if this perl's internals can cache the hash key.
356 if (exists $orig->{$key}) {
357 if ($orig->{$key} ne $value) {
358 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
359 " now ", _qq($value), "\n";
363 _print "# key ", _qq($key), " is ", _qq($value),
364 ", not in original.\n";
368 foreach (keys %$orig) {
369 # Force a hash recompute if this perl's internals can cache the hash key.
371 next if (exists $suspect->{$_});
372 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
383 _ok(!$@, _where(), "require $require");
391 _ok(!$@, _where(), "use $use");
394 # runperl - Runs a separate perl interpreter.
396 # switches => [ command-line switches ]
397 # nolib => 1 # don't use -I../lib (included by default)
398 # prog => one-liner (avoid quotes)
399 # progs => [ multi-liner (avoid quotes) ]
400 # progfile => perl script
401 # stdin => string to feed the stdin
402 # stderr => redirect stderr to stdout
403 # args => [ command-line arguments to the perl program ]
404 # verbose => print the command line
406 my $is_mswin = $^O eq 'MSWin32';
407 my $is_netware = $^O eq 'NetWare';
408 my $is_macos = $^O eq 'MacOS';
409 my $is_vms = $^O eq 'VMS';
410 my $is_cygwin = $^O eq 'cygwin';
413 my ($runperl, $args) = @_;
416 # In VMS protect with doublequotes because otherwise
417 # DCL will lowercase -- unless already doublequoted.
418 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
419 $$runperl .= ' ' . $_;
423 sub _create_runperl { # Create the string to qx in runperl().
425 my $runperl = which_perl();
426 if ($runperl =~ m/\s/) {
427 $runperl = qq{"$runperl"};
429 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
430 if ($ENV{PERL_RUNPERL_DEBUG}) {
431 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
433 unless ($args{nolib}) {
435 $runperl .= ' -I::lib';
436 # Use UNIX style error messages instead of MPW style.
437 $runperl .= ' -MMac::err=unix' if $args{stderr};
440 $runperl .= ' "-I../lib"'; # doublequotes because of VMS
443 if ($args{switches}) {
445 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
446 unless ref $args{switches} eq "ARRAY";
447 _quote_args(\$runperl, $args{switches});
449 if (defined $args{prog}) {
450 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
451 if defined $args{progs};
452 $args{progs} = [$args{prog}]
454 if (defined $args{progs}) {
455 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
456 unless ref $args{progs} eq "ARRAY";
457 foreach my $prog (@{$args{progs}}) {
458 if ($is_mswin || $is_netware || $is_vms) {
459 $runperl .= qq ( -e "$prog" );
462 $runperl .= qq ( -e '$prog' );
465 } elsif (defined $args{progfile}) {
466 $runperl .= qq( "$args{progfile}");
468 # You probaby didn't want to be sucking in from the upstream stdin
469 die "test.pl:runperl(): none of prog, progs, progfile, args, "
470 . " switches or stdin specified"
471 unless defined $args{args} or defined $args{switches}
472 or defined $args{stdin};
474 if (defined $args{stdin}) {
475 # so we don't try to put literal newlines and crs onto the
477 $args{stdin} =~ s/\n/\\n/g;
478 $args{stdin} =~ s/\r/\\r/g;
480 if ($is_mswin || $is_netware || $is_vms) {
481 $runperl = qq{$Perl -e "print qq(} .
482 $args{stdin} . q{)" | } . $runperl;
485 # MacOS can only do two processes under MPW at once;
486 # the test itself is one; we can't do two more, so
488 my $stdin = qq{$Perl -e 'print qq(} . $args{stdin} . qq{)' > teststdin; };
489 if ($args{verbose}) {
490 my $stdindisplay = $stdin;
491 $stdindisplay =~ s/\n/\n\#/g;
492 _print_stderr "# $stdindisplay\n";
495 $runperl .= q{ < teststdin };
498 $runperl = qq{$Perl -e 'print qq(} .
499 $args{stdin} . q{)' | } . $runperl;
502 if (defined $args{args}) {
503 _quote_args(\$runperl, $args{args});
505 $runperl .= ' 2>&1' if $args{stderr} && !$is_macos;
506 $runperl .= " \xB3 Dev:Null" if !$args{stderr} && $is_macos;
507 if ($args{verbose}) {
508 my $runperldisplay = $runperl;
509 $runperldisplay =~ s/\n/\n\#/g;
510 _print_stderr "# $runperldisplay\n";
516 die "test.pl:runperl() does not take a hashref"
517 if ref $_[0] and ref $_[0] eq 'HASH';
518 my $runperl = &_create_runperl;
521 my $tainted = ${^TAINT};
523 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
526 # We will assume that if you're running under -T, you really mean to
527 # run a fresh perl, so we'll brute force launder everything for you
530 if (! eval 'require Config; 1') {
531 warn "test.pl had problems loading Config: $@";
534 $sep = $Config::Config{path_sep};
537 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
538 local @ENV{@keys} = ();
539 # Untaint, plus take out . and empty string:
540 local $ENV{'DCL$PATH'} = $1 if $is_vms && ($ENV{'DCL$PATH'} =~ /(.*)/s);
541 $ENV{PATH} =~ /(.*)/s;
543 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
544 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
545 split quotemeta ($sep), $1;
546 $ENV{PATH} .= "$sep/bin" if $is_cygwin; # Must have /bin under Cygwin
551 $result = `$runperl`;
553 $result = `$runperl`;
555 $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
559 *run_perl = \&runperl; # Nice alias.
562 _print_stderr "# @_\n";
566 # A somewhat safer version of the sometimes wrong $^X.
568 unless (defined $Perl) {
571 # VMS should have 'perl' aliased properly
572 return $Perl if $^O eq 'VMS';
575 if (! eval 'require Config; 1') {
576 warn "test.pl had problems loading Config: $@";
579 $exe = $Config::Config{_exe};
581 $exe = '' unless defined $exe;
583 # This doesn't absolutize the path: beware of future chdirs().
584 # We could do File::Spec->abs2rel() but that does getcwd()s,
585 # which is a bit heavyweight to do here.
587 if ($Perl =~ /^perl\Q$exe\E$/i) {
588 my $perl = "perl$exe";
589 if (! eval 'require File::Spec; 1') {
590 warn "test.pl had problems loading File::Spec: $@";
593 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
597 # Build up the name of the executable file from the name of
600 if ($Perl !~ /\Q$exe\E$/i) {
604 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
606 # For subcommands to use.
607 $ENV{PERLEXE} = $Perl;
613 foreach my $file (@_) {
614 1 while unlink $file;
615 _print_stderr "# Couldn't unlink '$file': $!\n" if -f $file;
620 END { unlink_all keys %tmpfiles }
622 # A regexp that matches the tempfile names
623 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
625 # Avoid ++, avoid ranges, avoid split //
626 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);
633 $try .= $letters[$temp % 26];
634 $temp = int ($temp / 26);
636 # Need to note all the file names we allocated, as a second request may
637 # come before the first is created.
638 if (!-e $try && !$tmpfiles{$try}) {
644 } while $count < 26 * 26;
645 die "Can't find temporary file name starting 'tmp$$'";
648 # This is the temporary file for _fresh_perl
649 my $tmpfile = tempfile();
654 # The $resolve must be a subref that tests the first argument
655 # for success, or returns the definition of success (e.g. the
656 # expected scalar) if given no arguments.
660 my($prog, $resolve, $runperl_args, $name) = @_;
662 $runperl_args ||= {};
663 $runperl_args->{progfile} = $tmpfile;
664 $runperl_args->{stderr} = 1;
666 open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
670 $prog =~ s#/dev/null#NL:#;
673 $prog =~ s{if \(-e _ and -f _ and -r _\)}
678 close TEST or die "Cannot close $tmpfile: $!";
680 my $results = runperl(%$runperl_args);
683 # Clean up the results into something a bit more predictable.
684 $results =~ s/\n+$//;
685 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
686 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
688 # bison says 'parse error' instead of 'syntax error',
689 # various yaccs may or may not capitalize 'syntax'.
690 $results =~ s/^(syntax|parse) error/syntax error/mig;
693 # some tests will trigger VMS messages that won't be expected
694 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
696 # pipes double these sometimes
697 $results =~ s/\n\n/\n/g;
700 my $pass = $resolve->($results);
702 _diag "# PROG: \n$prog\n";
703 _diag "# EXPECTED:\n", $resolve->(), "\n";
704 _diag "# GOT:\n$results\n";
705 _diag "# STATUS: $status\n";
708 # Use the first line of the program as a name if none was given
710 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
711 $name .= '...' if length $first_line > length $name;
714 _ok($pass, _where(), "fresh_perl - $name");
720 # Combination of run_perl() and is().
724 my($prog, $expected, $runperl_args, $name) = @_;
727 sub { @_ ? $_[0] eq $expected : $expected },
728 $runperl_args, $name);
734 # Combination of run_perl() and like().
737 sub fresh_perl_like {
738 my($prog, $expected, $runperl_args, $name) = @_;
742 $_[0] =~ (ref $expected ? $expected : /$expected/) :
744 $runperl_args, $name);
748 my($proto, @methods) = @_;
749 my $class = ref $proto || $proto;
752 return _ok( 0, _where(), "$class->can(...)" );
756 foreach my $method (@methods) {
757 local($!, $@); # don't interfere with caller's $@
758 # eval sometimes resets $!
759 eval { $proto->can($method) } || push @nok, $method;
763 $name = @methods == 1 ? "$class->can('$methods[0]')"
764 : "$class->can(...)";
766 _ok( !@nok, _where(), $name );
770 my($object, $class, $obj_name) = @_;
773 $obj_name = 'The object' unless defined $obj_name;
774 my $name = "$obj_name isa $class";
775 if( !defined $object ) {
776 $diag = "$obj_name isn't defined";
778 elsif( !ref $object ) {
779 $diag = "$obj_name isn't a reference";
782 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
783 local($@, $!); # eval sometimes resets $!
784 my $rslt = eval { $object->isa($class) };
786 if( $@ =~ /^Can't call method "isa" on unblessed reference/ ) {
787 if( !UNIVERSAL::isa($object, $class) ) {
788 my $ref = ref $object;
789 $diag = "$obj_name isn't a '$class' it's a '$ref'";
793 WHOA! I tried to call ->isa on your object and got some weird error.
794 This should never happen. Please contact the author immediately.
801 my $ref = ref $object;
802 $diag = "$obj_name isn't a '$class' it's a '$ref'";
806 _ok( !$diag, _where(), $name );
809 # Set a watchdog to timeout the entire test file
810 # NOTE: If the test file uses 'threads', then call the watchdog() function
811 # _AFTER_ the 'threads' module is loaded.
815 my $timeout_msg = 'Test process timed out - terminating';
817 my $pid_to_kill = $$; # PID for this process
819 # Don't use a watchdog process if 'threads' is loaded -
820 # use a watchdog thread instead
821 if (! $threads::threads) {
823 # On Windows and VMS, try launching a watchdog process
824 # using system(1, ...) (see perlport.pod)
825 if (($^O eq 'MSWin32') || ($^O eq 'VMS')) {
826 # On Windows, try to get the 'real' PID
827 if ($^O eq 'MSWin32') {
828 eval { require Win32; };
829 if (defined(&Win32::GetCurrentProcessId)) {
830 $pid_to_kill = Win32::GetCurrentProcessId();
834 # If we still have a fake PID, we can't use this method at all
835 return if ($pid_to_kill <= 0);
837 # Launch watchdog process
840 local $SIG{'__WARN__'} = sub {
841 _diag("Watchdog warning: $_[0]");
843 my $sig = $^O eq 'VMS' ? 'TERM' : 'KILL';
844 $watchdog = system(1, which_perl(), '-e',
846 "warn('# $timeout_msg\n');" .
847 "kill($sig, $pid_to_kill);");
849 if ($@ || ($watchdog <= 0)) {
850 _diag('Failed to start watchdog');
856 # Add END block to parent to terminate and
857 # clean up watchdog process
858 eval "END { local \$! = 0; local \$? = 0;
859 wait() if kill('KILL', $watchdog); };";
863 # Try using fork() to generate a watchdog process
865 eval { $watchdog = fork() };
866 if (defined($watchdog)) {
867 if ($watchdog) { # Parent process
868 # Add END block to parent to terminate and
869 # clean up watchdog process
870 eval "END { local \$! = 0; local \$? = 0;
871 wait() if kill('KILL', $watchdog); };";
875 ### Watchdog process code
877 # Load POSIX if available
878 eval { require POSIX; };
880 # Execute the timeout
881 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
884 # Kill test process if still running
885 if (kill(0, $pid_to_kill)) {
887 kill('KILL', $pid_to_kill);
890 # Don't execute END block (added at beginning of this file)
893 # Terminate ourself (i.e., the watchdog)
894 POSIX::_exit(1) if (defined(&POSIX::_exit));
898 # fork() failed - fall through and try using a thread
901 # Use a watchdog thread because either 'threads' is loaded,
903 if (eval 'require threads; 1') {
904 threads->create(sub {
905 # Load POSIX if available
906 eval { require POSIX; };
908 # Execute the timeout
909 my $time_left = $timeout;
911 $time_left -= sleep($time_left);
912 } while ($time_left > 0);
914 # Kill the parent (and ourself)
915 select(STDERR); $| = 1;
917 POSIX::_exit(1) if (defined(&POSIX::_exit));
918 my $sig = $^O eq 'VMS' ? 'TERM' : 'KILL';
919 kill($sig, $pid_to_kill);
924 # If everything above fails, then just use an alarm timeout
925 if (eval { alarm($timeout); 1; }) {
926 # Load POSIX if available
927 eval { require POSIX; };
929 # Alarm handler will do the actual 'killing'
931 select(STDERR); $| = 1;
933 POSIX::_exit(1) if (defined(&POSIX::_exit));
934 my $sig = $^O eq 'VMS' ? 'TERM' : 'KILL';
935 kill($sig, $pid_to_kill);