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