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