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