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