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