This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
t/test.pl: Add comments about runperl vs fresh_perl
[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
90097c2d
KW
747# Since this uses backticks to run, it is subject to the rules of the shell.
748# Locale settings may pose a problem, depending on the program being run.
4cd2bd1f 749sub runperl {
9a731dbd
NC
750 die "test.pl:runperl() does not take a hashref"
751 if ref $_[0] and ref $_[0] eq 'HASH';
4cd2bd1f 752 my $runperl = &_create_runperl;
613de57f
NC
753 my $result;
754
8210c8d3
MB
755 my $tainted = ${^TAINT};
756 my %args = @_;
485f531e 757 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
8210c8d3
MB
758
759 if ($tainted) {
613de57f
NC
760 # We will assume that if you're running under -T, you really mean to
761 # run a fresh perl, so we'll brute force launder everything for you
762 my $sep;
763
cb01154c 764 if (! eval {require Config; 1}) {
613de57f
NC
765 warn "test.pl had problems loading Config: $@";
766 $sep = ':';
767 } else {
afe79e7b 768 $sep = $Config::Config{path_sep};
a70a1627 769 }
613de57f
NC
770
771 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
772 local @ENV{@keys} = ();
773 # Untaint, plus take out . and empty string:
02bb3106 774 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
613de57f 775 $ENV{PATH} =~ /(.*)/s;
8210c8d3 776 local $ENV{PATH} =
3b6d8381 777 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
326b5008 778 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
8210c8d3 779 split quotemeta ($sep), $1;
59aae9bd
JH
780 if ($is_cygwin) { # Must have /bin under Cygwin
781 if (length $ENV{PATH}) {
782 $ENV{PATH} = $ENV{PATH} . $sep;
783 }
784 $ENV{PATH} = $ENV{PATH} . '/bin';
785 }
613de57f
NC
786 $runperl =~ /(.*)/s;
787 $runperl = $1;
788
789 $result = `$runperl`;
790 } else {
791 $result = `$runperl`;
a70a1627 792 }
5b20939a 793 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
137352a2
RGS
794 return $result;
795}
796
140f5369
MS
797# Nice alias
798*run_perl = *run_perl = \&runperl; # shut up "used only once" warning
8799135f 799
c4fbe247 800sub DIE {
3d66076a 801 _print_stderr "# @_\n";
c4fbe247 802 exit 1;
8799135f
MS
803}
804
b5fe401b 805# A somewhat safer version of the sometimes wrong $^X.
17a740d5
JH
806sub which_perl {
807 unless (defined $Perl) {
808 $Perl = $^X;
8210c8d3 809
73421c4a 810 # VMS should have 'perl' aliased properly
4b0f0df6 811 return $Perl if $is_vms;
73421c4a 812
17a740d5 813 my $exe;
cb01154c 814 if (! eval {require Config; 1}) {
17a740d5
JH
815 warn "test.pl had problems loading Config: $@";
816 $exe = '';
85363d30 817 } else {
afe79e7b 818 $exe = $Config::Config{_exe};
85363d30 819 }
da405c16 820 $exe = '' unless defined $exe;
8210c8d3 821
17a740d5
JH
822 # This doesn't absolutize the path: beware of future chdirs().
823 # We could do File::Spec->abs2rel() but that does getcwd()s,
824 # which is a bit heavyweight to do here.
8210c8d3 825
17a740d5 826 if ($Perl =~ /^perl\Q$exe\E$/i) {
8db06b02 827 my $perl = "perl$exe";
cb01154c 828 if (! eval {require File::Spec; 1}) {
17a740d5 829 warn "test.pl had problems loading File::Spec: $@";
8db06b02 830 $Perl = "./$perl";
17a740d5 831 } else {
8db06b02 832 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
17a740d5
JH
833 }
834 }
196918b0
PG
835
836 # Build up the name of the executable file from the name of
837 # the command.
838
839 if ($Perl !~ /\Q$exe\E$/i) {
11ea18f2 840 $Perl = $Perl . $exe;
196918b0 841 }
c880be78 842
8db06b02 843 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
8210c8d3 844
17a740d5
JH
845 # For subcommands to use.
846 $ENV{PERLEXE} = $Perl;
85363d30 847 }
17a740d5 848 return $Perl;
b5fe401b
MS
849}
850
435e7af6 851sub unlink_all {
55b0687d 852 my $count = 0;
435e7af6
NC
853 foreach my $file (@_) {
854 1 while unlink $file;
55b0687d
BG
855 if( -f $file ){
856 _print_stderr "# Couldn't unlink '$file': $!\n";
857 }else{
393b66ef 858 $count = $count + 1; # don't use ++
55b0687d 859 }
435e7af6 860 }
55b0687d 861 $count;
435e7af6 862}
eeabcb2d 863
f6e25e60
BG
864# _num_to_alpha - Returns a string of letters representing a positive integer.
865# Arguments :
866# number to convert
2c36667f 867# maximum number of letters
f6e25e60
BG
868
869# returns undef if the number is negative
2c36667f 870# returns undef if the number of letters is greater than the maximum wanted
f6e25e60
BG
871
872# _num_to_alpha( 0) eq 'A';
873# _num_to_alpha( 1) eq 'B';
874# _num_to_alpha(25) eq 'Z';
875# _num_to_alpha(26) eq 'AA';
876# _num_to_alpha(27) eq 'AB';
877
48e9c5d4
BG
878my @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);
879
f6e25e60
BG
880# Avoid ++ -- ranges split negative numbers
881sub _num_to_alpha{
2c36667f 882 my($num,$max_char) = @_;
f6e25e60
BG
883 return unless $num >= 0;
884 my $alpha = '';
2c36667f
BG
885 my $char_count = 0;
886 $max_char = 0 if $max_char < 0;
887
f6e25e60
BG
888 while( 1 ){
889 $alpha = $letters[ $num % 26 ] . $alpha;
890 $num = int( $num / 26 );
891 last if $num == 0;
892 $num = $num - 1;
2c36667f
BG
893
894 # char limit
895 next unless $max_char;
896 $char_count = $char_count + 1;
897 return if $char_count == $max_char;
f6e25e60
BG
898 }
899 return $alpha;
900}
901
748a4b20
NC
902my %tmpfiles;
903END { unlink_all keys %tmpfiles }
904
905# A regexp that matches the tempfile names
906$::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
c1ddc35c 907
7a7e4936 908# Avoid ++, avoid ranges, avoid split //
7b29226f 909my $tempfile_count = 0;
7a7e4936 910sub tempfile {
7b29226f 911 while(1){
c0a22fcc 912 my $try = (-d "t" ? "t/" : "")."tmp$$";
7b29226f
BG
913 my $alpha = _num_to_alpha($tempfile_count,2);
914 last unless defined $alpha;
915 $try = $try . $alpha;
916 $tempfile_count = $tempfile_count + 1;
917
748a4b20
NC
918 # Need to note all the file names we allocated, as a second request may
919 # come before the first is created.
7b29226f 920 if (!$tmpfiles{$try} && !-e $try) {
c1ddc35c 921 # We have a winner
11ea18f2 922 $tmpfiles{$try} = 1;
c1ddc35c
NC
923 return $try;
924 }
7b29226f 925 }
9a8c1c8c 926 die "Can't find temporary file name starting \"tmp$$\"";
7a7e4936
NC
927}
928
5eccd97a
BG
929# register_tempfile - Adds a list of files to be removed at the end of the current test file
930# Arguments :
931# a list of files to be removed later
932
933# returns a count of how many file names were actually added
934
935# Reuses %tmpfiles so that tempfile() will also skip any files added here
936# even if the file doesn't exist yet.
937
938sub register_tempfile {
939 my $count = 0;
940 for( @_ ){
941 if( $tmpfiles{$_} ){
942 _print_stderr "# Temporary file '$_' already added\n";
943 }else{
944 $tmpfiles{$_} = 1;
945 $count = $count + 1;
946 }
947 }
948 return $count;
949}
950
f6203e99 951# This is the temporary file for fresh_perl
7a7e4936 952my $tmpfile = tempfile();
eeabcb2d 953
f6203e99
KW
954sub fresh_perl {
955 my($prog, $runperl_args) = @_;
956
957 # Run 'runperl' with the complete perl program contained in '$prog', and
958 # arguments in the hash referred to by '$runperl_args'. The results are
959 # returned, with $? set to the exit code. Unless overridden, stderr is
960 # redirected to stdout.
90097c2d
KW
961 #
962 # Placing the program in a file bypasses various sh vagaries
eeabcb2d 963
3c32184e 964 die sprintf "Second argument to fresh_perl_.* must be hashref of args to fresh_perl (or {})"
2a91eb11
DC
965 unless !(defined $runperl_args) || ref($runperl_args) eq 'HASH';
966
11ea18f2
NC
967 # Given the choice of the mis-parsable {}
968 # (we want an anon hash, but a borked lexer might think that it's a block)
969 # or relying on taking a reference to a lexical
970 # (\ might be mis-parsed, and the reference counting on the pad may go
971 # awry)
972 # it feels like the least-worse thing is to assume that auto-vivification
973 # works. At least, this is only going to be a run-time failure, so won't
974 # affect tests using this file but not this function.
c49688b0
MS
975 $runperl_args->{progfile} ||= $tmpfile;
976 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
eeabcb2d 977
1ae6ead9 978 open TEST, '>', $tmpfile or die "Cannot open $tmpfile: $!";
98c155b5 979 binmode TEST, ':utf8' if $runperl_args->{wide_chars};
0d65d7d5 980 print TEST $prog;
eeabcb2d
MS
981 close TEST or die "Cannot close $tmpfile: $!";
982
983 my $results = runperl(%$runperl_args);
f6203e99
KW
984 my $status = $?; # Not necessary to save this, but it makes it clear to
985 # future maintainers.
eeabcb2d
MS
986
987 # Clean up the results into something a bit more predictable.
50f17f89 988 $results =~ s/\n+$//;
748a4b20
NC
989 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
990 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
eeabcb2d
MS
991
992 # bison says 'parse error' instead of 'syntax error',
993 # various yaccs may or may not capitalize 'syntax'.
994 $results =~ s/^(syntax|parse) error/syntax error/mig;
995
4b0f0df6 996 if ($is_vms) {
eeabcb2d
MS
997 # some tests will trigger VMS messages that won't be expected
998 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
999
1000 # pipes double these sometimes
1001 $results =~ s/\n\n/\n/g;
1002 }
1003
f6203e99
KW
1004 $? = $status;
1005 return $results;
1006}
1007
1008
1009sub _fresh_perl {
1010 my($prog, $action, $expect, $runperl_args, $name) = @_;
1011
1012 my $results = fresh_perl($prog, $runperl_args);
1013 my $status = $?;
1014
e2c38acd
JH
1015 # Use the first line of the program as a name if none was given
1016 unless( $name ) {
1017 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
11ea18f2 1018 $name = $name . '...' if length $first_line > length $name;
e2c38acd 1019 }
eeabcb2d 1020
55280a0d
NC
1021 # Historically this was implemented using a closure, but then that means
1022 # that the tests for closures avoid using this code. Given that there
1023 # are exactly two callers, doing exactly two things, the simpler approach
1024 # feels like a better trade off.
1025 my $pass;
1026 if ($action eq 'eq') {
1027 $pass = is($results, $expect, $name);
1028 } elsif ($action eq '=~') {
1029 $pass = like($results, $expect, $name);
1030 } else {
1031 die "_fresh_perl can't process action '$action'";
1032 }
1033
1034 unless ($pass) {
1035 _diag "# PROG: \n$prog\n";
1036 _diag "# STATUS: $status\n";
1037 }
1038
1039 return $pass;
f5cda331
JH
1040}
1041
1042#
141f445b 1043# fresh_perl_is
f5cda331
JH
1044#
1045# Combination of run_perl() and is().
1046#
1047
1048sub fresh_perl_is {
1049 my($prog, $expected, $runperl_args, $name) = @_;
50f17f89
MS
1050
1051 # _fresh_perl() is going to clip the trailing newlines off the result.
1052 # This will make it so the test author doesn't have to know that.
1053 $expected =~ s/\n+$//;
1054
dcc7f481 1055 local $Level = 2;
55280a0d 1056 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
f5cda331
JH
1057}
1058
1059#
141f445b 1060# fresh_perl_like
f5cda331
JH
1061#
1062# Combination of run_perl() and like().
1063#
1064
1065sub fresh_perl_like {
1066 my($prog, $expected, $runperl_args, $name) = @_;
dcc7f481 1067 local $Level = 2;
55280a0d 1068 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
eeabcb2d
MS
1069}
1070
ebf2da99
NC
1071# Many tests use the same format in __DATA__ or external files to specify a
1072# sequence of (fresh) tests to run, extra files they may temporarily need, and
ebcaaa39
KW
1073# what the expected output is. Putting it here allows common code to serve
1074# these multiple tests.
a8775356
TC
1075#
1076# Each program is source code to run followed by an "EXPECT" line, followed
1077# by the expected output.
1078#
88d057ad
KW
1079# The first line of the code to run may be a command line switch such as -wE
1080# or -0777 (alphanumerics only; only one cluster, beginning with a minus is
1081# allowed). Later lines may contain (note the '# ' on each):
a8775356
TC
1082# # TODO reason for todo
1083# # SKIP reason for skip
1084# # SKIP ?code to test if this should be skipped
1085# # NAME name of the test (as with ok($ok, $name))
1086#
1087# The expected output may contain:
1088# OPTION list of options
1089# OPTIONS list of options
a8775356
TC
1090#
1091# The possible options for OPTION may be:
1092# regex - the expected output is a regular expression
1093# random - all lines match but in any order
1094# fatal - the code will fail fatally (croak, die)
1095#
1096# If the actual output contains a line "SKIPPED" the test will be
1097# skipped.
1098#
708e0e1d
KW
1099# If the actual output contains a line "PREFIX", any output starting with that
1100# line will be ignored when comparing with the expected output
1101#
a8775356
TC
1102# If the global variable $FATAL is true then OPTION fatal is the
1103# default.
ebf2da99 1104
9f5237ac
NC
1105sub _setup_one_file {
1106 my $fh = shift;
41732369
NC
1107 # Store the filename as a program that started at line 0.
1108 # Real files count lines starting at line 1.
1109 my @these = (0, shift);
1110 my ($lineno, $current);
1111 while (<$fh>) {
1112 if ($_ eq "########\n") {
1113 if (defined $current) {
1114 push @these, $lineno, $current;
1115 }
1116 undef $current;
1117 } else {
1118 if (!defined $current) {
1119 $lineno = $.;
1120 }
1121 $current .= $_;
1122 }
1123 }
1124 if (defined $current) {
1125 push @these, $lineno, $current;
1126 }
1127 ((scalar @these) / 2 - 1, @these);
9f5237ac
NC
1128}
1129
fdb35a63
NC
1130sub setup_multiple_progs {
1131 my ($tests, @prgs);
1132 foreach my $file (@_) {
1133 next if $file =~ /(?:~|\.orig|,v)$/;
1134 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1135 next if -d $file;
1136
1137 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1138 my $found;
1139 while (<$fh>) {
1140 if (/^__END__/) {
393b66ef 1141 $found = $found + 1; # don't use ++
fdb35a63
NC
1142 last;
1143 }
1144 }
1145 # This is an internal error, and should never happen. All bar one of
1146 # the files had an __END__ marker to signal the end of their preamble,
1147 # although for some it wasn't technically necessary as they have no
1148 # tests. It might be possible to process files without an __END__ by
1149 # seeking back to the start and treating the whole file as tests, but
1150 # it's simpler and more reliable just to make the rule that all files
1151 # must have __END__ in. This should never fail - a file without an
1152 # __END__ should not have been checked in, because the regression tests
1153 # would not have passed.
1154 die "Could not find '__END__' in $file"
1155 unless $found;
1156
41732369 1157 my ($t, @p) = _setup_one_file($fh, $file);
9f5237ac 1158 $tests += $t;
41732369 1159 push @prgs, @p;
fdb35a63
NC
1160
1161 close $fh
1162 or die "Cannot close $file: $!\n";
1163 }
1164 return ($tests, @prgs);
1165}
1166
ebf2da99 1167sub run_multiple_progs {
5f7e0818
NC
1168 my $up = shift;
1169 my @prgs;
1170 if ($up) {
1171 # The tests in lib run in a temporary subdirectory of t, and always
1172 # pass in a list of "programs" to run
1173 @prgs = @_;
1174 } else {
41732369
NC
1175 # The tests below t run in t and pass in a file handle. In theory we
1176 # can pass (caller)[1] as the second argument to report errors with
1177 # the filename of our caller, as the handle is always DATA. However,
1178 # line numbers in DATA count from the __END__ token, so will be wrong.
1179 # Which is more confusing than not providing line numbers. So, for now,
1180 # don't provide line numbers. No obvious clean solution - one hack
1181 # would be to seek DATA back to the start and read to the __END__ token,
1182 # but that feels almost like we should just open $0 instead.
1183
9f5237ac
NC
1184 # Not going to rely on undef in list assignment.
1185 my $dummy;
1186 ($dummy, @prgs) = _setup_one_file(shift);
5f7e0818
NC
1187 }
1188
ebf2da99
NC
1189 my $tmpfile = tempfile();
1190
41732369 1191 my ($file, $line);
c0044231 1192 PROGRAM:
41732369
NC
1193 while (defined ($line = shift @prgs)) {
1194 $_ = shift @prgs;
1195 unless ($line) {
1196 $file = $_;
1197 if (defined $file) {
1198 print "# From $file\n";
1199 }
ebf2da99
NC
1200 next;
1201 }
1202 my $switch = "";
1203 my @temps ;
1204 my @temp_path;
1205 if (s/^(\s*-\w+)//) {
1206 $switch = $1;
1207 }
1208 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1209
1210 my %reason;
1211 foreach my $what (qw(skip todo)) {
1212 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1213 # If the SKIP reason starts ? then it's taken as a code snippet to
1214 # evaluate. This provides the flexibility to have conditional SKIPs
1215 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1216 my $temp = eval $reason{$what};
1217 if ($@) {
1218 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1219 }
1220 $reason{$what} = $temp;
1221 }
1222 }
c0044231 1223
59e38755
TC
1224 my $name = '';
1225 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1226 $name = $1;
1227 }
ebf2da99 1228
c0044231
TC
1229 if ($reason{skip}) {
1230 SKIP:
1231 {
1232 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1233 }
1234 next PROGRAM;
1235 }
1236
ebf2da99 1237 if ($prog =~ /--FILE--/) {
e330f831 1238 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
ebf2da99
NC
1239 shift @files ;
1240 die "Internal error: test $_ didn't split into pairs, got " .
1241 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1242 if @files % 2;
1243 while (@files > 2) {
1244 my $filename = shift @files;
1245 my $code = shift @files;
1246 push @temps, $filename;
1247 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1248 require File::Path;
1249 File::Path::mkpath($1);
1250 push(@temp_path, $1);
1251 }
1252 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1253 print $fh $code;
1254 close $fh or die "Cannot close $filename: $!\n";
1255 }
1256 shift @files;
1257 $prog = shift @files;
1258 }
1259
1260 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1261 print $fh q{
1262 BEGIN {
3d7c117d 1263 push @INC, '.';
ebf2da99
NC
1264 open STDERR, '>&', STDOUT
1265 or die "Can't dup STDOUT->STDERR: $!;";
1266 }
1267 };
1268 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1269 print $fh $prog,"\n";
1270 close $fh or die "Cannot close $tmpfile: $!";
684b0eca 1271 my $results = runperl( stderr => 1, progfile => $tmpfile,
53f2736e 1272 stdin => undef, $up
5f7e0818
NC
1273 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1274 : (switches => [$switch])
1275 );
ebf2da99
NC
1276 my $status = $?;
1277 $results =~ s/\n+$//;
1278 # allow expected output to be written as if $prog is on STDIN
1279 $results =~ s/$::tempfile_regexp/-/g;
1280 if ($^O eq 'VMS') {
1281 # some tests will trigger VMS messages that won't be expected
1282 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1283
1284 # pipes double these sometimes
1285 $results =~ s/\n\n/\n/g;
1286 }
1287 # bison says 'parse error' instead of 'syntax error',
1288 # various yaccs may or may not capitalize 'syntax'.
1289 $results =~ s/^(syntax|parse) error/syntax error/mig;
1290 # allow all tests to run when there are leaks
1291 $results =~ s/Scalars leaked: \d+\n//g;
1292
1293 $expected =~ s/\n+$//;
1294 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1295 # any special options? (OPTIONS foo bar zap)
1296 my $option_regex = 0;
1297 my $option_random = 0;
59e38755 1298 my $fatal = $FATAL;
ebf2da99
NC
1299 if ($expected =~ s/^OPTIONS? (.+)\n//) {
1300 foreach my $option (split(' ', $1)) {
1301 if ($option eq 'regex') { # allow regular expressions
1302 $option_regex = 1;
1303 }
1304 elsif ($option eq 'random') { # all lines match, but in any order
1305 $option_random = 1;
1306 }
59e38755
TC
1307 elsif ($option eq 'fatal') { # perl should fail
1308 $fatal = 1;
1309 }
ebf2da99
NC
1310 else {
1311 die "$0: Unknown OPTION '$option'\n";
1312 }
1313 }
1314 }
1315 die "$0: can't have OPTION regex and random\n"
1316 if $option_regex + $option_random > 1;
1317 my $ok = 0;
1318 if ($results =~ s/^SKIPPED\n//) {
1319 print "$results\n" ;
1320 $ok = 1;
1321 }
ebf2da99 1322 else {
59e38755
TC
1323 if ($option_random) {
1324 my @got = sort split "\n", $results;
1325 my @expected = sort split "\n", $expected;
1326
1327 $ok = "@got" eq "@expected";
1328 }
1329 elsif ($option_regex) {
1330 $ok = $results =~ /^$expected/;
1331 }
1332 elsif ($prefix) {
1333 $ok = $results =~ /^\Q$expected/;
1334 }
1335 else {
1336 $ok = $results eq $expected;
1337 }
1338
1339 if ($ok && $fatal && !($status >> 8)) {
1340 $ok = 0;
1341 }
ebf2da99
NC
1342 }
1343
1344 local $::TODO = $reason{todo};
1345
1346 unless ($ok) {
1347 my $err_line = "PROG: $switch\n$prog\n" .
59e38755
TC
1348 "EXPECTED:\n$expected\n";
1349 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1350 $err_line .= "GOT:\n$results\n";
1351 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
ebf2da99
NC
1352 if ($::TODO) {
1353 $err_line =~ s/^/# /mg;
1354 print $err_line; # Harness can't filter it out from STDERR.
1355 }
1356 else {
1357 print STDERR $err_line;
1358 }
1359 }
1360
41732369
NC
1361 if (defined $file) {
1362 _ok($ok, "at $file line $line", $name);
1363 } else {
1364 # We don't have file and line number data for the test, so report
1365 # errors as coming from our caller.
1366 local $Level = $Level + 1;
1367 ok($ok, $name);
1368 }
ebf2da99
NC
1369
1370 foreach (@temps) {
1371 unlink $_ if $_;
1372 }
1373 foreach (@temp_path) {
1374 File::Path::rmtree $_ if -d $_;
1375 }
1376 }
1377}
1378
35a60386
RGS
1379sub can_ok ($@) {
1380 my($proto, @methods) = @_;
1381 my $class = ref $proto || $proto;
1382
1383 unless( @methods ) {
1384 return _ok( 0, _where(), "$class->can(...)" );
1385 }
1386
1387 my @nok = ();
1388 foreach my $method (@methods) {
1389 local($!, $@); # don't interfere with caller's $@
1390 # eval sometimes resets $!
1391 eval { $proto->can($method) } || push @nok, $method;
1392 }
1393
1394 my $name;
8210c8d3 1395 $name = @methods == 1 ? "$class->can('$methods[0]')"
35a60386 1396 : "$class->can(...)";
8210c8d3 1397
35a60386
RGS
1398 _ok( !@nok, _where(), $name );
1399}
1400
ad4e703e 1401
bbce3ca6 1402# Call $class->new( @$args ); and run the result through object_ok.
ad4e703e
MS
1403# See Test::More::new_ok
1404sub new_ok {
1405 my($class, $args, $obj_name) = @_;
1406 $args ||= [];
1407 $object_name = "The object" unless defined $obj_name;
1408
1409 local $Level = $Level + 1;
1410
1411 my $obj;
1412 my $ok = eval { $obj = $class->new(@$args); 1 };
1413 my $error = $@;
1414
1415 if($ok) {
bbce3ca6 1416 object_ok($obj, $class, $object_name);
ad4e703e
MS
1417 }
1418 else {
1419 ok( 0, "new() died" );
1420 diag("Error was: $@");
1421 }
1422
1423 return $obj;
1424
1425}
1426
1427
35a60386
RGS
1428sub isa_ok ($$;$) {
1429 my($object, $class, $obj_name) = @_;
1430
1431 my $diag;
1432 $obj_name = 'The object' unless defined $obj_name;
1433 my $name = "$obj_name isa $class";
1434 if( !defined $object ) {
1435 $diag = "$obj_name isn't defined";
1436 }
35a60386 1437 else {
b8ab4b0c
MS
1438 my $whatami = ref $object ? 'object' : 'class';
1439
35a60386
RGS
1440 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1441 local($@, $!); # eval sometimes resets $!
1442 my $rslt = eval { $object->isa($class) };
b8ab4b0c
MS
1443 my $error = $@; # in case something else blows away $@
1444
1445 if( $error ) {
1446 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1447 # It's an unblessed reference
1448 $obj_name = 'The reference' unless defined $obj_name;
35a60386
RGS
1449 if( !UNIVERSAL::isa($object, $class) ) {
1450 my $ref = ref $object;
1451 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1452 }
b8ab4b0c
MS
1453 }
1454 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1455 # It's something that can't even be a class
1456 $obj_name = 'The thing' unless defined $obj_name;
1457 $diag = "$obj_name isn't a class or reference";
1458 }
1459 else {
35a60386
RGS
1460 die <<WHOA;
1461WHOA! I tried to call ->isa on your object and got some weird error.
1462This should never happen. Please contact the author immediately.
1463Here's the error.
1464$@
1465WHOA
1466 }
1467 }
1468 elsif( !$rslt ) {
b8ab4b0c 1469 $obj_name = "The $whatami" unless defined $obj_name;
35a60386
RGS
1470 my $ref = ref $object;
1471 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1472 }
1473 }
1474
1475 _ok( !$diag, _where(), $name );
1476}
1477
bbce3ca6
MS
1478
1479sub class_ok {
1480 my($class, $isa, $class_name) = @_;
1481
1482 # Written so as to count as one test
1483 local $Level = $Level + 1;
1484 if( ref $class ) {
5c25e937 1485 ok( 0, "$class is a reference, not a class name" );
bbce3ca6
MS
1486 }
1487 else {
1488 isa_ok($class, $isa, $class_name);
1489 }
1490}
1491
1492
1493sub object_ok {
1494 my($obj, $isa, $obj_name) = @_;
1495
1496 local $Level = $Level + 1;
1497 if( !ref $obj ) {
1498 ok( 0, "$obj is not a reference" );
1499 }
1500 else {
1501 isa_ok($obj, $isa, $obj_name);
1502 }
1503}
1504
1505
9eb41b69
NC
1506# Purposefully avoiding a closure.
1507sub __capture {
1508 push @::__capture, join "", @_;
1509}
1510
3fbaac97
NC
1511sub capture_warnings {
1512 my $code = shift;
1513
9eb41b69
NC
1514 local @::__capture;
1515 local $SIG {__WARN__} = \&__capture;
7d3a9a28 1516 local $Level = 1;
3fbaac97 1517 &$code;
9eb41b69 1518 return @::__capture;
3fbaac97
NC
1519}
1520
1521# This will generate a variable number of tests.
1522# Use done_testing() instead of a fixed plan.
1523sub warnings_like {
1524 my ($code, $expect, $name) = @_;
f4554ed5
NC
1525 local $Level = $Level + 1;
1526
3fbaac97
NC
1527 my @w = capture_warnings($code);
1528
1529 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1530 foreach my $e (@$expect) {
f4554ed5 1531 if (ref $e) {
3fbaac97 1532 like(shift @w, $e, $name);
4d18b353 1533 } else {
3fbaac97 1534 is(shift @w, $e, $name);
4d18b353 1535 }
96980024 1536 }
3fbaac97
NC
1537 if (@w) {
1538 diag("Saw these additional warnings:");
1539 diag($_) foreach @w;
1540 }
1541}
1542
1543sub _fail_excess_warnings {
1544 my($expect, $got, $name) = @_;
1545 local $Level = $Level + 1;
1546 # This will fail, and produce diagnostics
1547 is($expect, scalar @$got, $name);
1548 diag("Saw these warnings:");
1549 diag($_) foreach @$got;
c11a8df3
NC
1550}
1551
4d18b353
NC
1552sub warning_is {
1553 my ($code, $expect, $name) = @_;
1554 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1555 if ref $expect;
f4554ed5 1556 local $Level = $Level + 1;
3fbaac97
NC
1557 my @w = capture_warnings($code);
1558 if (@w > 1) {
1559 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1560 } else {
1561 is($w[0], $expect, $name);
1562 }
4d18b353
NC
1563}
1564
1565sub warning_like {
1566 my ($code, $expect, $name) = @_;
1567 die sprintf "Expect must be a regexp object"
1568 unless ref $expect eq 'Regexp';
f4554ed5 1569 local $Level = $Level + 1;
3fbaac97
NC
1570 my @w = capture_warnings($code);
1571 if (@w > 1) {
1572 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1573 } else {
1574 like($w[0], $expect, $name);
1575 }
4d18b353
NC
1576}
1577
087986a7 1578# Set a watchdog to timeout the entire test file
5fe9b82b
JH
1579# NOTE: If the test file uses 'threads', then call the watchdog() function
1580# _AFTER_ the 'threads' module is loaded.
5732108f 1581sub watchdog ($;$)
087986a7
JH
1582{
1583 my $timeout = shift;
36436324 1584 my $method = shift || "";
087986a7
JH
1585 my $timeout_msg = 'Test process timed out - terminating';
1586
e07ce2e4
GG
1587 # Valgrind slows perl way down so give it more time before dying.
1588 $timeout *= 10 if $ENV{PERL_VALGRIND};
1589
087986a7
JH
1590 my $pid_to_kill = $$; # PID for this process
1591
5732108f
GG
1592 if ($method eq "alarm") {
1593 goto WATCHDOG_VIA_ALARM;
1594 }
1595
140f5369
MS
1596 # shut up use only once warning
1597 my $threads_on = $threads::threads && $threads::threads;
1598
5fe9b82b
JH
1599 # Don't use a watchdog process if 'threads' is loaded -
1600 # use a watchdog thread instead
78325d7a 1601 if (!$threads_on || $method eq "process") {
5fe9b82b
JH
1602
1603 # On Windows and VMS, try launching a watchdog process
1604 # using system(1, ...) (see perlport.pod)
4b0f0df6 1605 if ($is_mswin || $is_vms) {
5fe9b82b 1606 # On Windows, try to get the 'real' PID
4b0f0df6 1607 if ($is_mswin) {
5fe9b82b
JH
1608 eval { require Win32; };
1609 if (defined(&Win32::GetCurrentProcessId)) {
1610 $pid_to_kill = Win32::GetCurrentProcessId();
1611 }
087986a7 1612 }
087986a7 1613
5fe9b82b
JH
1614 # If we still have a fake PID, we can't use this method at all
1615 return if ($pid_to_kill <= 0);
1616
1617 # Launch watchdog process
1618 my $watchdog;
1619 eval {
1620 local $SIG{'__WARN__'} = sub {
1621 _diag("Watchdog warning: $_[0]");
1622 };
4b0f0df6 1623 my $sig = $is_vms ? 'TERM' : 'KILL';
a68d0dcb
SH
1624 my $prog = "sleep($timeout);" .
1625 "warn qq/# $timeout_msg" . '\n/;' .
1626 "kill(q/$sig/, $pid_to_kill);";
1627
1628 # On Windows use the indirect object plus LIST form to guarantee
1629 # that perl is launched directly rather than via the shell (see
1630 # perlfunc.pod), and ensure that the LIST has multiple elements
1631 # since the indirect object plus COMMANDSTRING form seems to
1632 # hang (see perl #121283). Don't do this on VMS, which doesn't
1633 # support the LIST form at all.
1634 if ($is_mswin) {
1635 my $runperl = which_perl();
1636 if ($runperl =~ m/\s/) {
1637 $runperl = qq{"$runperl"};
1638 }
1639 $watchdog = system({ $runperl } 1, $runperl, '-e', $prog);
1640 }
1641 else {
1642 my $cmd = _create_runperl(prog => $prog);
1643 $watchdog = system(1, $cmd);
1644 }
5fe9b82b
JH
1645 };
1646 if ($@ || ($watchdog <= 0)) {
1647 _diag('Failed to start watchdog');
1648 _diag($@) if $@;
1649 undef($watchdog);
1650 return;
1651 }
087986a7 1652
5fe9b82b
JH
1653 # Add END block to parent to terminate and
1654 # clean up watchdog process
a68d0dcb 1655 eval("END { local \$! = 0; local \$? = 0;
18ae2abf 1656 wait() if kill('KILL', $watchdog); };");
5fe9b82b 1657 return;
087986a7 1658 }
087986a7 1659
5fe9b82b
JH
1660 # Try using fork() to generate a watchdog process
1661 my $watchdog;
1662 eval { $watchdog = fork() };
1663 if (defined($watchdog)) {
1664 if ($watchdog) { # Parent process
1665 # Add END block to parent to terminate and
1666 # clean up watchdog process
7e1027b9
JH
1667 eval "END { local \$! = 0; local \$? = 0;
1668 wait() if kill('KILL', $watchdog); };";
5fe9b82b
JH
1669 return;
1670 }
1671
1672 ### Watchdog process code
087986a7 1673
5fe9b82b
JH
1674 # Load POSIX if available
1675 eval { require POSIX; };
087986a7 1676
5fe9b82b
JH
1677 # Execute the timeout
1678 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1679 sleep(2);
087986a7 1680
5fe9b82b
JH
1681 # Kill test process if still running
1682 if (kill(0, $pid_to_kill)) {
1683 _diag($timeout_msg);
1684 kill('KILL', $pid_to_kill);
1a34b28b
TC
1685 if ($is_cygwin) {
1686 # sometimes the above isn't enough on cygwin
1687 sleep 1; # wait a little, it might have worked after all
1688 system("/bin/kill -f $pid_to_kill");
1689 }
5fe9b82b 1690 }
087986a7 1691
5fe9b82b
JH
1692 # Don't execute END block (added at beginning of this file)
1693 $NO_ENDING = 1;
087986a7 1694
5fe9b82b
JH
1695 # Terminate ourself (i.e., the watchdog)
1696 POSIX::_exit(1) if (defined(&POSIX::_exit));
1697 exit(1);
087986a7
JH
1698 }
1699
5fe9b82b 1700 # fork() failed - fall through and try using a thread
087986a7
JH
1701 }
1702
5fe9b82b
JH
1703 # Use a watchdog thread because either 'threads' is loaded,
1704 # or fork() failed
cb01154c 1705 if (eval {require threads; 1}) {
b296285b 1706 'threads'->create(sub {
087986a7
JH
1707 # Load POSIX if available
1708 eval { require POSIX; };
1709
1710 # Execute the timeout
c1c45e36 1711 my $time_left = $timeout;
a6c9a815 1712 do {
11ea18f2 1713 $time_left = $time_left - sleep($time_left);
a6c9a815 1714 } while ($time_left > 0);
087986a7
JH
1715
1716 # Kill the parent (and ourself)
5fe9b82b 1717 select(STDERR); $| = 1;
087986a7
JH
1718 _diag($timeout_msg);
1719 POSIX::_exit(1) if (defined(&POSIX::_exit));
4b0f0df6 1720 my $sig = $is_vms ? 'TERM' : 'KILL';
c1c45e36 1721 kill($sig, $pid_to_kill);
087986a7
JH
1722 })->detach();
1723 return;
1724 }
1725
5fe9b82b 1726 # If everything above fails, then just use an alarm timeout
5732108f 1727WATCHDOG_VIA_ALARM:
087986a7
JH
1728 if (eval { alarm($timeout); 1; }) {
1729 # Load POSIX if available
1730 eval { require POSIX; };
1731
1732 # Alarm handler will do the actual 'killing'
1733 $SIG{'ALRM'} = sub {
5fe9b82b 1734 select(STDERR); $| = 1;
087986a7
JH
1735 _diag($timeout_msg);
1736 POSIX::_exit(1) if (defined(&POSIX::_exit));
4b0f0df6 1737 my $sig = $is_vms ? 'TERM' : 'KILL';
c1c45e36 1738 kill($sig, $pid_to_kill);
087986a7
JH
1739 };
1740 }
1741}
1742
d5c49855
N
1743# Orphaned Docker or Linux containers do not necessarily attach to PID 1. They might attach to 0 instead.
1744sub is_linux_container {
1745
1746 if ($^O eq 'linux' && open my $fh, '<', '/proc/1/cgroup') {
1747 while(<$fh>) {
1748 if (m{^\d+:pids:(.*)} && $1 ne '/init.scope') {
1749 return 1;
1750 }
1751 }
1752 }
1753
1754 return 0;
1755}
1756
69026470 17571;