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