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
27 # Use this instead of print to avoid interference while testing globals.
29 local($\, $", $,) = (undef, ' ', '');
34 local($\, $", $,) = (undef, ' ', '');
42 if ($n eq 'no_plan') {
50 _print "1..$n\n" unless $noplan;
57 if (defined $planned && $planned != $ran) {
59 "# Looks like you planned $planned tests but ran $ran.\n";
66 # Use this instead of "print STDERR" when outputing failure diagnostic
70 my @mess = map { /^#/ ? "$_\n" : "# $_\n" }
71 map { split /\n/ } @_;
72 $TODO ? _print(@mess) : _print_stderr(@mess);
81 _print "1..0 # Skipped: @_\n";
89 my ($pass, $where, $name, @mess) = @_;
90 # Do not try to microoptimize by factoring out the "not ".
94 # escape out '#' or it will interfere with '# skip' and such
96 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
98 $out = $pass ? "ok $test" : "not ok $test";
101 $out .= " # TODO $TODO" if $TODO;
105 _diag "# Failed $where\n";
108 # Ensure that the message is properly escaped.
111 $test = $test + 1; # don't use ++
117 my @caller = caller($Level);
118 return "at $caller[1] line $caller[2]";
121 # DON'T use this for matches. Use like() instead.
123 my ($pass, $name, @mess) = @_;
124 _ok($pass, _where(), $name, @mess);
129 return 'undef' unless defined $x;
138 return defined $x ? '"' . display ($x) . '"' : 'undef';
141 # keys are the codes \n etc map to, values are 2 char strings such as \n
142 my %backslash_escape;
143 foreach my $x (split //, 'nrtfa\\\'"') {
144 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
146 # A way to display scalars containing control characters and Unicode.
147 # Trying to avoid setting $_, or relying on local $_ to work.
151 if (defined $x and not ref $x) {
153 foreach my $c (unpack("U*", $x)) {
155 $y .= sprintf "\\x{%x}", $c;
156 } elsif ($backslash_escape{$c}) {
157 $y .= $backslash_escape{$c};
159 my $z = chr $c; # Maybe we can get away with a literal...
160 $z = sprintf "\\%03o", $c if $z =~ /[[:^print:]]/;
166 return $x unless wantarray;
173 my ($got, $expected, $name, @mess) = @_;
176 if( !defined $got || !defined $expected ) {
177 # undef only matches undef
178 $pass = !defined $got && !defined $expected;
181 $pass = $got eq $expected;
185 unshift(@mess, "# got "._q($got)."\n",
186 "# expected "._q($expected)."\n");
188 _ok($pass, _where(), $name, @mess);
192 my ($got, $isnt, $name, @mess) = @_;
195 if( !defined $got || !defined $isnt ) {
196 # undef only matches undef
197 $pass = defined $got || defined $isnt;
200 $pass = $got ne $isnt;
204 unshift(@mess, "# it should not be "._q($got)."\n",
207 _ok($pass, _where(), $name, @mess);
211 my($got, $type, $expected, $name, @mess) = @_;
216 local($@,$!); # don't interfere with $@
217 # eval() sometimes resets $!
218 $pass = eval "\$got $type \$expected";
221 # It seems Irix long doubles can have 2147483648 and 2147483648
222 # that stringify to the same thing but are acutally numerically
223 # different. Display the numbers if $type isn't a string operator,
224 # and the numbers are stringwise the same.
225 # (all string operators have alphabetic names, so tr/a-z// is true)
226 # This will also show numbers for some uneeded cases, but will
227 # definately be helpful for things such as == and <= that fail
228 if ($got eq $expected and $type !~ tr/a-z//) {
229 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
231 unshift(@mess, "# got "._q($got)."\n",
232 "# expected $type "._q($expected)."\n");
234 _ok($pass, _where(), $name, @mess);
237 # Check that $got is within $range of $expected
238 # if $range is 0, then check it's exact
239 # else if $expected is 0, then $range is an absolute value
240 # otherwise $range is a fractional error.
241 # Here $range must be numeric, >= 0
242 # Non numeric ranges might be a useful future extension. (eg %)
244 my ($got, $expected, $range, $name, @mess) = @_;
246 if (!defined $got or !defined $expected or !defined $range) {
247 # This is a fail, but doesn't need extra diagnostics
248 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
250 unshift @mess, "# got, expected and range must be numeric\n";
251 } elsif ($range < 0) {
252 # This is also a fail
253 unshift @mess, "# range must not be negative\n";
254 } elsif ($range == 0) {
256 $pass = $got == $expected;
257 } elsif ($expected == 0) {
258 # If expected is 0, treat range as absolute
259 $pass = ($got <= $range) && ($got >= - $range);
261 my $diff = $got - $expected;
262 $pass = abs ($diff / $expected) < $range;
265 if ($got eq $expected) {
266 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
268 unshift@mess, "# got "._q($got)."\n",
269 "# expected "._q($expected)." (within "._q($range).")\n";
271 _ok($pass, _where(), $name, @mess);
274 # Note: this isn't quite as fancy as Test::More::like().
276 sub like ($$@) { like_yn (0,@_) }; # 0 for -
277 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
280 my ($flip, $got, $expected, $name, @mess) = @_;
282 $pass = $got =~ /$expected/ if !$flip;
283 $pass = $got !~ /$expected/ if $flip;
285 unshift(@mess, "# got '$got'\n",
287 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
289 local $Level = $Level + 1;
290 _ok($pass, _where(), $name, @mess);
298 _ok(0, _where(), @_);
308 $test = $test + 1; # don't use ++
312 # Note: can't pass multipart messages since we try to
313 # be compatible with Test::More::skip().
316 my $n = @_ ? shift : 1;
318 _print "ok $test # skip: $why\n";
327 my $n = @_ ? shift : 1;
330 _print "not ok $test # TODO & SKIP: $why\n";
339 return 0 unless $#$ra == $#$rb;
340 for my $i (0..$#$ra) {
341 next if !defined $ra->[$i] && !defined $rb->[$i];
342 return 0 if !defined $ra->[$i];
343 return 0 if !defined $rb->[$i];
344 return 0 unless $ra->[$i] eq $rb->[$i];
350 my ($orig, $suspect) = @_;
352 while (my ($key, $value) = each %$suspect) {
353 # Force a hash recompute if this perl's internals can cache the hash key.
355 if (exists $orig->{$key}) {
356 if ($orig->{$key} ne $value) {
357 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
358 " now ", _qq($value), "\n";
362 _print "# key ", _qq($key), " is ", _qq($value),
363 ", not in original.\n";
367 foreach (keys %$orig) {
368 # Force a hash recompute if this perl's internals can cache the hash key.
370 next if (exists $suspect->{$_});
371 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
382 _ok(!$@, _where(), "require $require");
390 _ok(!$@, _where(), "use $use");
393 # runperl - Runs a separate perl interpreter.
395 # switches => [ command-line switches ]
396 # nolib => 1 # don't use -I../lib (included by default)
397 # prog => one-liner (avoid quotes)
398 # progs => [ multi-liner (avoid quotes) ]
399 # progfile => perl script
400 # stdin => string to feed the stdin
401 # stderr => redirect stderr to stdout
402 # args => [ command-line arguments to the perl program ]
403 # verbose => print the command line
405 my $is_mswin = $^O eq 'MSWin32';
406 my $is_netware = $^O eq 'NetWare';
407 my $is_macos = $^O eq 'MacOS';
408 my $is_vms = $^O eq 'VMS';
409 my $is_cygwin = $^O eq 'cygwin';
412 my ($runperl, $args) = @_;
415 # In VMS protect with doublequotes because otherwise
416 # DCL will lowercase -- unless already doublequoted.
417 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
418 $$runperl .= ' ' . $_;
422 sub _create_runperl { # Create the string to qx in runperl().
424 my $runperl = $^X =~ m/\s/ ? qq{"$^X"} : $^X;
425 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
426 if ($ENV{PERL_RUNPERL_DEBUG}) {
427 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
429 unless ($args{nolib}) {
431 $runperl .= ' -I::lib';
432 # Use UNIX style error messages instead of MPW style.
433 $runperl .= ' -MMac::err=unix' if $args{stderr};
436 $runperl .= ' "-I../lib"'; # doublequotes because of VMS
439 if ($args{switches}) {
441 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
442 unless ref $args{switches} eq "ARRAY";
443 _quote_args(\$runperl, $args{switches});
445 if (defined $args{prog}) {
446 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
447 if defined $args{progs};
448 $args{progs} = [$args{prog}]
450 if (defined $args{progs}) {
451 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
452 unless ref $args{progs} eq "ARRAY";
453 foreach my $prog (@{$args{progs}}) {
454 if ($is_mswin || $is_netware || $is_vms) {
455 $runperl .= qq ( -e "$prog" );
458 $runperl .= qq ( -e '$prog' );
461 } elsif (defined $args{progfile}) {
462 $runperl .= qq( "$args{progfile}");
464 # You probaby didn't want to be sucking in from the upstream stdin
465 die "test.pl:runperl(): none of prog, progs, progfile, args, "
466 . " switches or stdin specified"
467 unless defined $args{args} or defined $args{switches}
468 or defined $args{stdin};
470 if (defined $args{stdin}) {
471 # so we don't try to put literal newlines and crs onto the
473 $args{stdin} =~ s/\n/\\n/g;
474 $args{stdin} =~ s/\r/\\r/g;
476 if ($is_mswin || $is_netware || $is_vms) {
477 $runperl = qq{$^X -e "print qq(} .
478 $args{stdin} . q{)" | } . $runperl;
481 # MacOS can only do two processes under MPW at once;
482 # the test itself is one; we can't do two more, so
484 my $stdin = qq{$^X -e 'print qq(} . $args{stdin} . qq{)' > teststdin; };
485 if ($args{verbose}) {
486 my $stdindisplay = $stdin;
487 $stdindisplay =~ s/\n/\n\#/g;
488 _print_stderr "# $stdindisplay\n";
491 $runperl .= q{ < teststdin };
494 $runperl = qq{$^X -e 'print qq(} .
495 $args{stdin} . q{)' | } . $runperl;
498 if (defined $args{args}) {
499 _quote_args(\$runperl, $args{args});
501 $runperl .= ' 2>&1' if $args{stderr} && !$is_macos;
502 $runperl .= " \xB3 Dev:Null" if !$args{stderr} && $is_macos;
503 if ($args{verbose}) {
504 my $runperldisplay = $runperl;
505 $runperldisplay =~ s/\n/\n\#/g;
506 _print_stderr "# $runperldisplay\n";
512 die "test.pl:runperl() does not take a hashref"
513 if ref $_[0] and ref $_[0] eq 'HASH';
514 my $runperl = &_create_runperl;
517 my $tainted = ${^TAINT};
519 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
522 # We will assume that if you're running under -T, you really mean to
523 # run a fresh perl, so we'll brute force launder everything for you
526 eval "require Config; Config->import";
528 warn "test.pl had problems loading Config: $@";
531 $sep = $Config{path_sep};
534 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
535 local @ENV{@keys} = ();
536 # Untaint, plus take out . and empty string:
537 local $ENV{'DCL$PATH'} = $1 if $is_vms && ($ENV{'DCL$PATH'} =~ /(.*)/s);
538 $ENV{PATH} =~ /(.*)/s;
540 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
541 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
542 split quotemeta ($sep), $1;
543 $ENV{PATH} .= "$sep/bin" if $is_cygwin; # Must have /bin under Cygwin
548 $result = `$runperl`;
550 $result = `$runperl`;
552 $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
556 *run_perl = \&runperl; # Nice alias.
559 _print_stderr "# @_\n";
563 # A somewhat safer version of the sometimes wrong $^X.
566 unless (defined $Perl) {
569 # VMS should have 'perl' aliased properly
570 return $Perl if $^O eq 'VMS';
573 eval "require Config; Config->import";
575 warn "test.pl had problems loading Config: $@";
578 $exe = $Config{_exe};
580 $exe = '' unless defined $exe;
582 # This doesn't absolutize the path: beware of future chdirs().
583 # We could do File::Spec->abs2rel() but that does getcwd()s,
584 # which is a bit heavyweight to do here.
586 if ($Perl =~ /^perl\Q$exe\E$/i) {
587 my $perl = "perl$exe";
588 eval "require File::Spec";
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 my $tmpfile = "misctmp000";
621 1 while -f ++$tmpfile;
622 END { unlink_all $tmpfile }
627 # The $resolve must be a subref that tests the first argument
628 # for success, or returns the definition of success (e.g. the
629 # expected scalar) if given no arguments.
633 my($prog, $resolve, $runperl_args, $name) = @_;
635 $runperl_args ||= {};
636 $runperl_args->{progfile} = $tmpfile;
637 $runperl_args->{stderr} = 1;
639 open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
643 $prog =~ s#/dev/null#NL:#;
646 $prog =~ s{if \(-e _ and -f _ and -r _\)}
651 close TEST or die "Cannot close $tmpfile: $!";
653 my $results = runperl(%$runperl_args);
656 # Clean up the results into something a bit more predictable.
657 $results =~ s/\n+$//;
658 $results =~ s/at\s+misctmp\d+\s+line/at - line/g;
659 $results =~ s/of\s+misctmp\d+\s+aborted/of - aborted/g;
661 # bison says 'parse error' instead of 'syntax error',
662 # various yaccs may or may not capitalize 'syntax'.
663 $results =~ s/^(syntax|parse) error/syntax error/mig;
666 # some tests will trigger VMS messages that won't be expected
667 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
669 # pipes double these sometimes
670 $results =~ s/\n\n/\n/g;
673 my $pass = $resolve->($results);
675 _diag "# PROG: \n$prog\n";
676 _diag "# EXPECTED:\n", $resolve->(), "\n";
677 _diag "# GOT:\n$results\n";
678 _diag "# STATUS: $status\n";
681 # Use the first line of the program as a name if none was given
683 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
684 $name .= '...' if length $first_line > length $name;
687 _ok($pass, _where(), "fresh_perl - $name");
693 # Combination of run_perl() and is().
697 my($prog, $expected, $runperl_args, $name) = @_;
700 sub { @_ ? $_[0] eq $expected : $expected },
701 $runperl_args, $name);
707 # Combination of run_perl() and like().
710 sub fresh_perl_like {
711 my($prog, $expected, $runperl_args, $name) = @_;
715 $_[0] =~ (ref $expected ? $expected : /$expected/) :
717 $runperl_args, $name);
721 my($proto, @methods) = @_;
722 my $class = ref $proto || $proto;
725 return _ok( 0, _where(), "$class->can(...)" );
729 foreach my $method (@methods) {
730 local($!, $@); # don't interfere with caller's $@
731 # eval sometimes resets $!
732 eval { $proto->can($method) } || push @nok, $method;
736 $name = @methods == 1 ? "$class->can('$methods[0]')"
737 : "$class->can(...)";
739 _ok( !@nok, _where(), $name );
743 my($object, $class, $obj_name) = @_;
746 $obj_name = 'The object' unless defined $obj_name;
747 my $name = "$obj_name isa $class";
748 if( !defined $object ) {
749 $diag = "$obj_name isn't defined";
751 elsif( !ref $object ) {
752 $diag = "$obj_name isn't a reference";
755 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
756 local($@, $!); # eval sometimes resets $!
757 my $rslt = eval { $object->isa($class) };
759 if( $@ =~ /^Can't call method "isa" on unblessed reference/ ) {
760 if( !UNIVERSAL::isa($object, $class) ) {
761 my $ref = ref $object;
762 $diag = "$obj_name isn't a '$class' it's a '$ref'";
766 WHOA! I tried to call ->isa on your object and got some weird error.
767 This should never happen. Please contact the author immediately.
774 my $ref = ref $object;
775 $diag = "$obj_name isn't a '$class' it's a '$ref'";
779 _ok( !$diag, _where(), $name );
782 # Set a watchdog to timeout the entire test file
786 my $timeout_msg = 'Test process timed out - terminating';
788 my $pid_to_kill = $$; # PID for this process
790 # On Windows and VMS, try launching a watchdog process
791 # using system(1, ...) (see perlport.pod)
792 if (($^O eq 'MSWin32') || ($^O eq 'VMS')) {
793 # On Windows, try to get the 'real' PID
794 if ($^O eq 'MSWin32') {
795 eval { require Win32; };
796 if (defined(&Win32::GetCurrentProcessId)) {
797 $pid_to_kill = Win32::GetCurrentProcessId();
801 # If we still have a fake PID, we can't use this method at all
802 return if ($pid_to_kill <= 0);
804 # Launch watchdog process
807 local $SIG{'__WARN__'} = sub {};
808 $watchdog = system(1, $^X, '-e', "sleep($timeout);" .
809 "kill('KILL', $pid_to_kill);");
812 # If the above worked, add END block to parent
813 # to clean up watchdog process
814 if (! $@ && ($watchdog > 0)) {
815 eval "END { kill('KILL', $watchdog); }";
821 # Try using fork() to generate a watchdog process
823 eval { $watchdog = fork() };
824 if (defined($watchdog)) {
825 if ($watchdog) { # Parent process
826 # Add END block to parent to clean up watchdog process
827 eval "END { kill('KILL', $watchdog); }";
831 ### Watchdog process code
833 # Load POSIX if available
834 eval { require POSIX; };
836 # Execute the timeout
837 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
840 # Kill test process if still running
841 if (kill(0, $pid_to_kill)) {
843 kill('KILL', $pid_to_kill);
846 # Terminate ourself (i.e., the watchdog)
847 POSIX::_exit(1) if (defined(&POSIX::_exit));
851 # fork() failed - try a thread
852 if (eval { require threads; }) {
853 threads->create(sub {
854 # Load POSIX if available
855 eval { require POSIX; };
857 # Execute the timeout
860 # Kill the parent (and ourself)
862 POSIX::_exit(1) if (defined(&POSIX::_exit));
863 kill('KILL', $pid_to_kill);
868 # Threads failed, too - try use alarm()
870 # Try to set the timeout
871 if (eval { alarm($timeout); 1; }) {
872 # Load POSIX if available
873 eval { require POSIX; };
875 # Alarm handler will do the actual 'killing'
878 POSIX::_exit(1) if (defined(&POSIX::_exit));
879 kill('KILL', $pid_to_kill);