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