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