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