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