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