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