This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
re/anyof.t: Add debugging info
[perl5.git] / t / test.pl
CommitLineData
69026470 1#
91d6f8a5 2# t/test.pl - most of Test::More functionality without the fuss
485f531e
DL
3
4
5# NOTE:
6#
94b9cb53
AC
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
c42fde61 10# example, increment ($x++) has a certain amount of cleverness for things like
485f531e
DL
11#
12# $x = 'zz';
13# $x++; # $x eq 'aaa';
69026470 14#
c42fde61 15# This stands more chance of breaking than just a simple
485f531e
DL
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
69026470 21
470e8f06 22$| = 1;
81c73c11 23our $Level = 1;
69026470
JH
24my $test = 1;
25my $planned;
6137113d 26my $noplan;
5fe9b82b 27my $Perl; # Safer version of $^X set by which_perl()
69026470 28
ef237063
NC
29# This defines ASCII/UTF-8 vs EBCDIC/UTF-EBCDIC
30$::IS_ASCII = ord 'A' == 65;
31$::IS_EBCDIC = ord 'A' == 193;
32
81c73c11
TR
33# This is 'our' to enable harness to account for TODO-ed tests in
34# overall grade of PASS or FAIL
35our $TODO = 0;
36our $NO_ENDING = 0;
37our $Tests_Are_Passing = 1;
7d932aad 38
3d66076a
MS
39# Use this instead of print to avoid interference while testing globals.
40sub _print {
41 local($\, $", $,) = (undef, ' ', '');
42 print STDOUT @_;
43}
44
45sub _print_stderr {
46 local($\, $", $,) = (undef, ' ', '');
47 print STDERR @_;
48}
49
69026470
JH
50sub plan {
51 my $n;
52 if (@_ == 1) {
53 $n = shift;
6137113d
NC
54 if ($n eq 'no_plan') {
55 undef $n;
56 $noplan = 1;
57 }
69026470
JH
58 } else {
59 my %plan = @_;
80654023 60 $plan{skip_all} and skip_all($plan{skip_all});
8210c8d3 61 $n = $plan{tests};
69026470 62 }
3d66076a 63 _print "1..$n\n" unless $noplan;
69026470
JH
64 $planned = $n;
65}
66
c4ef7183
MS
67
68# Set the plan at the end. See Test::More::done_testing.
69sub done_testing {
70 my $n = $test - 1;
71 $n = shift if @_;
72
73 _print "1..$n\n";
74 $planned = $n;
75}
76
77
69026470
JH
78END {
79 my $ran = $test - 1;
6137113d
NC
80 if (!$NO_ENDING) {
81 if (defined $planned && $planned != $ran) {
3d66076a 82 _print_stderr
6137113d
NC
83 "# Looks like you planned $planned tests but ran $ran.\n";
84 } elsif ($noplan) {
3d66076a 85 _print "1..$ran\n";
6137113d 86 }
69026470
JH
87 }
88}
89
de522f7a 90sub _diag {
cf8feb78 91 return unless @_;
92c9394b 92 my @mess = _comment(@_);
44826442 93 $TODO ? _print(@mess) : _print_stderr(@mess);
de522f7a
MS
94}
95
93f09d7b 96# Use this instead of "print STDERR" when outputting failure diagnostic
92c9394b 97# messages
485f531e
DL
98sub diag {
99 _diag(@_);
100}
101
93f09d7b 102# Use this instead of "print" when outputting informational messages
92c9394b
MS
103sub note {
104 return unless @_;
105 _print( _comment(@_) );
106}
107
445876fa
KW
108sub is_miniperl {
109 return !defined &DynaLoader::boot_DynaLoader;
110}
111
43ece5b1
FC
112sub set_up_inc {
113 # Don’t clobber @INC under miniperl
114 @INC = () unless is_miniperl;
115 unshift @INC, @_;
116}
117
92c9394b
MS
118sub _comment {
119 return map { /^#/ ? "$_\n" : "# $_\n" }
120 map { split /\n/ } @_;
121}
122
f12ade25
FC
123sub _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
69026470
JH
133sub skip_all {
134 if (@_) {
7bb7fa38 135 _print "1..0 # Skip @_\n";
69026470 136 } else {
3d66076a 137 _print "1..0\n";
69026470
JH
138 }
139 exit(0);
140}
141
c82d0e1e 142sub skip_all_if_miniperl {
445876fa 143 skip_all(@_) if is_miniperl();
c82d0e1e
NC
144}
145
273be65c 146sub skip_all_without_dynamic_extension {
f12ade25 147 my ($extension) = @_;
273be65c 148 skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
f12ade25 149 return if &_have_dynamic_extension;
7465bc32
NC
150 skip_all("$extension was not built");
151}
152
e05e9c3d
NC
153sub skip_all_without_perlio {
154 skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
155}
156
9c8416b2 157sub skip_all_without_config {
cb01154c 158 unless (eval {require Config; 1}) {
9c8416b2
NC
159 warn "test.pl had problems loading Config: $@";
160 return;
161 }
77ba2250
NC
162 foreach (@_) {
163 next if $Config::Config{$_};
164 my $key = $_; # Need to copy, before trying to modify.
9c8416b2
NC
165 $key =~ s/^use//;
166 $key =~ s/^d_//;
77ba2250 167 skip_all("no $key");
9c8416b2 168 }
9c8416b2
NC
169}
170
2b08d1e2
FC
171sub skip_all_without_unicode_tables { # (but only under miniperl)
172 if (is_miniperl()) {
173 skip_all_if_miniperl("Unicode tables not built yet")
048bdb72 174 unless eval 'require "unicore/UCD.pl"';
2b08d1e2
FC
175 }
176}
177
9c86860c 178sub find_git_or_skip {
fb7d5399 179 my ($source_dir, $reason);
2e279f82
N
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
962ff913 189 if (-d '.git') {
fb7d5399 190 $source_dir = '.';
962ff913 191 } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
7eccb5a9 192 my $where = readlink 'MANIFEST';
b53d6a00 193 die "Can't readlink MANIFEST: $!" unless defined $where;
7eccb5a9
NC
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
fb7d5399
NC
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;
7eccb5a9 205 }
111f3874 206 } elsif (exists $ENV{GIT_DIR} || -f '.git') {
6b44ec68
DK
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 }
7eccb5a9 213 }
2aac7c0f
NT
214 if ($ENV{'PERL_BUILD_PACKAGING'}) {
215 $reason = 'PERL_BUILD_PACKAGING is set';
216 } elsif ($source_dir) {
962ff913
NC
217 my $version_string = `git --version`;
218 if (defined $version_string
219 && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
fb7d5399 220 return $source_dir if eval "v$1 ge v1.5.0";
962ff913
NC
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 }
9c86860c
NC
229 skip_all($reason) if $_[0] && $_[0] eq 'all';
230 skip($reason, @_);
231}
232
779248a0
CK
233sub BAIL_OUT {
234 my ($reason) = @_;
235 _print("Bail out! $reason\n");
236 exit 255;
237}
238
69026470 239sub _ok {
7d932aad 240 my ($pass, $where, $name, @mess) = @_;
69026470
JH
241 # Do not try to microoptimize by factoring out the "not ".
242 # VMS will avenge.
7d932aad
MS
243 my $out;
244 if ($name) {
b734d6c9
MS
245 # escape out '#' or it will interfere with '# skip' and such
246 $name =~ s/#/\\#/g;
7d932aad 247 $out = $pass ? "ok $test - $name" : "not ok $test - $name";
69026470 248 } else {
7d932aad 249 $out = $pass ? "ok $test" : "not ok $test";
69026470 250 }
7d932aad 251
02455492
NC
252 if ($TODO) {
253 $out = $out . " # TODO $TODO";
254 } else {
255 $Tests_Are_Passing = 0 unless $pass;
256 }
257
3d66076a 258 _print "$out\n";
7d932aad 259
9b9ae264
DM
260 if ($pass) {
261 note @mess; # Ensure that the message is properly escaped.
262 }
263 else {
ffb73d65
CB
264 my $msg = "# Failed test $test - ";
265 $msg.= "$name " if $name;
266 $msg .= "$where\n";
267 _diag $msg;
9b9ae264 268 _diag @mess;
69026470 269 }
7d932aad 270
485f531e 271 $test = $test + 1; # don't use ++
1577bb16
MS
272
273 return $pass;
69026470
JH
274}
275
276sub _where {
dcc7f481 277 my @caller = caller($Level);
69026470
JH
278 return "at $caller[1] line $caller[2]";
279}
280
1d662fb6 281# DON'T use this for matches. Use like() instead.
c3029c66 282sub ok ($@) {
7d932aad
MS
283 my ($pass, $name, @mess) = @_;
284 _ok($pass, _where(), $name, @mess);
69026470
JH
285}
286
b3c72391
JH
287sub _q {
288 my $x = shift;
289 return 'undef' unless defined $x;
290 my $q = $x;
d279d8f8
NC
291 $q =~ s/\\/\\\\/g;
292 $q =~ s/'/\\'/g;
b3c72391
JH
293 return "'$q'";
294}
295
677fb045
NC
296sub _qq {
297 my $x = shift;
298 return defined $x ? '"' . display ($x) . '"' : 'undef';
299};
300
94b9cb53
AC
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 ("!").
303my $chars_template = defined(eval { pack "W*", 90 }) ? "W*" : "U*";
304eval 'sub re::is_regexp { ref($_[0]) eq "Regexp" }'
305 if !defined &re::is_regexp;
306
677fb045
NC
307# keys are the codes \n etc map to, values are 2 char strings such as \n
308my %backslash_escape;
1cc44f92 309foreach my $x (split //, 'enrtfa\\\'"') {
677fb045
NC
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.
314sub display {
315 my @result;
316 foreach my $x (@_) {
317 if (defined $x and not ref $x) {
318 my $y = '';
94b9cb53 319 foreach my $c (unpack($chars_template, $x)) {
677fb045 320 if ($c > 255) {
11ea18f2 321 $y = $y . sprintf "\\x{%x}", $c;
677fb045 322 } elsif ($backslash_escape{$c}) {
11ea18f2 323 $y = $y . $backslash_escape{$c};
1f9a87c4
KW
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;
677fb045
NC
335 }
336 }
337 $x = $y;
338 }
339 return $x unless wantarray;
340 push @result, $x;
341 }
342 return @result;
343}
344
c3029c66 345sub is ($$@) {
7d932aad 346 my ($got, $expected, $name, @mess) = @_;
c831d34f
MS
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
69026470 357 unless ($pass) {
d5f8084a
KW
358 unshift(@mess, "# got "._qq($got)."\n",
359 "# expected "._qq($expected)."\n");
69026470 360 }
7d932aad 361 _ok($pass, _where(), $name, @mess);
69026470
JH
362}
363
c3029c66 364sub isnt ($$@) {
3e90d5a3 365 my ($got, $isnt, $name, @mess) = @_;
c831d34f
MS
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
3e90d5a3 376 unless( $pass ) {
d5f8084a 377 unshift(@mess, "# it should not be "._qq($got)."\n",
3e90d5a3
MS
378 "# but it is.\n");
379 }
380 _ok($pass, _where(), $name, @mess);
381}
382
c3029c66 383sub cmp_ok ($$$@) {
58d76dfd
JH
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
93f09d7b 395 # that stringify to the same thing but are actually numerically
58d76dfd
JH
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)
93f09d7b
PA
399 # This will also show numbers for some unneeded cases, but will
400 # definitely be helpful for things such as == and <= that fail
58d76dfd
JH
401 if ($got eq $expected and $type !~ tr/a-z//) {
402 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
403 }
d5f8084a
KW
404 unshift(@mess, "# got "._qq($got)."\n",
405 "# expected $type "._qq($expected)."\n");
58d76dfd
JH
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 %)
c3029c66 416sub within ($$$@) {
58d76dfd
JH
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 }
d5f8084a
KW
441 unshift@mess, "# got "._qq($got)."\n",
442 "# expected "._qq($expected)." (within "._qq($range).")\n";
58d76dfd
JH
443 }
444 _ok($pass, _where(), $name, @mess);
445}
446
69026470 447# Note: this isn't quite as fancy as Test::More::like().
724aa791
JC
448
449sub like ($$@) { like_yn (0,@_) }; # 0 for -
450sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
451
452sub like_yn ($$$@) {
0973e8e6 453 my ($flip, undef, $expected, $name, @mess) = @_;
aaa63dae
AB
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
69026470 462 my $pass;
0973e8e6
NC
463 $pass = $_[1] =~ /$expected/ if !$flip;
464 $pass = $_[1] !~ /$expected/ if $flip;
d9a72bf2
KW
465 my $display_got = $_[1];
466 $display_got = display($display_got);
467 my $display_expected = $expected;
468 $display_expected = display($display_expected);
724aa791 469 unless ($pass) {
d9a72bf2 470 unshift(@mess, "# got '$display_got'\n",
5a4a8c8b 471 $flip
d9a72bf2
KW
472 ? "# expected !~ /$display_expected/\n"
473 : "# expected /$display_expected/\n");
69026470 474 }
5693d826 475 local $Level = $Level + 1;
7d932aad 476 _ok($pass, _where(), $name, @mess);
69026470
JH
477}
478
479sub pass {
480 _ok(1, '', @_);
481}
482
483sub fail {
484 _ok(0, _where(), @_);
485}
486
ad20d923 487sub curr_test {
cf8feb78 488 $test = shift if @_;
ad20d923
MS
489 return $test;
490}
491
3e90d5a3 492sub next_test {
178eff92 493 my $retval = $test;
485f531e 494 $test = $test + 1; # don't use ++
178eff92 495 $retval;
3e90d5a3
MS
496}
497
69026470
JH
498# Note: can't pass multipart messages since we try to
499# be compatible with Test::More::skip().
500sub skip {
7d932aad 501 my $why = shift;
62904ca6 502 my $n = @_ ? shift : 1;
e96513a2 503 my $bad_swap;
afa691d5 504 my $both_zero;
e96513a2
JH
505 {
506 local $^W = 0;
507 $bad_swap = $why > 0 && $n == 0;
afa691d5 508 $both_zero = $why == 0 && $n == 0;
e96513a2 509 }
afa691d5
JH
510 if ($bad_swap || $both_zero || @_) {
511 my $arg = "'$why', '$n'";
62904ca6
JH
512 if (@_) {
513 $arg .= join(", ", '', map { qq['$_'] } @_);
514 }
515 die qq[$0: expected skip(why, count), got skip($arg)\n];
e96513a2 516 }
69026470 517 for (1..$n) {
7bb7fa38 518 _print "ok $test # skip $why\n";
485f531e 519 $test = $test + 1;
69026470
JH
520 }
521 local $^W = 0;
522 last SKIP;
523}
524
8c49cd2e 525sub skip_if_miniperl {
445876fa 526 skip(@_) if is_miniperl();
8c49cd2e
NC
527}
528
f12ade25 529sub skip_without_dynamic_extension {
afa691d5
JH
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", @_);
f12ade25
FC
535}
536
09f04786
MS
537sub todo_skip {
538 my $why = shift;
539 my $n = @_ ? shift : 1;
540
541 for (1..$n) {
7bb7fa38 542 _print "not ok $test # TODO & SKIP $why\n";
485f531e 543 $test = $test + 1;
09f04786
MS
544 }
545 local $^W = 0;
546 last TODO;
547}
548
69026470
JH
549sub eq_array {
550 my ($ra, $rb) = @_;
551 return 0 unless $#$ra == $#$rb;
552 for my $i (0..$#$ra) {
8210c8d3 553 next if !defined $ra->[$i] && !defined $rb->[$i];
135d199b
DM
554 return 0 if !defined $ra->[$i];
555 return 0 if !defined $rb->[$i];
69026470
JH
556 return 0 unless $ra->[$i] eq $rb->[$i];
557 }
558 return 1;
559}
560
677fb045
NC
561sub 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}) {
fb75be7e
HS
568 if (
569 defined $orig->{$key} != defined $value
570 || (defined $value && $orig->{$key} ne $value)
571 ) {
3d66076a 572 _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
de522f7a 573 " now ", _qq($value), "\n";
677fb045
NC
574 $fail = 1;
575 }
576 } else {
3d66076a 577 _print "# key ", _qq($key), " is ", _qq($value),
75385f53 578 ", not in original.\n";
677fb045
NC
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->{$_});
3d66076a 586 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
677fb045
NC
587 $fail = 1;
588 }
589 !$fail;
590}
591
d47bdea7 592# We only provide a subset of the Test::More functionality.
c3029c66 593sub require_ok ($) {
69026470 594 my ($require) = @_;
d47bdea7
NC
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;
69026470
JH
599require $require;
600REQUIRE_OK
d47bdea7
NC
601 is($@, '', _where(), "require $require");
602 }
69026470
JH
603}
604
c3029c66 605sub use_ok ($) {
69026470 606 my ($use) = @_;
d47bdea7
NC
607 if ($use =~ tr/[A-Za-z0-9:.]//c) {
608 fail("Invalid character in \"$use\", passed to use");
609 } else {
610 eval <<USE_OK;
69026470
JH
611use $use;
612USE_OK
d47bdea7
NC
613 is($@, '', _where(), "use $use");
614 }
69026470
JH
615}
616
1e9024cf 617# runperl, run_perl - Runs a separate perl interpreter and returns its output.
137352a2
RGS
618# Arguments :
619# switches => [ command-line switches ]
620# nolib => 1 # don't use -I../lib (included by default)
3d7a9343 621# non_portable => Don't warn if a one liner contains quotes
137352a2 622# prog => one-liner (avoid quotes)
d83945bc 623# progs => [ multi-liner (avoid quotes) ]
137352a2 624# progfile => perl script
53f2736e 625# stdin => string to feed the stdin (or undef to redirect from /dev/null)
97dffe50
KW
626# stderr => If 'devnull' suppresses stderr, if other TRUE value redirect
627# stderr to stdout
137352a2 628# args => [ command-line arguments to the perl program ]
cb9c5e20 629# verbose => print the command line
137352a2
RGS
630
631my $is_mswin = $^O eq 'MSWin32';
137352a2 632my $is_vms = $^O eq 'VMS';
e67ed694 633my $is_cygwin = $^O eq 'cygwin';
137352a2 634
cb9c5e20
JH
635sub _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.
ea9ac5ad 641 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
1cce9906 642 $runperl = $runperl . ' ' . $_;
cb9c5e20 643 }
1cce9906 644 return $runperl;
cb9c5e20
JH
645}
646
4cd2bd1f 647sub _create_runperl { # Create the string to qx in runperl().
137352a2 648 my %args = @_;
5fe9b82b
JH
649 my $runperl = which_perl();
650 if ($runperl =~ m/\s/) {
651 $runperl = qq{"$runperl"};
652 }
6cf707aa
RGS
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 }
f93a5f07 657 unless ($args{nolib}) {
3d7c117d 658 $runperl = $runperl . ' "-I../lib" "-I." '; # doublequotes because of VMS
137352a2 659 }
d83945bc 660 if ($args{switches}) {
343d4a7b
JH
661 local $Level = 2;
662 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
663 unless ref $args{switches} eq "ARRAY";
1cce9906 664 $runperl = _quote_args($runperl, $args{switches});
d83945bc 665 }
137352a2 666 if (defined $args{prog}) {
21820af6
JH
667 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
668 if defined $args{progs};
fc4a4b82 669 $args{progs} = [split /\n/, $args{prog}, -1]
d83945bc
A
670 }
671 if (defined $args{progs}) {
21820af6
JH
672 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
673 unless ref $args{progs} eq "ARRAY";
d83945bc 674 foreach my $prog (@{$args{progs}}) {
ecadf9b7
FC
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 }
3d7a9343 685 }
2eb109a4 686 if ($is_mswin || $is_vms) {
11ea18f2 687 $runperl = $runperl . qq ( -e "$prog" );
d83945bc
A
688 }
689 else {
11ea18f2 690 $runperl = $runperl . qq ( -e '$prog' );
d83945bc
A
691 }
692 }
137352a2 693 } elsif (defined $args{progfile}) {
11ea18f2 694 $runperl = $runperl . qq( "$args{progfile}");
9a731dbd 695 } else {
93f09d7b 696 # You probably didn't want to be sucking in from the upstream stdin
9a731dbd
NC
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};
137352a2
RGS
701 }
702 if (defined $args{stdin}) {
dc459aad
JH
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;
5ae09a77 707
2eb109a4 708 if ($is_mswin || $is_vms) {
5fe9b82b 709 $runperl = qq{$Perl -e "print qq(} .
137352a2
RGS
710 $args{stdin} . q{)" | } . $runperl;
711 }
712 else {
5fe9b82b 713 $runperl = qq{$Perl -e 'print qq(} .
137352a2
RGS
714 $args{stdin} . q{)' | } . $runperl;
715 }
53f2736e
NC
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');
137352a2
RGS
738 }
739 if (defined $args{args}) {
1cce9906 740 $runperl = _quote_args($runperl, $args{args});
cb9c5e20 741 }
5fd8fad5 742 if (exists $args{stderr} && $args{stderr} eq 'devnull') {
97dffe50
KW
743 $runperl = $runperl . ($is_mswin ? ' 2>nul' : ' 2>/dev/null');
744 }
745 elsif ($args{stderr}) {
746 $runperl = $runperl . ' 2>&1';
747 }
cb9c5e20
JH
748 if ($args{verbose}) {
749 my $runperldisplay = $runperl;
750 $runperldisplay =~ s/\n/\n\#/g;
3d66076a 751 _print_stderr "# $runperldisplay\n";
137352a2 752 }
4cd2bd1f
JH
753 return $runperl;
754}
755
ace7eef0
TC
756# usage:
757# $ENV{PATH} =~ /(.*)/s;
758# local $ENV{PATH} = untaint_path($1);
759sub 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 }
780
781 $path;
782}
783
e2f82642 784# sub run_perl {} is alias to below
90097c2d
KW
785# Since this uses backticks to run, it is subject to the rules of the shell.
786# Locale settings may pose a problem, depending on the program being run.
4cd2bd1f 787sub runperl {
9a731dbd
NC
788 die "test.pl:runperl() does not take a hashref"
789 if ref $_[0] and ref $_[0] eq 'HASH';
4cd2bd1f 790 my $runperl = &_create_runperl;
613de57f
NC
791 my $result;
792
8210c8d3
MB
793 my $tainted = ${^TAINT};
794 my %args = @_;
485f531e 795 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
8210c8d3
MB
796
797 if ($tainted) {
613de57f
NC
798 # We will assume that if you're running under -T, you really mean to
799 # run a fresh perl, so we'll brute force launder everything for you
613de57f
NC
800 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
801 local @ENV{@keys} = ();
802 # Untaint, plus take out . and empty string:
02bb3106 803 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
ace7eef0
TC
804 $ENV{PATH} =~ /(.*)/s;
805 local $ENV{PATH} = untaint_path($1);
613de57f
NC
806 $runperl =~ /(.*)/s;
807 $runperl = $1;
808
809 $result = `$runperl`;
810 } else {
811 $result = `$runperl`;
a70a1627 812 }
5b20939a 813 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
137352a2
RGS
814 return $result;
815}
816
140f5369
MS
817# Nice alias
818*run_perl = *run_perl = \&runperl; # shut up "used only once" warning
8799135f 819
ed56936b
YO
820# Run perl with specified environment and arguments, return (STDOUT, STDERR)
821# set DEBUG_RUNENV=1 in the environment to debug.
a37ef82c 822sub runperl_and_capture {
a37ef82c
YO
823 my ($env, $args) = @_;
824
ed56936b
YO
825 my $STDOUT = tempfile();
826 my $STDERR = tempfile();
827 my $PERL = $^X;
828 my $FAILURE_CODE = 119;
829
a37ef82c
YO
830 local %ENV = %ENV;
831 delete $ENV{PERLLIB};
832 delete $ENV{PERL5LIB};
833 delete $ENV{PERL5OPT};
834 delete $ENV{PERL_USE_UNSAFE_INC};
835 my $pid = fork;
836 return (0, "Couldn't fork: $!") unless defined $pid; # failure
837 if ($pid) { # parent
ed56936b
YO
838 waitpid $pid,0;
839 my $exit_code = $? ? $? >> 8 : 0;
840 my ($out, $err)= ("", "");
a37ef82c 841 local $/;
ed56936b
YO
842 if (open my $stdout, '<', $STDOUT) {
843 $out .= <$stdout>;
844 } else {
845 $err .= "Could not read STDOUT '$STDOUT' file: $!\n";
846 }
847 if (open my $stderr, '<', $STDERR) {
848 $err .= <$stderr>;
849 } else {
850 $err .= "Could not read STDERR '$STDERR' file: $!\n";
851 }
852 if ($exit_code == $FAILURE_CODE) {
853 $err .= "Something went wrong. Received FAILURE_CODE as exit code.\n";
854 }
855 if ($ENV{DEBUG_RUNENV}) {
856 print "OUT: $out\n";
857 print "ERR: $err\n";
858 }
859 return ($out, $err);
860 } elsif (defined $pid) { # child
861 # Just in case the order we update the environment changes how
862 # the environment is set up we sort the keys here for consistency.
863 for my $k (sort keys %$env) {
a37ef82c
YO
864 $ENV{$k} = $env->{$k};
865 }
ed56936b
YO
866 if ($ENV{DEBUG_RUNENV}) {
867 print "Child Process $$ Executing:\n$PERL @$args\n";
868 }
869 open STDOUT, '>', $STDOUT
870 or do {
871 print "Failed to dup STDOUT to '$STDOUT': $!";
872 exit $FAILURE_CODE;
873 };
874 open STDERR, '>', $STDERR
875 or do {
876 print "Failed to dup STDERR to '$STDERR': $!";
877 exit $FAILURE_CODE;
878 };
c3c9d6b1
YO
879 exec $PERL, @$args
880 or print STDERR "Failed to exec: ",
ed56936b
YO
881 join(" ",map { "'$_'" } $^X, @$args),
882 ": $!\n";
a37ef82c
YO
883 exit $FAILURE_CODE;
884 }
885}
886
c4fbe247 887sub DIE {
3d66076a 888 _print_stderr "# @_\n";
c4fbe247 889 exit 1;
8799135f
MS
890}
891
b5fe401b 892# A somewhat safer version of the sometimes wrong $^X.
17a740d5
JH
893sub which_perl {
894 unless (defined $Perl) {
895 $Perl = $^X;
8210c8d3 896
73421c4a 897 # VMS should have 'perl' aliased properly
4b0f0df6 898 return $Perl if $is_vms;
73421c4a 899
17a740d5 900 my $exe;
cb01154c 901 if (! eval {require Config; 1}) {
17a740d5
JH
902 warn "test.pl had problems loading Config: $@";
903 $exe = '';
85363d30 904 } else {
afe79e7b 905 $exe = $Config::Config{_exe};
85363d30 906 }
da405c16 907 $exe = '' unless defined $exe;
8210c8d3 908
17a740d5
JH
909 # This doesn't absolutize the path: beware of future chdirs().
910 # We could do File::Spec->abs2rel() but that does getcwd()s,
911 # which is a bit heavyweight to do here.
8210c8d3 912
17a740d5 913 if ($Perl =~ /^perl\Q$exe\E$/i) {
8db06b02 914 my $perl = "perl$exe";
cb01154c 915 if (! eval {require File::Spec; 1}) {
17a740d5 916 warn "test.pl had problems loading File::Spec: $@";
8db06b02 917 $Perl = "./$perl";
17a740d5 918 } else {
8db06b02 919 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
17a740d5
JH
920 }
921 }
196918b0
PG
922
923 # Build up the name of the executable file from the name of
924 # the command.
925
926 if ($Perl !~ /\Q$exe\E$/i) {
11ea18f2 927 $Perl = $Perl . $exe;
196918b0 928 }
c880be78 929
8db06b02 930 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
8210c8d3 931
17a740d5
JH
932 # For subcommands to use.
933 $ENV{PERLEXE} = $Perl;
85363d30 934 }
17a740d5 935 return $Perl;
b5fe401b
MS
936}
937
435e7af6 938sub unlink_all {
55b0687d 939 my $count = 0;
435e7af6
NC
940 foreach my $file (@_) {
941 1 while unlink $file;
55b0687d
BG
942 if( -f $file ){
943 _print_stderr "# Couldn't unlink '$file': $!\n";
944 }else{
393b66ef 945 $count = $count + 1; # don't use ++
55b0687d 946 }
435e7af6 947 }
55b0687d 948 $count;
435e7af6 949}
eeabcb2d 950
f6e25e60
BG
951# _num_to_alpha - Returns a string of letters representing a positive integer.
952# Arguments :
953# number to convert
2c36667f 954# maximum number of letters
f6e25e60
BG
955
956# returns undef if the number is negative
2c36667f 957# returns undef if the number of letters is greater than the maximum wanted
f6e25e60
BG
958
959# _num_to_alpha( 0) eq 'A';
960# _num_to_alpha( 1) eq 'B';
961# _num_to_alpha(25) eq 'Z';
962# _num_to_alpha(26) eq 'AA';
963# _num_to_alpha(27) eq 'AB';
964
48e9c5d4
BG
965my @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);
966
f6e25e60 967# Avoid ++ -- ranges split negative numbers
3314e65f 968sub _num_to_alpha {
2c36667f 969 my($num,$max_char) = @_;
f6e25e60
BG
970 return unless $num >= 0;
971 my $alpha = '';
2c36667f 972 my $char_count = 0;
3314e65f 973 $max_char = 0 if !defined($max_char) or $max_char < 0;
2c36667f 974
f6e25e60
BG
975 while( 1 ){
976 $alpha = $letters[ $num % 26 ] . $alpha;
977 $num = int( $num / 26 );
978 last if $num == 0;
979 $num = $num - 1;
2c36667f
BG
980
981 # char limit
982 next unless $max_char;
983 $char_count = $char_count + 1;
984 return if $char_count == $max_char;
f6e25e60
BG
985 }
986 return $alpha;
987}
988
748a4b20 989my %tmpfiles;
b9f2b820
YO
990sub unlink_tempfiles {
991 unlink_all keys %tmpfiles;
992 %tempfiles = ();
993}
994
995END { unlink_tempfiles(); }
748a4b20 996
3314e65f
YO
997
998# NOTE: tempfile() may be used as a module names in our tests
999# so the result must be restricted to only legal characters for a module
1000# name.
1001
748a4b20 1002# A regexp that matches the tempfile names
3314e65f 1003$::tempfile_regexp = 'tmp_[A-Z]+_[A-Z]+';
c1ddc35c 1004
7a7e4936 1005# Avoid ++, avoid ranges, avoid split //
7b29226f 1006my $tempfile_count = 0;
3314e65f 1007my $max_file_chars = 3;
7a7e4936 1008sub tempfile {
3314e65f
YO
1009 # if you change the format returned by tempfile() you MUST change
1010 # the $::tempfile_regex define above.
1011 my $try_prefix = (-d "t" ? "t/" : "")."tmp_"._num_to_alpha($$);
1012 while (1) {
1013 my $alpha = _num_to_alpha($tempfile_count,$max_file_chars);
7b29226f 1014 last unless defined $alpha;
3314e65f 1015 my $try = $try_prefix . "_" . $alpha;
7b29226f
BG
1016 $tempfile_count = $tempfile_count + 1;
1017
3314e65f
YO
1018 # Need to note all the file names we allocated, as a second request
1019 # may come before the first is created. Also we are avoiding ++ here
1020 # so we aren't using the normal idiom for this kind of test.
7b29226f 1021 if (!$tmpfiles{$try} && !-e $try) {
c1ddc35c 1022 # We have a winner
11ea18f2 1023 $tmpfiles{$try} = 1;
c1ddc35c
NC
1024 return $try;
1025 }
7b29226f 1026 }
3314e65f
YO
1027 die sprintf
1028 'panic: Too many tempfile()s with prefix "%s", limit of %d reached',
1029 $try_prefix, 26 ** $max_file_chars;
7a7e4936
NC
1030}
1031
5eccd97a
BG
1032# register_tempfile - Adds a list of files to be removed at the end of the current test file
1033# Arguments :
1034# a list of files to be removed later
1035
1036# returns a count of how many file names were actually added
1037
1038# Reuses %tmpfiles so that tempfile() will also skip any files added here
1039# even if the file doesn't exist yet.
1040
1041sub register_tempfile {
1042 my $count = 0;
1043 for( @_ ){
1044 if( $tmpfiles{$_} ){
1045 _print_stderr "# Temporary file '$_' already added\n";
1046 }else{
1047 $tmpfiles{$_} = 1;
1048 $count = $count + 1;
1049 }
1050 }
1051 return $count;
1052}
1053
f6203e99 1054# This is the temporary file for fresh_perl
7a7e4936 1055my $tmpfile = tempfile();
eeabcb2d 1056
f6203e99
KW
1057sub fresh_perl {
1058 my($prog, $runperl_args) = @_;
1059
1060 # Run 'runperl' with the complete perl program contained in '$prog', and
1061 # arguments in the hash referred to by '$runperl_args'. The results are
1062 # returned, with $? set to the exit code. Unless overridden, stderr is
1063 # redirected to stdout.
90097c2d
KW
1064 #
1065 # Placing the program in a file bypasses various sh vagaries
eeabcb2d 1066
3c32184e 1067 die sprintf "Second argument to fresh_perl_.* must be hashref of args to fresh_perl (or {})"
2a91eb11
DC
1068 unless !(defined $runperl_args) || ref($runperl_args) eq 'HASH';
1069
11ea18f2
NC
1070 # Given the choice of the mis-parsable {}
1071 # (we want an anon hash, but a borked lexer might think that it's a block)
1072 # or relying on taking a reference to a lexical
1073 # (\ might be mis-parsed, and the reference counting on the pad may go
1074 # awry)
1075 # it feels like the least-worse thing is to assume that auto-vivification
1076 # works. At least, this is only going to be a run-time failure, so won't
1077 # affect tests using this file but not this function.
c49688b0
MS
1078 $runperl_args->{progfile} ||= $tmpfile;
1079 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
eeabcb2d 1080
1ae6ead9 1081 open TEST, '>', $tmpfile or die "Cannot open $tmpfile: $!";
98c155b5 1082 binmode TEST, ':utf8' if $runperl_args->{wide_chars};
0d65d7d5 1083 print TEST $prog;
eeabcb2d
MS
1084 close TEST or die "Cannot close $tmpfile: $!";
1085
1086 my $results = runperl(%$runperl_args);
f6203e99
KW
1087 my $status = $?; # Not necessary to save this, but it makes it clear to
1088 # future maintainers.
eeabcb2d
MS
1089
1090 # Clean up the results into something a bit more predictable.
50f17f89 1091 $results =~ s/\n+$//;
748a4b20
NC
1092 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
1093 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
eeabcb2d
MS
1094
1095 # bison says 'parse error' instead of 'syntax error',
1096 # various yaccs may or may not capitalize 'syntax'.
1097 $results =~ s/^(syntax|parse) error/syntax error/mig;
1098
4b0f0df6 1099 if ($is_vms) {
eeabcb2d
MS
1100 # some tests will trigger VMS messages that won't be expected
1101 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1102
1103 # pipes double these sometimes
1104 $results =~ s/\n\n/\n/g;
1105 }
1106
f6203e99
KW
1107 $? = $status;
1108 return $results;
1109}
1110
1111
1112sub _fresh_perl {
1113 my($prog, $action, $expect, $runperl_args, $name) = @_;
1114
1115 my $results = fresh_perl($prog, $runperl_args);
1116 my $status = $?;
1117
e2c38acd
JH
1118 # Use the first line of the program as a name if none was given
1119 unless( $name ) {
81c73c11 1120 (my $first_line, $name) = $prog =~ /^((.{1,50}).*)/;
11ea18f2 1121 $name = $name . '...' if length $first_line > length $name;
e2c38acd 1122 }
eeabcb2d 1123
55280a0d
NC
1124 # Historically this was implemented using a closure, but then that means
1125 # that the tests for closures avoid using this code. Given that there
1126 # are exactly two callers, doing exactly two things, the simpler approach
1127 # feels like a better trade off.
1128 my $pass;
1129 if ($action eq 'eq') {
1130 $pass = is($results, $expect, $name);
1131 } elsif ($action eq '=~') {
1132 $pass = like($results, $expect, $name);
1133 } else {
1134 die "_fresh_perl can't process action '$action'";
1135 }
1136
1137 unless ($pass) {
1138 _diag "# PROG: \n$prog\n";
1139 _diag "# STATUS: $status\n";
1140 }
1141
1142 return $pass;
f5cda331
JH
1143}
1144
1145#
141f445b 1146# fresh_perl_is
f5cda331
JH
1147#
1148# Combination of run_perl() and is().
1149#
1150
1151sub fresh_perl_is {
1152 my($prog, $expected, $runperl_args, $name) = @_;
50f17f89
MS
1153
1154 # _fresh_perl() is going to clip the trailing newlines off the result.
1155 # This will make it so the test author doesn't have to know that.
1156 $expected =~ s/\n+$//;
1157
dcc7f481 1158 local $Level = 2;
55280a0d 1159 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
f5cda331
JH
1160}
1161
1162#
141f445b 1163# fresh_perl_like
f5cda331
JH
1164#
1165# Combination of run_perl() and like().
1166#
1167
1168sub fresh_perl_like {
1169 my($prog, $expected, $runperl_args, $name) = @_;
dcc7f481 1170 local $Level = 2;
55280a0d 1171 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
eeabcb2d
MS
1172}
1173
ebf2da99
NC
1174# Many tests use the same format in __DATA__ or external files to specify a
1175# sequence of (fresh) tests to run, extra files they may temporarily need, and
ebcaaa39
KW
1176# what the expected output is. Putting it here allows common code to serve
1177# these multiple tests.
a8775356
TC
1178#
1179# Each program is source code to run followed by an "EXPECT" line, followed
1180# by the expected output.
1181#
88d057ad
KW
1182# The first line of the code to run may be a command line switch such as -wE
1183# or -0777 (alphanumerics only; only one cluster, beginning with a minus is
1184# allowed). Later lines may contain (note the '# ' on each):
a8775356
TC
1185# # TODO reason for todo
1186# # SKIP reason for skip
1187# # SKIP ?code to test if this should be skipped
1188# # NAME name of the test (as with ok($ok, $name))
1189#
1190# The expected output may contain:
1191# OPTION list of options
1192# OPTIONS list of options
a8775356
TC
1193#
1194# The possible options for OPTION may be:
1195# regex - the expected output is a regular expression
1196# random - all lines match but in any order
1197# fatal - the code will fail fatally (croak, die)
a2f2a4e3 1198# nonfatal - the code is not expected to fail fatally
a8775356
TC
1199#
1200# If the actual output contains a line "SKIPPED" the test will be
1201# skipped.
1202#
708e0e1d
KW
1203# If the actual output contains a line "PREFIX", any output starting with that
1204# line will be ignored when comparing with the expected output
1205#
a8775356
TC
1206# If the global variable $FATAL is true then OPTION fatal is the
1207# default.
ebf2da99 1208
81c73c11 1209our $FATAL;
9f5237ac
NC
1210sub _setup_one_file {
1211 my $fh = shift;
41732369
NC
1212 # Store the filename as a program that started at line 0.
1213 # Real files count lines starting at line 1.
1214 my @these = (0, shift);
1215 my ($lineno, $current);
1216 while (<$fh>) {
1217 if ($_ eq "########\n") {
1218 if (defined $current) {
1219 push @these, $lineno, $current;
1220 }
1221 undef $current;
1222 } else {
1223 if (!defined $current) {
1224 $lineno = $.;
1225 }
1226 $current .= $_;
1227 }
1228 }
1229 if (defined $current) {
1230 push @these, $lineno, $current;
1231 }
1232 ((scalar @these) / 2 - 1, @these);
9f5237ac
NC
1233}
1234
fdb35a63
NC
1235sub setup_multiple_progs {
1236 my ($tests, @prgs);
1237 foreach my $file (@_) {
1238 next if $file =~ /(?:~|\.orig|,v)$/;
1239 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1240 next if -d $file;
1241
1242 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1243 my $found;
1244 while (<$fh>) {
1245 if (/^__END__/) {
393b66ef 1246 $found = $found + 1; # don't use ++
fdb35a63
NC
1247 last;
1248 }
1249 }
1250 # This is an internal error, and should never happen. All bar one of
1251 # the files had an __END__ marker to signal the end of their preamble,
1252 # although for some it wasn't technically necessary as they have no
1253 # tests. It might be possible to process files without an __END__ by
1254 # seeking back to the start and treating the whole file as tests, but
1255 # it's simpler and more reliable just to make the rule that all files
1256 # must have __END__ in. This should never fail - a file without an
1257 # __END__ should not have been checked in, because the regression tests
1258 # would not have passed.
1259 die "Could not find '__END__' in $file"
1260 unless $found;
1261
41732369 1262 my ($t, @p) = _setup_one_file($fh, $file);
9f5237ac 1263 $tests += $t;
41732369 1264 push @prgs, @p;
fdb35a63
NC
1265
1266 close $fh
1267 or die "Cannot close $file: $!\n";
1268 }
1269 return ($tests, @prgs);
1270}
1271
ebf2da99 1272sub run_multiple_progs {
5f7e0818
NC
1273 my $up = shift;
1274 my @prgs;
1275 if ($up) {
1276 # The tests in lib run in a temporary subdirectory of t, and always
1277 # pass in a list of "programs" to run
1278 @prgs = @_;
1279 } else {
41732369
NC
1280 # The tests below t run in t and pass in a file handle. In theory we
1281 # can pass (caller)[1] as the second argument to report errors with
1282 # the filename of our caller, as the handle is always DATA. However,
1283 # line numbers in DATA count from the __END__ token, so will be wrong.
1284 # Which is more confusing than not providing line numbers. So, for now,
1285 # don't provide line numbers. No obvious clean solution - one hack
1286 # would be to seek DATA back to the start and read to the __END__ token,
1287 # but that feels almost like we should just open $0 instead.
1288
9f5237ac
NC
1289 # Not going to rely on undef in list assignment.
1290 my $dummy;
1291 ($dummy, @prgs) = _setup_one_file(shift);
5f7e0818
NC
1292 }
1293
ebf2da99
NC
1294 my $tmpfile = tempfile();
1295
b130c675 1296 my $count_failures = 0;
41732369 1297 my ($file, $line);
c0044231 1298 PROGRAM:
41732369
NC
1299 while (defined ($line = shift @prgs)) {
1300 $_ = shift @prgs;
1301 unless ($line) {
1302 $file = $_;
1303 if (defined $file) {
1304 print "# From $file\n";
1305 }
ebf2da99
NC
1306 next;
1307 }
1308 my $switch = "";
1309 my @temps ;
1310 my @temp_path;
1311 if (s/^(\s*-\w+)//) {
1312 $switch = $1;
1313 }
1314 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1315
1316 my %reason;
1317 foreach my $what (qw(skip todo)) {
1318 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1319 # If the SKIP reason starts ? then it's taken as a code snippet to
1320 # evaluate. This provides the flexibility to have conditional SKIPs
1321 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1322 my $temp = eval $reason{$what};
1323 if ($@) {
1324 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1325 }
1326 $reason{$what} = $temp;
1327 }
1328 }
c0044231 1329
20471155
N
1330 my $name = '';
1331 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1332 $name = $1;
1333 } elsif (defined $file) {
1334 $name = "test from $file at line $line";
1335 }
ebf2da99 1336
c0044231
TC
1337 if ($reason{skip}) {
1338 SKIP:
1339 {
1340 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1341 }
1342 next PROGRAM;
1343 }
1344
ebf2da99 1345 if ($prog =~ /--FILE--/) {
e330f831 1346 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
ebf2da99
NC
1347 shift @files ;
1348 die "Internal error: test $_ didn't split into pairs, got " .
1349 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1350 if @files % 2;
1351 while (@files > 2) {
1352 my $filename = shift @files;
1353 my $code = shift @files;
1354 push @temps, $filename;
1355 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1356 require File::Path;
1357 File::Path::mkpath($1);
1358 push(@temp_path, $1);
1359 }
1360 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1361 print $fh $code;
1362 close $fh or die "Cannot close $filename: $!\n";
1363 }
1364 shift @files;
1365 $prog = shift @files;
1366 }
1367
1368 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1369 print $fh q{
1370 BEGIN {
3d7c117d 1371 push @INC, '.';
ebf2da99
NC
1372 open STDERR, '>&', STDOUT
1373 or die "Can't dup STDOUT->STDERR: $!;";
1374 }
1375 };
1376 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1377 print $fh $prog,"\n";
1378 close $fh or die "Cannot close $tmpfile: $!";
684b0eca 1379 my $results = runperl( stderr => 1, progfile => $tmpfile,
53f2736e 1380 stdin => undef, $up
5f7e0818
NC
1381 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1382 : (switches => [$switch])
1383 );
ebf2da99
NC
1384 my $status = $?;
1385 $results =~ s/\n+$//;
1386 # allow expected output to be written as if $prog is on STDIN
1387 $results =~ s/$::tempfile_regexp/-/g;
1388 if ($^O eq 'VMS') {
1389 # some tests will trigger VMS messages that won't be expected
1390 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1391
1392 # pipes double these sometimes
1393 $results =~ s/\n\n/\n/g;
1394 }
1395 # bison says 'parse error' instead of 'syntax error',
1396 # various yaccs may or may not capitalize 'syntax'.
1397 $results =~ s/^(syntax|parse) error/syntax error/mig;
1398 # allow all tests to run when there are leaks
1399 $results =~ s/Scalars leaked: \d+\n//g;
1400
1401 $expected =~ s/\n+$//;
1402 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1403 # any special options? (OPTIONS foo bar zap)
1404 my $option_regex = 0;
1405 my $option_random = 0;
59e38755 1406 my $fatal = $FATAL;
a2f2a4e3 1407 if ($expected =~ s/^OPTIONS? (.+)(?:\n|\Z)//) {
ebf2da99
NC
1408 foreach my $option (split(' ', $1)) {
1409 if ($option eq 'regex') { # allow regular expressions
1410 $option_regex = 1;
1411 }
1412 elsif ($option eq 'random') { # all lines match, but in any order
1413 $option_random = 1;
1414 }
59e38755
TC
1415 elsif ($option eq 'fatal') { # perl should fail
1416 $fatal = 1;
1417 }
dd4888cb
TC
1418 elsif ($option eq 'nonfatal') {
1419 # used to turn off default fatal
1420 $fatal = 0;
1421 }
ebf2da99
NC
1422 else {
1423 die "$0: Unknown OPTION '$option'\n";
1424 }
1425 }
1426 }
1427 die "$0: can't have OPTION regex and random\n"
1428 if $option_regex + $option_random > 1;
1429 my $ok = 0;
1430 if ($results =~ s/^SKIPPED\n//) {
1431 print "$results\n" ;
1432 $ok = 1;
1433 }
ebf2da99 1434 else {
59e38755
TC
1435 if ($option_random) {
1436 my @got = sort split "\n", $results;
1437 my @expected = sort split "\n", $expected;
1438
1439 $ok = "@got" eq "@expected";
1440 }
1441 elsif ($option_regex) {
1442 $ok = $results =~ /^$expected/;
1443 }
1444 elsif ($prefix) {
1445 $ok = $results =~ /^\Q$expected/;
1446 }
1447 else {
1448 $ok = $results eq $expected;
1449 }
1450
1451 if ($ok && $fatal && !($status >> 8)) {
1452 $ok = 0;
1453 }
ebf2da99
NC
1454 }
1455
1456 local $::TODO = $reason{todo};
1457
1458 unless ($ok) {
a1bd6395
N
1459 my $err_line = '';
1460 $err_line .= "FILE: $file ; line $line\n" if defined $file;
1461 $err_line .= "PROG: $switch\n$prog\n" .
1462 "EXPECTED:\n$expected\n";
1463 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1464 $err_line .= "GOT:\n$results\n";
1465 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1466 if ($::TODO) {
1467 $err_line =~ s/^/# /mg;
1468 print $err_line; # Harness can't filter it out from STDERR.
1469 }
1470 else {
1471 print STDERR $err_line;
b130c675
N
1472 ++$count_failures;
1473 die "PERL_TEST_ABORT_FIRST_FAILURE set Test Failure"
1474 if $ENV{PERL_TEST_ABORT_FIRST_FAILURE};
a1bd6395
N
1475 }
1476 }
ebf2da99 1477
41732369
NC
1478 if (defined $file) {
1479 _ok($ok, "at $file line $line", $name);
1480 } else {
1481 # We don't have file and line number data for the test, so report
1482 # errors as coming from our caller.
1483 local $Level = $Level + 1;
1484 ok($ok, $name);
1485 }
ebf2da99
NC
1486
1487 foreach (@temps) {
1488 unlink $_ if $_;
1489 }
1490 foreach (@temp_path) {
1491 File::Path::rmtree $_ if -d $_;
1492 }
1493 }
b130c675
N
1494
1495 if ( $count_failures ) {
1496 print STDERR <<'EOS';
1497#
1498# Note: 'run_multiple_progs' run has one or more failures
1499# you can consider setting the environment variable
1500# PERL_TEST_ABORT_FIRST_FAILURE=1 before running the test
1501# to stop on the first error.
1502#
1503EOS
1504 }
1505
1506
1507 return;
ebf2da99
NC
1508}
1509
35a60386
RGS
1510sub can_ok ($@) {
1511 my($proto, @methods) = @_;
1512 my $class = ref $proto || $proto;
1513
1514 unless( @methods ) {
1515 return _ok( 0, _where(), "$class->can(...)" );
1516 }
1517
1518 my @nok = ();
1519 foreach my $method (@methods) {
1520 local($!, $@); # don't interfere with caller's $@
1521 # eval sometimes resets $!
1522 eval { $proto->can($method) } || push @nok, $method;
1523 }
1524
1525 my $name;
8210c8d3 1526 $name = @methods == 1 ? "$class->can('$methods[0]')"
35a60386 1527 : "$class->can(...)";
8210c8d3 1528
35a60386
RGS
1529 _ok( !@nok, _where(), $name );
1530}
1531
ad4e703e 1532
bbce3ca6 1533# Call $class->new( @$args ); and run the result through object_ok.
ad4e703e
MS
1534# See Test::More::new_ok
1535sub new_ok {
1536 my($class, $args, $obj_name) = @_;
1537 $args ||= [];
81c73c11 1538 $obj_name = "The object" unless defined $obj_name;
ad4e703e
MS
1539
1540 local $Level = $Level + 1;
1541
1542 my $obj;
1543 my $ok = eval { $obj = $class->new(@$args); 1 };
1544 my $error = $@;
1545
1546 if($ok) {
81c73c11 1547 object_ok($obj, $class, $obj_name);
ad4e703e
MS
1548 }
1549 else {
1550 ok( 0, "new() died" );
1551 diag("Error was: $@");
1552 }
1553
1554 return $obj;
1555
1556}
1557
1558
35a60386
RGS
1559sub isa_ok ($$;$) {
1560 my($object, $class, $obj_name) = @_;
1561
1562 my $diag;
1563 $obj_name = 'The object' unless defined $obj_name;
1564 my $name = "$obj_name isa $class";
1565 if( !defined $object ) {
1566 $diag = "$obj_name isn't defined";
1567 }
35a60386 1568 else {
b8ab4b0c
MS
1569 my $whatami = ref $object ? 'object' : 'class';
1570
35a60386
RGS
1571 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1572 local($@, $!); # eval sometimes resets $!
1573 my $rslt = eval { $object->isa($class) };
b8ab4b0c
MS
1574 my $error = $@; # in case something else blows away $@
1575
1576 if( $error ) {
1577 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1578 # It's an unblessed reference
1579 $obj_name = 'The reference' unless defined $obj_name;
35a60386
RGS
1580 if( !UNIVERSAL::isa($object, $class) ) {
1581 my $ref = ref $object;
1582 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1583 }
b8ab4b0c
MS
1584 }
1585 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1586 # It's something that can't even be a class
1587 $obj_name = 'The thing' unless defined $obj_name;
1588 $diag = "$obj_name isn't a class or reference";
1589 }
1590 else {
35a60386
RGS
1591 die <<WHOA;
1592WHOA! I tried to call ->isa on your object and got some weird error.
1593This should never happen. Please contact the author immediately.
1594Here's the error.
1595$@
1596WHOA
1597 }
1598 }
1599 elsif( !$rslt ) {
b8ab4b0c 1600 $obj_name = "The $whatami" unless defined $obj_name;
35a60386
RGS
1601 my $ref = ref $object;
1602 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1603 }
1604 }
1605
1606 _ok( !$diag, _where(), $name );
1607}
1608
bbce3ca6
MS
1609
1610sub class_ok {
1611 my($class, $isa, $class_name) = @_;
1612
1613 # Written so as to count as one test
1614 local $Level = $Level + 1;
1615 if( ref $class ) {
5c25e937 1616 ok( 0, "$class is a reference, not a class name" );
bbce3ca6
MS
1617 }
1618 else {
1619 isa_ok($class, $isa, $class_name);
1620 }
1621}
1622
1623
1624sub object_ok {
1625 my($obj, $isa, $obj_name) = @_;
1626
1627 local $Level = $Level + 1;
1628 if( !ref $obj ) {
1629 ok( 0, "$obj is not a reference" );
1630 }
1631 else {
1632 isa_ok($obj, $isa, $obj_name);
1633 }
1634}
1635
1636
9eb41b69
NC
1637# Purposefully avoiding a closure.
1638sub __capture {
1639 push @::__capture, join "", @_;
1640}
1641
3fbaac97
NC
1642sub capture_warnings {
1643 my $code = shift;
1644
9eb41b69
NC
1645 local @::__capture;
1646 local $SIG {__WARN__} = \&__capture;
7d3a9a28 1647 local $Level = 1;
3fbaac97 1648 &$code;
9eb41b69 1649 return @::__capture;
3fbaac97
NC
1650}
1651
1652# This will generate a variable number of tests.
1653# Use done_testing() instead of a fixed plan.
1654sub warnings_like {
1655 my ($code, $expect, $name) = @_;
f4554ed5
NC
1656 local $Level = $Level + 1;
1657
3fbaac97
NC
1658 my @w = capture_warnings($code);
1659
1660 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1661 foreach my $e (@$expect) {
f4554ed5 1662 if (ref $e) {
3fbaac97 1663 like(shift @w, $e, $name);
4d18b353 1664 } else {
3fbaac97 1665 is(shift @w, $e, $name);
4d18b353 1666 }
96980024 1667 }
3fbaac97
NC
1668 if (@w) {
1669 diag("Saw these additional warnings:");
1670 diag($_) foreach @w;
1671 }
1672}
1673
1674sub _fail_excess_warnings {
1675 my($expect, $got, $name) = @_;
1676 local $Level = $Level + 1;
1677 # This will fail, and produce diagnostics
1678 is($expect, scalar @$got, $name);
1679 diag("Saw these warnings:");
1680 diag($_) foreach @$got;
c11a8df3
NC
1681}
1682
4d18b353
NC
1683sub warning_is {
1684 my ($code, $expect, $name) = @_;
1685 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1686 if ref $expect;
f4554ed5 1687 local $Level = $Level + 1;
3fbaac97
NC
1688 my @w = capture_warnings($code);
1689 if (@w > 1) {
1690 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1691 } else {
1692 is($w[0], $expect, $name);
1693 }
4d18b353
NC
1694}
1695
1696sub warning_like {
1697 my ($code, $expect, $name) = @_;
1698 die sprintf "Expect must be a regexp object"
1699 unless ref $expect eq 'Regexp';
f4554ed5 1700 local $Level = $Level + 1;
3fbaac97
NC
1701 my @w = capture_warnings($code);
1702 if (@w > 1) {
1703 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1704 } else {
1705 like($w[0], $expect, $name);
1706 }
4d18b353
NC
1707}
1708
087986a7 1709# Set a watchdog to timeout the entire test file
5fe9b82b
JH
1710# NOTE: If the test file uses 'threads', then call the watchdog() function
1711# _AFTER_ the 'threads' module is loaded.
5732108f 1712sub watchdog ($;$)
087986a7
JH
1713{
1714 my $timeout = shift;
36436324 1715 my $method = shift || "";
087986a7
JH
1716 my $timeout_msg = 'Test process timed out - terminating';
1717
e07ce2e4
GG
1718 # Valgrind slows perl way down so give it more time before dying.
1719 $timeout *= 10 if $ENV{PERL_VALGRIND};
1720
087986a7
JH
1721 my $pid_to_kill = $$; # PID for this process
1722
5732108f
GG
1723 if ($method eq "alarm") {
1724 goto WATCHDOG_VIA_ALARM;
1725 }
1726
140f5369
MS
1727 # shut up use only once warning
1728 my $threads_on = $threads::threads && $threads::threads;
1729
5fe9b82b
JH
1730 # Don't use a watchdog process if 'threads' is loaded -
1731 # use a watchdog thread instead
78325d7a 1732 if (!$threads_on || $method eq "process") {
5fe9b82b
JH
1733
1734 # On Windows and VMS, try launching a watchdog process
1735 # using system(1, ...) (see perlport.pod)
4b0f0df6 1736 if ($is_mswin || $is_vms) {
5fe9b82b 1737 # On Windows, try to get the 'real' PID
4b0f0df6 1738 if ($is_mswin) {
5fe9b82b
JH
1739 eval { require Win32; };
1740 if (defined(&Win32::GetCurrentProcessId)) {
1741 $pid_to_kill = Win32::GetCurrentProcessId();
1742 }
087986a7 1743 }
087986a7 1744
5fe9b82b
JH
1745 # If we still have a fake PID, we can't use this method at all
1746 return if ($pid_to_kill <= 0);
1747
1748 # Launch watchdog process
1749 my $watchdog;
1750 eval {
1751 local $SIG{'__WARN__'} = sub {
1752 _diag("Watchdog warning: $_[0]");
1753 };
4b0f0df6 1754 my $sig = $is_vms ? 'TERM' : 'KILL';
a68d0dcb
SH
1755 my $prog = "sleep($timeout);" .
1756 "warn qq/# $timeout_msg" . '\n/;' .
1757 "kill(q/$sig/, $pid_to_kill);";
1758
ace7eef0
TC
1759 # If we're in taint mode PATH will be tainted
1760 $ENV{PATH} =~ /(.*)/s;
1761 local $ENV{PATH} = untaint_path($1);
1762
a68d0dcb
SH
1763 # On Windows use the indirect object plus LIST form to guarantee
1764 # that perl is launched directly rather than via the shell (see
1765 # perlfunc.pod), and ensure that the LIST has multiple elements
1766 # since the indirect object plus COMMANDSTRING form seems to
1767 # hang (see perl #121283). Don't do this on VMS, which doesn't
1768 # support the LIST form at all.
1769 if ($is_mswin) {
1770 my $runperl = which_perl();
ace7eef0
TC
1771 $runperl =~ /(.*)/;
1772 $runperl = $1;
a68d0dcb
SH
1773 if ($runperl =~ m/\s/) {
1774 $runperl = qq{"$runperl"};
1775 }
1776 $watchdog = system({ $runperl } 1, $runperl, '-e', $prog);
1777 }
1778 else {
1779 my $cmd = _create_runperl(prog => $prog);
1780 $watchdog = system(1, $cmd);
1781 }
5fe9b82b
JH
1782 };
1783 if ($@ || ($watchdog <= 0)) {
1784 _diag('Failed to start watchdog');
1785 _diag($@) if $@;
1786 undef($watchdog);
1787 return;
1788 }
087986a7 1789
5fe9b82b
JH
1790 # Add END block to parent to terminate and
1791 # clean up watchdog process
a68d0dcb 1792 eval("END { local \$! = 0; local \$? = 0;
18ae2abf 1793 wait() if kill('KILL', $watchdog); };");
5fe9b82b 1794 return;
087986a7 1795 }
087986a7 1796
5fe9b82b
JH
1797 # Try using fork() to generate a watchdog process
1798 my $watchdog;
1799 eval { $watchdog = fork() };
1800 if (defined($watchdog)) {
1801 if ($watchdog) { # Parent process
1802 # Add END block to parent to terminate and
1803 # clean up watchdog process
7e1027b9
JH
1804 eval "END { local \$! = 0; local \$? = 0;
1805 wait() if kill('KILL', $watchdog); };";
5fe9b82b
JH
1806 return;
1807 }
1808
1809 ### Watchdog process code
087986a7 1810
5fe9b82b
JH
1811 # Load POSIX if available
1812 eval { require POSIX; };
087986a7 1813
5fe9b82b
JH
1814 # Execute the timeout
1815 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1816 sleep(2);
087986a7 1817
5fe9b82b
JH
1818 # Kill test process if still running
1819 if (kill(0, $pid_to_kill)) {
1820 _diag($timeout_msg);
1821 kill('KILL', $pid_to_kill);
1a34b28b
TC
1822 if ($is_cygwin) {
1823 # sometimes the above isn't enough on cygwin
1824 sleep 1; # wait a little, it might have worked after all
bbd21b34 1825 system("/bin/kill -f $pid_to_kill") if kill(0, $pid_to_kill);
1a34b28b 1826 }
5fe9b82b 1827 }
087986a7 1828
5fe9b82b
JH
1829 # Don't execute END block (added at beginning of this file)
1830 $NO_ENDING = 1;
087986a7 1831
5fe9b82b
JH
1832 # Terminate ourself (i.e., the watchdog)
1833 POSIX::_exit(1) if (defined(&POSIX::_exit));
1834 exit(1);
087986a7
JH
1835 }
1836
5fe9b82b 1837 # fork() failed - fall through and try using a thread
087986a7
JH
1838 }
1839
5fe9b82b
JH
1840 # Use a watchdog thread because either 'threads' is loaded,
1841 # or fork() failed
cb01154c 1842 if (eval {require threads; 1}) {
b296285b 1843 'threads'->create(sub {
087986a7
JH
1844 # Load POSIX if available
1845 eval { require POSIX; };
1846
1847 # Execute the timeout
c1c45e36 1848 my $time_left = $timeout;
a6c9a815 1849 do {
11ea18f2 1850 $time_left = $time_left - sleep($time_left);
a6c9a815 1851 } while ($time_left > 0);
087986a7
JH
1852
1853 # Kill the parent (and ourself)
5fe9b82b 1854 select(STDERR); $| = 1;
087986a7
JH
1855 _diag($timeout_msg);
1856 POSIX::_exit(1) if (defined(&POSIX::_exit));
4b0f0df6 1857 my $sig = $is_vms ? 'TERM' : 'KILL';
c1c45e36 1858 kill($sig, $pid_to_kill);
087986a7
JH
1859 })->detach();
1860 return;
1861 }
1862
5fe9b82b 1863 # If everything above fails, then just use an alarm timeout
5732108f 1864WATCHDOG_VIA_ALARM:
087986a7
JH
1865 if (eval { alarm($timeout); 1; }) {
1866 # Load POSIX if available
1867 eval { require POSIX; };
1868
1869 # Alarm handler will do the actual 'killing'
1870 $SIG{'ALRM'} = sub {
5fe9b82b 1871 select(STDERR); $| = 1;
087986a7
JH
1872 _diag($timeout_msg);
1873 POSIX::_exit(1) if (defined(&POSIX::_exit));
4b0f0df6 1874 my $sig = $is_vms ? 'TERM' : 'KILL';
c1c45e36 1875 kill($sig, $pid_to_kill);
087986a7
JH
1876 };
1877 }
1878}
1879
d5c49855
N
1880# Orphaned Docker or Linux containers do not necessarily attach to PID 1. They might attach to 0 instead.
1881sub is_linux_container {
1882
1883 if ($^O eq 'linux' && open my $fh, '<', '/proc/1/cgroup') {
1884 while(<$fh>) {
1885 if (m{^\d+:pids:(.*)} && $1 ne '/init.scope') {
1886 return 1;
1887 }
1888 }
1889 }
1890
1891 return 0;
1892}
1893
69026470 18941;