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