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