This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Porting/mergelog is no more
[perl5.git] / t / test.pl
1 #
2 # t/test.pl - most of Test::More functionality without the fuss, plus
3 # has mappings native_to_latin1 and latin1_to_native so that fewer tests
4 # on non ASCII-ish platforms need to be skipped
5
6
7 # NOTE:
8 #
9 # Increment ($x++) has a certain amount of cleverness for things like
10 #
11 #   $x = 'zz';
12 #   $x++; # $x eq 'aaa';
13 #
14 # stands more chance of breaking than just a simple
15 #
16 #   $x = $x + 1
17 #
18 # In this file, we use the latter "Baby Perl" approach, and increment
19 # will be worked over by t/op/inc.t
20
21 $Level = 1;
22 my $test = 1;
23 my $planned;
24 my $noplan;
25 my $Perl;       # Safer version of $^X set by which_perl()
26
27 $TODO = 0;
28 $NO_ENDING = 0;
29
30 # Use this instead of print to avoid interference while testing globals.
31 sub _print {
32     local($\, $", $,) = (undef, ' ', '');
33     print STDOUT @_;
34 }
35
36 sub _print_stderr {
37     local($\, $", $,) = (undef, ' ', '');
38     print STDERR @_;
39 }
40
41 sub plan {
42     my $n;
43     if (@_ == 1) {
44         $n = shift;
45         if ($n eq 'no_plan') {
46           undef $n;
47           $noplan = 1;
48         }
49     } else {
50         my %plan = @_;
51         $n = $plan{tests};
52     }
53     _print "1..$n\n" unless $noplan;
54     $planned = $n;
55 }
56
57 END {
58     my $ran = $test - 1;
59     if (!$NO_ENDING) {
60         if (defined $planned && $planned != $ran) {
61             _print_stderr
62                 "# Looks like you planned $planned tests but ran $ran.\n";
63         } elsif ($noplan) {
64             _print "1..$ran\n";
65         }
66     }
67 }
68
69 # Use this instead of "print STDERR" when outputing failure diagnostic
70 # messages
71 sub _diag {
72     return unless @_;
73     my @mess = map { /^#/ ? "$_\n" : "# $_\n" }
74                map { split /\n/ } @_;
75     $TODO ? _print(@mess) : _print_stderr(@mess);
76 }
77
78 sub diag {
79     _diag(@_);
80 }
81
82 sub skip_all {
83     if (@_) {
84         _print "1..0 # Skip @_\n";
85     } else {
86         _print "1..0\n";
87     }
88     exit(0);
89 }
90
91 sub _ok {
92     my ($pass, $where, $name, @mess) = @_;
93     # Do not try to microoptimize by factoring out the "not ".
94     # VMS will avenge.
95     my $out;
96     if ($name) {
97         # escape out '#' or it will interfere with '# skip' and such
98         $name =~ s/#/\\#/g;
99         $out = $pass ? "ok $test - $name" : "not ok $test - $name";
100     } else {
101         $out = $pass ? "ok $test" : "not ok $test";
102     }
103
104     $out = $out . " # TODO $TODO" if $TODO;
105     _print "$out\n";
106
107     unless ($pass) {
108         _diag "# Failed $where\n";
109     }
110
111     # Ensure that the message is properly escaped.
112     _diag @mess;
113
114     $test = $test + 1; # don't use ++
115
116     return $pass;
117 }
118
119 sub _where {
120     my @caller = caller($Level);
121     return "at $caller[1] line $caller[2]";
122 }
123
124 # DON'T use this for matches. Use like() instead.
125 sub ok ($@) {
126     my ($pass, $name, @mess) = @_;
127     _ok($pass, _where(), $name, @mess);
128 }
129
130 sub _q {
131     my $x = shift;
132     return 'undef' unless defined $x;
133     my $q = $x;
134     $q =~ s/\\/\\\\/g;
135     $q =~ s/'/\\'/g;
136     return "'$q'";
137 }
138
139 sub _qq {
140     my $x = shift;
141     return defined $x ? '"' . display ($x) . '"' : 'undef';
142 };
143
144 # keys are the codes \n etc map to, values are 2 char strings such as \n
145 my %backslash_escape;
146 foreach my $x (split //, 'nrtfa\\\'"') {
147     $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
148 }
149 # A way to display scalars containing control characters and Unicode.
150 # Trying to avoid setting $_, or relying on local $_ to work.
151 sub display {
152     my @result;
153     foreach my $x (@_) {
154         if (defined $x and not ref $x) {
155             my $y = '';
156             foreach my $c (unpack("U*", $x)) {
157                 if ($c > 255) {
158                     $y = $y . sprintf "\\x{%x}", $c;
159                 } elsif ($backslash_escape{$c}) {
160                     $y = $y . $backslash_escape{$c};
161                 } else {
162                     my $z = chr $c; # Maybe we can get away with a literal...
163                     if ($z =~ /[[:^print:]]/) {
164
165                         # Use octal for characters traditionally expressed as
166                         # such: the low controls
167                         if ($c <= 037) {
168                             $z = sprintf "\\%03o", $c;
169                         } else {
170                             $z = sprintf "\\x{%x}", $c;
171                         }
172                     }
173                     $y = $y . $z;
174                 }
175             }
176             $x = $y;
177         }
178         return $x unless wantarray;
179         push @result, $x;
180     }
181     return @result;
182 }
183
184 sub is ($$@) {
185     my ($got, $expected, $name, @mess) = @_;
186
187     my $pass;
188     if( !defined $got || !defined $expected ) {
189         # undef only matches undef
190         $pass = !defined $got && !defined $expected;
191     }
192     else {
193         $pass = $got eq $expected;
194     }
195
196     unless ($pass) {
197         unshift(@mess, "#      got "._qq($got)."\n",
198                        "# expected "._qq($expected)."\n");
199     }
200     _ok($pass, _where(), $name, @mess);
201 }
202
203 sub isnt ($$@) {
204     my ($got, $isnt, $name, @mess) = @_;
205
206     my $pass;
207     if( !defined $got || !defined $isnt ) {
208         # undef only matches undef
209         $pass = defined $got || defined $isnt;
210     }
211     else {
212         $pass = $got ne $isnt;
213     }
214
215     unless( $pass ) {
216         unshift(@mess, "# it should not be "._qq($got)."\n",
217                        "# but it is.\n");
218     }
219     _ok($pass, _where(), $name, @mess);
220 }
221
222 sub cmp_ok ($$$@) {
223     my($got, $type, $expected, $name, @mess) = @_;
224
225     my $pass;
226     {
227         local $^W = 0;
228         local($@,$!);   # don't interfere with $@
229                         # eval() sometimes resets $!
230         $pass = eval "\$got $type \$expected";
231     }
232     unless ($pass) {
233         # It seems Irix long doubles can have 2147483648 and 2147483648
234         # that stringify to the same thing but are acutally numerically
235         # different. Display the numbers if $type isn't a string operator,
236         # and the numbers are stringwise the same.
237         # (all string operators have alphabetic names, so tr/a-z// is true)
238         # This will also show numbers for some uneeded cases, but will
239         # definately be helpful for things such as == and <= that fail
240         if ($got eq $expected and $type !~ tr/a-z//) {
241             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
242         }
243         unshift(@mess, "#      got "._qq($got)."\n",
244                        "# expected $type "._qq($expected)."\n");
245     }
246     _ok($pass, _where(), $name, @mess);
247 }
248
249 # Check that $got is within $range of $expected
250 # if $range is 0, then check it's exact
251 # else if $expected is 0, then $range is an absolute value
252 # otherwise $range is a fractional error.
253 # Here $range must be numeric, >= 0
254 # Non numeric ranges might be a useful future extension. (eg %)
255 sub within ($$$@) {
256     my ($got, $expected, $range, $name, @mess) = @_;
257     my $pass;
258     if (!defined $got or !defined $expected or !defined $range) {
259         # This is a fail, but doesn't need extra diagnostics
260     } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
261         # This is a fail
262         unshift @mess, "# got, expected and range must be numeric\n";
263     } elsif ($range < 0) {
264         # This is also a fail
265         unshift @mess, "# range must not be negative\n";
266     } elsif ($range == 0) {
267         # Within 0 is ==
268         $pass = $got == $expected;
269     } elsif ($expected == 0) {
270         # If expected is 0, treat range as absolute
271         $pass = ($got <= $range) && ($got >= - $range);
272     } else {
273         my $diff = $got - $expected;
274         $pass = abs ($diff / $expected) < $range;
275     }
276     unless ($pass) {
277         if ($got eq $expected) {
278             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
279         }
280         unshift@mess, "#      got "._qq($got)."\n",
281                       "# expected "._qq($expected)." (within "._qq($range).")\n";
282     }
283     _ok($pass, _where(), $name, @mess);
284 }
285
286 # Note: this isn't quite as fancy as Test::More::like().
287
288 sub like   ($$@) { like_yn (0,@_) }; # 0 for -
289 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
290
291 sub like_yn ($$$@) {
292     my ($flip, $got, $expected, $name, @mess) = @_;
293     my $pass;
294     $pass = $got =~ /$expected/ if !$flip;
295     $pass = $got !~ /$expected/ if $flip;
296     unless ($pass) {
297         unshift(@mess, "#      got '$got'\n",
298                 $flip
299                 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
300     }
301     local $Level = $Level + 1;
302     _ok($pass, _where(), $name, @mess);
303 }
304
305 sub pass {
306     _ok(1, '', @_);
307 }
308
309 sub fail {
310     _ok(0, _where(), @_);
311 }
312
313 sub curr_test {
314     $test = shift if @_;
315     return $test;
316 }
317
318 sub next_test {
319   my $retval = $test;
320   $test = $test + 1; # don't use ++
321   $retval;
322 }
323
324 # Note: can't pass multipart messages since we try to
325 # be compatible with Test::More::skip().
326 sub skip {
327     my $why = shift;
328     my $n    = @_ ? shift : 1;
329     for (1..$n) {
330         _print "ok $test # skip $why\n";
331         $test = $test + 1;
332     }
333     local $^W = 0;
334     last SKIP;
335 }
336
337 sub todo_skip {
338     my $why = shift;
339     my $n   = @_ ? shift : 1;
340
341     for (1..$n) {
342         _print "not ok $test # TODO & SKIP $why\n";
343         $test = $test + 1;
344     }
345     local $^W = 0;
346     last TODO;
347 }
348
349 sub eq_array {
350     my ($ra, $rb) = @_;
351     return 0 unless $#$ra == $#$rb;
352     for my $i (0..$#$ra) {
353         next     if !defined $ra->[$i] && !defined $rb->[$i];
354         return 0 if !defined $ra->[$i];
355         return 0 if !defined $rb->[$i];
356         return 0 unless $ra->[$i] eq $rb->[$i];
357     }
358     return 1;
359 }
360
361 sub eq_hash {
362   my ($orig, $suspect) = @_;
363   my $fail;
364   while (my ($key, $value) = each %$suspect) {
365     # Force a hash recompute if this perl's internals can cache the hash key.
366     $key = "" . $key;
367     if (exists $orig->{$key}) {
368       if ($orig->{$key} ne $value) {
369         _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
370                      " now ", _qq($value), "\n";
371         $fail = 1;
372       }
373     } else {
374       _print "# key ", _qq($key), " is ", _qq($value),
375                    ", not in original.\n";
376       $fail = 1;
377     }
378   }
379   foreach (keys %$orig) {
380     # Force a hash recompute if this perl's internals can cache the hash key.
381     $_ = "" . $_;
382     next if (exists $suspect->{$_});
383     _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
384     $fail = 1;
385   }
386   !$fail;
387 }
388
389 sub require_ok ($) {
390     my ($require) = @_;
391     eval <<REQUIRE_OK;
392 require $require;
393 REQUIRE_OK
394     _ok(!$@, _where(), "require $require");
395 }
396
397 sub use_ok ($) {
398     my ($use) = @_;
399     eval <<USE_OK;
400 use $use;
401 USE_OK
402     _ok(!$@, _where(), "use $use");
403 }
404
405 # runperl - Runs a separate perl interpreter.
406 # Arguments :
407 #   switches => [ command-line switches ]
408 #   nolib    => 1 # don't use -I../lib (included by default)
409 #   prog     => one-liner (avoid quotes)
410 #   progs    => [ multi-liner (avoid quotes) ]
411 #   progfile => perl script
412 #   stdin    => string to feed the stdin
413 #   stderr   => redirect stderr to stdout
414 #   args     => [ command-line arguments to the perl program ]
415 #   verbose  => print the command line
416
417 my $is_mswin    = $^O eq 'MSWin32';
418 my $is_netware  = $^O eq 'NetWare';
419 my $is_vms      = $^O eq 'VMS';
420 my $is_cygwin   = $^O eq 'cygwin';
421
422 sub _quote_args {
423     my ($runperl, $args) = @_;
424
425     foreach (@$args) {
426         # In VMS protect with doublequotes because otherwise
427         # DCL will lowercase -- unless already doublequoted.
428        $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
429        $runperl = $runperl . ' ' . $_;
430     }
431     return $runperl;
432 }
433
434 sub _create_runperl { # Create the string to qx in runperl().
435     my %args = @_;
436     my $runperl = which_perl();
437     if ($runperl =~ m/\s/) {
438         $runperl = qq{"$runperl"};
439     }
440     #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
441     if ($ENV{PERL_RUNPERL_DEBUG}) {
442         $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
443     }
444     unless ($args{nolib}) {
445         $runperl = $runperl . ' "-I../lib"'; # doublequotes because of VMS
446     }
447     if ($args{switches}) {
448         local $Level = 2;
449         die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
450             unless ref $args{switches} eq "ARRAY";
451         $runperl = _quote_args($runperl, $args{switches});
452     }
453     if (defined $args{prog}) {
454         die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
455             if defined $args{progs};
456         $args{progs} = [$args{prog}]
457     }
458     if (defined $args{progs}) {
459         die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
460             unless ref $args{progs} eq "ARRAY";
461         foreach my $prog (@{$args{progs}}) {
462             if ($is_mswin || $is_netware || $is_vms) {
463                 $runperl = $runperl . qq ( -e "$prog" );
464             }
465             else {
466                 $runperl = $runperl . qq ( -e '$prog' );
467             }
468         }
469     } elsif (defined $args{progfile}) {
470         $runperl = $runperl . qq( "$args{progfile}");
471     } else {
472         # You probaby didn't want to be sucking in from the upstream stdin
473         die "test.pl:runperl(): none of prog, progs, progfile, args, "
474             . " switches or stdin specified"
475             unless defined $args{args} or defined $args{switches}
476                 or defined $args{stdin};
477     }
478     if (defined $args{stdin}) {
479         # so we don't try to put literal newlines and crs onto the
480         # command line.
481         $args{stdin} =~ s/\n/\\n/g;
482         $args{stdin} =~ s/\r/\\r/g;
483
484         if ($is_mswin || $is_netware || $is_vms) {
485             $runperl = qq{$Perl -e "print qq(} .
486                 $args{stdin} . q{)" | } . $runperl;
487         }
488         else {
489             $runperl = qq{$Perl -e 'print qq(} .
490                 $args{stdin} . q{)' | } . $runperl;
491         }
492     }
493     if (defined $args{args}) {
494         $runperl = _quote_args($runperl, $args{args});
495     }
496     $runperl = $runperl . ' 2>&1' if $args{stderr};
497     if ($args{verbose}) {
498         my $runperldisplay = $runperl;
499         $runperldisplay =~ s/\n/\n\#/g;
500         _print_stderr "# $runperldisplay\n";
501     }
502     return $runperl;
503 }
504
505 sub runperl {
506     die "test.pl:runperl() does not take a hashref"
507         if ref $_[0] and ref $_[0] eq 'HASH';
508     my $runperl = &_create_runperl;
509     my $result;
510
511     my $tainted = ${^TAINT};
512     my %args = @_;
513     exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
514
515     if ($tainted) {
516         # We will assume that if you're running under -T, you really mean to
517         # run a fresh perl, so we'll brute force launder everything for you
518         my $sep;
519
520         if (! eval 'require Config; 1') {
521             warn "test.pl had problems loading Config: $@";
522             $sep = ':';
523         } else {
524             $sep = $Config::Config{path_sep};
525         }
526
527         my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
528         local @ENV{@keys} = ();
529         # Untaint, plus take out . and empty string:
530         local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
531         $ENV{PATH} =~ /(.*)/s;
532         local $ENV{PATH} =
533             join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
534                 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
535                     split quotemeta ($sep), $1;
536         $ENV{PATH} = $ENV{PATH} . "$sep/bin" if $is_cygwin;  # Must have /bin under Cygwin
537
538         $runperl =~ /(.*)/s;
539         $runperl = $1;
540
541         $result = `$runperl`;
542     } else {
543         $result = `$runperl`;
544     }
545     $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
546     return $result;
547 }
548
549 *run_perl = \&runperl; # Nice alias.
550
551 sub DIE {
552     _print_stderr "# @_\n";
553     exit 1;
554 }
555
556 # A somewhat safer version of the sometimes wrong $^X.
557 sub which_perl {
558     unless (defined $Perl) {
559         $Perl = $^X;
560
561         # VMS should have 'perl' aliased properly
562         return $Perl if $^O eq 'VMS';
563
564         my $exe;
565         if (! eval 'require Config; 1') {
566             warn "test.pl had problems loading Config: $@";
567             $exe = '';
568         } else {
569             $exe = $Config::Config{_exe};
570         }
571        $exe = '' unless defined $exe;
572
573         # This doesn't absolutize the path: beware of future chdirs().
574         # We could do File::Spec->abs2rel() but that does getcwd()s,
575         # which is a bit heavyweight to do here.
576
577         if ($Perl =~ /^perl\Q$exe\E$/i) {
578             my $perl = "perl$exe";
579             if (! eval 'require File::Spec; 1') {
580                 warn "test.pl had problems loading File::Spec: $@";
581                 $Perl = "./$perl";
582             } else {
583                 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
584             }
585         }
586
587         # Build up the name of the executable file from the name of
588         # the command.
589
590         if ($Perl !~ /\Q$exe\E$/i) {
591             $Perl = $Perl . $exe;
592         }
593
594         warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
595
596         # For subcommands to use.
597         $ENV{PERLEXE} = $Perl;
598     }
599     return $Perl;
600 }
601
602 sub unlink_all {
603     foreach my $file (@_) {
604         1 while unlink $file;
605         _print_stderr "# Couldn't unlink '$file': $!\n" if -f $file;
606     }
607 }
608
609 my %tmpfiles;
610 END { unlink_all keys %tmpfiles }
611
612 # A regexp that matches the tempfile names
613 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
614
615 # Avoid ++, avoid ranges, avoid split //
616 my @letters = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);
617 sub tempfile {
618     my $count = 0;
619     do {
620         my $temp = $count;
621         my $try = "tmp$$";
622         do {
623             $try = $try . $letters[$temp % 26];
624             $temp = int ($temp / 26);
625         } while $temp;
626         # Need to note all the file names we allocated, as a second request may
627         # come before the first is created.
628         if (!-e $try && !$tmpfiles{$try}) {
629             # We have a winner
630             $tmpfiles{$try} = 1;
631             return $try;
632         }
633         $count = $count + 1;
634     } while $count < 26 * 26;
635     die "Can't find temporary file name starting 'tmp$$'";
636 }
637
638 # This is the temporary file for _fresh_perl
639 my $tmpfile = tempfile();
640
641 #
642 # _fresh_perl
643 #
644 # The $resolve must be a subref that tests the first argument
645 # for success, or returns the definition of success (e.g. the
646 # expected scalar) if given no arguments.
647 #
648
649 sub _fresh_perl {
650     my($prog, $resolve, $runperl_args, $name) = @_;
651
652     # Given the choice of the mis-parsable {}
653     # (we want an anon hash, but a borked lexer might think that it's a block)
654     # or relying on taking a reference to a lexical
655     # (\ might be mis-parsed, and the reference counting on the pad may go
656     #  awry)
657     # it feels like the least-worse thing is to assume that auto-vivification
658     # works. At least, this is only going to be a run-time failure, so won't
659     # affect tests using this file but not this function.
660     $runperl_args->{progfile} = $tmpfile;
661     $runperl_args->{stderr} = 1;
662
663     open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
664
665     # VMS adjustments
666     if( $^O eq 'VMS' ) {
667         $prog =~ s#/dev/null#NL:#;
668
669         # VMS file locking
670         $prog =~ s{if \(-e _ and -f _ and -r _\)}
671                   {if (-e _ and -f _)}
672     }
673
674     print TEST $prog;
675     close TEST or die "Cannot close $tmpfile: $!";
676
677     my $results = runperl(%$runperl_args);
678     my $status = $?;
679
680     # Clean up the results into something a bit more predictable.
681     $results  =~ s/\n+$//;
682     $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
683     $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
684
685     # bison says 'parse error' instead of 'syntax error',
686     # various yaccs may or may not capitalize 'syntax'.
687     $results =~ s/^(syntax|parse) error/syntax error/mig;
688
689     if ($^O eq 'VMS') {
690         # some tests will trigger VMS messages that won't be expected
691         $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
692
693         # pipes double these sometimes
694         $results =~ s/\n\n/\n/g;
695     }
696
697     my $pass = $resolve->($results);
698     unless ($pass) {
699         _diag "# PROG: \n$prog\n";
700         _diag "# EXPECTED:\n", $resolve->(), "\n";
701         _diag "# GOT:\n$results\n";
702         _diag "# STATUS: $status\n";
703     }
704
705     # Use the first line of the program as a name if none was given
706     unless( $name ) {
707         ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
708         $name = $name . '...' if length $first_line > length $name;
709     }
710
711     _ok($pass, _where(), "fresh_perl - $name");
712 }
713
714 #
715 # fresh_perl_is
716 #
717 # Combination of run_perl() and is().
718 #
719
720 sub fresh_perl_is {
721     my($prog, $expected, $runperl_args, $name) = @_;
722
723     # _fresh_perl() is going to clip the trailing newlines off the result.
724     # This will make it so the test author doesn't have to know that.
725     $expected =~ s/\n+$//;
726
727     local $Level = 2;
728     _fresh_perl($prog,
729                 sub { @_ ? $_[0] eq $expected : $expected },
730                 $runperl_args, $name);
731 }
732
733 #
734 # fresh_perl_like
735 #
736 # Combination of run_perl() and like().
737 #
738
739 sub fresh_perl_like {
740     my($prog, $expected, $runperl_args, $name) = @_;
741     local $Level = 2;
742     _fresh_perl($prog,
743                 sub { @_ ? $_[0] =~ $expected : $expected },
744                 $runperl_args, $name);
745 }
746
747 sub can_ok ($@) {
748     my($proto, @methods) = @_;
749     my $class = ref $proto || $proto;
750
751     unless( @methods ) {
752         return _ok( 0, _where(), "$class->can(...)" );
753     }
754
755     my @nok = ();
756     foreach my $method (@methods) {
757         local($!, $@);  # don't interfere with caller's $@
758                         # eval sometimes resets $!
759         eval { $proto->can($method) } || push @nok, $method;
760     }
761
762     my $name;
763     $name = @methods == 1 ? "$class->can('$methods[0]')"
764                           : "$class->can(...)";
765
766     _ok( !@nok, _where(), $name );
767 }
768
769 sub isa_ok ($$;$) {
770     my($object, $class, $obj_name) = @_;
771
772     my $diag;
773     $obj_name = 'The object' unless defined $obj_name;
774     my $name = "$obj_name isa $class";
775     if( !defined $object ) {
776         $diag = "$obj_name isn't defined";
777     }
778     elsif( !ref $object ) {
779         $diag = "$obj_name isn't a reference";
780     }
781     else {
782         # We can't use UNIVERSAL::isa because we want to honor isa() overrides
783         local($@, $!);  # eval sometimes resets $!
784         my $rslt = eval { $object->isa($class) };
785         if( $@ ) {
786             if( $@ =~ /^Can't call method "isa" on unblessed reference/ ) {
787                 if( !UNIVERSAL::isa($object, $class) ) {
788                     my $ref = ref $object;
789                     $diag = "$obj_name isn't a '$class' it's a '$ref'";
790                 }
791             } else {
792                 die <<WHOA;
793 WHOA! I tried to call ->isa on your object and got some weird error.
794 This should never happen.  Please contact the author immediately.
795 Here's the error.
796 $@
797 WHOA
798             }
799         }
800         elsif( !$rslt ) {
801             my $ref = ref $object;
802             $diag = "$obj_name isn't a '$class' it's a '$ref'";
803         }
804     }
805
806     _ok( !$diag, _where(), $name );
807 }
808
809 # Set a watchdog to timeout the entire test file
810 # NOTE:  If the test file uses 'threads', then call the watchdog() function
811 #        _AFTER_ the 'threads' module is loaded.
812 sub watchdog ($;$)
813 {
814     my $timeout = shift;
815     my $method  = shift || "";
816     my $timeout_msg = 'Test process timed out - terminating';
817
818     # Valgrind slows perl way down so give it more time before dying.
819     $timeout *= 10 if $ENV{PERL_VALGRIND};
820
821     my $pid_to_kill = $$;   # PID for this process
822
823     if ($method eq "alarm") {
824         goto WATCHDOG_VIA_ALARM;
825     }
826
827     # Don't use a watchdog process if 'threads' is loaded -
828     #   use a watchdog thread instead
829     if (! $threads::threads) {
830
831         # On Windows and VMS, try launching a watchdog process
832         #   using system(1, ...) (see perlport.pod)
833         if (($^O eq 'MSWin32') || ($^O eq 'VMS')) {
834             # On Windows, try to get the 'real' PID
835             if ($^O eq 'MSWin32') {
836                 eval { require Win32; };
837                 if (defined(&Win32::GetCurrentProcessId)) {
838                     $pid_to_kill = Win32::GetCurrentProcessId();
839                 }
840             }
841
842             # If we still have a fake PID, we can't use this method at all
843             return if ($pid_to_kill <= 0);
844
845             # Launch watchdog process
846             my $watchdog;
847             eval {
848                 local $SIG{'__WARN__'} = sub {
849                     _diag("Watchdog warning: $_[0]");
850                 };
851                 my $sig = $^O eq 'VMS' ? 'TERM' : 'KILL';
852                 my $cmd = _create_runperl( prog =>  "sleep($timeout);" .
853                                                     "warn qq/# $timeout_msg" . '\n/;' .
854                                                     "kill($sig, $pid_to_kill);");
855                 $watchdog = system(1, $cmd);
856             };
857             if ($@ || ($watchdog <= 0)) {
858                 _diag('Failed to start watchdog');
859                 _diag($@) if $@;
860                 undef($watchdog);
861                 return;
862             }
863
864             # Add END block to parent to terminate and
865             #   clean up watchdog process
866             eval "END { local \$! = 0; local \$? = 0;
867                         wait() if kill('KILL', $watchdog); };";
868             return;
869         }
870
871         # Try using fork() to generate a watchdog process
872         my $watchdog;
873         eval { $watchdog = fork() };
874         if (defined($watchdog)) {
875             if ($watchdog) {   # Parent process
876                 # Add END block to parent to terminate and
877                 #   clean up watchdog process
878                 eval "END { local \$! = 0; local \$? = 0;
879                             wait() if kill('KILL', $watchdog); };";
880                 return;
881             }
882
883             ### Watchdog process code
884
885             # Load POSIX if available
886             eval { require POSIX; };
887
888             # Execute the timeout
889             sleep($timeout - 2) if ($timeout > 2);   # Workaround for perlbug #49073
890             sleep(2);
891
892             # Kill test process if still running
893             if (kill(0, $pid_to_kill)) {
894                 _diag($timeout_msg);
895                 kill('KILL', $pid_to_kill);
896             }
897
898             # Don't execute END block (added at beginning of this file)
899             $NO_ENDING = 1;
900
901             # Terminate ourself (i.e., the watchdog)
902             POSIX::_exit(1) if (defined(&POSIX::_exit));
903             exit(1);
904         }
905
906         # fork() failed - fall through and try using a thread
907     }
908
909     # Use a watchdog thread because either 'threads' is loaded,
910     #   or fork() failed
911     if (eval 'require threads; 1') {
912         threads->create(sub {
913                 # Load POSIX if available
914                 eval { require POSIX; };
915
916                 # Execute the timeout
917                 my $time_left = $timeout;
918                 do {
919                     $time_left = $time_left - sleep($time_left);
920                 } while ($time_left > 0);
921
922                 # Kill the parent (and ourself)
923                 select(STDERR); $| = 1;
924                 _diag($timeout_msg);
925                 POSIX::_exit(1) if (defined(&POSIX::_exit));
926                 my $sig = $^O eq 'VMS' ? 'TERM' : 'KILL';
927                 kill($sig, $pid_to_kill);
928             })->detach();
929         return;
930     }
931
932     # If everything above fails, then just use an alarm timeout
933 WATCHDOG_VIA_ALARM:
934     if (eval { alarm($timeout); 1; }) {
935         # Load POSIX if available
936         eval { require POSIX; };
937
938         # Alarm handler will do the actual 'killing'
939         $SIG{'ALRM'} = sub {
940             select(STDERR); $| = 1;
941             _diag($timeout_msg);
942             POSIX::_exit(1) if (defined(&POSIX::_exit));
943             my $sig = $^O eq 'VMS' ? 'TERM' : 'KILL';
944             kill($sig, $pid_to_kill);
945         };
946     }
947 }
948
949 my $cp_0037 =   # EBCDIC code page 0037
950     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x25\x0B\x0C\x0D\x0E\x0F' .
951     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
952     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
953     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
954     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
955     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xBA\xE0\xBB\xB0\x6D' .
956     '\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
957     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07' .
958     '\x20\x21\x22\x23\x24\x15\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
959     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\xFF' .
960     '\x41\xAA\x4A\xB1\x9F\xB2\x6A\xB5\xBD\xB4\x9A\x8A\x5F\xCA\xAF\xBC' .
961     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
962     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
963     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xFD\xFE\xFB\xFC\xAD\xAE\x59' .
964     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
965     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xDD\xDE\xDB\xDC\x8D\x8E\xDF';
966
967 my $cp_1047 =   # EBCDIC code page 1047
968     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x15\x0B\x0C\x0D\x0E\x0F' .
969     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
970     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
971     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
972     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
973     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xAD\xE0\xBD\x5F\x6D' .
974     '\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
975     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07' .
976     '\x20\x21\x22\x23\x24\x25\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
977     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\xFF' .
978     '\x41\xAA\x4A\xB1\x9F\xB2\x6A\xB5\xBB\xB4\x9A\x8A\xB0\xCA\xAF\xBC' .
979     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
980     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
981     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xFD\xFE\xFB\xFC\xBA\xAE\x59' .
982     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
983     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xDD\xDE\xDB\xDC\x8D\x8E\xDF';
984
985 my $cp_bc = # EBCDIC code page POSiX-BC
986     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x15\x0B\x0C\x0D\x0E\x0F' .
987     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
988     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
989     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
990     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
991     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xBB\xBC\xBD\x6A\x6D' .
992     '\x4A\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
993     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xFB\x4F\xFD\xFF\x07' .
994     '\x20\x21\x22\x23\x24\x25\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
995     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\x5F' .
996     '\x41\xAA\xB0\xB1\x9F\xB2\xD0\xB5\x79\xB4\x9A\x8A\xBA\xCA\xAF\xA1' .
997     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
998     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
999     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xE0\xFE\xDD\xFC\xAD\xAE\x59' .
1000     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1001     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xC0\xDE\xDB\xDC\x8D\x8E\xDF';
1002
1003 my $straight =  # Avoid ranges
1004     '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F' .
1005     '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F' .
1006     '\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F' .
1007     '\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F' .
1008     '\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F' .
1009     '\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F' .
1010     '\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F' .
1011     '\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F' .
1012     '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F' .
1013     '\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F' .
1014     '\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF' .
1015     '\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF' .
1016     '\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF' .
1017     '\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF' .
1018     '\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF' .
1019     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF';
1020
1021 # The following 2 functions allow tests to work on both EBCDIC and
1022 # ASCII-ish platforms.  They convert string scalars between the native
1023 # character set and the set of 256 characters which is usually called
1024 # Latin1.
1025 #
1026 # These routines don't work on UTF-EBCDIC and UTF-8.
1027
1028 sub native_to_latin1($) {
1029     my $string = shift;
1030
1031     return $string if ord('^') == 94;   # ASCII, Latin1
1032     my $cp;
1033     if (ord('^') == 95) {    # EBCDIC 1047
1034         $cp = \$cp_1047;
1035     }
1036     elsif (ord('^') == 106) {   # EBCDIC POSIX-BC
1037         $cp = \$cp_bc;
1038     }
1039     elsif (ord('^') == 176)  {   # EBCDIC 037 */
1040         $cp = \$cp_0037;
1041     }
1042     else {
1043         die "Unknown native character set";
1044     }
1045
1046     eval '$string =~ tr/' . $$cp . '/' . $straight . '/';
1047     return $string;
1048 }
1049
1050 sub latin1_to_native($) {
1051     my $string = shift;
1052
1053     return $string if ord('^') == 94;   # ASCII, Latin1
1054     my $cp;
1055     if (ord('^') == 95) {    # EBCDIC 1047
1056         $cp = \$cp_1047;
1057     }
1058     elsif (ord('^') == 106) {   # EBCDIC POSIX-BC
1059         $cp = \$cp_bc;
1060     }
1061     elsif (ord('^') == 176)  {   # EBCDIC 037 */
1062         $cp = \$cp_0037;
1063     }
1064     else {
1065         die "Unknown native character set";
1066     }
1067
1068     eval '$string =~ tr/' . $straight . '/' . $$cp . '/';
1069     return $string;
1070 }
1071
1072 1;