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