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
31 if ($n eq 'no_plan') {
39 print STDOUT "1..$n\n" unless $noplan;
46 if (defined $planned && $planned != $ran) {
48 "# Looks like you planned $planned tests but ran $ran.\n";
55 # Use this instead of "print STDERR" when outputing failure diagnostic
59 my @mess = map { /^#/ ? "$_\n" : "# $_\n" }
60 map { split /\n/ } @_;
61 my $fh = $TODO ? *STDOUT : *STDERR;
72 print STDOUT "1..0 # Skipped: @_\n";
74 print STDOUT "1..0\n";
80 my ($pass, $where, $name, @mess) = @_;
81 # Do not try to microoptimize by factoring out the "not ".
85 # escape out '#' or it will interfere with '# skip' and such
87 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
89 $out = $pass ? "ok $test" : "not ok $test";
92 $out .= " # TODO $TODO" if $TODO;
93 print STDOUT "$out\n";
96 _diag "# Failed $where\n";
99 # Ensure that the message is properly escaped.
102 $test = $test + 1; # don't use ++
108 my @caller = caller($Level);
109 return "at $caller[1] line $caller[2]";
112 # DON'T use this for matches. Use like() instead.
114 my ($pass, $name, @mess) = @_;
115 _ok($pass, _where(), $name, @mess);
120 return 'undef' unless defined $x;
129 return defined $x ? '"' . display ($x) . '"' : 'undef';
132 # keys are the codes \n etc map to, values are 2 char strings such as \n
133 my %backslash_escape;
134 foreach my $x (split //, 'nrtfa\\\'"') {
135 $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
137 # A way to display scalars containing control characters and Unicode.
138 # Trying to avoid setting $_, or relying on local $_ to work.
142 if (defined $x and not ref $x) {
144 foreach my $c (unpack("U*", $x)) {
146 $y .= sprintf "\\x{%x}", $c;
147 } elsif ($backslash_escape{$c}) {
148 $y .= $backslash_escape{$c};
150 my $z = chr $c; # Maybe we can get away with a literal...
151 $z = sprintf "\\%03o", $c if $z =~ /[[:^print:]]/;
157 return $x unless wantarray;
164 my ($got, $expected, $name, @mess) = @_;
167 if( !defined $got || !defined $expected ) {
168 # undef only matches undef
169 $pass = !defined $got && !defined $expected;
172 $pass = $got eq $expected;
176 unshift(@mess, "# got "._q($got)."\n",
177 "# expected "._q($expected)."\n");
179 _ok($pass, _where(), $name, @mess);
183 my ($got, $isnt, $name, @mess) = @_;
186 if( !defined $got || !defined $isnt ) {
187 # undef only matches undef
188 $pass = defined $got || defined $isnt;
191 $pass = $got ne $isnt;
195 unshift(@mess, "# it should not be "._q($got)."\n",
198 _ok($pass, _where(), $name, @mess);
202 my($got, $type, $expected, $name, @mess) = @_;
207 local($@,$!); # don't interfere with $@
208 # eval() sometimes resets $!
209 $pass = eval "\$got $type \$expected";
212 # It seems Irix long doubles can have 2147483648 and 2147483648
213 # that stringify to the same thing but are acutally numerically
214 # different. Display the numbers if $type isn't a string operator,
215 # and the numbers are stringwise the same.
216 # (all string operators have alphabetic names, so tr/a-z// is true)
217 # This will also show numbers for some uneeded cases, but will
218 # definately be helpful for things such as == and <= that fail
219 if ($got eq $expected and $type !~ tr/a-z//) {
220 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
222 unshift(@mess, "# got "._q($got)."\n",
223 "# expected $type "._q($expected)."\n");
225 _ok($pass, _where(), $name, @mess);
228 # Check that $got is within $range of $expected
229 # if $range is 0, then check it's exact
230 # else if $expected is 0, then $range is an absolute value
231 # otherwise $range is a fractional error.
232 # Here $range must be numeric, >= 0
233 # Non numeric ranges might be a useful future extension. (eg %)
235 my ($got, $expected, $range, $name, @mess) = @_;
237 if (!defined $got or !defined $expected or !defined $range) {
238 # This is a fail, but doesn't need extra diagnostics
239 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
241 unshift @mess, "# got, expected and range must be numeric\n";
242 } elsif ($range < 0) {
243 # This is also a fail
244 unshift @mess, "# range must not be negative\n";
245 } elsif ($range == 0) {
247 $pass = $got == $expected;
248 } elsif ($expected == 0) {
249 # If expected is 0, treat range as absolute
250 $pass = ($got <= $range) && ($got >= - $range);
252 my $diff = $got - $expected;
253 $pass = abs ($diff / $expected) < $range;
256 if ($got eq $expected) {
257 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
259 unshift@mess, "# got "._q($got)."\n",
260 "# expected "._q($expected)." (within "._q($range).")\n";
262 _ok($pass, _where(), $name, @mess);
265 # Note: this isn't quite as fancy as Test::More::like().
267 sub like ($$@) { like_yn (0,@_) }; # 0 for -
268 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
271 my ($flip, $got, $expected, $name, @mess) = @_;
273 $pass = $got =~ /$expected/ if !$flip;
274 $pass = $got !~ /$expected/ if $flip;
276 unshift(@mess, "# got '$got'\n",
278 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
280 local $Level = $Level + 1;
281 _ok($pass, _where(), $name, @mess);
289 _ok(0, _where(), @_);
299 $test = $test + 1; # don't use ++
303 # Note: can't pass multipart messages since we try to
304 # be compatible with Test::More::skip().
307 my $n = @_ ? shift : 1;
309 print STDOUT "ok $test # skip: $why\n";
318 my $n = @_ ? shift : 1;
321 print STDOUT "not ok $test # TODO & SKIP: $why\n";
330 return 0 unless $#$ra == $#$rb;
331 for my $i (0..$#$ra) {
332 next if !defined $ra->[$i] && !defined $rb->[$i];
333 return 0 if !defined $ra->[$i];
334 return 0 if !defined $rb->[$i];
335 return 0 unless $ra->[$i] eq $rb->[$i];
341 my ($orig, $suspect) = @_;
343 while (my ($key, $value) = each %$suspect) {
344 # Force a hash recompute if this perl's internals can cache the hash key.
346 if (exists $orig->{$key}) {
347 if ($orig->{$key} ne $value) {
348 print STDOUT "# key ", _qq($key), " was ", _qq($orig->{$key}),
349 " now ", _qq($value), "\n";
353 print STDOUT "# key ", _qq($key), " is ", _qq($value),
354 ", not in original.\n";
358 foreach (keys %$orig) {
359 # Force a hash recompute if this perl's internals can cache the hash key.
361 next if (exists $suspect->{$_});
362 print STDOUT "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
373 _ok(!$@, _where(), "require $require");
381 _ok(!$@, _where(), "use $use");
384 # runperl - Runs a separate perl interpreter.
386 # switches => [ command-line switches ]
387 # nolib => 1 # don't use -I../lib (included by default)
388 # prog => one-liner (avoid quotes)
389 # progs => [ multi-liner (avoid quotes) ]
390 # progfile => perl script
391 # stdin => string to feed the stdin
392 # stderr => redirect stderr to stdout
393 # args => [ command-line arguments to the perl program ]
394 # verbose => print the command line
396 my $is_mswin = $^O eq 'MSWin32';
397 my $is_netware = $^O eq 'NetWare';
398 my $is_macos = $^O eq 'MacOS';
399 my $is_vms = $^O eq 'VMS';
402 my ($runperl, $args) = @_;
405 # In VMS protect with doublequotes because otherwise
406 # DCL will lowercase -- unless already doublequoted.
407 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
408 $$runperl .= ' ' . $_;
412 sub _create_runperl { # Create the string to qx in runperl().
414 my $runperl = $^X =~ m/\s/ ? qq{"$^X"} : $^X;
415 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
416 if ($ENV{PERL_RUNPERL_DEBUG}) {
417 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
419 unless ($args{nolib}) {
421 $runperl .= ' -I::lib';
422 # Use UNIX style error messages instead of MPW style.
423 $runperl .= ' -MMac::err=unix' if $args{stderr};
426 $runperl .= ' "-I../lib"'; # doublequotes because of VMS
429 if ($args{switches}) {
431 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
432 unless ref $args{switches} eq "ARRAY";
433 _quote_args(\$runperl, $args{switches});
435 if (defined $args{prog}) {
436 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
437 if defined $args{progs};
438 $args{progs} = [$args{prog}]
440 if (defined $args{progs}) {
441 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
442 unless ref $args{progs} eq "ARRAY";
443 foreach my $prog (@{$args{progs}}) {
444 if ($is_mswin || $is_netware || $is_vms) {
445 $runperl .= qq ( -e "$prog" );
448 $runperl .= qq ( -e '$prog' );
451 } elsif (defined $args{progfile}) {
452 $runperl .= qq( "$args{progfile}");
454 # You probaby didn't want to be sucking in from the upstream stdin
455 die "test.pl:runperl(): none of prog, progs, progfile, args, "
456 . " switches or stdin specified"
457 unless defined $args{args} or defined $args{switches}
458 or defined $args{stdin};
460 if (defined $args{stdin}) {
461 # so we don't try to put literal newlines and crs onto the
463 $args{stdin} =~ s/\n/\\n/g;
464 $args{stdin} =~ s/\r/\\r/g;
466 if ($is_mswin || $is_netware || $is_vms) {
467 $runperl = qq{$^X -e "print qq(} .
468 $args{stdin} . q{)" | } . $runperl;
471 # MacOS can only do two processes under MPW at once;
472 # the test itself is one; we can't do two more, so
474 my $stdin = qq{$^X -e 'print qq(} . $args{stdin} . qq{)' > teststdin; };
475 if ($args{verbose}) {
476 my $stdindisplay = $stdin;
477 $stdindisplay =~ s/\n/\n\#/g;
478 print STDERR "# $stdindisplay\n";
481 $runperl .= q{ < teststdin };
484 $runperl = qq{$^X -e 'print qq(} .
485 $args{stdin} . q{)' | } . $runperl;
488 if (defined $args{args}) {
489 _quote_args(\$runperl, $args{args});
491 $runperl .= ' 2>&1' if $args{stderr} && !$is_macos;
492 $runperl .= " \xB3 Dev:Null" if !$args{stderr} && $is_macos;
493 if ($args{verbose}) {
494 my $runperldisplay = $runperl;
495 $runperldisplay =~ s/\n/\n\#/g;
496 print STDERR "# $runperldisplay\n";
502 die "test.pl:runperl() does not take a hashref"
503 if ref $_[0] and ref $_[0] eq 'HASH';
504 my $runperl = &_create_runperl;
507 my $tainted = ${^TAINT};
509 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
512 # We will assume that if you're running under -T, you really mean to
513 # run a fresh perl, so we'll brute force launder everything for you
516 eval "require Config; Config->import";
518 warn "test.pl had problems loading Config: $@";
521 $sep = $Config{path_sep};
524 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
525 local @ENV{@keys} = ();
526 # Untaint, plus take out . and empty string:
527 local $ENV{'DCL$PATH'} = $1 if $is_vms && ($ENV{'DCL$PATH'} =~ /(.*)/s);
528 $ENV{PATH} =~ /(.*)/s;
530 join $sep, grep { $_ ne "" and $_ ne "." and
531 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
532 split quotemeta ($sep), $1;
537 $result = `$runperl`;
539 $result = `$runperl`;
541 $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
545 *run_perl = \&runperl; # Nice alias.
548 print STDERR "# @_\n";
552 # A somewhat safer version of the sometimes wrong $^X.
555 unless (defined $Perl) {
558 # VMS should have 'perl' aliased properly
559 return $Perl if $^O eq 'VMS';
562 eval "require Config; Config->import";
564 warn "test.pl had problems loading Config: $@";
567 $exe = $Config{_exe};
569 $exe = '' unless defined $exe;
571 # This doesn't absolutize the path: beware of future chdirs().
572 # We could do File::Spec->abs2rel() but that does getcwd()s,
573 # which is a bit heavyweight to do here.
575 if ($Perl =~ /^perl\Q$exe\E$/i) {
576 my $perl = "perl$exe";
577 eval "require File::Spec";
579 warn "test.pl had problems loading File::Spec: $@";
582 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
586 # Build up the name of the executable file from the name of
589 if ($Perl !~ /\Q$exe\E$/i) {
593 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
595 # For subcommands to use.
596 $ENV{PERLEXE} = $Perl;
602 foreach my $file (@_) {
603 1 while unlink $file;
604 print STDERR "# Couldn't unlink '$file': $!\n" if -f $file;
609 my $tmpfile = "misctmp000";
610 1 while -f ++$tmpfile;
611 END { unlink_all $tmpfile }
616 # The $resolve must be a subref that tests the first argument
617 # for success, or returns the definition of success (e.g. the
618 # expected scalar) if given no arguments.
622 my($prog, $resolve, $runperl_args, $name) = @_;
624 $runperl_args ||= {};
625 $runperl_args->{progfile} = $tmpfile;
626 $runperl_args->{stderr} = 1;
628 open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
632 $prog =~ s#/dev/null#NL:#;
635 $prog =~ s{if \(-e _ and -f _ and -r _\)}
640 close TEST or die "Cannot close $tmpfile: $!";
642 my $results = runperl(%$runperl_args);
645 # Clean up the results into something a bit more predictable.
646 $results =~ s/\n+$//;
647 $results =~ s/at\s+misctmp\d+\s+line/at - line/g;
648 $results =~ s/of\s+misctmp\d+\s+aborted/of - aborted/g;
650 # bison says 'parse error' instead of 'syntax error',
651 # various yaccs may or may not capitalize 'syntax'.
652 $results =~ s/^(syntax|parse) error/syntax error/mig;
655 # some tests will trigger VMS messages that won't be expected
656 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
658 # pipes double these sometimes
659 $results =~ s/\n\n/\n/g;
662 my $pass = $resolve->($results);
664 _diag "# PROG: \n$prog\n";
665 _diag "# EXPECTED:\n", $resolve->(), "\n";
666 _diag "# GOT:\n$results\n";
667 _diag "# STATUS: $status\n";
670 # Use the first line of the program as a name if none was given
672 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
673 $name .= '...' if length $first_line > length $name;
676 _ok($pass, _where(), "fresh_perl - $name");
682 # Combination of run_perl() and is().
686 my($prog, $expected, $runperl_args, $name) = @_;
689 sub { @_ ? $_[0] eq $expected : $expected },
690 $runperl_args, $name);
696 # Combination of run_perl() and like().
699 sub fresh_perl_like {
700 my($prog, $expected, $runperl_args, $name) = @_;
704 $_[0] =~ (ref $expected ? $expected : /$expected/) :
706 $runperl_args, $name);
710 my($proto, @methods) = @_;
711 my $class = ref $proto || $proto;
714 return _ok( 0, _where(), "$class->can(...)" );
718 foreach my $method (@methods) {
719 local($!, $@); # don't interfere with caller's $@
720 # eval sometimes resets $!
721 eval { $proto->can($method) } || push @nok, $method;
725 $name = @methods == 1 ? "$class->can('$methods[0]')"
726 : "$class->can(...)";
728 _ok( !@nok, _where(), $name );
732 my($object, $class, $obj_name) = @_;
735 $obj_name = 'The object' unless defined $obj_name;
736 my $name = "$obj_name isa $class";
737 if( !defined $object ) {
738 $diag = "$obj_name isn't defined";
740 elsif( !ref $object ) {
741 $diag = "$obj_name isn't a reference";
744 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
745 local($@, $!); # eval sometimes resets $!
746 my $rslt = eval { $object->isa($class) };
748 if( $@ =~ /^Can't call method "isa" on unblessed reference/ ) {
749 if( !UNIVERSAL::isa($object, $class) ) {
750 my $ref = ref $object;
751 $diag = "$obj_name isn't a '$class' it's a '$ref'";
755 WHOA! I tried to call ->isa on your object and got some weird error.
756 This should never happen. Please contact the author immediately.
763 my $ref = ref $object;
764 $diag = "$obj_name isn't a '$class' it's a '$ref'";
768 _ok( !$diag, _where(), $name );