This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
toke.c: Avoid a conversion to/from UTF-8
[perl5.git] / t / test.pl
1 #
2 # t/test.pl - most of Test::More functionality without the fuss
3
4
5 # NOTE:
6 #
7 # Do not rely on features found only in more modern Perls here, as some CPAN
8 # distributions copy this file and must operate on older Perls. Similarly, keep
9 # things, simple as this may be run under fairly broken circumstances. For
10 # example, increment ($x++) has a certain amount of cleverness for things like
11 #
12 #   $x = 'zz';
13 #   $x++; # $x eq 'aaa';
14 #
15 # This stands more chance of breaking than just a simple
16 #
17 #   $x = $x + 1
18 #
19 # In this file, we use the latter "Baby Perl" approach, and increment
20 # will be worked over by t/op/inc.t
21
22 $Level = 1;
23 my $test = 1;
24 my $planned;
25 my $noplan;
26 my $Perl;       # Safer version of $^X set by which_perl()
27
28 # This defines ASCII/UTF-8 vs EBCDIC/UTF-EBCDIC
29 $::IS_ASCII  = ord 'A' ==  65;
30 $::IS_EBCDIC = ord 'A' == 193;
31
32 $TODO = 0;
33 $NO_ENDING = 0;
34 $Tests_Are_Passing = 1;
35
36 # Use this instead of print to avoid interference while testing globals.
37 sub _print {
38     local($\, $", $,) = (undef, ' ', '');
39     print STDOUT @_;
40 }
41
42 sub _print_stderr {
43     local($\, $", $,) = (undef, ' ', '');
44     print STDERR @_;
45 }
46
47 sub plan {
48     my $n;
49     if (@_ == 1) {
50         $n = shift;
51         if ($n eq 'no_plan') {
52           undef $n;
53           $noplan = 1;
54         }
55     } else {
56         my %plan = @_;
57         $plan{skip_all} and skip_all($plan{skip_all});
58         $n = $plan{tests};
59     }
60     _print "1..$n\n" unless $noplan;
61     $planned = $n;
62 }
63
64
65 # Set the plan at the end.  See Test::More::done_testing.
66 sub done_testing {
67     my $n = $test - 1;
68     $n = shift if @_;
69
70     _print "1..$n\n";
71     $planned = $n;
72 }
73
74
75 END {
76     my $ran = $test - 1;
77     if (!$NO_ENDING) {
78         if (defined $planned && $planned != $ran) {
79             _print_stderr
80                 "# Looks like you planned $planned tests but ran $ran.\n";
81         } elsif ($noplan) {
82             _print "1..$ran\n";
83         }
84     }
85 }
86
87 sub _diag {
88     return unless @_;
89     my @mess = _comment(@_);
90     $TODO ? _print(@mess) : _print_stderr(@mess);
91 }
92
93 # Use this instead of "print STDERR" when outputting failure diagnostic
94 # messages
95 sub diag {
96     _diag(@_);
97 }
98
99 # Use this instead of "print" when outputting informational messages
100 sub note {
101     return unless @_;
102     _print( _comment(@_) );
103 }
104
105 sub is_miniperl {
106     return !defined &DynaLoader::boot_DynaLoader;
107 }
108
109 sub set_up_inc {
110     # Don’t clobber @INC under miniperl
111     @INC = () unless is_miniperl;
112     unshift @INC, @_;
113 }
114
115 sub _comment {
116     return map { /^#/ ? "$_\n" : "# $_\n" }
117            map { split /\n/ } @_;
118 }
119
120 sub _have_dynamic_extension {
121     my $extension = shift;
122     unless (eval {require Config; 1}) {
123         warn "test.pl had problems loading Config: $@";
124         return 1;
125     }
126     $extension =~ s!::!/!g;
127     return 1 if ($Config::Config{extensions} =~ /\b$extension\b/);
128 }
129
130 sub skip_all {
131     if (@_) {
132         _print "1..0 # Skip @_\n";
133     } else {
134         _print "1..0\n";
135     }
136     exit(0);
137 }
138
139 sub skip_all_if_miniperl {
140     skip_all(@_) if is_miniperl();
141 }
142
143 sub skip_all_without_dynamic_extension {
144     my ($extension) = @_;
145     skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
146     return if &_have_dynamic_extension;
147     skip_all("$extension was not built");
148 }
149
150 sub skip_all_without_perlio {
151     skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
152 }
153
154 sub skip_all_without_config {
155     unless (eval {require Config; 1}) {
156         warn "test.pl had problems loading Config: $@";
157         return;
158     }
159     foreach (@_) {
160         next if $Config::Config{$_};
161         my $key = $_; # Need to copy, before trying to modify.
162         $key =~ s/^use//;
163         $key =~ s/^d_//;
164         skip_all("no $key");
165     }
166 }
167
168 sub skip_all_without_unicode_tables { # (but only under miniperl)
169     if (is_miniperl()) {
170         skip_all_if_miniperl("Unicode tables not built yet")
171             unless eval 'require "unicore/Heavy.pl"';
172     }
173 }
174
175 sub find_git_or_skip {
176     my ($source_dir, $reason);
177     if (-d '.git') {
178         $source_dir = '.';
179     } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
180         my $where = readlink 'MANIFEST';
181         die "Can't readling MANIFEST: $!" unless defined $where;
182         die "Confusing symlink target for MANIFEST, '$where'"
183             unless $where =~ s!/MANIFEST\z!!;
184         if (-d "$where/.git") {
185             # Looks like we are in a symlink tree
186             if (exists $ENV{GIT_DIR}) {
187                 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it");
188             } else {
189                 note("Found source tree at $where, setting \$ENV{GIT_DIR}");
190                 $ENV{GIT_DIR} = "$where/.git";
191             }
192             $source_dir = $where;
193         }
194     } elsif (exists $ENV{GIT_DIR}) {
195         my $commit = '8d063cd8450e59ea1c611a2f4f5a21059a2804f1';
196         my $out = `git rev-parse --verify --quiet '$commit^{commit}'`;
197         chomp $out;
198         if($out eq $commit) {
199             $source_dir = '.'
200         }
201     }
202     if ($source_dir) {
203         my $version_string = `git --version`;
204         if (defined $version_string
205               && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
206             return $source_dir if eval "v$1 ge v1.5.0";
207             # If you have earlier than 1.5.0 and it works, change this test
208             $reason = "in git checkout, but git version '$1$2' too old";
209         } else {
210             $reason = "in git checkout, but cannot run git";
211         }
212     } else {
213         $reason = 'not being run from a git checkout';
214     }
215     skip_all($reason) if $_[0] && $_[0] eq 'all';
216     skip($reason, @_);
217 }
218
219 sub BAIL_OUT {
220     my ($reason) = @_;
221     _print("Bail out!  $reason\n");
222     exit 255;
223 }
224
225 sub _ok {
226     my ($pass, $where, $name, @mess) = @_;
227     # Do not try to microoptimize by factoring out the "not ".
228     # VMS will avenge.
229     my $out;
230     if ($name) {
231         # escape out '#' or it will interfere with '# skip' and such
232         $name =~ s/#/\\#/g;
233         $out = $pass ? "ok $test - $name" : "not ok $test - $name";
234     } else {
235         $out = $pass ? "ok $test" : "not ok $test";
236     }
237
238     if ($TODO) {
239         $out = $out . " # TODO $TODO";
240     } else {
241         $Tests_Are_Passing = 0 unless $pass;
242     }
243
244     _print "$out\n";
245
246     if ($pass) {
247         note @mess; # Ensure that the message is properly escaped.
248     }
249     else {
250         my $msg = "# Failed test $test - ";
251         $msg.= "$name " if $name;
252         $msg .= "$where\n";
253         _diag $msg;
254         _diag @mess;
255     }
256
257     $test = $test + 1; # don't use ++
258
259     return $pass;
260 }
261
262 sub _where {
263     my @caller = caller($Level);
264     return "at $caller[1] line $caller[2]";
265 }
266
267 # DON'T use this for matches. Use like() instead.
268 sub ok ($@) {
269     my ($pass, $name, @mess) = @_;
270     _ok($pass, _where(), $name, @mess);
271 }
272
273 sub _q {
274     my $x = shift;
275     return 'undef' unless defined $x;
276     my $q = $x;
277     $q =~ s/\\/\\\\/g;
278     $q =~ s/'/\\'/g;
279     return "'$q'";
280 }
281
282 sub _qq {
283     my $x = shift;
284     return defined $x ? '"' . display ($x) . '"' : 'undef';
285 };
286
287 # Support pre-5.10 Perls, for the benefit of CPAN dists that copy this file.
288 # Note that chr(90) exists in both ASCII ("Z") and EBCDIC ("!").
289 my $chars_template = defined(eval { pack "W*", 90 }) ? "W*" : "U*";
290 eval 'sub re::is_regexp { ref($_[0]) eq "Regexp" }'
291     if !defined &re::is_regexp;
292
293 # keys are the codes \n etc map to, values are 2 char strings such as \n
294 my %backslash_escape;
295 foreach my $x (split //, 'nrtfa\\\'"') {
296     $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
297 }
298 # A way to display scalars containing control characters and Unicode.
299 # Trying to avoid setting $_, or relying on local $_ to work.
300 sub display {
301     my @result;
302     foreach my $x (@_) {
303         if (defined $x and not ref $x) {
304             my $y = '';
305             foreach my $c (unpack($chars_template, $x)) {
306                 if ($c > 255) {
307                     $y = $y . sprintf "\\x{%x}", $c;
308                 } elsif ($backslash_escape{$c}) {
309                     $y = $y . $backslash_escape{$c};
310                 } else {
311                     my $z = chr $c; # Maybe we can get away with a literal...
312
313                     if ($z !~ /[^[:^print:][:^ascii:]]/) {
314                         # The pattern above is equivalent (by de Morgan's
315                         # laws) to:
316                         #     $z !~ /(?[ [:print:] & [:ascii:] ])/
317                         # or, $z is not an ascii printable character
318
319                         # Use octal for characters with small ordinals that
320                         # are traditionally expressed as octal: the controls
321                         # below space, which on EBCDIC are almost all the
322                         # controls, but on ASCII don't include DEL nor the C1
323                         # controls.
324                         if ($c < ord " ") {
325                             $z = sprintf "\\%03o", $c;
326                         } else {
327                             $z = sprintf "\\x{%x}", $c;
328                         }
329                     }
330                     $y = $y . $z;
331                 }
332             }
333             $x = $y;
334         }
335         return $x unless wantarray;
336         push @result, $x;
337     }
338     return @result;
339 }
340
341 sub is ($$@) {
342     my ($got, $expected, $name, @mess) = @_;
343
344     my $pass;
345     if( !defined $got || !defined $expected ) {
346         # undef only matches undef
347         $pass = !defined $got && !defined $expected;
348     }
349     else {
350         $pass = $got eq $expected;
351     }
352
353     unless ($pass) {
354         unshift(@mess, "#      got "._qq($got)."\n",
355                        "# expected "._qq($expected)."\n");
356     }
357     _ok($pass, _where(), $name, @mess);
358 }
359
360 sub isnt ($$@) {
361     my ($got, $isnt, $name, @mess) = @_;
362
363     my $pass;
364     if( !defined $got || !defined $isnt ) {
365         # undef only matches undef
366         $pass = defined $got || defined $isnt;
367     }
368     else {
369         $pass = $got ne $isnt;
370     }
371
372     unless( $pass ) {
373         unshift(@mess, "# it should not be "._qq($got)."\n",
374                        "# but it is.\n");
375     }
376     _ok($pass, _where(), $name, @mess);
377 }
378
379 sub cmp_ok ($$$@) {
380     my($got, $type, $expected, $name, @mess) = @_;
381
382     my $pass;
383     {
384         local $^W = 0;
385         local($@,$!);   # don't interfere with $@
386                         # eval() sometimes resets $!
387         $pass = eval "\$got $type \$expected";
388     }
389     unless ($pass) {
390         # It seems Irix long doubles can have 2147483648 and 2147483648
391         # that stringify to the same thing but are actually numerically
392         # different. Display the numbers if $type isn't a string operator,
393         # and the numbers are stringwise the same.
394         # (all string operators have alphabetic names, so tr/a-z// is true)
395         # This will also show numbers for some unneeded cases, but will
396         # definitely be helpful for things such as == and <= that fail
397         if ($got eq $expected and $type !~ tr/a-z//) {
398             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
399         }
400         unshift(@mess, "#      got "._qq($got)."\n",
401                        "# expected $type "._qq($expected)."\n");
402     }
403     _ok($pass, _where(), $name, @mess);
404 }
405
406 # Check that $got is within $range of $expected
407 # if $range is 0, then check it's exact
408 # else if $expected is 0, then $range is an absolute value
409 # otherwise $range is a fractional error.
410 # Here $range must be numeric, >= 0
411 # Non numeric ranges might be a useful future extension. (eg %)
412 sub within ($$$@) {
413     my ($got, $expected, $range, $name, @mess) = @_;
414     my $pass;
415     if (!defined $got or !defined $expected or !defined $range) {
416         # This is a fail, but doesn't need extra diagnostics
417     } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
418         # This is a fail
419         unshift @mess, "# got, expected and range must be numeric\n";
420     } elsif ($range < 0) {
421         # This is also a fail
422         unshift @mess, "# range must not be negative\n";
423     } elsif ($range == 0) {
424         # Within 0 is ==
425         $pass = $got == $expected;
426     } elsif ($expected == 0) {
427         # If expected is 0, treat range as absolute
428         $pass = ($got <= $range) && ($got >= - $range);
429     } else {
430         my $diff = $got - $expected;
431         $pass = abs ($diff / $expected) < $range;
432     }
433     unless ($pass) {
434         if ($got eq $expected) {
435             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
436         }
437         unshift@mess, "#      got "._qq($got)."\n",
438                       "# expected "._qq($expected)." (within "._qq($range).")\n";
439     }
440     _ok($pass, _where(), $name, @mess);
441 }
442
443 # Note: this isn't quite as fancy as Test::More::like().
444
445 sub like   ($$@) { like_yn (0,@_) }; # 0 for -
446 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
447
448 sub like_yn ($$$@) {
449     my ($flip, undef, $expected, $name, @mess) = @_;
450
451     # We just accept like(..., qr/.../), not like(..., '...'), and
452     # definitely not like(..., '/.../') like
453     # Test::Builder::maybe_regex() does.
454     unless (re::is_regexp($expected)) {
455         die "PANIC: The value '$expected' isn't a regexp. The like() function needs a qr// pattern, not a string";
456     }
457
458     my $pass;
459     $pass = $_[1] =~ /$expected/ if !$flip;
460     $pass = $_[1] !~ /$expected/ if $flip;
461     my $display_got = $_[1];
462     $display_got = display($display_got);
463     my $display_expected = $expected;
464     $display_expected = display($display_expected);
465     unless ($pass) {
466         unshift(@mess, "#      got '$display_got'\n",
467                 $flip
468                 ? "# expected !~ /$display_expected/\n"
469                 : "# expected /$display_expected/\n");
470     }
471     local $Level = $Level + 1;
472     _ok($pass, _where(), $name, @mess);
473 }
474
475 sub pass {
476     _ok(1, '', @_);
477 }
478
479 sub fail {
480     _ok(0, _where(), @_);
481 }
482
483 sub curr_test {
484     $test = shift if @_;
485     return $test;
486 }
487
488 sub next_test {
489   my $retval = $test;
490   $test = $test + 1; # don't use ++
491   $retval;
492 }
493
494 # Note: can't pass multipart messages since we try to
495 # be compatible with Test::More::skip().
496 sub skip {
497     my $why = shift;
498     my $n   = @_ ? shift : 1;
499     my $bad_swap;
500     my $both_zero;
501     {
502       local $^W = 0;
503       $bad_swap = $why > 0 && $n == 0;
504       $both_zero = $why == 0 && $n == 0;
505     }
506     if ($bad_swap || $both_zero || @_) {
507       my $arg = "'$why', '$n'";
508       if (@_) {
509         $arg .= join(", ", '', map { qq['$_'] } @_);
510       }
511       die qq[$0: expected skip(why, count), got skip($arg)\n];
512     }
513     for (1..$n) {
514         _print "ok $test # skip $why\n";
515         $test = $test + 1;
516     }
517     local $^W = 0;
518     last SKIP;
519 }
520
521 sub skip_if_miniperl {
522     skip(@_) if is_miniperl();
523 }
524
525 sub skip_without_dynamic_extension {
526     my $extension = shift;
527     skip("no dynamic loading on miniperl, no extension $extension", @_)
528         if is_miniperl();
529     return if &_have_dynamic_extension($extension);
530     skip("extension $extension was not built", @_);
531 }
532
533 sub todo_skip {
534     my $why = shift;
535     my $n   = @_ ? shift : 1;
536
537     for (1..$n) {
538         _print "not ok $test # TODO & SKIP $why\n";
539         $test = $test + 1;
540     }
541     local $^W = 0;
542     last TODO;
543 }
544
545 sub eq_array {
546     my ($ra, $rb) = @_;
547     return 0 unless $#$ra == $#$rb;
548     for my $i (0..$#$ra) {
549         next     if !defined $ra->[$i] && !defined $rb->[$i];
550         return 0 if !defined $ra->[$i];
551         return 0 if !defined $rb->[$i];
552         return 0 unless $ra->[$i] eq $rb->[$i];
553     }
554     return 1;
555 }
556
557 sub eq_hash {
558   my ($orig, $suspect) = @_;
559   my $fail;
560   while (my ($key, $value) = each %$suspect) {
561     # Force a hash recompute if this perl's internals can cache the hash key.
562     $key = "" . $key;
563     if (exists $orig->{$key}) {
564       if (
565         defined $orig->{$key} != defined $value
566         || (defined $value && $orig->{$key} ne $value)
567       ) {
568         _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
569                      " now ", _qq($value), "\n";
570         $fail = 1;
571       }
572     } else {
573       _print "# key ", _qq($key), " is ", _qq($value),
574                    ", not in original.\n";
575       $fail = 1;
576     }
577   }
578   foreach (keys %$orig) {
579     # Force a hash recompute if this perl's internals can cache the hash key.
580     $_ = "" . $_;
581     next if (exists $suspect->{$_});
582     _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
583     $fail = 1;
584   }
585   !$fail;
586 }
587
588 # We only provide a subset of the Test::More functionality.
589 sub require_ok ($) {
590     my ($require) = @_;
591     if ($require =~ tr/[A-Za-z0-9:.]//c) {
592         fail("Invalid character in \"$require\", passed to require_ok");
593     } else {
594         eval <<REQUIRE_OK;
595 require $require;
596 REQUIRE_OK
597         is($@, '', _where(), "require $require");
598     }
599 }
600
601 sub use_ok ($) {
602     my ($use) = @_;
603     if ($use =~ tr/[A-Za-z0-9:.]//c) {
604         fail("Invalid character in \"$use\", passed to use");
605     } else {
606         eval <<USE_OK;
607 use $use;
608 USE_OK
609         is($@, '', _where(), "use $use");
610     }
611 }
612
613 # runperl - Runs a separate perl interpreter and returns its output.
614 # Arguments :
615 #   switches => [ command-line switches ]
616 #   nolib    => 1 # don't use -I../lib (included by default)
617 #   non_portable => Don't warn if a one liner contains quotes
618 #   prog     => one-liner (avoid quotes)
619 #   progs    => [ multi-liner (avoid quotes) ]
620 #   progfile => perl script
621 #   stdin    => string to feed the stdin (or undef to redirect from /dev/null)
622 #   stderr   => If 'devnull' suppresses stderr, if other TRUE value redirect
623 #               stderr to stdout
624 #   args     => [ command-line arguments to the perl program ]
625 #   verbose  => print the command line
626
627 my $is_mswin    = $^O eq 'MSWin32';
628 my $is_netware  = $^O eq 'NetWare';
629 my $is_vms      = $^O eq 'VMS';
630 my $is_cygwin   = $^O eq 'cygwin';
631
632 sub _quote_args {
633     my ($runperl, $args) = @_;
634
635     foreach (@$args) {
636         # In VMS protect with doublequotes because otherwise
637         # DCL will lowercase -- unless already doublequoted.
638        $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
639        $runperl = $runperl . ' ' . $_;
640     }
641     return $runperl;
642 }
643
644 sub _create_runperl { # Create the string to qx in runperl().
645     my %args = @_;
646     my $runperl = which_perl();
647     if ($runperl =~ m/\s/) {
648         $runperl = qq{"$runperl"};
649     }
650     #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
651     if ($ENV{PERL_RUNPERL_DEBUG}) {
652         $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
653     }
654     unless ($args{nolib}) {
655         $runperl = $runperl . ' "-I../lib" "-I." '; # doublequotes because of VMS
656     }
657     if ($args{switches}) {
658         local $Level = 2;
659         die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
660             unless ref $args{switches} eq "ARRAY";
661         $runperl = _quote_args($runperl, $args{switches});
662     }
663     if (defined $args{prog}) {
664         die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
665             if defined $args{progs};
666         $args{progs} = [split /\n/, $args{prog}, -1]
667     }
668     if (defined $args{progs}) {
669         die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
670             unless ref $args{progs} eq "ARRAY";
671         foreach my $prog (@{$args{progs}}) {
672             if (!$args{non_portable}) {
673                 if ($prog =~ tr/'"//) {
674                     warn "quotes in prog >>$prog<< are not portable";
675                 }
676                 if ($prog =~ /^([<>|]|2>)/) {
677                     warn "Initial $1 in prog >>$prog<< is not portable";
678                 }
679                 if ($prog =~ /&\z/) {
680                     warn "Trailing & in prog >>$prog<< is not portable";
681                 }
682             }
683             if ($is_mswin || $is_netware || $is_vms) {
684                 $runperl = $runperl . qq ( -e "$prog" );
685             }
686             else {
687                 $runperl = $runperl . qq ( -e '$prog' );
688             }
689         }
690     } elsif (defined $args{progfile}) {
691         $runperl = $runperl . qq( "$args{progfile}");
692     } else {
693         # You probably didn't want to be sucking in from the upstream stdin
694         die "test.pl:runperl(): none of prog, progs, progfile, args, "
695             . " switches or stdin specified"
696             unless defined $args{args} or defined $args{switches}
697                 or defined $args{stdin};
698     }
699     if (defined $args{stdin}) {
700         # so we don't try to put literal newlines and crs onto the
701         # command line.
702         $args{stdin} =~ s/\n/\\n/g;
703         $args{stdin} =~ s/\r/\\r/g;
704
705         if ($is_mswin || $is_netware || $is_vms) {
706             $runperl = qq{$Perl -e "print qq(} .
707                 $args{stdin} . q{)" | } . $runperl;
708         }
709         else {
710             $runperl = qq{$Perl -e 'print qq(} .
711                 $args{stdin} . q{)' | } . $runperl;
712         }
713     } elsif (exists $args{stdin}) {
714         # Using the pipe construction above can cause fun on systems which use
715         # ksh as /bin/sh, as ksh does pipes differently (with one less process)
716         # With sh, for the command line 'perl -e 'print qq()' | perl -e ...'
717         # the sh process forks two children, which use exec to start the two
718         # perl processes. The parent shell process persists for the duration of
719         # the pipeline, and the second perl process starts with no children.
720         # With ksh (and zsh), the shell saves a process by forking a child for
721         # just the first perl process, and execing itself to start the second.
722         # This means that the second perl process starts with one child which
723         # it didn't create. This causes "fun" when if the tests assume that
724         # wait (or waitpid) will only return information about processes
725         # started within the test.
726         # They also cause fun on VMS, where the pipe implementation returns
727         # the exit code of the process at the front of the pipeline, not the
728         # end. This messes up any test using OPTION FATAL.
729         # Hence it's useful to have a way to make STDIN be at eof without
730         # needing a pipeline, so that the fork tests have a sane environment
731         # without these surprises.
732
733         # /dev/null appears to be surprisingly portable.
734         $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null');
735     }
736     if (defined $args{args}) {
737         $runperl = _quote_args($runperl, $args{args});
738     }
739     if (exists $args{stderr} && $args{stderr} eq 'devnull') {
740         $runperl = $runperl . ($is_mswin ? ' 2>nul' : ' 2>/dev/null');
741     }
742     elsif ($args{stderr}) {
743         $runperl = $runperl . ' 2>&1';
744     }
745     if ($args{verbose}) {
746         my $runperldisplay = $runperl;
747         $runperldisplay =~ s/\n/\n\#/g;
748         _print_stderr "# $runperldisplay\n";
749     }
750     return $runperl;
751 }
752
753 # sub run_perl {} is alias to below
754 sub runperl {
755     die "test.pl:runperl() does not take a hashref"
756         if ref $_[0] and ref $_[0] eq 'HASH';
757     my $runperl = &_create_runperl;
758     my $result;
759
760     my $tainted = ${^TAINT};
761     my %args = @_;
762     exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
763
764     if ($tainted) {
765         # We will assume that if you're running under -T, you really mean to
766         # run a fresh perl, so we'll brute force launder everything for you
767         my $sep;
768
769         if (! eval {require Config; 1}) {
770             warn "test.pl had problems loading Config: $@";
771             $sep = ':';
772         } else {
773             $sep = $Config::Config{path_sep};
774         }
775
776         my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
777         local @ENV{@keys} = ();
778         # Untaint, plus take out . and empty string:
779         local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
780         $ENV{PATH} =~ /(.*)/s;
781         local $ENV{PATH} =
782             join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
783                 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
784                     split quotemeta ($sep), $1;
785         if ($is_cygwin) {   # Must have /bin under Cygwin
786             if (length $ENV{PATH}) {
787                 $ENV{PATH} = $ENV{PATH} . $sep;
788             }
789             $ENV{PATH} = $ENV{PATH} . '/bin';
790         }
791         $runperl =~ /(.*)/s;
792         $runperl = $1;
793
794         $result = `$runperl`;
795     } else {
796         $result = `$runperl`;
797     }
798     $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
799     return $result;
800 }
801
802 # Nice alias
803 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
804
805 sub DIE {
806     _print_stderr "# @_\n";
807     exit 1;
808 }
809
810 # A somewhat safer version of the sometimes wrong $^X.
811 sub which_perl {
812     unless (defined $Perl) {
813         $Perl = $^X;
814
815         # VMS should have 'perl' aliased properly
816         return $Perl if $is_vms;
817
818         my $exe;
819         if (! eval {require Config; 1}) {
820             warn "test.pl had problems loading Config: $@";
821             $exe = '';
822         } else {
823             $exe = $Config::Config{_exe};
824         }
825        $exe = '' unless defined $exe;
826
827         # This doesn't absolutize the path: beware of future chdirs().
828         # We could do File::Spec->abs2rel() but that does getcwd()s,
829         # which is a bit heavyweight to do here.
830
831         if ($Perl =~ /^perl\Q$exe\E$/i) {
832             my $perl = "perl$exe";
833             if (! eval {require File::Spec; 1}) {
834                 warn "test.pl had problems loading File::Spec: $@";
835                 $Perl = "./$perl";
836             } else {
837                 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
838             }
839         }
840
841         # Build up the name of the executable file from the name of
842         # the command.
843
844         if ($Perl !~ /\Q$exe\E$/i) {
845             $Perl = $Perl . $exe;
846         }
847
848         warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
849
850         # For subcommands to use.
851         $ENV{PERLEXE} = $Perl;
852     }
853     return $Perl;
854 }
855
856 sub unlink_all {
857     my $count = 0;
858     foreach my $file (@_) {
859         1 while unlink $file;
860         if( -f $file ){
861             _print_stderr "# Couldn't unlink '$file': $!\n";
862         }else{
863             ++$count;
864         }
865     }
866     $count;
867 }
868
869 # _num_to_alpha - Returns a string of letters representing a positive integer.
870 # Arguments :
871 #   number to convert
872 #   maximum number of letters
873
874 # returns undef if the number is negative
875 # returns undef if the number of letters is greater than the maximum wanted
876
877 # _num_to_alpha( 0) eq 'A';
878 # _num_to_alpha( 1) eq 'B';
879 # _num_to_alpha(25) eq 'Z';
880 # _num_to_alpha(26) eq 'AA';
881 # _num_to_alpha(27) eq 'AB';
882
883 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);
884
885 # Avoid ++ -- ranges split negative numbers
886 sub _num_to_alpha{
887     my($num,$max_char) = @_;
888     return unless $num >= 0;
889     my $alpha = '';
890     my $char_count = 0;
891     $max_char = 0 if $max_char < 0;
892
893     while( 1 ){
894         $alpha = $letters[ $num % 26 ] . $alpha;
895         $num = int( $num / 26 );
896         last if $num == 0;
897         $num = $num - 1;
898
899         # char limit
900         next unless $max_char;
901         $char_count = $char_count + 1;
902         return if $char_count == $max_char;
903     }
904     return $alpha;
905 }
906
907 my %tmpfiles;
908 END { unlink_all keys %tmpfiles }
909
910 # A regexp that matches the tempfile names
911 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
912
913 # Avoid ++, avoid ranges, avoid split //
914 my $tempfile_count = 0;
915 sub tempfile {
916     while(1){
917         my $try = "tmp$$";
918         my $alpha = _num_to_alpha($tempfile_count,2);
919         last unless defined $alpha;
920         $try = $try . $alpha;
921         $tempfile_count = $tempfile_count + 1;
922
923         # Need to note all the file names we allocated, as a second request may
924         # come before the first is created.
925         if (!$tmpfiles{$try} && !-e $try) {
926             # We have a winner
927             $tmpfiles{$try} = 1;
928             return $try;
929         }
930     }
931     die "Can't find temporary file name starting \"tmp$$\"";
932 }
933
934 # register_tempfile - Adds a list of files to be removed at the end of the current test file
935 # Arguments :
936 #   a list of files to be removed later
937
938 # returns a count of how many file names were actually added
939
940 # Reuses %tmpfiles so that tempfile() will also skip any files added here
941 # even if the file doesn't exist yet.
942
943 sub register_tempfile {
944     my $count = 0;
945     for( @_ ){
946         if( $tmpfiles{$_} ){
947             _print_stderr "# Temporary file '$_' already added\n";
948         }else{
949             $tmpfiles{$_} = 1;
950             $count = $count + 1;
951         }
952     }
953     return $count;
954 }
955
956 # This is the temporary file for fresh_perl
957 my $tmpfile = tempfile();
958
959 sub fresh_perl {
960     my($prog, $runperl_args) = @_;
961
962     # Run 'runperl' with the complete perl program contained in '$prog', and
963     # arguments in the hash referred to by '$runperl_args'.  The results are
964     # returned, with $? set to the exit code.  Unless overridden, stderr is
965     # redirected to stdout.
966
967     die sprintf "Third argument to fresh_perl_.* must be hashref of args to fresh_perl (or {})"
968         unless !(defined $runperl_args) || ref($runperl_args) eq 'HASH';
969
970     # Given the choice of the mis-parsable {}
971     # (we want an anon hash, but a borked lexer might think that it's a block)
972     # or relying on taking a reference to a lexical
973     # (\ might be mis-parsed, and the reference counting on the pad may go
974     #  awry)
975     # it feels like the least-worse thing is to assume that auto-vivification
976     # works. At least, this is only going to be a run-time failure, so won't
977     # affect tests using this file but not this function.
978     $runperl_args->{progfile} ||= $tmpfile;
979     $runperl_args->{stderr}     = 1 unless exists $runperl_args->{stderr};
980
981     open TEST, '>', $tmpfile or die "Cannot open $tmpfile: $!";
982     print TEST $prog;
983     close TEST or die "Cannot close $tmpfile: $!";
984
985     my $results = runperl(%$runperl_args);
986     my $status = $?;    # Not necessary to save this, but it makes it clear to
987                         # future maintainers.
988
989     # Clean up the results into something a bit more predictable.
990     $results  =~ s/\n+$//;
991     $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
992     $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
993
994     # bison says 'parse error' instead of 'syntax error',
995     # various yaccs may or may not capitalize 'syntax'.
996     $results =~ s/^(syntax|parse) error/syntax error/mig;
997
998     if ($is_vms) {
999         # some tests will trigger VMS messages that won't be expected
1000         $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1001
1002         # pipes double these sometimes
1003         $results =~ s/\n\n/\n/g;
1004     }
1005
1006     $? = $status;
1007     return $results;
1008 }
1009
1010
1011 sub _fresh_perl {
1012     my($prog, $action, $expect, $runperl_args, $name) = @_;
1013
1014     my $results = fresh_perl($prog, $runperl_args);
1015     my $status = $?;
1016
1017     # Use the first line of the program as a name if none was given
1018     unless( $name ) {
1019         ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
1020         $name = $name . '...' if length $first_line > length $name;
1021     }
1022
1023     # Historically this was implemented using a closure, but then that means
1024     # that the tests for closures avoid using this code. Given that there
1025     # are exactly two callers, doing exactly two things, the simpler approach
1026     # feels like a better trade off.
1027     my $pass;
1028     if ($action eq 'eq') {
1029         $pass = is($results, $expect, $name);
1030     } elsif ($action eq '=~') {
1031         $pass = like($results, $expect, $name);
1032     } else {
1033         die "_fresh_perl can't process action '$action'";
1034     }
1035         
1036     unless ($pass) {
1037         _diag "# PROG: \n$prog\n";
1038         _diag "# STATUS: $status\n";
1039     }
1040
1041     return $pass;
1042 }
1043
1044 #
1045 # fresh_perl_is
1046 #
1047 # Combination of run_perl() and is().
1048 #
1049
1050 sub fresh_perl_is {
1051     my($prog, $expected, $runperl_args, $name) = @_;
1052
1053     # _fresh_perl() is going to clip the trailing newlines off the result.
1054     # This will make it so the test author doesn't have to know that.
1055     $expected =~ s/\n+$//;
1056
1057     local $Level = 2;
1058     _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
1059 }
1060
1061 #
1062 # fresh_perl_like
1063 #
1064 # Combination of run_perl() and like().
1065 #
1066
1067 sub fresh_perl_like {
1068     my($prog, $expected, $runperl_args, $name) = @_;
1069     local $Level = 2;
1070     _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
1071 }
1072
1073 # Many tests use the same format in __DATA__ or external files to specify a
1074 # sequence of (fresh) tests to run, extra files they may temporarily need, and
1075 # what the expected output is.  Putting it here allows common code to serve
1076 # these multiple tests.
1077 #
1078 # Each program is source code to run followed by an "EXPECT" line, followed
1079 # by the expected output.
1080 #
1081 # The first line of the code to run may be a command line switch such as -wE
1082 # or -0777 (alphanumerics only; only one cluster, beginning with a minus is
1083 # allowed).  Later lines may contain (note the '# ' on each):
1084 #   # TODO reason for todo
1085 #   # SKIP reason for skip
1086 #   # SKIP ?code to test if this should be skipped
1087 #   # NAME name of the test (as with ok($ok, $name))
1088 #
1089 # The expected output may contain:
1090 #   OPTION list of options
1091 #   OPTIONS list of options
1092 #
1093 # The possible options for OPTION may be:
1094 #   regex - the expected output is a regular expression
1095 #   random - all lines match but in any order
1096 #   fatal - the code will fail fatally (croak, die)
1097 #
1098 # If the actual output contains a line "SKIPPED" the test will be
1099 # skipped.
1100 #
1101 # If the actual output contains a line "PREFIX", any output starting with that
1102 # line will be ignored when comparing with the expected output
1103 #
1104 # If the global variable $FATAL is true then OPTION fatal is the
1105 # default.
1106
1107 sub _setup_one_file {
1108     my $fh = shift;
1109     # Store the filename as a program that started at line 0.
1110     # Real files count lines starting at line 1.
1111     my @these = (0, shift);
1112     my ($lineno, $current);
1113     while (<$fh>) {
1114         if ($_ eq "########\n") {
1115             if (defined $current) {
1116                 push @these, $lineno, $current;
1117             }
1118             undef $current;
1119         } else {
1120             if (!defined $current) {
1121                 $lineno = $.;
1122             }
1123             $current .= $_;
1124         }
1125     }
1126     if (defined $current) {
1127         push @these, $lineno, $current;
1128     }
1129     ((scalar @these) / 2 - 1, @these);
1130 }
1131
1132 sub setup_multiple_progs {
1133     my ($tests, @prgs);
1134     foreach my $file (@_) {
1135         next if $file =~ /(?:~|\.orig|,v)$/;
1136         next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1137         next if -d $file;
1138
1139         open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1140         my $found;
1141         while (<$fh>) {
1142             if (/^__END__/) {
1143                 ++$found;
1144                 last;
1145             }
1146         }
1147         # This is an internal error, and should never happen. All bar one of
1148         # the files had an __END__ marker to signal the end of their preamble,
1149         # although for some it wasn't technically necessary as they have no
1150         # tests. It might be possible to process files without an __END__ by
1151         # seeking back to the start and treating the whole file as tests, but
1152         # it's simpler and more reliable just to make the rule that all files
1153         # must have __END__ in. This should never fail - a file without an
1154         # __END__ should not have been checked in, because the regression tests
1155         # would not have passed.
1156         die "Could not find '__END__' in $file"
1157             unless $found;
1158
1159         my ($t, @p) = _setup_one_file($fh, $file);
1160         $tests += $t;
1161         push @prgs, @p;
1162
1163         close $fh
1164             or die "Cannot close $file: $!\n";
1165     }
1166     return ($tests, @prgs);
1167 }
1168
1169 sub run_multiple_progs {
1170     my $up = shift;
1171     my @prgs;
1172     if ($up) {
1173         # The tests in lib run in a temporary subdirectory of t, and always
1174         # pass in a list of "programs" to run
1175         @prgs = @_;
1176     } else {
1177         # The tests below t run in t and pass in a file handle. In theory we
1178         # can pass (caller)[1] as the second argument to report errors with
1179         # the filename of our caller, as the handle is always DATA. However,
1180         # line numbers in DATA count from the __END__ token, so will be wrong.
1181         # Which is more confusing than not providing line numbers. So, for now,
1182         # don't provide line numbers. No obvious clean solution - one hack
1183         # would be to seek DATA back to the start and read to the __END__ token,
1184         # but that feels almost like we should just open $0 instead.
1185
1186         # Not going to rely on undef in list assignment.
1187         my $dummy;
1188         ($dummy, @prgs) = _setup_one_file(shift);
1189     }
1190
1191     my $tmpfile = tempfile();
1192
1193     my ($file, $line);
1194   PROGRAM:
1195     while (defined ($line = shift @prgs)) {
1196         $_ = shift @prgs;
1197         unless ($line) {
1198             $file = $_;
1199             if (defined $file) {
1200                 print "# From $file\n";
1201             }
1202             next;
1203         }
1204         my $switch = "";
1205         my @temps ;
1206         my @temp_path;
1207         if (s/^(\s*-\w+)//) {
1208             $switch = $1;
1209         }
1210         my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1211
1212         my %reason;
1213         foreach my $what (qw(skip todo)) {
1214             $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1215             # If the SKIP reason starts ? then it's taken as a code snippet to
1216             # evaluate. This provides the flexibility to have conditional SKIPs
1217             if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1218                 my $temp = eval $reason{$what};
1219                 if ($@) {
1220                     die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1221                 }
1222                 $reason{$what} = $temp;
1223             }
1224         }
1225
1226         my $name = '';
1227         if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1228             $name = $1;
1229         }
1230
1231         if ($reason{skip}) {
1232         SKIP:
1233           {
1234             skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1235           }
1236           next PROGRAM;
1237         }
1238
1239         if ($prog =~ /--FILE--/) {
1240             my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1241             shift @files ;
1242             die "Internal error: test $_ didn't split into pairs, got " .
1243                 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1244                     if @files % 2;
1245             while (@files > 2) {
1246                 my $filename = shift @files;
1247                 my $code = shift @files;
1248                 push @temps, $filename;
1249                 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1250                     require File::Path;
1251                     File::Path::mkpath($1);
1252                     push(@temp_path, $1);
1253                 }
1254                 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1255                 print $fh $code;
1256                 close $fh or die "Cannot close $filename: $!\n";
1257             }
1258             shift @files;
1259             $prog = shift @files;
1260         }
1261
1262         open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1263         print $fh q{
1264         BEGIN {
1265             push @INC, '.';
1266             open STDERR, '>&', STDOUT
1267               or die "Can't dup STDOUT->STDERR: $!;";
1268         }
1269         };
1270         print $fh "\n#line 1\n";  # So the line numbers don't get messed up.
1271         print $fh $prog,"\n";
1272         close $fh or die "Cannot close $tmpfile: $!";
1273         my $results = runperl( stderr => 1, progfile => $tmpfile,
1274                                stdin => undef, $up
1275                                ? (switches => ["-I$up/lib", $switch], nolib => 1)
1276                                : (switches => [$switch])
1277                                 );
1278         my $status = $?;
1279         $results =~ s/\n+$//;
1280         # allow expected output to be written as if $prog is on STDIN
1281         $results =~ s/$::tempfile_regexp/-/g;
1282         if ($^O eq 'VMS') {
1283             # some tests will trigger VMS messages that won't be expected
1284             $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1285
1286             # pipes double these sometimes
1287             $results =~ s/\n\n/\n/g;
1288         }
1289         # bison says 'parse error' instead of 'syntax error',
1290         # various yaccs may or may not capitalize 'syntax'.
1291         $results =~ s/^(syntax|parse) error/syntax error/mig;
1292         # allow all tests to run when there are leaks
1293         $results =~ s/Scalars leaked: \d+\n//g;
1294
1295         $expected =~ s/\n+$//;
1296         my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1297         # any special options? (OPTIONS foo bar zap)
1298         my $option_regex = 0;
1299         my $option_random = 0;
1300         my $fatal = $FATAL;
1301         if ($expected =~ s/^OPTIONS? (.+)\n//) {
1302             foreach my $option (split(' ', $1)) {
1303                 if ($option eq 'regex') { # allow regular expressions
1304                     $option_regex = 1;
1305                 }
1306                 elsif ($option eq 'random') { # all lines match, but in any order
1307                     $option_random = 1;
1308                 }
1309                 elsif ($option eq 'fatal') { # perl should fail
1310                     $fatal = 1;
1311                 }
1312                 else {
1313                     die "$0: Unknown OPTION '$option'\n";
1314                 }
1315             }
1316         }
1317         die "$0: can't have OPTION regex and random\n"
1318             if $option_regex + $option_random > 1;
1319         my $ok = 0;
1320         if ($results =~ s/^SKIPPED\n//) {
1321             print "$results\n" ;
1322             $ok = 1;
1323         }
1324         else {
1325             if ($option_random) {
1326                 my @got = sort split "\n", $results;
1327                 my @expected = sort split "\n", $expected;
1328
1329                 $ok = "@got" eq "@expected";
1330             }
1331             elsif ($option_regex) {
1332                 $ok = $results =~ /^$expected/;
1333             }
1334             elsif ($prefix) {
1335                 $ok = $results =~ /^\Q$expected/;
1336             }
1337             else {
1338                 $ok = $results eq $expected;
1339             }
1340
1341             if ($ok && $fatal && !($status >> 8)) {
1342                 $ok = 0;
1343             }
1344         }
1345
1346         local $::TODO = $reason{todo};
1347
1348         unless ($ok) {
1349             my $err_line = "PROG: $switch\n$prog\n" .
1350                            "EXPECTED:\n$expected\n";
1351             $err_line   .= "EXIT STATUS: != 0\n" if $fatal;
1352             $err_line   .= "GOT:\n$results\n";
1353             $err_line   .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1354             if ($::TODO) {
1355                 $err_line =~ s/^/# /mg;
1356                 print $err_line;  # Harness can't filter it out from STDERR.
1357             }
1358             else {
1359                 print STDERR $err_line;
1360             }
1361         }
1362
1363         if (defined $file) {
1364             _ok($ok, "at $file line $line", $name);
1365         } else {
1366             # We don't have file and line number data for the test, so report
1367             # errors as coming from our caller.
1368             local $Level = $Level + 1;
1369             ok($ok, $name);
1370         }
1371
1372         foreach (@temps) {
1373             unlink $_ if $_;
1374         }
1375         foreach (@temp_path) {
1376             File::Path::rmtree $_ if -d $_;
1377         }
1378     }
1379 }
1380
1381 sub can_ok ($@) {
1382     my($proto, @methods) = @_;
1383     my $class = ref $proto || $proto;
1384
1385     unless( @methods ) {
1386         return _ok( 0, _where(), "$class->can(...)" );
1387     }
1388
1389     my @nok = ();
1390     foreach my $method (@methods) {
1391         local($!, $@);  # don't interfere with caller's $@
1392                         # eval sometimes resets $!
1393         eval { $proto->can($method) } || push @nok, $method;
1394     }
1395
1396     my $name;
1397     $name = @methods == 1 ? "$class->can('$methods[0]')"
1398                           : "$class->can(...)";
1399
1400     _ok( !@nok, _where(), $name );
1401 }
1402
1403
1404 # Call $class->new( @$args ); and run the result through object_ok.
1405 # See Test::More::new_ok
1406 sub new_ok {
1407     my($class, $args, $obj_name) = @_;
1408     $args ||= [];
1409     $object_name = "The object" unless defined $obj_name;
1410
1411     local $Level = $Level + 1;
1412
1413     my $obj;
1414     my $ok = eval { $obj = $class->new(@$args); 1 };
1415     my $error = $@;
1416
1417     if($ok) {
1418         object_ok($obj, $class, $object_name);
1419     }
1420     else {
1421         ok( 0, "new() died" );
1422         diag("Error was:  $@");
1423     }
1424
1425     return $obj;
1426
1427 }
1428
1429
1430 sub isa_ok ($$;$) {
1431     my($object, $class, $obj_name) = @_;
1432
1433     my $diag;
1434     $obj_name = 'The object' unless defined $obj_name;
1435     my $name = "$obj_name isa $class";
1436     if( !defined $object ) {
1437         $diag = "$obj_name isn't defined";
1438     }
1439     else {
1440         my $whatami = ref $object ? 'object' : 'class';
1441
1442         # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1443         local($@, $!);  # eval sometimes resets $!
1444         my $rslt = eval { $object->isa($class) };
1445         my $error = $@;  # in case something else blows away $@
1446
1447         if( $error ) {
1448             if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1449                 # It's an unblessed reference
1450                 $obj_name = 'The reference' unless defined $obj_name;
1451                 if( !UNIVERSAL::isa($object, $class) ) {
1452                     my $ref = ref $object;
1453                     $diag = "$obj_name isn't a '$class' it's a '$ref'";
1454                 }
1455             }
1456             elsif( $error =~ /Can't call method "isa" without a package/ ) {
1457                 # It's something that can't even be a class
1458                 $obj_name = 'The thing' unless defined $obj_name;
1459                 $diag = "$obj_name isn't a class or reference";
1460             }
1461             else {
1462                 die <<WHOA;
1463 WHOA! I tried to call ->isa on your object and got some weird error.
1464 This should never happen.  Please contact the author immediately.
1465 Here's the error.
1466 $@
1467 WHOA
1468             }
1469         }
1470         elsif( !$rslt ) {
1471             $obj_name = "The $whatami" unless defined $obj_name;
1472             my $ref = ref $object;
1473             $diag = "$obj_name isn't a '$class' it's a '$ref'";
1474         }
1475     }
1476
1477     _ok( !$diag, _where(), $name );
1478 }
1479
1480
1481 sub class_ok {
1482     my($class, $isa, $class_name) = @_;
1483
1484     # Written so as to count as one test
1485     local $Level = $Level + 1;
1486     if( ref $class ) {
1487         ok( 0, "$class is a reference, not a class name" );
1488     }
1489     else {
1490         isa_ok($class, $isa, $class_name);
1491     }
1492 }
1493
1494
1495 sub object_ok {
1496     my($obj, $isa, $obj_name) = @_;
1497
1498     local $Level = $Level + 1;
1499     if( !ref $obj ) {
1500         ok( 0, "$obj is not a reference" );
1501     }
1502     else {
1503         isa_ok($obj, $isa, $obj_name);
1504     }
1505 }
1506
1507
1508 # Purposefully avoiding a closure.
1509 sub __capture {
1510     push @::__capture, join "", @_;
1511 }
1512     
1513 sub capture_warnings {
1514     my $code = shift;
1515
1516     local @::__capture;
1517     local $SIG {__WARN__} = \&__capture;
1518     &$code;
1519     return @::__capture;
1520 }
1521
1522 # This will generate a variable number of tests.
1523 # Use done_testing() instead of a fixed plan.
1524 sub warnings_like {
1525     my ($code, $expect, $name) = @_;
1526     local $Level = $Level + 1;
1527
1528     my @w = capture_warnings($code);
1529
1530     cmp_ok(scalar @w, '==', scalar @$expect, $name);
1531     foreach my $e (@$expect) {
1532         if (ref $e) {
1533             like(shift @w, $e, $name);
1534         } else {
1535             is(shift @w, $e, $name);
1536         }
1537     }
1538     if (@w) {
1539         diag("Saw these additional warnings:");
1540         diag($_) foreach @w;
1541     }
1542 }
1543
1544 sub _fail_excess_warnings {
1545     my($expect, $got, $name) = @_;
1546     local $Level = $Level + 1;
1547     # This will fail, and produce diagnostics
1548     is($expect, scalar @$got, $name);
1549     diag("Saw these warnings:");
1550     diag($_) foreach @$got;
1551 }
1552
1553 sub warning_is {
1554     my ($code, $expect, $name) = @_;
1555     die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1556         if ref $expect;
1557     local $Level = $Level + 1;
1558     my @w = capture_warnings($code);
1559     if (@w > 1) {
1560         _fail_excess_warnings(0 + defined $expect, \@w, $name);
1561     } else {
1562         is($w[0], $expect, $name);
1563     }
1564 }
1565
1566 sub warning_like {
1567     my ($code, $expect, $name) = @_;
1568     die sprintf "Expect must be a regexp object"
1569         unless ref $expect eq 'Regexp';
1570     local $Level = $Level + 1;
1571     my @w = capture_warnings($code);
1572     if (@w > 1) {
1573         _fail_excess_warnings(0 + defined $expect, \@w, $name);
1574     } else {
1575         like($w[0], $expect, $name);
1576     }
1577 }
1578
1579 # Set a watchdog to timeout the entire test file
1580 # NOTE:  If the test file uses 'threads', then call the watchdog() function
1581 #        _AFTER_ the 'threads' module is loaded.
1582 sub watchdog ($;$)
1583 {
1584     my $timeout = shift;
1585     my $method  = shift || "";
1586     my $timeout_msg = 'Test process timed out - terminating';
1587
1588     # Valgrind slows perl way down so give it more time before dying.
1589     $timeout *= 10 if $ENV{PERL_VALGRIND};
1590
1591     my $pid_to_kill = $$;   # PID for this process
1592
1593     if ($method eq "alarm") {
1594         goto WATCHDOG_VIA_ALARM;
1595     }
1596
1597     # shut up use only once warning
1598     my $threads_on = $threads::threads && $threads::threads;
1599
1600     # Don't use a watchdog process if 'threads' is loaded -
1601     #   use a watchdog thread instead
1602     if (!$threads_on || $method eq "process") {
1603
1604         # On Windows and VMS, try launching a watchdog process
1605         #   using system(1, ...) (see perlport.pod)
1606         if ($is_mswin || $is_vms) {
1607             # On Windows, try to get the 'real' PID
1608             if ($is_mswin) {
1609                 eval { require Win32; };
1610                 if (defined(&Win32::GetCurrentProcessId)) {
1611                     $pid_to_kill = Win32::GetCurrentProcessId();
1612                 }
1613             }
1614
1615             # If we still have a fake PID, we can't use this method at all
1616             return if ($pid_to_kill <= 0);
1617
1618             # Launch watchdog process
1619             my $watchdog;
1620             eval {
1621                 local $SIG{'__WARN__'} = sub {
1622                     _diag("Watchdog warning: $_[0]");
1623                 };
1624                 my $sig = $is_vms ? 'TERM' : 'KILL';
1625                 my $prog = "sleep($timeout);" .
1626                            "warn qq/# $timeout_msg" . '\n/;' .
1627                            "kill(q/$sig/, $pid_to_kill);";
1628
1629                 # On Windows use the indirect object plus LIST form to guarantee
1630                 # that perl is launched directly rather than via the shell (see
1631                 # perlfunc.pod), and ensure that the LIST has multiple elements
1632                 # since the indirect object plus COMMANDSTRING form seems to
1633                 # hang (see perl #121283). Don't do this on VMS, which doesn't
1634                 # support the LIST form at all.
1635                 if ($is_mswin) {
1636                     my $runperl = which_perl();
1637                     if ($runperl =~ m/\s/) {
1638                         $runperl = qq{"$runperl"};
1639                     }
1640                     $watchdog = system({ $runperl } 1, $runperl, '-e', $prog);
1641                 }
1642                 else {
1643                     my $cmd = _create_runperl(prog => $prog);
1644                     $watchdog = system(1, $cmd);
1645                 }
1646             };
1647             if ($@ || ($watchdog <= 0)) {
1648                 _diag('Failed to start watchdog');
1649                 _diag($@) if $@;
1650                 undef($watchdog);
1651                 return;
1652             }
1653
1654             # Add END block to parent to terminate and
1655             #   clean up watchdog process
1656             eval("END { local \$! = 0; local \$? = 0;
1657                         wait() if kill('KILL', $watchdog); };");
1658             return;
1659         }
1660
1661         # Try using fork() to generate a watchdog process
1662         my $watchdog;
1663         eval { $watchdog = fork() };
1664         if (defined($watchdog)) {
1665             if ($watchdog) {   # Parent process
1666                 # Add END block to parent to terminate and
1667                 #   clean up watchdog process
1668                 eval "END { local \$! = 0; local \$? = 0;
1669                             wait() if kill('KILL', $watchdog); };";
1670                 return;
1671             }
1672
1673             ### Watchdog process code
1674
1675             # Load POSIX if available
1676             eval { require POSIX; };
1677
1678             # Execute the timeout
1679             sleep($timeout - 2) if ($timeout > 2);   # Workaround for perlbug #49073
1680             sleep(2);
1681
1682             # Kill test process if still running
1683             if (kill(0, $pid_to_kill)) {
1684                 _diag($timeout_msg);
1685                 kill('KILL', $pid_to_kill);
1686                 if ($is_cygwin) {
1687                     # sometimes the above isn't enough on cygwin
1688                     sleep 1; # wait a little, it might have worked after all
1689                     system("/bin/kill -f $pid_to_kill");
1690                 }
1691             }
1692
1693             # Don't execute END block (added at beginning of this file)
1694             $NO_ENDING = 1;
1695
1696             # Terminate ourself (i.e., the watchdog)
1697             POSIX::_exit(1) if (defined(&POSIX::_exit));
1698             exit(1);
1699         }
1700
1701         # fork() failed - fall through and try using a thread
1702     }
1703
1704     # Use a watchdog thread because either 'threads' is loaded,
1705     #   or fork() failed
1706     if (eval {require threads; 1}) {
1707         'threads'->create(sub {
1708                 # Load POSIX if available
1709                 eval { require POSIX; };
1710
1711                 # Execute the timeout
1712                 my $time_left = $timeout;
1713                 do {
1714                     $time_left = $time_left - sleep($time_left);
1715                 } while ($time_left > 0);
1716
1717                 # Kill the parent (and ourself)
1718                 select(STDERR); $| = 1;
1719                 _diag($timeout_msg);
1720                 POSIX::_exit(1) if (defined(&POSIX::_exit));
1721                 my $sig = $is_vms ? 'TERM' : 'KILL';
1722                 kill($sig, $pid_to_kill);
1723             })->detach();
1724         return;
1725     }
1726
1727     # If everything above fails, then just use an alarm timeout
1728 WATCHDOG_VIA_ALARM:
1729     if (eval { alarm($timeout); 1; }) {
1730         # Load POSIX if available
1731         eval { require POSIX; };
1732
1733         # Alarm handler will do the actual 'killing'
1734         $SIG{'ALRM'} = sub {
1735             select(STDERR); $| = 1;
1736             _diag($timeout_msg);
1737             POSIX::_exit(1) if (defined(&POSIX::_exit));
1738             my $sig = $is_vms ? 'TERM' : 'KILL';
1739             kill($sig, $pid_to_kill);
1740         };
1741     }
1742 }
1743
1744 1;