made eq_array in t/test.pl handle undef values better
[p5sagit/p5-mst-13.2.git] / t / test.pl
1 #
2 # t/test.pl - most of Test::More functionality without the fuss
3 #
4
5 $Level = 1;
6 my $test = 1;
7 my $planned;
8 my $noplan;
9
10 $TODO = 0;
11 $NO_ENDING = 0;
12
13 sub plan {
14     my $n;
15     if (@_ == 1) {
16         $n = shift;
17         if ($n eq 'no_plan') {
18           undef $n;
19           $noplan = 1;
20         }
21     } else {
22         my %plan = @_;
23         $n = $plan{tests}; 
24     }
25     print STDOUT "1..$n\n" unless $noplan;
26     $planned = $n;
27 }
28
29 END {
30     my $ran = $test - 1;
31     if (!$NO_ENDING) {
32         if (defined $planned && $planned != $ran) {
33             print STDERR
34                 "# Looks like you planned $planned tests but ran $ran.\n";
35         } elsif ($noplan) {
36             print "1..$ran\n";
37         }
38     }
39 }
40
41 # Use this instead of "print STDERR" when outputing failure diagnostic 
42 # messages
43 sub _diag {
44     return unless @_;
45     my @mess = map { /^#/ ? "$_\n" : "# $_\n" } 
46                map { split /\n/ } @_;
47     my $fh = $TODO ? *STDOUT : *STDERR;
48     print $fh @mess;
49
50 }
51
52 sub skip_all {
53     if (@_) {
54         print STDOUT "1..0 # Skipped: @_\n";
55     } else {
56         print STDOUT "1..0\n";
57     }
58     exit(0);
59 }
60
61 sub _ok {
62     my ($pass, $where, $name, @mess) = @_;
63     # Do not try to microoptimize by factoring out the "not ".
64     # VMS will avenge.
65     my $out;
66     if ($name) {
67         # escape out '#' or it will interfere with '# skip' and such
68         $name =~ s/#/\\#/g;
69         $out = $pass ? "ok $test - $name" : "not ok $test - $name";
70     } else {
71         $out = $pass ? "ok $test" : "not ok $test";
72     }
73
74     $out .= " # TODO $TODO" if $TODO;
75     print STDOUT "$out\n";
76
77     unless ($pass) {
78         _diag "# Failed $where\n";
79     }
80
81     # Ensure that the message is properly escaped.
82     _diag @mess;
83
84     $test++;
85
86     return $pass;
87 }
88
89 sub _where {
90     my @caller = caller($Level);
91     return "at $caller[1] line $caller[2]";
92 }
93
94 # DON'T use this for matches. Use like() instead.
95 sub ok ($@) {
96     my ($pass, $name, @mess) = @_;
97     _ok($pass, _where(), $name, @mess);
98 }
99
100 sub _q {
101     my $x = shift;
102     return 'undef' unless defined $x;
103     my $q = $x;
104     $q =~ s/\\/\\\\/;
105     $q =~ s/'/\\'/;
106     return "'$q'";
107 }
108
109 sub _qq {
110     my $x = shift;
111     return defined $x ? '"' . display ($x) . '"' : 'undef';
112 };
113
114 # keys are the codes \n etc map to, values are 2 char strings such as \n
115 my %backslash_escape;
116 foreach my $x (split //, 'nrtfa\\\'"') {
117     $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
118 }
119 # A way to display scalars containing control characters and Unicode.
120 # Trying to avoid setting $_, or relying on local $_ to work.
121 sub display {
122     my @result;
123     foreach my $x (@_) {
124         if (defined $x and not ref $x) {
125             my $y = '';
126             foreach my $c (unpack("U*", $x)) {
127                 if ($c > 255) {
128                     $y .= sprintf "\\x{%x}", $c;
129                 } elsif ($backslash_escape{$c}) {
130                     $y .= $backslash_escape{$c};
131                 } else {
132                     my $z = chr $c; # Maybe we can get away with a literal...
133                     $z = sprintf "\\%03o", $c if $z =~ /[[:^print:]]/;
134                     $y .= $z;
135                 }
136             }
137             $x = $y;
138         }
139         return $x unless wantarray;
140         push @result, $x;
141     }
142     return @result;
143 }
144
145 sub is ($$@) {
146     my ($got, $expected, $name, @mess) = @_;
147
148     my $pass;
149     if( !defined $got || !defined $expected ) {
150         # undef only matches undef
151         $pass = !defined $got && !defined $expected;
152     }
153     else {
154         $pass = $got eq $expected;
155     }
156
157     unless ($pass) {
158         unshift(@mess, "#      got "._q($got)."\n",
159                        "# expected "._q($expected)."\n");
160     }
161     _ok($pass, _where(), $name, @mess);
162 }
163
164 sub isnt ($$@) {
165     my ($got, $isnt, $name, @mess) = @_;
166
167     my $pass;
168     if( !defined $got || !defined $isnt ) {
169         # undef only matches undef
170         $pass = defined $got || defined $isnt;
171     }
172     else {
173         $pass = $got ne $isnt;
174     }
175
176     unless( $pass ) {
177         unshift(@mess, "# it should not be "._q($got)."\n",
178                        "# but it is.\n");
179     }
180     _ok($pass, _where(), $name, @mess);
181 }
182
183 sub cmp_ok ($$$@) {
184     my($got, $type, $expected, $name, @mess) = @_;
185
186     my $pass;
187     {
188         local $^W = 0;
189         local($@,$!);   # don't interfere with $@
190                         # eval() sometimes resets $!
191         $pass = eval "\$got $type \$expected";
192     }
193     unless ($pass) {
194         # It seems Irix long doubles can have 2147483648 and 2147483648
195         # that stringify to the same thing but are acutally numerically
196         # different. Display the numbers if $type isn't a string operator,
197         # and the numbers are stringwise the same.
198         # (all string operators have alphabetic names, so tr/a-z// is true)
199         # This will also show numbers for some uneeded cases, but will
200         # definately be helpful for things such as == and <= that fail
201         if ($got eq $expected and $type !~ tr/a-z//) {
202             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
203         }
204         unshift(@mess, "#      got "._q($got)."\n",
205                        "# expected $type "._q($expected)."\n");
206     }
207     _ok($pass, _where(), $name, @mess);
208 }
209
210 # Check that $got is within $range of $expected
211 # if $range is 0, then check it's exact
212 # else if $expected is 0, then $range is an absolute value
213 # otherwise $range is a fractional error.
214 # Here $range must be numeric, >= 0
215 # Non numeric ranges might be a useful future extension. (eg %)
216 sub within ($$$@) {
217     my ($got, $expected, $range, $name, @mess) = @_;
218     my $pass;
219     if (!defined $got or !defined $expected or !defined $range) {
220         # This is a fail, but doesn't need extra diagnostics
221     } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
222         # This is a fail
223         unshift @mess, "# got, expected and range must be numeric\n";
224     } elsif ($range < 0) {
225         # This is also a fail
226         unshift @mess, "# range must not be negative\n";
227     } elsif ($range == 0) {
228         # Within 0 is ==
229         $pass = $got == $expected;
230     } elsif ($expected == 0) {
231         # If expected is 0, treat range as absolute
232         $pass = ($got <= $range) && ($got >= - $range);
233     } else {
234         my $diff = $got - $expected;
235         $pass = abs ($diff / $expected) < $range;
236     }
237     unless ($pass) {
238         if ($got eq $expected) {
239             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
240         }
241         unshift@mess, "#      got "._q($got)."\n",
242                       "# expected "._q($expected)." (within "._q($range).")\n";
243     }
244     _ok($pass, _where(), $name, @mess);
245 }
246
247 # Note: this isn't quite as fancy as Test::More::like().
248
249 sub like   ($$@) { like_yn (0,@_) }; # 0 for -
250 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
251
252 sub like_yn ($$$@) {
253     my ($flip, $got, $expected, $name, @mess) = @_;
254     my $pass;
255     $pass = $got =~ /$expected/ if !$flip;
256     $pass = $got !~ /$expected/ if $flip;
257     unless ($pass) {
258         unshift(@mess, "#      got '$got'\n",
259                 "# expected /$expected/\n");
260     }
261     _ok($pass, _where(), $name, @mess);
262 }
263
264 sub pass {
265     _ok(1, '', @_);
266 }
267
268 sub fail {
269     _ok(0, _where(), @_);
270 }
271
272 sub curr_test {
273     $test = shift if @_;
274     return $test;
275 }
276
277 sub next_test {
278   $test++;
279 }
280
281 # Note: can't pass multipart messages since we try to
282 # be compatible with Test::More::skip().
283 sub skip {
284     my $why = shift;
285     my $n    = @_ ? shift : 1;
286     for (1..$n) {
287         print STDOUT "ok $test # skip: $why\n";
288         $test++;
289     }
290     local $^W = 0;
291     last SKIP;
292 }
293
294 sub eq_array {
295     my ($ra, $rb) = @_;
296     return 0 unless $#$ra == $#$rb;
297     for my $i (0..$#$ra) {
298         next     if !defined $ra->[$i] && !defined $rb->[$i]; 
299         return 0 if !defined $ra->[$i];
300         return 0 if !defined $rb->[$i];
301         return 0 unless $ra->[$i] eq $rb->[$i];
302     }
303     return 1;
304 }
305
306 sub eq_hash {
307   my ($orig, $suspect) = @_;
308   my $fail;
309   while (my ($key, $value) = each %$suspect) {
310     # Force a hash recompute if this perl's internals can cache the hash key.
311     $key = "" . $key;
312     if (exists $orig->{$key}) {
313       if ($orig->{$key} ne $value) {
314         print STDOUT "# key ", _qq($key), " was ", _qq($orig->{$key}),
315                      " now ", _qq($value), "\n";
316         $fail = 1;
317       }
318     } else {
319       print STDOUT "# key ", _qq($key), " is ", _qq($value), 
320                    ", not in original.\n";
321       $fail = 1;
322     }
323   }
324   foreach (keys %$orig) {
325     # Force a hash recompute if this perl's internals can cache the hash key.
326     $_ = "" . $_;
327     next if (exists $suspect->{$_});
328     print STDOUT "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
329     $fail = 1;
330   }
331   !$fail;
332 }
333
334 sub require_ok ($) {
335     my ($require) = @_;
336     eval <<REQUIRE_OK;
337 require $require;
338 REQUIRE_OK
339     _ok(!$@, _where(), "require $require");
340 }
341
342 sub use_ok ($) {
343     my ($use) = @_;
344     eval <<USE_OK;
345 use $use;
346 USE_OK
347     _ok(!$@, _where(), "use $use");
348 }
349
350 # runperl - Runs a separate perl interpreter.
351 # Arguments :
352 #   switches => [ command-line switches ]
353 #   nolib    => 1 # don't use -I../lib (included by default)
354 #   prog     => one-liner (avoid quotes)
355 #   progs    => [ multi-liner (avoid quotes) ]
356 #   progfile => perl script
357 #   stdin    => string to feed the stdin
358 #   stderr   => redirect stderr to stdout
359 #   args     => [ command-line arguments to the perl program ]
360 #   verbose  => print the command line
361
362 my $is_mswin    = $^O eq 'MSWin32';
363 my $is_netware  = $^O eq 'NetWare';
364 my $is_macos    = $^O eq 'MacOS';
365 my $is_vms      = $^O eq 'VMS';
366
367 sub _quote_args {
368     my ($runperl, $args) = @_;
369
370     foreach (@$args) {
371         # In VMS protect with doublequotes because otherwise
372         # DCL will lowercase -- unless already doublequoted.
373        $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
374         $$runperl .= ' ' . $_;
375     }
376 }
377
378 sub _create_runperl { # Create the string to qx in runperl().
379     my %args = @_;
380     my $runperl = $^X =~ m/\s/ ? qq{"$^X"} : $^X;
381     unless ($args{nolib}) {
382         if ($is_macos) {
383             $runperl .= ' -I::lib';
384             # Use UNIX style error messages instead of MPW style.
385             $runperl .= ' -MMac::err=unix' if $args{stderr};
386         }
387         else {
388             $runperl .= ' "-I../lib"'; # doublequotes because of VMS
389         }
390     }
391     if ($args{switches}) {
392         local $Level = 2;
393         die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
394             unless ref $args{switches} eq "ARRAY";
395         _quote_args(\$runperl, $args{switches});
396     }
397     if (defined $args{prog}) {
398         die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
399             if defined $args{progs};
400         $args{progs} = [$args{prog}]
401     }
402     if (defined $args{progs}) {
403         die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
404             unless ref $args{progs} eq "ARRAY";
405         foreach my $prog (@{$args{progs}}) {
406             if ($is_mswin || $is_netware || $is_vms) {
407                 $runperl .= qq ( -e "$prog" );
408             }
409             else {
410                 $runperl .= qq ( -e '$prog' );
411             }
412         }
413     } elsif (defined $args{progfile}) {
414         $runperl .= qq( "$args{progfile}");
415     }
416     if (defined $args{stdin}) {
417         # so we don't try to put literal newlines and crs onto the
418         # command line.
419         $args{stdin} =~ s/\n/\\n/g;
420         $args{stdin} =~ s/\r/\\r/g;
421
422         if ($is_mswin || $is_netware || $is_vms) {
423             $runperl = qq{$^X -e "print qq(} .
424                 $args{stdin} . q{)" | } . $runperl;
425         }
426         elsif ($is_macos) {
427             # MacOS can only do two processes under MPW at once;
428             # the test itself is one; we can't do two more, so
429             # write to temp file
430             my $stdin = qq{$^X -e 'print qq(} . $args{stdin} . qq{)' > teststdin; };
431             if ($args{verbose}) {
432                 my $stdindisplay = $stdin;
433                 $stdindisplay =~ s/\n/\n\#/g;
434                 print STDERR "# $stdindisplay\n";
435             }
436             `$stdin`;
437             $runperl .= q{ < teststdin };
438         }
439         else {
440             $runperl = qq{$^X -e 'print qq(} .
441                 $args{stdin} . q{)' | } . $runperl;
442         }
443     }
444     if (defined $args{args}) {
445         _quote_args(\$runperl, $args{args});
446     }
447     $runperl .= ' 2>&1'          if  $args{stderr} && !$is_macos;
448     $runperl .= " \xB3 Dev:Null" if !$args{stderr} &&  $is_macos;
449     if ($args{verbose}) {
450         my $runperldisplay = $runperl;
451         $runperldisplay =~ s/\n/\n\#/g;
452         print STDERR "# $runperldisplay\n";
453     }
454     return $runperl;
455 }
456
457 sub runperl {
458     my $runperl = &_create_runperl;
459     my $result = `$runperl`;
460     $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
461     return $result;
462 }
463
464 *run_perl = \&runperl; # Nice alias.
465
466 sub DIE {
467     print STDERR "# @_\n";
468     exit 1;
469 }
470
471 # A somewhat safer version of the sometimes wrong $^X.
472 my $Perl;
473 sub which_perl {
474     unless (defined $Perl) {
475         $Perl = $^X;
476         
477         # VMS should have 'perl' aliased properly
478         return $Perl if $^O eq 'VMS';
479
480         my $exe;
481         eval "require Config; Config->import";
482         if ($@) {
483             warn "test.pl had problems loading Config: $@";
484             $exe = '';
485         } else {
486             $exe = $Config{_exe};
487         }
488        $exe = '' unless defined $exe;
489         
490         # This doesn't absolutize the path: beware of future chdirs().
491         # We could do File::Spec->abs2rel() but that does getcwd()s,
492         # which is a bit heavyweight to do here.
493         
494         if ($Perl =~ /^perl\Q$exe\E$/i) {
495             my $perl = "perl$exe";
496             eval "require File::Spec";
497             if ($@) {
498                 warn "test.pl had problems loading File::Spec: $@";
499                 $Perl = "./$perl";
500             } else {
501                 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
502             }
503         }
504
505         # Build up the name of the executable file from the name of
506         # the command.
507
508         if ($Perl !~ /\Q$exe\E$/i) {
509             $Perl .= $exe;
510         }
511
512         warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
513         
514         # For subcommands to use.
515         $ENV{PERLEXE} = $Perl;
516     }
517     return $Perl;
518 }
519
520 sub unlink_all {
521     foreach my $file (@_) {
522         1 while unlink $file;
523         print STDERR "# Couldn't unlink '$file': $!\n" if -f $file;
524     }
525 }
526
527
528 my $tmpfile = "misctmp000";
529 1 while -f ++$tmpfile;
530 END { unlink_all $tmpfile }
531
532 #
533 # _fresh_perl
534 #
535 # The $resolve must be a subref that tests the first argument
536 # for success, or returns the definition of success (e.g. the
537 # expected scalar) if given no arguments.
538 #
539
540 sub _fresh_perl {
541     my($prog, $resolve, $runperl_args, $name) = @_;
542
543     $runperl_args ||= {};
544     $runperl_args->{progfile} = $tmpfile;
545     $runperl_args->{stderr} = 1;
546
547     open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
548
549     # VMS adjustments
550     if( $^O eq 'VMS' ) {
551         $prog =~ s#/dev/null#NL:#;
552
553         # VMS file locking 
554         $prog =~ s{if \(-e _ and -f _ and -r _\)}
555                   {if (-e _ and -f _)}
556     }
557
558     print TEST $prog, "\n";
559     close TEST or die "Cannot close $tmpfile: $!";
560
561     my $results = runperl(%$runperl_args);
562     my $status = $?;
563
564     # Clean up the results into something a bit more predictable.
565     $results =~ s/\n+$//;
566     $results =~ s/at\s+misctmp\d+\s+line/at - line/g;
567     $results =~ s/of\s+misctmp\d+\s+aborted/of - aborted/g;
568
569     # bison says 'parse error' instead of 'syntax error',
570     # various yaccs may or may not capitalize 'syntax'.
571     $results =~ s/^(syntax|parse) error/syntax error/mig;
572
573     if ($^O eq 'VMS') {
574         # some tests will trigger VMS messages that won't be expected
575         $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
576
577         # pipes double these sometimes
578         $results =~ s/\n\n/\n/g;
579     }
580
581     my $pass = $resolve->($results);
582     unless ($pass) {
583         _diag "# PROG: \n$prog\n";
584         _diag "# EXPECTED:\n", $resolve->(), "\n";
585         _diag "# GOT:\n$results\n";
586         _diag "# STATUS: $status\n";
587     }
588
589     # Use the first line of the program as a name if none was given
590     unless( $name ) {
591         ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
592         $name .= '...' if length $first_line > length $name;
593     }
594
595     _ok($pass, _where(), "fresh_perl - $name");
596 }
597
598 #
599 # fresh_perl_is
600 #
601 # Combination of run_perl() and is().
602 #
603
604 sub fresh_perl_is {
605     my($prog, $expected, $runperl_args, $name) = @_;
606     local $Level = 2;
607     _fresh_perl($prog,
608                 sub { @_ ? $_[0] eq $expected : $expected },
609                 $runperl_args, $name);
610 }
611
612 #
613 # fresh_perl_like
614 #
615 # Combination of run_perl() and like().
616 #
617
618 sub fresh_perl_like {
619     my($prog, $expected, $runperl_args, $name) = @_;
620     local $Level = 2;
621     _fresh_perl($prog,
622                 sub { @_ ?
623                           $_[0] =~ (ref $expected ? $expected : /$expected/) :
624                           $expected },
625                 $runperl_args, $name);
626 }
627
628 1;