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