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 my $func = $TODO ? \&_print : \&_print_stderr;
83 _print "1..0 # Skipped: @_\n";
91 my ($pass, $where, $name, @mess) = @_;
92 # Do not try to microoptimize by factoring out the "not ".
96 # escape out '#' or it will interfere with '# skip' and such
98 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
100 $out = $pass ? "ok $test" : "not ok $test";
103 $out .= " # TODO $TODO" if $TODO;
107 _diag "# Failed $where\n";
110 # Ensure that the message is properly escaped.
113 $test = $test + 1; # don't use ++
119 my @caller = caller($Level);
120 return "at $caller[1] line $caller[2]";
123 # DON'T use this for matches. Use like() instead.
125 my ($pass, $name, @mess) = @_;
126 _ok($pass, _where(), $name, @mess);
131 return 'undef' unless defined $x;
140 return defined $x ? '"' . display ($x) . '"' : 'undef';
143 # keys are the codes \n etc map to, values are 2 char strings such as \n
144 my %backslash_escape;
145 foreach my $x (split //, 'nrtfa\\\'"') {
146 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
148 # A way to display scalars containing control characters and Unicode.
149 # Trying to avoid setting $_, or relying on local $_ to work.
153 if (defined $x and not ref $x) {
155 foreach my $c (unpack("U*", $x)) {
157 $y .= sprintf "\\x{%x}", $c;
158 } elsif ($backslash_escape{$c}) {
159 $y .= $backslash_escape{$c};
161 my $z = chr $c; # Maybe we can get away with a literal...
162 $z = sprintf "\\%03o", $c if $z =~ /[[:^print:]]/;
168 return $x unless wantarray;
175 my ($got, $expected, $name, @mess) = @_;
178 if( !defined $got || !defined $expected ) {
179 # undef only matches undef
180 $pass = !defined $got && !defined $expected;
183 $pass = $got eq $expected;
187 unshift(@mess, "# got "._q($got)."\n",
188 "# expected "._q($expected)."\n");
190 _ok($pass, _where(), $name, @mess);
194 my ($got, $isnt, $name, @mess) = @_;
197 if( !defined $got || !defined $isnt ) {
198 # undef only matches undef
199 $pass = defined $got || defined $isnt;
202 $pass = $got ne $isnt;
206 unshift(@mess, "# it should not be "._q($got)."\n",
209 _ok($pass, _where(), $name, @mess);
213 my($got, $type, $expected, $name, @mess) = @_;
218 local($@,$!); # don't interfere with $@
219 # eval() sometimes resets $!
220 $pass = eval "\$got $type \$expected";
223 # It seems Irix long doubles can have 2147483648 and 2147483648
224 # that stringify to the same thing but are acutally numerically
225 # different. Display the numbers if $type isn't a string operator,
226 # and the numbers are stringwise the same.
227 # (all string operators have alphabetic names, so tr/a-z// is true)
228 # This will also show numbers for some uneeded cases, but will
229 # definately be helpful for things such as == and <= that fail
230 if ($got eq $expected and $type !~ tr/a-z//) {
231 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
233 unshift(@mess, "# got "._q($got)."\n",
234 "# expected $type "._q($expected)."\n");
236 _ok($pass, _where(), $name, @mess);
239 # Check that $got is within $range of $expected
240 # if $range is 0, then check it's exact
241 # else if $expected is 0, then $range is an absolute value
242 # otherwise $range is a fractional error.
243 # Here $range must be numeric, >= 0
244 # Non numeric ranges might be a useful future extension. (eg %)
246 my ($got, $expected, $range, $name, @mess) = @_;
248 if (!defined $got or !defined $expected or !defined $range) {
249 # This is a fail, but doesn't need extra diagnostics
250 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
252 unshift @mess, "# got, expected and range must be numeric\n";
253 } elsif ($range < 0) {
254 # This is also a fail
255 unshift @mess, "# range must not be negative\n";
256 } elsif ($range == 0) {
258 $pass = $got == $expected;
259 } elsif ($expected == 0) {
260 # If expected is 0, treat range as absolute
261 $pass = ($got <= $range) && ($got >= - $range);
263 my $diff = $got - $expected;
264 $pass = abs ($diff / $expected) < $range;
267 if ($got eq $expected) {
268 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
270 unshift@mess, "# got "._q($got)."\n",
271 "# expected "._q($expected)." (within "._q($range).")\n";
273 _ok($pass, _where(), $name, @mess);
276 # Note: this isn't quite as fancy as Test::More::like().
278 sub like ($$@) { like_yn (0,@_) }; # 0 for -
279 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
282 my ($flip, $got, $expected, $name, @mess) = @_;
284 $pass = $got =~ /$expected/ if !$flip;
285 $pass = $got !~ /$expected/ if $flip;
287 unshift(@mess, "# got '$got'\n",
289 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
291 local $Level = $Level + 1;
292 _ok($pass, _where(), $name, @mess);
300 _ok(0, _where(), @_);
310 $test = $test + 1; # don't use ++
314 # Note: can't pass multipart messages since we try to
315 # be compatible with Test::More::skip().
318 my $n = @_ ? shift : 1;
320 _print "ok $test # skip: $why\n";
329 my $n = @_ ? shift : 1;
332 _print "not ok $test # TODO & SKIP: $why\n";
341 return 0 unless $#$ra == $#$rb;
342 for my $i (0..$#$ra) {
343 next if !defined $ra->[$i] && !defined $rb->[$i];
344 return 0 if !defined $ra->[$i];
345 return 0 if !defined $rb->[$i];
346 return 0 unless $ra->[$i] eq $rb->[$i];
352 my ($orig, $suspect) = @_;
354 while (my ($key, $value) = each %$suspect) {
355 # Force a hash recompute if this perl's internals can cache the hash key.
357 if (exists $orig->{$key}) {
358 if ($orig->{$key} ne $value) {
359 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
360 " now ", _qq($value), "\n";
364 _print "# key ", _qq($key), " is ", _qq($value),
365 ", not in original.\n";
369 foreach (keys %$orig) {
370 # Force a hash recompute if this perl's internals can cache the hash key.
372 next if (exists $suspect->{$_});
373 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
384 _ok(!$@, _where(), "require $require");
392 _ok(!$@, _where(), "use $use");
395 # runperl - Runs a separate perl interpreter.
397 # switches => [ command-line switches ]
398 # nolib => 1 # don't use -I../lib (included by default)
399 # prog => one-liner (avoid quotes)
400 # progs => [ multi-liner (avoid quotes) ]
401 # progfile => perl script
402 # stdin => string to feed the stdin
403 # stderr => redirect stderr to stdout
404 # args => [ command-line arguments to the perl program ]
405 # verbose => print the command line
407 my $is_mswin = $^O eq 'MSWin32';
408 my $is_netware = $^O eq 'NetWare';
409 my $is_macos = $^O eq 'MacOS';
410 my $is_vms = $^O eq 'VMS';
411 my $is_cygwin = $^O eq 'cygwin';
414 my ($runperl, $args) = @_;
417 # In VMS protect with doublequotes because otherwise
418 # DCL will lowercase -- unless already doublequoted.
419 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
420 $$runperl .= ' ' . $_;
424 sub _create_runperl { # Create the string to qx in runperl().
426 my $runperl = $^X =~ m/\s/ ? qq{"$^X"} : $^X;
427 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
428 if ($ENV{PERL_RUNPERL_DEBUG}) {
429 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
431 unless ($args{nolib}) {
433 $runperl .= ' -I::lib';
434 # Use UNIX style error messages instead of MPW style.
435 $runperl .= ' -MMac::err=unix' if $args{stderr};
438 $runperl .= ' "-I../lib"'; # doublequotes because of VMS
441 if ($args{switches}) {
443 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
444 unless ref $args{switches} eq "ARRAY";
445 _quote_args(\$runperl, $args{switches});
447 if (defined $args{prog}) {
448 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
449 if defined $args{progs};
450 $args{progs} = [$args{prog}]
452 if (defined $args{progs}) {
453 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
454 unless ref $args{progs} eq "ARRAY";
455 foreach my $prog (@{$args{progs}}) {
456 if ($is_mswin || $is_netware || $is_vms) {
457 $runperl .= qq ( -e "$prog" );
460 $runperl .= qq ( -e '$prog' );
463 } elsif (defined $args{progfile}) {
464 $runperl .= qq( "$args{progfile}");
466 # You probaby didn't want to be sucking in from the upstream stdin
467 die "test.pl:runperl(): none of prog, progs, progfile, args, "
468 . " switches or stdin specified"
469 unless defined $args{args} or defined $args{switches}
470 or defined $args{stdin};
472 if (defined $args{stdin}) {
473 # so we don't try to put literal newlines and crs onto the
475 $args{stdin} =~ s/\n/\\n/g;
476 $args{stdin} =~ s/\r/\\r/g;
478 if ($is_mswin || $is_netware || $is_vms) {
479 $runperl = qq{$^X -e "print qq(} .
480 $args{stdin} . q{)" | } . $runperl;
483 # MacOS can only do two processes under MPW at once;
484 # the test itself is one; we can't do two more, so
486 my $stdin = qq{$^X -e 'print qq(} . $args{stdin} . qq{)' > teststdin; };
487 if ($args{verbose}) {
488 my $stdindisplay = $stdin;
489 $stdindisplay =~ s/\n/\n\#/g;
490 _print_stderr "# $stdindisplay\n";
493 $runperl .= q{ < teststdin };
496 $runperl = qq{$^X -e 'print qq(} .
497 $args{stdin} . q{)' | } . $runperl;
500 if (defined $args{args}) {
501 _quote_args(\$runperl, $args{args});
503 $runperl .= ' 2>&1' if $args{stderr} && !$is_macos;
504 $runperl .= " \xB3 Dev:Null" if !$args{stderr} && $is_macos;
505 if ($args{verbose}) {
506 my $runperldisplay = $runperl;
507 $runperldisplay =~ s/\n/\n\#/g;
508 _print_stderr "# $runperldisplay\n";
514 die "test.pl:runperl() does not take a hashref"
515 if ref $_[0] and ref $_[0] eq 'HASH';
516 my $runperl = &_create_runperl;
519 my $tainted = ${^TAINT};
521 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
524 # We will assume that if you're running under -T, you really mean to
525 # run a fresh perl, so we'll brute force launder everything for you
528 eval "require Config; Config->import";
530 warn "test.pl had problems loading Config: $@";
533 $sep = $Config{path_sep};
536 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
537 local @ENV{@keys} = ();
538 # Untaint, plus take out . and empty string:
539 local $ENV{'DCL$PATH'} = $1 if $is_vms && ($ENV{'DCL$PATH'} =~ /(.*)/s);
540 $ENV{PATH} =~ /(.*)/s;
542 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
543 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
544 split quotemeta ($sep), $1;
545 $ENV{PATH} .= "$sep/bin" if $is_cygwin; # Must have /bin under Cygwin
550 $result = `$runperl`;
552 $result = `$runperl`;
554 $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
558 *run_perl = \&runperl; # Nice alias.
561 _print_stderr "# @_\n";
565 # 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 eval "require Config; Config->import";
577 warn "test.pl had problems loading Config: $@";
580 $exe = $Config{_exe};
582 $exe = '' unless defined $exe;
584 # This doesn't absolutize the path: beware of future chdirs().
585 # We could do File::Spec->abs2rel() but that does getcwd()s,
586 # which is a bit heavyweight to do here.
588 if ($Perl =~ /^perl\Q$exe\E$/i) {
589 my $perl = "perl$exe";
590 eval "require File::Spec";
592 warn "test.pl had problems loading File::Spec: $@";
595 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
599 # Build up the name of the executable file from the name of
602 if ($Perl !~ /\Q$exe\E$/i) {
606 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
608 # For subcommands to use.
609 $ENV{PERLEXE} = $Perl;
615 foreach my $file (@_) {
616 1 while unlink $file;
617 _print_stderr "# Couldn't unlink '$file': $!\n" if -f $file;
622 my $tmpfile = "misctmp000";
623 1 while -f ++$tmpfile;
624 END { unlink_all $tmpfile }
629 # The $resolve must be a subref that tests the first argument
630 # for success, or returns the definition of success (e.g. the
631 # expected scalar) if given no arguments.
635 my($prog, $resolve, $runperl_args, $name) = @_;
637 $runperl_args ||= {};
638 $runperl_args->{progfile} = $tmpfile;
639 $runperl_args->{stderr} = 1;
641 open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
645 $prog =~ s#/dev/null#NL:#;
648 $prog =~ s{if \(-e _ and -f _ and -r _\)}
653 close TEST or die "Cannot close $tmpfile: $!";
655 my $results = runperl(%$runperl_args);
658 # Clean up the results into something a bit more predictable.
659 $results =~ s/\n+$//;
660 $results =~ s/at\s+misctmp\d+\s+line/at - line/g;
661 $results =~ s/of\s+misctmp\d+\s+aborted/of - aborted/g;
663 # bison says 'parse error' instead of 'syntax error',
664 # various yaccs may or may not capitalize 'syntax'.
665 $results =~ s/^(syntax|parse) error/syntax error/mig;
668 # some tests will trigger VMS messages that won't be expected
669 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
671 # pipes double these sometimes
672 $results =~ s/\n\n/\n/g;
675 my $pass = $resolve->($results);
677 _diag "# PROG: \n$prog\n";
678 _diag "# EXPECTED:\n", $resolve->(), "\n";
679 _diag "# GOT:\n$results\n";
680 _diag "# STATUS: $status\n";
683 # Use the first line of the program as a name if none was given
685 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
686 $name .= '...' if length $first_line > length $name;
689 _ok($pass, _where(), "fresh_perl - $name");
695 # Combination of run_perl() and is().
699 my($prog, $expected, $runperl_args, $name) = @_;
702 sub { @_ ? $_[0] eq $expected : $expected },
703 $runperl_args, $name);
709 # Combination of run_perl() and like().
712 sub fresh_perl_like {
713 my($prog, $expected, $runperl_args, $name) = @_;
717 $_[0] =~ (ref $expected ? $expected : /$expected/) :
719 $runperl_args, $name);
723 my($proto, @methods) = @_;
724 my $class = ref $proto || $proto;
727 return _ok( 0, _where(), "$class->can(...)" );
731 foreach my $method (@methods) {
732 local($!, $@); # don't interfere with caller's $@
733 # eval sometimes resets $!
734 eval { $proto->can($method) } || push @nok, $method;
738 $name = @methods == 1 ? "$class->can('$methods[0]')"
739 : "$class->can(...)";
741 _ok( !@nok, _where(), $name );
745 my($object, $class, $obj_name) = @_;
748 $obj_name = 'The object' unless defined $obj_name;
749 my $name = "$obj_name isa $class";
750 if( !defined $object ) {
751 $diag = "$obj_name isn't defined";
753 elsif( !ref $object ) {
754 $diag = "$obj_name isn't a reference";
757 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
758 local($@, $!); # eval sometimes resets $!
759 my $rslt = eval { $object->isa($class) };
761 if( $@ =~ /^Can't call method "isa" on unblessed reference/ ) {
762 if( !UNIVERSAL::isa($object, $class) ) {
763 my $ref = ref $object;
764 $diag = "$obj_name isn't a '$class' it's a '$ref'";
768 WHOA! I tried to call ->isa on your object and got some weird error.
769 This should never happen. Please contact the author immediately.
776 my $ref = ref $object;
777 $diag = "$obj_name isn't a '$class' it's a '$ref'";
781 _ok( !$diag, _where(), $name );
784 # Set a watchdog to timeout the entire test file
788 my $timeout_msg = 'Test process timed out - terminating';
790 my $pid_to_kill = $$; # PID for this process
792 # On Windows and VMS, try launching a watchdog process
793 # using system(1, ...) (see perlport.pod)
794 if (($^O eq 'MSWin32') || ($^O eq 'VMS')) {
795 # On Windows, try to get the 'real' PID
796 if ($^O eq 'MSWin32') {
797 eval { require Win32; };
798 if (defined(&Win32::GetCurrentProcessId)) {
799 $pid_to_kill = Win32::GetCurrentProcessId();
803 # If we still have a fake PID, we can't use this method at all
804 return if ($pid_to_kill <= 0);
806 # Launch watchdog process
809 local $SIG{'__WARN__'} = sub {};
810 $watchdog = system(1, $^X, '-e', "sleep($timeout);" .
811 "kill('KILL', $pid_to_kill);");
814 # If the above worked, add END block to parent
815 # to clean up watchdog process
816 if (! $@ && ($watchdog > 0)) {
817 eval "END { kill('KILL', $watchdog); }";
823 # Try using fork() to generate a watchdog process
825 eval { $watchdog = fork() };
826 if (defined($watchdog)) {
827 if ($watchdog) { # Parent process
828 # Add END block to parent to clean up watchdog process
829 eval "END { kill('KILL', $watchdog); }";
833 ### Watchdog process code
835 # Load POSIX if available
836 eval { require POSIX; };
838 # Execute the timeout
839 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
842 # Kill test process if still running
843 if (kill(0, $pid_to_kill)) {
845 kill('KILL', $pid_to_kill);
848 # Terminate ourself (i.e., the watchdog)
849 POSIX::_exit(1) if (defined(&POSIX::_exit));
853 # fork() failed - try a thread
854 if (eval { require threads; }) {
855 threads->create(sub {
856 # Load POSIX if available
857 eval { require POSIX; };
859 # Execute the timeout
862 # Kill the parent (and ourself)
864 POSIX::_exit(1) if (defined(&POSIX::_exit));
865 kill('KILL', $pid_to_kill);
870 # Threads failed, too - try use alarm()
872 # Try to set the timeout
873 if (eval { alarm($timeout); 1; }) {
874 # Load POSIX if available
875 eval { require POSIX; };
877 # Alarm handler will do the actual 'killing'
880 POSIX::_exit(1) if (defined(&POSIX::_exit));
881 kill('KILL', $pid_to_kill);