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