This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Test that tempfile() in t/test.pl skips files that already exist
[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
PAR
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)
137352a2
RGS
567# stderr => redirect stderr to stdout
568# args => [ command-line arguments to the perl program ]
cb9c5e20 569# verbose => print the command line
137352a2
RGS
570
571my $is_mswin = $^O eq 'MSWin32';
572my $is_netware = $^O eq 'NetWare';
137352a2 573my $is_vms = $^O eq 'VMS';
e67ed694 574my $is_cygwin = $^O eq 'cygwin';
137352a2 575
cb9c5e20
JH
576sub _quote_args {
577 my ($runperl, $args) = @_;
578
579 foreach (@$args) {
580 # In VMS protect with doublequotes because otherwise
581 # DCL will lowercase -- unless already doublequoted.
ea9ac5ad 582 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
1cce9906 583 $runperl = $runperl . ' ' . $_;
cb9c5e20 584 }
1cce9906 585 return $runperl;
cb9c5e20
JH
586}
587
4cd2bd1f 588sub _create_runperl { # Create the string to qx in runperl().
137352a2 589 my %args = @_;
5fe9b82b
JH
590 my $runperl = which_perl();
591 if ($runperl =~ m/\s/) {
592 $runperl = qq{"$runperl"};
593 }
6cf707aa
RGS
594 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
595 if ($ENV{PERL_RUNPERL_DEBUG}) {
596 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
597 }
f93a5f07 598 unless ($args{nolib}) {
11ea18f2 599 $runperl = $runperl . ' "-I../lib"'; # doublequotes because of VMS
137352a2 600 }
d83945bc 601 if ($args{switches}) {
343d4a7b
JH
602 local $Level = 2;
603 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
604 unless ref $args{switches} eq "ARRAY";
1cce9906 605 $runperl = _quote_args($runperl, $args{switches});
d83945bc 606 }
137352a2 607 if (defined $args{prog}) {
21820af6
JH
608 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
609 if defined $args{progs};
d83945bc
A
610 $args{progs} = [$args{prog}]
611 }
612 if (defined $args{progs}) {
21820af6
JH
613 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
614 unless ref $args{progs} eq "ARRAY";
d83945bc 615 foreach my $prog (@{$args{progs}}) {
ecadf9b7
FC
616 if (!$args{non_portable}) {
617 if ($prog =~ tr/'"//) {
618 warn "quotes in prog >>$prog<< are not portable";
619 }
620 if ($prog =~ /^([<>|]|2>)/) {
621 warn "Initial $1 in prog >>$prog<< is not portable";
622 }
623 if ($prog =~ /&\z/) {
624 warn "Trailing & in prog >>$prog<< is not portable";
625 }
3d7a9343 626 }
d83945bc 627 if ($is_mswin || $is_netware || $is_vms) {
11ea18f2 628 $runperl = $runperl . qq ( -e "$prog" );
d83945bc
A
629 }
630 else {
11ea18f2 631 $runperl = $runperl . qq ( -e '$prog' );
d83945bc
A
632 }
633 }
137352a2 634 } elsif (defined $args{progfile}) {
11ea18f2 635 $runperl = $runperl . qq( "$args{progfile}");
9a731dbd 636 } else {
93f09d7b 637 # You probably didn't want to be sucking in from the upstream stdin
9a731dbd
NC
638 die "test.pl:runperl(): none of prog, progs, progfile, args, "
639 . " switches or stdin specified"
640 unless defined $args{args} or defined $args{switches}
641 or defined $args{stdin};
137352a2
RGS
642 }
643 if (defined $args{stdin}) {
dc459aad
JH
644 # so we don't try to put literal newlines and crs onto the
645 # command line.
646 $args{stdin} =~ s/\n/\\n/g;
647 $args{stdin} =~ s/\r/\\r/g;
5ae09a77 648
137352a2 649 if ($is_mswin || $is_netware || $is_vms) {
5fe9b82b 650 $runperl = qq{$Perl -e "print qq(} .
137352a2
RGS
651 $args{stdin} . q{)" | } . $runperl;
652 }
653 else {
5fe9b82b 654 $runperl = qq{$Perl -e 'print qq(} .
137352a2
RGS
655 $args{stdin} . q{)' | } . $runperl;
656 }
53f2736e
NC
657 } elsif (exists $args{stdin}) {
658 # Using the pipe construction above can cause fun on systems which use
659 # ksh as /bin/sh, as ksh does pipes differently (with one less process)
660 # With sh, for the command line 'perl -e 'print qq()' | perl -e ...'
661 # the sh process forks two children, which use exec to start the two
662 # perl processes. The parent shell process persists for the duration of
663 # the pipeline, and the second perl process starts with no children.
664 # With ksh (and zsh), the shell saves a process by forking a child for
665 # just the first perl process, and execing itself to start the second.
666 # This means that the second perl process starts with one child which
667 # it didn't create. This causes "fun" when if the tests assume that
668 # wait (or waitpid) will only return information about processes
669 # started within the test.
670 # They also cause fun on VMS, where the pipe implementation returns
671 # the exit code of the process at the front of the pipeline, not the
672 # end. This messes up any test using OPTION FATAL.
673 # Hence it's useful to have a way to make STDIN be at eof without
674 # needing a pipeline, so that the fork tests have a sane environment
675 # without these surprises.
676
677 # /dev/null appears to be surprisingly portable.
678 $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null');
137352a2
RGS
679 }
680 if (defined $args{args}) {
1cce9906 681 $runperl = _quote_args($runperl, $args{args});
cb9c5e20 682 }
11ea18f2 683 $runperl = $runperl . ' 2>&1' if $args{stderr};
cb9c5e20
JH
684 if ($args{verbose}) {
685 my $runperldisplay = $runperl;
686 $runperldisplay =~ s/\n/\n\#/g;
3d66076a 687 _print_stderr "# $runperldisplay\n";
137352a2 688 }
4cd2bd1f
JH
689 return $runperl;
690}
691
692sub runperl {
9a731dbd
NC
693 die "test.pl:runperl() does not take a hashref"
694 if ref $_[0] and ref $_[0] eq 'HASH';
4cd2bd1f 695 my $runperl = &_create_runperl;
613de57f
NC
696 my $result;
697
8210c8d3
MB
698 my $tainted = ${^TAINT};
699 my %args = @_;
485f531e 700 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
8210c8d3
MB
701
702 if ($tainted) {
613de57f
NC
703 # We will assume that if you're running under -T, you really mean to
704 # run a fresh perl, so we'll brute force launder everything for you
705 my $sep;
706
cb01154c 707 if (! eval {require Config; 1}) {
613de57f
NC
708 warn "test.pl had problems loading Config: $@";
709 $sep = ':';
710 } else {
afe79e7b 711 $sep = $Config::Config{path_sep};
a70a1627 712 }
613de57f
NC
713
714 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
715 local @ENV{@keys} = ();
716 # Untaint, plus take out . and empty string:
02bb3106 717 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
613de57f 718 $ENV{PATH} =~ /(.*)/s;
8210c8d3 719 local $ENV{PATH} =
3b6d8381 720 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
326b5008 721 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
8210c8d3 722 split quotemeta ($sep), $1;
59aae9bd
JH
723 if ($is_cygwin) { # Must have /bin under Cygwin
724 if (length $ENV{PATH}) {
725 $ENV{PATH} = $ENV{PATH} . $sep;
726 }
727 $ENV{PATH} = $ENV{PATH} . '/bin';
728 }
613de57f
NC
729 $runperl =~ /(.*)/s;
730 $runperl = $1;
731
732 $result = `$runperl`;
733 } else {
734 $result = `$runperl`;
a70a1627 735 }
5b20939a 736 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these
137352a2
RGS
737 return $result;
738}
739
140f5369
MS
740# Nice alias
741*run_perl = *run_perl = \&runperl; # shut up "used only once" warning
8799135f 742
c4fbe247 743sub DIE {
3d66076a 744 _print_stderr "# @_\n";
c4fbe247 745 exit 1;
8799135f
MS
746}
747
b5fe401b 748# A somewhat safer version of the sometimes wrong $^X.
17a740d5
JH
749sub which_perl {
750 unless (defined $Perl) {
751 $Perl = $^X;
8210c8d3 752
73421c4a 753 # VMS should have 'perl' aliased properly
4b0f0df6 754 return $Perl if $is_vms;
73421c4a 755
17a740d5 756 my $exe;
cb01154c 757 if (! eval {require Config; 1}) {
17a740d5
JH
758 warn "test.pl had problems loading Config: $@";
759 $exe = '';
85363d30 760 } else {
afe79e7b 761 $exe = $Config::Config{_exe};
85363d30 762 }
da405c16 763 $exe = '' unless defined $exe;
8210c8d3 764
17a740d5
JH
765 # This doesn't absolutize the path: beware of future chdirs().
766 # We could do File::Spec->abs2rel() but that does getcwd()s,
767 # which is a bit heavyweight to do here.
8210c8d3 768
17a740d5 769 if ($Perl =~ /^perl\Q$exe\E$/i) {
8db06b02 770 my $perl = "perl$exe";
cb01154c 771 if (! eval {require File::Spec; 1}) {
17a740d5 772 warn "test.pl had problems loading File::Spec: $@";
8db06b02 773 $Perl = "./$perl";
17a740d5 774 } else {
8db06b02 775 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
17a740d5
JH
776 }
777 }
196918b0
PG
778
779 # Build up the name of the executable file from the name of
780 # the command.
781
782 if ($Perl !~ /\Q$exe\E$/i) {
11ea18f2 783 $Perl = $Perl . $exe;
196918b0 784 }
c880be78 785
8db06b02 786 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
8210c8d3 787
17a740d5
JH
788 # For subcommands to use.
789 $ENV{PERLEXE} = $Perl;
85363d30 790 }
17a740d5 791 return $Perl;
b5fe401b
MS
792}
793
435e7af6 794sub unlink_all {
55b0687d 795 my $count = 0;
435e7af6
NC
796 foreach my $file (@_) {
797 1 while unlink $file;
55b0687d
BG
798 if( -f $file ){
799 _print_stderr "# Couldn't unlink '$file': $!\n";
800 }else{
801 ++$count;
802 }
435e7af6 803 }
55b0687d 804 $count;
435e7af6 805}
eeabcb2d 806
f6e25e60
BG
807# _num_to_alpha - Returns a string of letters representing a positive integer.
808# Arguments :
809# number to convert
2c36667f 810# maximum number of letters
f6e25e60
BG
811
812# returns undef if the number is negative
2c36667f 813# returns undef if the number of letters is greater than the maximum wanted
f6e25e60
BG
814
815# _num_to_alpha( 0) eq 'A';
816# _num_to_alpha( 1) eq 'B';
817# _num_to_alpha(25) eq 'Z';
818# _num_to_alpha(26) eq 'AA';
819# _num_to_alpha(27) eq 'AB';
820
48e9c5d4
BG
821my @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);
822
f6e25e60
BG
823# Avoid ++ -- ranges split negative numbers
824sub _num_to_alpha{
2c36667f 825 my($num,$max_char) = @_;
f6e25e60
BG
826 return unless $num >= 0;
827 my $alpha = '';
2c36667f
BG
828 my $char_count = 0;
829 $max_char = 0 if $max_char < 0;
830
f6e25e60
BG
831 while( 1 ){
832 $alpha = $letters[ $num % 26 ] . $alpha;
833 $num = int( $num / 26 );
834 last if $num == 0;
835 $num = $num - 1;
2c36667f
BG
836
837 # char limit
838 next unless $max_char;
839 $char_count = $char_count + 1;
840 return if $char_count == $max_char;
f6e25e60
BG
841 }
842 return $alpha;
843}
844
748a4b20
NC
845my %tmpfiles;
846END { unlink_all keys %tmpfiles }
847
848# A regexp that matches the tempfile names
849$::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
c1ddc35c 850
7a7e4936 851# Avoid ++, avoid ranges, avoid split //
7b29226f 852my $tempfile_count = 0;
7a7e4936 853sub tempfile {
7b29226f 854 while(1){
7a7e4936 855 my $try = "tmp$$";
7b29226f
BG
856 my $alpha = _num_to_alpha($tempfile_count,2);
857 last unless defined $alpha;
858 $try = $try . $alpha;
859 $tempfile_count = $tempfile_count + 1;
860
748a4b20
NC
861 # Need to note all the file names we allocated, as a second request may
862 # come before the first is created.
7b29226f 863 if (!$tmpfiles{$try} && !-e $try) {
c1ddc35c 864 # We have a winner
11ea18f2 865 $tmpfiles{$try} = 1;
c1ddc35c
NC
866 return $try;
867 }
7b29226f 868 }
9a8c1c8c 869 die "Can't find temporary file name starting \"tmp$$\"";
7a7e4936
NC
870}
871
c1ddc35c 872# This is the temporary file for _fresh_perl
7a7e4936 873my $tmpfile = tempfile();
eeabcb2d 874
f5cda331 875sub _fresh_perl {
55280a0d 876 my($prog, $action, $expect, $runperl_args, $name) = @_;
eeabcb2d 877
11ea18f2
NC
878 # Given the choice of the mis-parsable {}
879 # (we want an anon hash, but a borked lexer might think that it's a block)
880 # or relying on taking a reference to a lexical
881 # (\ might be mis-parsed, and the reference counting on the pad may go
882 # awry)
883 # it feels like the least-worse thing is to assume that auto-vivification
884 # works. At least, this is only going to be a run-time failure, so won't
885 # affect tests using this file but not this function.
c49688b0
MS
886 $runperl_args->{progfile} ||= $tmpfile;
887 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr};
eeabcb2d
MS
888
889 open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
0d65d7d5 890 print TEST $prog;
eeabcb2d
MS
891 close TEST or die "Cannot close $tmpfile: $!";
892
893 my $results = runperl(%$runperl_args);
894 my $status = $?;
895
896 # Clean up the results into something a bit more predictable.
50f17f89 897 $results =~ s/\n+$//;
748a4b20
NC
898 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
899 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
eeabcb2d
MS
900
901 # bison says 'parse error' instead of 'syntax error',
902 # various yaccs may or may not capitalize 'syntax'.
903 $results =~ s/^(syntax|parse) error/syntax error/mig;
904
4b0f0df6 905 if ($is_vms) {
eeabcb2d
MS
906 # some tests will trigger VMS messages that won't be expected
907 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
908
909 # pipes double these sometimes
910 $results =~ s/\n\n/\n/g;
911 }
912
e2c38acd
JH
913 # Use the first line of the program as a name if none was given
914 unless( $name ) {
915 ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
11ea18f2 916 $name = $name . '...' if length $first_line > length $name;
e2c38acd 917 }
eeabcb2d 918
55280a0d
NC
919 # Historically this was implemented using a closure, but then that means
920 # that the tests for closures avoid using this code. Given that there
921 # are exactly two callers, doing exactly two things, the simpler approach
922 # feels like a better trade off.
923 my $pass;
924 if ($action eq 'eq') {
925 $pass = is($results, $expect, $name);
926 } elsif ($action eq '=~') {
927 $pass = like($results, $expect, $name);
928 } else {
929 die "_fresh_perl can't process action '$action'";
930 }
931
932 unless ($pass) {
933 _diag "# PROG: \n$prog\n";
934 _diag "# STATUS: $status\n";
935 }
936
937 return $pass;
f5cda331
JH
938}
939
940#
141f445b 941# fresh_perl_is
f5cda331
JH
942#
943# Combination of run_perl() and is().
944#
945
946sub fresh_perl_is {
947 my($prog, $expected, $runperl_args, $name) = @_;
50f17f89
MS
948
949 # _fresh_perl() is going to clip the trailing newlines off the result.
950 # This will make it so the test author doesn't have to know that.
951 $expected =~ s/\n+$//;
952
dcc7f481 953 local $Level = 2;
55280a0d 954 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
f5cda331
JH
955}
956
957#
141f445b 958# fresh_perl_like
f5cda331
JH
959#
960# Combination of run_perl() and like().
961#
962
963sub fresh_perl_like {
964 my($prog, $expected, $runperl_args, $name) = @_;
dcc7f481 965 local $Level = 2;
55280a0d 966 _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
eeabcb2d
MS
967}
968
ebf2da99
NC
969# Many tests use the same format in __DATA__ or external files to specify a
970# sequence of (fresh) tests to run, extra files they may temporarily need, and
ebcaaa39
KW
971# what the expected output is. Putting it here allows common code to serve
972# these multiple tests.
a8775356
TC
973#
974# Each program is source code to run followed by an "EXPECT" line, followed
975# by the expected output.
976#
09b6b4fb
FC
977# The code to run may begin with a command line switch such as -w or -0777
978# (alphanumerics only), and may contain (note the '# ' on each):
a8775356
TC
979# # TODO reason for todo
980# # SKIP reason for skip
981# # SKIP ?code to test if this should be skipped
982# # NAME name of the test (as with ok($ok, $name))
983#
984# The expected output may contain:
985# OPTION list of options
986# OPTIONS list of options
a8775356
TC
987#
988# The possible options for OPTION may be:
989# regex - the expected output is a regular expression
990# random - all lines match but in any order
991# fatal - the code will fail fatally (croak, die)
992#
993# If the actual output contains a line "SKIPPED" the test will be
994# skipped.
995#
708e0e1d
KW
996# If the actual output contains a line "PREFIX", any output starting with that
997# line will be ignored when comparing with the expected output
998#
a8775356
TC
999# If the global variable $FATAL is true then OPTION fatal is the
1000# default.
ebf2da99 1001
9f5237ac
NC
1002sub _setup_one_file {
1003 my $fh = shift;
41732369
NC
1004 # Store the filename as a program that started at line 0.
1005 # Real files count lines starting at line 1.
1006 my @these = (0, shift);
1007 my ($lineno, $current);
1008 while (<$fh>) {
1009 if ($_ eq "########\n") {
1010 if (defined $current) {
1011 push @these, $lineno, $current;
1012 }
1013 undef $current;
1014 } else {
1015 if (!defined $current) {
1016 $lineno = $.;
1017 }
1018 $current .= $_;
1019 }
1020 }
1021 if (defined $current) {
1022 push @these, $lineno, $current;
1023 }
1024 ((scalar @these) / 2 - 1, @these);
9f5237ac
NC
1025}
1026
fdb35a63
NC
1027sub setup_multiple_progs {
1028 my ($tests, @prgs);
1029 foreach my $file (@_) {
1030 next if $file =~ /(?:~|\.orig|,v)$/;
1031 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
1032 next if -d $file;
1033
1034 open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
1035 my $found;
1036 while (<$fh>) {
1037 if (/^__END__/) {
1038 ++$found;
1039 last;
1040 }
1041 }
1042 # This is an internal error, and should never happen. All bar one of
1043 # the files had an __END__ marker to signal the end of their preamble,
1044 # although for some it wasn't technically necessary as they have no
1045 # tests. It might be possible to process files without an __END__ by
1046 # seeking back to the start and treating the whole file as tests, but
1047 # it's simpler and more reliable just to make the rule that all files
1048 # must have __END__ in. This should never fail - a file without an
1049 # __END__ should not have been checked in, because the regression tests
1050 # would not have passed.
1051 die "Could not find '__END__' in $file"
1052 unless $found;
1053
41732369 1054 my ($t, @p) = _setup_one_file($fh, $file);
9f5237ac 1055 $tests += $t;
41732369 1056 push @prgs, @p;
fdb35a63
NC
1057
1058 close $fh
1059 or die "Cannot close $file: $!\n";
1060 }
1061 return ($tests, @prgs);
1062}
1063
ebf2da99 1064sub run_multiple_progs {
5f7e0818
NC
1065 my $up = shift;
1066 my @prgs;
1067 if ($up) {
1068 # The tests in lib run in a temporary subdirectory of t, and always
1069 # pass in a list of "programs" to run
1070 @prgs = @_;
1071 } else {
41732369
NC
1072 # The tests below t run in t and pass in a file handle. In theory we
1073 # can pass (caller)[1] as the second argument to report errors with
1074 # the filename of our caller, as the handle is always DATA. However,
1075 # line numbers in DATA count from the __END__ token, so will be wrong.
1076 # Which is more confusing than not providing line numbers. So, for now,
1077 # don't provide line numbers. No obvious clean solution - one hack
1078 # would be to seek DATA back to the start and read to the __END__ token,
1079 # but that feels almost like we should just open $0 instead.
1080
9f5237ac
NC
1081 # Not going to rely on undef in list assignment.
1082 my $dummy;
1083 ($dummy, @prgs) = _setup_one_file(shift);
5f7e0818
NC
1084 }
1085
ebf2da99
NC
1086 my $tmpfile = tempfile();
1087
41732369 1088 my ($file, $line);
c0044231 1089 PROGRAM:
41732369
NC
1090 while (defined ($line = shift @prgs)) {
1091 $_ = shift @prgs;
1092 unless ($line) {
1093 $file = $_;
1094 if (defined $file) {
1095 print "# From $file\n";
1096 }
ebf2da99
NC
1097 next;
1098 }
1099 my $switch = "";
1100 my @temps ;
1101 my @temp_path;
1102 if (s/^(\s*-\w+)//) {
1103 $switch = $1;
1104 }
1105 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1106
1107 my %reason;
1108 foreach my $what (qw(skip todo)) {
1109 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1110 # If the SKIP reason starts ? then it's taken as a code snippet to
1111 # evaluate. This provides the flexibility to have conditional SKIPs
1112 if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1113 my $temp = eval $reason{$what};
1114 if ($@) {
1115 die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1116 }
1117 $reason{$what} = $temp;
1118 }
1119 }
c0044231 1120
59e38755
TC
1121 my $name = '';
1122 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1123 $name = $1;
1124 }
ebf2da99 1125
c0044231
TC
1126 if ($reason{skip}) {
1127 SKIP:
1128 {
1129 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1130 }
1131 next PROGRAM;
1132 }
1133
ebf2da99 1134 if ($prog =~ /--FILE--/) {
e330f831 1135 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
ebf2da99
NC
1136 shift @files ;
1137 die "Internal error: test $_ didn't split into pairs, got " .
1138 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1139 if @files % 2;
1140 while (@files > 2) {
1141 my $filename = shift @files;
1142 my $code = shift @files;
1143 push @temps, $filename;
1144 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1145 require File::Path;
1146 File::Path::mkpath($1);
1147 push(@temp_path, $1);
1148 }
1149 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1150 print $fh $code;
1151 close $fh or die "Cannot close $filename: $!\n";
1152 }
1153 shift @files;
1154 $prog = shift @files;
1155 }
1156
1157 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1158 print $fh q{
1159 BEGIN {
1160 open STDERR, '>&', STDOUT
1161 or die "Can't dup STDOUT->STDERR: $!;";
1162 }
1163 };
1164 print $fh "\n#line 1\n"; # So the line numbers don't get messed up.
1165 print $fh $prog,"\n";
1166 close $fh or die "Cannot close $tmpfile: $!";
684b0eca 1167 my $results = runperl( stderr => 1, progfile => $tmpfile,
53f2736e 1168 stdin => undef, $up
5f7e0818
NC
1169 ? (switches => ["-I$up/lib", $switch], nolib => 1)
1170 : (switches => [$switch])
1171 );
ebf2da99
NC
1172 my $status = $?;
1173 $results =~ s/\n+$//;
1174 # allow expected output to be written as if $prog is on STDIN
1175 $results =~ s/$::tempfile_regexp/-/g;
1176 if ($^O eq 'VMS') {
1177 # some tests will trigger VMS messages that won't be expected
1178 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1179
1180 # pipes double these sometimes
1181 $results =~ s/\n\n/\n/g;
1182 }
1183 # bison says 'parse error' instead of 'syntax error',
1184 # various yaccs may or may not capitalize 'syntax'.
1185 $results =~ s/^(syntax|parse) error/syntax error/mig;
1186 # allow all tests to run when there are leaks
1187 $results =~ s/Scalars leaked: \d+\n//g;
1188
1189 $expected =~ s/\n+$//;
1190 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1191 # any special options? (OPTIONS foo bar zap)
1192 my $option_regex = 0;
1193 my $option_random = 0;
59e38755 1194 my $fatal = $FATAL;
ebf2da99
NC
1195 if ($expected =~ s/^OPTIONS? (.+)\n//) {
1196 foreach my $option (split(' ', $1)) {
1197 if ($option eq 'regex') { # allow regular expressions
1198 $option_regex = 1;
1199 }
1200 elsif ($option eq 'random') { # all lines match, but in any order
1201 $option_random = 1;
1202 }
59e38755
TC
1203 elsif ($option eq 'fatal') { # perl should fail
1204 $fatal = 1;
1205 }
ebf2da99
NC
1206 else {
1207 die "$0: Unknown OPTION '$option'\n";
1208 }
1209 }
1210 }
1211 die "$0: can't have OPTION regex and random\n"
1212 if $option_regex + $option_random > 1;
1213 my $ok = 0;
1214 if ($results =~ s/^SKIPPED\n//) {
1215 print "$results\n" ;
1216 $ok = 1;
1217 }
ebf2da99 1218 else {
59e38755
TC
1219 if ($option_random) {
1220 my @got = sort split "\n", $results;
1221 my @expected = sort split "\n", $expected;
1222
1223 $ok = "@got" eq "@expected";
1224 }
1225 elsif ($option_regex) {
1226 $ok = $results =~ /^$expected/;
1227 }
1228 elsif ($prefix) {
1229 $ok = $results =~ /^\Q$expected/;
1230 }
1231 else {
1232 $ok = $results eq $expected;
1233 }
1234
1235 if ($ok && $fatal && !($status >> 8)) {
1236 $ok = 0;
1237 }
ebf2da99
NC
1238 }
1239
1240 local $::TODO = $reason{todo};
1241
1242 unless ($ok) {
1243 my $err_line = "PROG: $switch\n$prog\n" .
59e38755
TC
1244 "EXPECTED:\n$expected\n";
1245 $err_line .= "EXIT STATUS: != 0\n" if $fatal;
1246 $err_line .= "GOT:\n$results\n";
1247 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
ebf2da99
NC
1248 if ($::TODO) {
1249 $err_line =~ s/^/# /mg;
1250 print $err_line; # Harness can't filter it out from STDERR.
1251 }
1252 else {
1253 print STDERR $err_line;
1254 }
1255 }
1256
41732369
NC
1257 if (defined $file) {
1258 _ok($ok, "at $file line $line", $name);
1259 } else {
1260 # We don't have file and line number data for the test, so report
1261 # errors as coming from our caller.
1262 local $Level = $Level + 1;
1263 ok($ok, $name);
1264 }
ebf2da99
NC
1265
1266 foreach (@temps) {
1267 unlink $_ if $_;
1268 }
1269 foreach (@temp_path) {
1270 File::Path::rmtree $_ if -d $_;
1271 }
1272 }
1273}
1274
35a60386
RGS
1275sub can_ok ($@) {
1276 my($proto, @methods) = @_;
1277 my $class = ref $proto || $proto;
1278
1279 unless( @methods ) {
1280 return _ok( 0, _where(), "$class->can(...)" );
1281 }
1282
1283 my @nok = ();
1284 foreach my $method (@methods) {
1285 local($!, $@); # don't interfere with caller's $@
1286 # eval sometimes resets $!
1287 eval { $proto->can($method) } || push @nok, $method;
1288 }
1289
1290 my $name;
8210c8d3 1291 $name = @methods == 1 ? "$class->can('$methods[0]')"
35a60386 1292 : "$class->can(...)";
8210c8d3 1293
35a60386
RGS
1294 _ok( !@nok, _where(), $name );
1295}
1296
ad4e703e 1297
bbce3ca6 1298# Call $class->new( @$args ); and run the result through object_ok.
ad4e703e
MS
1299# See Test::More::new_ok
1300sub new_ok {
1301 my($class, $args, $obj_name) = @_;
1302 $args ||= [];
1303 $object_name = "The object" unless defined $obj_name;
1304
1305 local $Level = $Level + 1;
1306
1307 my $obj;
1308 my $ok = eval { $obj = $class->new(@$args); 1 };
1309 my $error = $@;
1310
1311 if($ok) {
bbce3ca6 1312 object_ok($obj, $class, $object_name);
ad4e703e
MS
1313 }
1314 else {
1315 ok( 0, "new() died" );
1316 diag("Error was: $@");
1317 }
1318
1319 return $obj;
1320
1321}
1322
1323
35a60386
RGS
1324sub isa_ok ($$;$) {
1325 my($object, $class, $obj_name) = @_;
1326
1327 my $diag;
1328 $obj_name = 'The object' unless defined $obj_name;
1329 my $name = "$obj_name isa $class";
1330 if( !defined $object ) {
1331 $diag = "$obj_name isn't defined";
1332 }
35a60386 1333 else {
b8ab4b0c
MS
1334 my $whatami = ref $object ? 'object' : 'class';
1335
35a60386
RGS
1336 # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1337 local($@, $!); # eval sometimes resets $!
1338 my $rslt = eval { $object->isa($class) };
b8ab4b0c
MS
1339 my $error = $@; # in case something else blows away $@
1340
1341 if( $error ) {
1342 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1343 # It's an unblessed reference
1344 $obj_name = 'The reference' unless defined $obj_name;
35a60386
RGS
1345 if( !UNIVERSAL::isa($object, $class) ) {
1346 my $ref = ref $object;
1347 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1348 }
b8ab4b0c
MS
1349 }
1350 elsif( $error =~ /Can't call method "isa" without a package/ ) {
1351 # It's something that can't even be a class
1352 $obj_name = 'The thing' unless defined $obj_name;
1353 $diag = "$obj_name isn't a class or reference";
1354 }
1355 else {
35a60386
RGS
1356 die <<WHOA;
1357WHOA! I tried to call ->isa on your object and got some weird error.
1358This should never happen. Please contact the author immediately.
1359Here's the error.
1360$@
1361WHOA
1362 }
1363 }
1364 elsif( !$rslt ) {
b8ab4b0c 1365 $obj_name = "The $whatami" unless defined $obj_name;
35a60386
RGS
1366 my $ref = ref $object;
1367 $diag = "$obj_name isn't a '$class' it's a '$ref'";
1368 }
1369 }
1370
1371 _ok( !$diag, _where(), $name );
1372}
1373
bbce3ca6
MS
1374
1375sub class_ok {
1376 my($class, $isa, $class_name) = @_;
1377
1378 # Written so as to count as one test
1379 local $Level = $Level + 1;
1380 if( ref $class ) {
1381 ok( 0, "$class is a refrence, not a class name" );
1382 }
1383 else {
1384 isa_ok($class, $isa, $class_name);
1385 }
1386}
1387
1388
1389sub object_ok {
1390 my($obj, $isa, $obj_name) = @_;
1391
1392 local $Level = $Level + 1;
1393 if( !ref $obj ) {
1394 ok( 0, "$obj is not a reference" );
1395 }
1396 else {
1397 isa_ok($obj, $isa, $obj_name);
1398 }
1399}
1400
1401
9eb41b69
NC
1402# Purposefully avoiding a closure.
1403sub __capture {
1404 push @::__capture, join "", @_;
1405}
1406
3fbaac97
NC
1407sub capture_warnings {
1408 my $code = shift;
1409
9eb41b69
NC
1410 local @::__capture;
1411 local $SIG {__WARN__} = \&__capture;
3fbaac97 1412 &$code;
9eb41b69 1413 return @::__capture;
3fbaac97
NC
1414}
1415
1416# This will generate a variable number of tests.
1417# Use done_testing() instead of a fixed plan.
1418sub warnings_like {
1419 my ($code, $expect, $name) = @_;
f4554ed5
NC
1420 local $Level = $Level + 1;
1421
3fbaac97
NC
1422 my @w = capture_warnings($code);
1423
1424 cmp_ok(scalar @w, '==', scalar @$expect, $name);
1425 foreach my $e (@$expect) {
f4554ed5 1426 if (ref $e) {
3fbaac97 1427 like(shift @w, $e, $name);
4d18b353 1428 } else {
3fbaac97 1429 is(shift @w, $e, $name);
4d18b353 1430 }
96980024 1431 }
3fbaac97
NC
1432 if (@w) {
1433 diag("Saw these additional warnings:");
1434 diag($_) foreach @w;
1435 }
1436}
1437
1438sub _fail_excess_warnings {
1439 my($expect, $got, $name) = @_;
1440 local $Level = $Level + 1;
1441 # This will fail, and produce diagnostics
1442 is($expect, scalar @$got, $name);
1443 diag("Saw these warnings:");
1444 diag($_) foreach @$got;
c11a8df3
NC
1445}
1446
4d18b353
NC
1447sub warning_is {
1448 my ($code, $expect, $name) = @_;
1449 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1450 if ref $expect;
f4554ed5 1451 local $Level = $Level + 1;
3fbaac97
NC
1452 my @w = capture_warnings($code);
1453 if (@w > 1) {
1454 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1455 } else {
1456 is($w[0], $expect, $name);
1457 }
4d18b353
NC
1458}
1459
1460sub warning_like {
1461 my ($code, $expect, $name) = @_;
1462 die sprintf "Expect must be a regexp object"
1463 unless ref $expect eq 'Regexp';
f4554ed5 1464 local $Level = $Level + 1;
3fbaac97
NC
1465 my @w = capture_warnings($code);
1466 if (@w > 1) {
1467 _fail_excess_warnings(0 + defined $expect, \@w, $name);
1468 } else {
1469 like($w[0], $expect, $name);
1470 }
4d18b353
NC
1471}
1472
087986a7 1473# Set a watchdog to timeout the entire test file
5fe9b82b
JH
1474# NOTE: If the test file uses 'threads', then call the watchdog() function
1475# _AFTER_ the 'threads' module is loaded.
5732108f 1476sub watchdog ($;$)
087986a7
JH
1477{
1478 my $timeout = shift;
36436324 1479 my $method = shift || "";
087986a7
JH
1480 my $timeout_msg = 'Test process timed out - terminating';
1481
e07ce2e4
GG
1482 # Valgrind slows perl way down so give it more time before dying.
1483 $timeout *= 10 if $ENV{PERL_VALGRIND};
1484
087986a7
JH
1485 my $pid_to_kill = $$; # PID for this process
1486
5732108f
GG
1487 if ($method eq "alarm") {
1488 goto WATCHDOG_VIA_ALARM;
1489 }
1490
140f5369
MS
1491 # shut up use only once warning
1492 my $threads_on = $threads::threads && $threads::threads;
1493
5fe9b82b
JH
1494 # Don't use a watchdog process if 'threads' is loaded -
1495 # use a watchdog thread instead
78325d7a 1496 if (!$threads_on || $method eq "process") {
5fe9b82b
JH
1497
1498 # On Windows and VMS, try launching a watchdog process
1499 # using system(1, ...) (see perlport.pod)
4b0f0df6 1500 if ($is_mswin || $is_vms) {
5fe9b82b 1501 # On Windows, try to get the 'real' PID
4b0f0df6 1502 if ($is_mswin) {
5fe9b82b
JH
1503 eval { require Win32; };
1504 if (defined(&Win32::GetCurrentProcessId)) {
1505 $pid_to_kill = Win32::GetCurrentProcessId();
1506 }
087986a7 1507 }
087986a7 1508
5fe9b82b
JH
1509 # If we still have a fake PID, we can't use this method at all
1510 return if ($pid_to_kill <= 0);
1511
1512 # Launch watchdog process
1513 my $watchdog;
1514 eval {
1515 local $SIG{'__WARN__'} = sub {
1516 _diag("Watchdog warning: $_[0]");
1517 };
4b0f0df6 1518 my $sig = $is_vms ? 'TERM' : 'KILL';
9b7a5066
CB
1519 my $cmd = _create_runperl( prog => "sleep($timeout);" .
1520 "warn qq/# $timeout_msg" . '\n/;' .
c1c45e36 1521 "kill($sig, $pid_to_kill);");
9b7a5066 1522 $watchdog = system(1, $cmd);
5fe9b82b
JH
1523 };
1524 if ($@ || ($watchdog <= 0)) {
1525 _diag('Failed to start watchdog');
1526 _diag($@) if $@;
1527 undef($watchdog);
1528 return;
1529 }
087986a7 1530
5fe9b82b
JH
1531 # Add END block to parent to terminate and
1532 # clean up watchdog process
7e1027b9
JH
1533 eval "END { local \$! = 0; local \$? = 0;
1534 wait() if kill('KILL', $watchdog); };";
5fe9b82b 1535 return;
087986a7 1536 }
087986a7 1537
5fe9b82b
JH
1538 # Try using fork() to generate a watchdog process
1539 my $watchdog;
1540 eval { $watchdog = fork() };
1541 if (defined($watchdog)) {
1542 if ($watchdog) { # Parent process
1543 # Add END block to parent to terminate and
1544 # clean up watchdog process
7e1027b9
JH
1545 eval "END { local \$! = 0; local \$? = 0;
1546 wait() if kill('KILL', $watchdog); };";
5fe9b82b
JH
1547 return;
1548 }
1549
1550 ### Watchdog process code
087986a7 1551
5fe9b82b
JH
1552 # Load POSIX if available
1553 eval { require POSIX; };
087986a7 1554
5fe9b82b
JH
1555 # Execute the timeout
1556 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073
1557 sleep(2);
087986a7 1558
5fe9b82b
JH
1559 # Kill test process if still running
1560 if (kill(0, $pid_to_kill)) {
1561 _diag($timeout_msg);
1562 kill('KILL', $pid_to_kill);
1a34b28b
TC
1563 if ($is_cygwin) {
1564 # sometimes the above isn't enough on cygwin
1565 sleep 1; # wait a little, it might have worked after all
1566 system("/bin/kill -f $pid_to_kill");
1567 }
5fe9b82b 1568 }
087986a7 1569
5fe9b82b
JH
1570 # Don't execute END block (added at beginning of this file)
1571 $NO_ENDING = 1;
087986a7 1572
5fe9b82b
JH
1573 # Terminate ourself (i.e., the watchdog)
1574 POSIX::_exit(1) if (defined(&POSIX::_exit));
1575 exit(1);
087986a7
JH
1576 }
1577
5fe9b82b 1578 # fork() failed - fall through and try using a thread
087986a7
JH
1579 }
1580
5fe9b82b
JH
1581 # Use a watchdog thread because either 'threads' is loaded,
1582 # or fork() failed
cb01154c 1583 if (eval {require threads; 1}) {
b296285b 1584 'threads'->create(sub {
087986a7
JH
1585 # Load POSIX if available
1586 eval { require POSIX; };
1587
1588 # Execute the timeout
c1c45e36 1589 my $time_left = $timeout;
a6c9a815 1590 do {
11ea18f2 1591 $time_left = $time_left - sleep($time_left);
a6c9a815 1592 } while ($time_left > 0);
087986a7
JH
1593
1594 # Kill the parent (and ourself)
5fe9b82b 1595 select(STDERR); $| = 1;
087986a7
JH
1596 _diag($timeout_msg);
1597 POSIX::_exit(1) if (defined(&POSIX::_exit));
4b0f0df6 1598 my $sig = $is_vms ? 'TERM' : 'KILL';
c1c45e36 1599 kill($sig, $pid_to_kill);
087986a7
JH
1600 })->detach();
1601 return;
1602 }
1603
5fe9b82b 1604 # If everything above fails, then just use an alarm timeout
5732108f 1605WATCHDOG_VIA_ALARM:
087986a7
JH
1606 if (eval { alarm($timeout); 1; }) {
1607 # Load POSIX if available
1608 eval { require POSIX; };
1609
1610 # Alarm handler will do the actual 'killing'
1611 $SIG{'ALRM'} = sub {
5fe9b82b 1612 select(STDERR); $| = 1;
087986a7
JH
1613 _diag($timeout_msg);
1614 POSIX::_exit(1) if (defined(&POSIX::_exit));
4b0f0df6 1615 my $sig = $is_vms ? 'TERM' : 'KILL';
c1c45e36 1616 kill($sig, $pid_to_kill);
087986a7
JH
1617 };
1618 }
1619}
1620
f69d9fdf
KW
1621# The following 2 functions allow tests to work on both EBCDIC and
1622# ASCII-ish platforms. They convert string scalars between the native
1623# character set and the set of 256 characters which is usually called
1624# Latin1.
f69d9fdf
KW
1625
1626sub native_to_latin1($) {
1627 my $string = shift;
1628
1629 return $string if ord('^') == 94; # ASCII, Latin1
ae4842ab
KW
1630 my $output = "";
1631 for my $i (0 .. length($string) - 1) {
1632 $output .= chr(ord_native_to_latin1(ord(substr($string, $i, 1))));
f69d9fdf 1633 }
ae4842ab
KW
1634 # Preserve utf8ness of input onto the output, even if it didn't need to be
1635 # utf8
1636 utf8::upgrade($output) if utf8::is_utf8($string);
f69d9fdf 1637
ae4842ab 1638 return $output;
f69d9fdf
KW
1639}
1640
1641sub latin1_to_native($) {
1642 my $string = shift;
1643
1644 return $string if ord('^') == 94; # ASCII, Latin1
ae4842ab
KW
1645 my $output = "";
1646 for my $i (0 .. length($string) - 1) {
1647 $output .= chr(ord_latin1_to_native(ord(substr($string, $i, 1))));
f69d9fdf 1648 }
ae4842ab
KW
1649 # Preserve utf8ness of input onto the output, even if it didn't need to be
1650 # utf8
1651 utf8::upgrade($output) if utf8::is_utf8($string);
f69d9fdf 1652
ae4842ab 1653 return $output;
f69d9fdf
KW
1654}
1655
883cce4a 1656sub ord_latin1_to_native {
ec0363d9
KW
1657 # given an input code point, return the platform's native
1658 # equivalent value. Anything above latin1 is itself.
883cce4a 1659
ec0363d9 1660 my $ord = shift;
61bbb486
KW
1661 return $ord if ord('^') == 94; # ASCII, Latin1
1662 return utf8::unicode_to_native($ord);
883cce4a
KW
1663}
1664
1665sub ord_native_to_latin1 {
ec0363d9
KW
1666 # given an input platform code point, return the latin1 equivalent value.
1667 # Anything above latin1 is itself.
883cce4a 1668
ec0363d9 1669 my $ord = shift;
61bbb486
KW
1670 return $ord if ord('^') == 94; # ASCII, Latin1
1671 return utf8::native_to_unicode($ord);
883cce4a
KW
1672}
1673
69026470 16741;