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