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