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