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