1# 2# t/test.pl - most of Test::More functionality without the fuss 3 4 5# NOTE: 6# 7# Do not rely on features found only in more modern Perls here, as some CPAN 8# distributions copy this file and must operate on older Perls. Similarly, keep 9# things, simple as this may be run under fairly broken circumstances. For 10# example, increment ($x++) has a certain amount of cleverness for things like 11# 12# $x = 'zz'; 13# $x++; # $x eq 'aaa'; 14# 15# This stands more chance of breaking than just a simple 16# 17# $x = $x + 1 18# 19# In this file, we use the latter "Baby Perl" approach, and increment 20# will be worked over by t/op/inc.t 21 22$| = 1; 23our $Level = 1; 24my $test = 1; 25my $planned; 26my $noplan; 27my $Perl; # Safer version of $^X set by which_perl() 28 29# This defines ASCII/UTF-8 vs EBCDIC/UTF-EBCDIC 30$::IS_ASCII = ord 'A' == 65; 31$::IS_EBCDIC = ord 'A' == 193; 32 33# This is 'our' to enable harness to account for TODO-ed tests in 34# overall grade of PASS or FAIL 35our $TODO = 0; 36our $NO_ENDING = 0; 37our $Tests_Are_Passing = 1; 38 39# Use this instead of print to avoid interference while testing globals. 40sub _print { 41 local($\, $", $,) = (undef, ' ', ''); 42 print STDOUT @_; 43} 44 45sub _print_stderr { 46 local($\, $", $,) = (undef, ' ', ''); 47 print STDERR @_; 48} 49 50sub plan { 51 my $n; 52 if (@_ == 1) { 53 $n = shift; 54 if ($n eq 'no_plan') { 55 undef $n; 56 $noplan = 1; 57 } 58 } else { 59 my %plan = @_; 60 $plan{skip_all} and skip_all($plan{skip_all}); 61 $n = $plan{tests}; 62 } 63 _print "1..$n\n" unless $noplan; 64 $planned = $n; 65} 66 67 68# Set the plan at the end. See Test::More::done_testing. 69sub done_testing { 70 my $n = $test - 1; 71 $n = shift if @_; 72 73 _print "1..$n\n"; 74 $planned = $n; 75} 76 77 78END { 79 my $ran = $test - 1; 80 if (!$NO_ENDING) { 81 if (defined $planned && $planned != $ran) { 82 _print_stderr 83 "# Looks like you planned $planned tests but ran $ran.\n"; 84 } elsif ($noplan) { 85 _print "1..$ran\n"; 86 } 87 } 88} 89 90sub _diag { 91 return unless @_; 92 my @mess = _comment(@_); 93 $TODO ? _print(@mess) : _print_stderr(@mess); 94} 95 96# Use this instead of "print STDERR" when outputting failure diagnostic 97# messages 98sub diag { 99 _diag(@_); 100} 101 102# Use this instead of "print" when outputting informational messages 103sub note { 104 return unless @_; 105 _print( _comment(@_) ); 106} 107 108sub is_miniperl { 109 return !defined &DynaLoader::boot_DynaLoader; 110} 111 112sub set_up_inc { 113 # Don���t clobber @INC under miniperl 114 @INC = () unless is_miniperl; 115 unshift @INC, @_; 116} 117 118sub _comment { 119 return map { /^#/ ? "$_\n" : "# $_\n" } 120 map { split /\n/ } @_; 121} 122 123sub _have_dynamic_extension { 124 my $extension = shift; 125 unless (eval {require Config; 1}) { 126 warn "test.pl had problems loading Config: $@"; 127 return 1; 128 } 129 $extension =~ s!::!/!g; 130 return 1 if ($Config::Config{extensions} =~ /\b$extension\b/); 131} 132 133sub skip_all { 134 if (@_) { 135 _print "1..0 # Skip @_\n"; 136 } else { 137 _print "1..0\n"; 138 } 139 exit(0); 140} 141 142sub skip_all_if_miniperl { 143 skip_all(@_) if is_miniperl(); 144} 145 146sub skip_all_without_dynamic_extension { 147 my ($extension) = @_; 148 skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl(); 149 return if &_have_dynamic_extension; 150 skip_all("$extension was not built"); 151} 152 153sub skip_all_without_perlio { 154 skip_all('no PerlIO') unless PerlIO::Layer->find('perlio'); 155} 156 157sub skip_all_without_config { 158 unless (eval {require Config; 1}) { 159 warn "test.pl had problems loading Config: $@"; 160 return; 161 } 162 foreach (@_) { 163 next if $Config::Config{$_}; 164 my $key = $_; # Need to copy, before trying to modify. 165 $key =~ s/^use//; 166 $key =~ s/^d_//; 167 skip_all("no $key"); 168 } 169} 170 171sub skip_all_without_unicode_tables { # (but only under miniperl) 172 if (is_miniperl()) { 173 skip_all_if_miniperl("Unicode tables not built yet") 174 unless eval 'require "unicore/UCD.pl"'; 175 } 176} 177 178sub find_git_or_skip { 179 my ($source_dir, $reason); 180 181 if ( $ENV{CONTINUOUS_INTEGRATION} && $ENV{WORKSPACE} ) { 182 $source_dir = $ENV{WORKSPACE}; 183 if ( -d "${source_dir}/.git" ) { 184 $ENV{GIT_DIR} = "${source_dir}/.git"; 185 return $source_dir; 186 } 187 } 188 189 if (-d '.git') { 190 $source_dir = '.'; 191 } elsif (-l 'MANIFEST' && -l 'AUTHORS') { 192 my $where = readlink 'MANIFEST'; 193 die "Can't readlink MANIFEST: $!" unless defined $where; 194 die "Confusing symlink target for MANIFEST, '$where'" 195 unless $where =~ s!/MANIFEST\z!!; 196 if (-d "$where/.git") { 197 # Looks like we are in a symlink tree 198 if (exists $ENV{GIT_DIR}) { 199 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it"); 200 } else { 201 note("Found source tree at $where, setting \$ENV{GIT_DIR}"); 202 $ENV{GIT_DIR} = "$where/.git"; 203 } 204 $source_dir = $where; 205 } 206 } elsif (exists $ENV{GIT_DIR} || -f '.git') { 207 my $commit = '8d063cd8450e59ea1c611a2f4f5a21059a2804f1'; 208 my $out = `git rev-parse --verify --quiet '$commit^{commit}'`; 209 chomp $out; 210 if($out eq $commit) { 211 $source_dir = '.' 212 } 213 } 214 if ($ENV{'PERL_BUILD_PACKAGING'}) { 215 $reason = 'PERL_BUILD_PACKAGING is set'; 216 } elsif ($source_dir) { 217 my $version_string = `git --version`; 218 if (defined $version_string 219 && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) { 220 return $source_dir if eval "v$1 ge v1.5.0"; 221 # If you have earlier than 1.5.0 and it works, change this test 222 $reason = "in git checkout, but git version '$1$2' too old"; 223 } else { 224 $reason = "in git checkout, but cannot run git"; 225 } 226 } else { 227 $reason = 'not being run from a git checkout'; 228 } 229 skip_all($reason) if $_[0] && $_[0] eq 'all'; 230 skip($reason, @_); 231} 232 233sub BAIL_OUT { 234 my ($reason) = @_; 235 _print("Bail out! $reason\n"); 236 exit 255; 237} 238 239sub _ok { 240 my ($pass, $where, $name, @mess) = @_; 241 # Do not try to microoptimize by factoring out the "not ". 242 # VMS will avenge. 243 my $out; 244 if ($name) { 245 # escape out '#' or it will interfere with '# skip' and such 246 $name =~ s/#/\\#/g; 247 $out = $pass ? "ok $test - $name" : "not ok $test - $name"; 248 } else { 249 $out = $pass ? "ok $test - [$where]" : "not ok $test - [$where]"; 250 } 251 252 if ($TODO) { 253 $out = $out . " # TODO $TODO"; 254 } else { 255 $Tests_Are_Passing = 0 unless $pass; 256 } 257 258 _print "$out\n"; 259 260 if ($pass) { 261 note @mess; # Ensure that the message is properly escaped. 262 } 263 else { 264 my $msg = "# Failed test $test - "; 265 $msg.= "$name " if $name; 266 $msg .= "$where\n"; 267 _diag $msg; 268 _diag @mess; 269 } 270 271 $test = $test + 1; # don't use ++ 272 273 return $pass; 274} 275 276sub _where { 277 my (undef, $filename, $lineno) = caller($Level); 278 return "at $filename line $lineno"; 279} 280 281# DON'T use this for matches. Use like() instead. 282sub ok ($@) { 283 my ($pass, $name, @mess) = @_; 284 _ok($pass, _where(), $name, @mess); 285} 286 287sub _q { 288 my $x = shift; 289 return 'undef' unless defined $x; 290 my $q = $x; 291 $q =~ s/\\/\\\\/g; 292 $q =~ s/'/\\'/g; 293 return "'$q'"; 294} 295 296sub _qq { 297 my $x = shift; 298 return defined $x ? '"' . display ($x) . '"' : 'undef'; 299}; 300 301# Support pre-5.10 Perls, for the benefit of CPAN dists that copy this file. 302# Note that chr(90) exists in both ASCII ("Z") and EBCDIC ("!"). 303my $chars_template = defined(eval { pack "W*", 90 }) ? "W*" : "U*"; 304eval 'sub re::is_regexp { ref($_[0]) eq "Regexp" }' 305 if !defined &re::is_regexp; 306 307# keys are the codes \n etc map to, values are 2 char strings such as \n 308my %backslash_escape; 309foreach my $x (split //, 'enrtfa\\\'"') { 310 $backslash_escape{ord eval "\"\\$x\""} = "\\$x"; 311} 312# A way to display scalars containing control characters and Unicode. 313# Trying to avoid setting $_, or relying on local $_ to work. 314sub display { 315 my @result; 316 foreach my $x (@_) { 317 if (defined $x and not ref $x) { 318 my $y = ''; 319 foreach my $c (unpack($chars_template, $x)) { 320 if ($c > 255) { 321 $y = $y . sprintf "\\x{%x}", $c; 322 } elsif ($backslash_escape{$c}) { 323 $y = $y . $backslash_escape{$c}; 324 } elsif ($c < ord " ") { 325 # Use octal for characters with small ordinals that are 326 # traditionally expressed as octal: the controls below 327 # space, which on EBCDIC are almost all the controls, but 328 # on ASCII don't include DEL nor the C1 controls. 329 $y = $y . sprintf "\\%03o", $c; 330 } elsif (chr $c =~ /[[:print:]]/a) { 331 $y = $y . chr $c; 332 } 333 else { 334 $y = $y . sprintf "\\x%02X", $c; 335 } 336 } 337 $x = $y; 338 } 339 return $x unless wantarray; 340 push @result, $x; 341 } 342 return @result; 343} 344 345sub is ($$@) { 346 my ($got, $expected, $name, @mess) = @_; 347 348 my $pass; 349 if( !defined $got || !defined $expected ) { 350 # undef only matches undef 351 $pass = !defined $got && !defined $expected; 352 } 353 else { 354 $pass = $got eq $expected; 355 } 356 357 unless ($pass) { 358 unshift(@mess, "# got "._qq($got)."\n", 359 "# expected "._qq($expected)."\n"); 360 if (defined $got and defined $expected and 361 (length($got)>20 or length($expected)>20)) 362 { 363 my $p = 0; 364 $p++ while substr($got,$p,1) eq substr($expected,$p,1); 365 push @mess,"# diff at $p\n"; 366 push @mess,"# after "._qq(substr($got,$p-40<0 ? 0 : $p-40,40))."\n"; 367 push @mess,"# have "._qq(substr($got,$p,40))."\n"; 368 push @mess,"# want "._qq(substr($expected,$p,40))."\n"; 369 } 370 } 371 _ok($pass, _where(), $name, @mess); 372} 373 374sub isnt ($$@) { 375 my ($got, $isnt, $name, @mess) = @_; 376 377 my $pass; 378 if( !defined $got || !defined $isnt ) { 379 # undef only matches undef 380 $pass = defined $got || defined $isnt; 381 } 382 else { 383 $pass = $got ne $isnt; 384 } 385 386 unless( $pass ) { 387 unshift(@mess, "# it should not be "._qq($got)."\n", 388 "# but it is.\n"); 389 } 390 _ok($pass, _where(), $name, @mess); 391} 392 393sub cmp_ok ($$$@) { 394 my($got, $type, $expected, $name, @mess) = @_; 395 396 my $pass; 397 { 398 local $^W = 0; 399 local($@,$!); # don't interfere with $@ 400 # eval() sometimes resets $! 401 $pass = eval "\$got $type \$expected"; 402 } 403 unless ($pass) { 404 # It seems Irix long doubles can have 2147483648 and 2147483648 405 # that stringify to the same thing but are actually numerically 406 # different. Display the numbers if $type isn't a string operator, 407 # and the numbers are stringwise the same. 408 # (all string operators have alphabetic names, so tr/a-z// is true) 409 # This will also show numbers for some unneeded cases, but will 410 # definitely be helpful for things such as == and <= that fail 411 if ($got eq $expected and $type !~ tr/a-z//) { 412 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n"; 413 } 414 unshift(@mess, "# got "._qq($got)."\n", 415 "# expected $type "._qq($expected)."\n"); 416 } 417 _ok($pass, _where(), $name, @mess); 418} 419 420# Check that $got is within $range of $expected 421# if $range is 0, then check it's exact 422# else if $expected is 0, then $range is an absolute value 423# otherwise $range is a fractional error. 424# Here $range must be numeric, >= 0 425# Non numeric ranges might be a useful future extension. (eg %) 426sub within ($$$@) { 427 my ($got, $expected, $range, $name, @mess) = @_; 428 my $pass; 429 if (!defined $got or !defined $expected or !defined $range) { 430 # This is a fail, but doesn't need extra diagnostics 431 } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) { 432 # This is a fail 433 unshift @mess, "# got, expected and range must be numeric\n"; 434 } elsif ($range < 0) { 435 # This is also a fail 436 unshift @mess, "# range must not be negative\n"; 437 } elsif ($range == 0) { 438 # Within 0 is == 439 $pass = $got == $expected; 440 } elsif ($expected == 0) { 441 # If expected is 0, treat range as absolute 442 $pass = ($got <= $range) && ($got >= - $range); 443 } else { 444 my $diff = $got - $expected; 445 $pass = abs ($diff / $expected) < $range; 446 } 447 unless ($pass) { 448 if ($got eq $expected) { 449 unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n"; 450 } 451 unshift@mess, "# got "._qq($got)."\n", 452 "# expected "._qq($expected)." (within "._qq($range).")\n"; 453 } 454 _ok($pass, _where(), $name, @mess); 455} 456 457# Note: this isn't quite as fancy as Test::More::like(). 458 459sub like ($$@) { like_yn (0,@_) }; # 0 for - 460sub unlike ($$@) { like_yn (1,@_) }; # 1 for un- 461 462sub like_yn ($$$@) { 463 my ($flip, undef, $expected, $name, @mess) = @_; 464 465 # We just accept like(..., qr/.../), not like(..., '...'), and 466 # definitely not like(..., '/.../') like 467 # Test::Builder::maybe_regex() does. 468 unless (re::is_regexp($expected)) { 469 die "PANIC: The value '$expected' isn't a regexp. The like() function needs a qr// pattern, not a string"; 470 } 471 472 my $pass; 473 $pass = $_[1] =~ /$expected/ if !$flip; 474 $pass = $_[1] !~ /$expected/ if $flip; 475 my $display_got = $_[1]; 476 $display_got = display($display_got); 477 my $display_expected = $expected; 478 $display_expected = display($display_expected); 479 unless ($pass) { 480 unshift(@mess, "# got '$display_got'\n", 481 $flip 482 ? "# expected !~ /$display_expected/\n" 483 : "# expected /$display_expected/\n"); 484 } 485 local $Level = $Level + 1; 486 _ok($pass, _where(), $name, @mess); 487} 488 489sub refcount_is { 490 # Don't unpack first arg; access it directly via $_[0] to avoid creating 491 # another reference and upsetting the refcount 492 my (undef, $expected, $name, @mess) = @_; 493 my $got = &Internals::SvREFCNT($_[0]) + 1; # +1 to account for the & calling style 494 my $pass = $got == $expected; 495 unless ($pass) { 496 unshift @mess, "# got $got references\n" . 497 "# expected $expected\n"; 498 } 499 _ok($pass, _where(), $name, @mess); 500} 501 502sub pass { 503 _ok(1, '', @_); 504} 505 506sub fail { 507 _ok(0, _where(), @_); 508} 509 510sub curr_test { 511 $test = shift if @_; 512 return $test; 513} 514 515sub next_test { 516 my $retval = $test; 517 $test = $test + 1; # don't use ++ 518 $retval; 519} 520 521# Note: can't pass multipart messages since we try to 522# be compatible with Test::More::skip(). 523sub skip { 524 my $why = shift; 525 my $n = @_ ? shift : 1; 526 my $bad_swap; 527 my $both_zero; 528 { 529 local $^W = 0; 530 $bad_swap = $why > 0 && $n == 0; 531 $both_zero = $why == 0 && $n == 0; 532 } 533 if ($bad_swap || $both_zero || @_) { 534 my $arg = "'$why', '$n'"; 535 if (@_) { 536 $arg .= join(", ", '', map { qq['$_'] } @_); 537 } 538 die qq[$0: expected skip(why, count), got skip($arg)\n]; 539 } 540 for (1..$n) { 541 _print "ok $test # skip $why\n"; 542 $test = $test + 1; 543 } 544 local $^W = 0; 545 last SKIP; 546} 547 548sub skip_if_miniperl { 549 skip(@_) if is_miniperl(); 550} 551 552sub skip_without_dynamic_extension { 553 my $extension = shift; 554 skip("no dynamic loading on miniperl, no extension $extension", @_) 555 if is_miniperl(); 556 return if &_have_dynamic_extension($extension); 557 skip("extension $extension was not built", @_); 558} 559 560sub todo_skip { 561 my $why = shift; 562 my $n = @_ ? shift : 1; 563 564 for (1..$n) { 565 _print "not ok $test # TODO & SKIP $why\n"; 566 $test = $test + 1; 567 } 568 local $^W = 0; 569 last TODO; 570} 571 572sub eq_array { 573 my ($ra, $rb) = @_; 574 return 0 unless $#$ra == $#$rb; 575 for my $i (0..$#$ra) { 576 next if !defined $ra->[$i] && !defined $rb->[$i]; 577 return 0 if !defined $ra->[$i]; 578 return 0 if !defined $rb->[$i]; 579 return 0 unless $ra->[$i] eq $rb->[$i]; 580 } 581 return 1; 582} 583 584sub eq_hash { 585 my ($orig, $suspect) = @_; 586 my $fail; 587 while (my ($key, $value) = each %$suspect) { 588 # Force a hash recompute if this perl's internals can cache the hash key. 589 $key = "" . $key; 590 if (exists $orig->{$key}) { 591 if ( 592 defined $orig->{$key} != defined $value 593 || (defined $value && $orig->{$key} ne $value) 594 ) { 595 _print "# key ", _qq($key), " was ", _qq($orig->{$key}), 596 " now ", _qq($value), "\n"; 597 $fail = 1; 598 } 599 } else { 600 _print "# key ", _qq($key), " is ", _qq($value), 601 ", not in original.\n"; 602 $fail = 1; 603 } 604 } 605 foreach (keys %$orig) { 606 # Force a hash recompute if this perl's internals can cache the hash key. 607 $_ = "" . $_; 608 next if (exists $suspect->{$_}); 609 _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n"; 610 $fail = 1; 611 } 612 !$fail; 613} 614 615# We only provide a subset of the Test::More functionality. 616sub require_ok ($) { 617 my ($require) = @_; 618 if ($require =~ tr/[A-Za-z0-9:.]//c) { 619 fail("Invalid character in \"$require\", passed to require_ok"); 620 } else { 621 eval <<REQUIRE_OK; 622require $require; 623REQUIRE_OK 624 is($@, '', _where(), "require $require"); 625 } 626} 627 628sub use_ok ($) { 629 my ($use) = @_; 630 if ($use =~ tr/[A-Za-z0-9:.]//c) { 631 fail("Invalid character in \"$use\", passed to use"); 632 } else { 633 eval <<USE_OK; 634use $use; 635USE_OK 636 is($@, '', _where(), "use $use"); 637 } 638} 639 640# runperl, run_perl - Runs a separate perl interpreter and returns its output. 641# Arguments : 642# switches => [ command-line switches ] 643# nolib => 1 # don't use -I../lib (included by default) 644# non_portable => Don't warn if a one liner contains quotes 645# prog => one-liner (avoid quotes) 646# progs => [ multi-liner (avoid quotes) ] 647# progfile => perl script 648# stdin => string to feed the stdin (or undef to redirect from /dev/null) 649# stderr => If 'devnull' suppresses stderr, if other TRUE value redirect 650# stderr to stdout 651# args => [ command-line arguments to the perl program ] 652# verbose => print the command line 653 654my $is_mswin = $^O eq 'MSWin32'; 655my $is_vms = $^O eq 'VMS'; 656my $is_cygwin = $^O eq 'cygwin'; 657 658sub _quote_args { 659 my ($runperl, $args) = @_; 660 661 foreach (@$args) { 662 # In VMS protect with doublequotes because otherwise 663 # DCL will lowercase -- unless already doublequoted. 664 $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0; 665 $runperl = $runperl . ' ' . $_; 666 } 667 return $runperl; 668} 669 670sub _create_runperl { # Create the string to qx in runperl(). 671 my %args = @_; 672 my $runperl = which_perl(); 673 if ($runperl =~ m/\s/) { 674 $runperl = qq{"$runperl"}; 675 } 676 #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind 677 if ($ENV{PERL_RUNPERL_DEBUG}) { 678 $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl"; 679 } 680 unless ($args{nolib}) { 681 $runperl = $runperl . ' "-I../lib" "-I." '; # doublequotes because of VMS 682 } 683 if ($args{switches}) { 684 local $Level = 2; 685 die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where() 686 unless ref $args{switches} eq "ARRAY"; 687 $runperl = _quote_args($runperl, $args{switches}); 688 } 689 if (defined $args{prog}) { 690 die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where() 691 if defined $args{progs}; 692 $args{progs} = [split /\n/, $args{prog}, -1] 693 } 694 if (defined $args{progs}) { 695 die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where() 696 unless ref $args{progs} eq "ARRAY"; 697 foreach my $prog (@{$args{progs}}) { 698 if (!$args{non_portable}) { 699 if ($prog =~ tr/'"//) { 700 warn "quotes in prog >>$prog<< are not portable"; 701 } 702 if ($prog =~ /^([<>|]|2>)/) { 703 warn "Initial $1 in prog >>$prog<< is not portable"; 704 } 705 if ($prog =~ /&\z/) { 706 warn "Trailing & in prog >>$prog<< is not portable"; 707 } 708 } 709 if ($is_mswin || $is_vms) { 710 $runperl = $runperl . qq ( -e "$prog" ); 711 } 712 else { 713 $runperl = $runperl . qq ( -e '$prog' ); 714 } 715 } 716 } elsif (defined $args{progfile}) { 717 $runperl = $runperl . qq( "$args{progfile}"); 718 } else { 719 # You probably didn't want to be sucking in from the upstream stdin 720 die "test.pl:runperl(): none of prog, progs, progfile, args, " 721 . " switches or stdin specified" 722 unless defined $args{args} or defined $args{switches} 723 or defined $args{stdin}; 724 } 725 if (defined $args{stdin}) { 726 # so we don't try to put literal newlines and crs onto the 727 # command line. 728 $args{stdin} =~ s/\n/\\n/g; 729 $args{stdin} =~ s/\r/\\r/g; 730 731 if ($is_mswin || $is_vms) { 732 $runperl = qq{$Perl -e "print qq(} . 733 $args{stdin} . q{)" | } . $runperl; 734 } 735 else { 736 $runperl = qq{$Perl -e 'print qq(} . 737 $args{stdin} . q{)' | } . $runperl; 738 } 739 } elsif (exists $args{stdin}) { 740 # Using the pipe construction above can cause fun on systems which use 741 # ksh as /bin/sh, as ksh does pipes differently (with one less process) 742 # With sh, for the command line 'perl -e 'print qq()' | perl -e ...' 743 # the sh process forks two children, which use exec to start the two 744 # perl processes. The parent shell process persists for the duration of 745 # the pipeline, and the second perl process starts with no children. 746 # With ksh (and zsh), the shell saves a process by forking a child for 747 # just the first perl process, and execing itself to start the second. 748 # This means that the second perl process starts with one child which 749 # it didn't create. This causes "fun" when if the tests assume that 750 # wait (or waitpid) will only return information about processes 751 # started within the test. 752 # They also cause fun on VMS, where the pipe implementation returns 753 # the exit code of the process at the front of the pipeline, not the 754 # end. This messes up any test using OPTION FATAL. 755 # Hence it's useful to have a way to make STDIN be at eof without 756 # needing a pipeline, so that the fork tests have a sane environment 757 # without these surprises. 758 759 # /dev/null appears to be surprisingly portable. 760 $runperl = $runperl . ($is_mswin ? ' <nul' : ' </dev/null'); 761 } 762 if (defined $args{args}) { 763 $runperl = _quote_args($runperl, $args{args}); 764 } 765 if (exists $args{stderr} && $args{stderr} eq 'devnull') { 766 $runperl = $runperl . ($is_mswin ? ' 2>nul' : ' 2>/dev/null'); 767 } 768 elsif ($args{stderr}) { 769 $runperl = $runperl . ' 2>&1'; 770 } 771 if ($args{verbose}) { 772 my $runperldisplay = $runperl; 773 $runperldisplay =~ s/\n/\n\#/g; 774 _print_stderr "# $runperldisplay\n"; 775 } 776 return $runperl; 777} 778 779# usage: 780# $ENV{PATH} =~ /(.*)/s; 781# local $ENV{PATH} = untaint_path($1); 782sub untaint_path { 783 my $path = shift; 784 my $sep; 785 786 if (! eval {require Config; 1}) { 787 warn "test.pl had problems loading Config: $@"; 788 $sep = ':'; 789 } else { 790 $sep = $Config::Config{path_sep}; 791 } 792 793 $path = 794 join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and 795 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) } 796 split quotemeta ($sep), $1; 797 if ($is_cygwin) { # Must have /bin under Cygwin 798 if (length $path) { 799 $path = $path . $sep; 800 } 801 $path = $path . '/bin'; 802 } elsif (!$is_vms and !length $path) { 803 # empty PATH is the same as a path of "." on *nix so to prevent 804 # tests from dieing under taint we need to return something 805 # absolute. Perhaps "/" would be better? Anything absolute will do. 806 $path = "/usr/bin"; 807 } 808 809 $path; 810} 811 812# sub run_perl {} is alias to below 813# Since this uses backticks to run, it is subject to the rules of the shell. 814# Locale settings may pose a problem, depending on the program being run. 815sub runperl { 816 die "test.pl:runperl() does not take a hashref" 817 if ref $_[0] and ref $_[0] eq 'HASH'; 818 my $runperl = &_create_runperl; 819 my $result; 820 821 my $tainted = ${^TAINT}; 822 my %args = @_; 823 exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1; 824 825 if ($tainted) { 826 # We will assume that if you're running under -T, you really mean to 827 # run a fresh perl, so we'll brute force launder everything for you 828 my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV); 829 local @ENV{@keys} = (); 830 # Untaint, plus take out . and empty string: 831 local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s); 832 $ENV{PATH} =~ /(.*)/s; 833 local $ENV{PATH} = untaint_path($1); 834 $runperl =~ /(.*)/s; 835 $runperl = $1; 836 837 $result = `$runperl`; 838 } else { 839 $result = `$runperl`; 840 } 841 $result =~ s/\n\n/\n/g if $is_vms; # XXX pipes sometimes double these 842 return $result; 843} 844 845# Nice alias 846*run_perl = *run_perl = \&runperl; # shut up "used only once" warning 847 848# Run perl with specified environment and arguments, return (STDOUT, STDERR) 849# set DEBUG_RUNENV=1 in the environment to debug. 850sub runperl_and_capture { 851 my ($env, $args) = @_; 852 853 my $STDOUT = tempfile(); 854 my $STDERR = tempfile(); 855 my $PERL = $^X; 856 my $FAILURE_CODE = 119; 857 858 local %ENV = %ENV; 859 delete $ENV{PERLLIB}; 860 delete $ENV{PERL5LIB}; 861 delete $ENV{PERL5OPT}; 862 delete $ENV{PERL_USE_UNSAFE_INC}; 863 my $pid = fork; 864 return (0, "Couldn't fork: $!") unless defined $pid; # failure 865 if ($pid) { # parent 866 waitpid $pid,0; 867 my $exit_code = $? ? $? >> 8 : 0; 868 my ($out, $err)= ("", ""); 869 local $/; 870 if (open my $stdout, '<', $STDOUT) { 871 $out .= <$stdout>; 872 } else { 873 $err .= "Could not read STDOUT '$STDOUT' file: $!\n"; 874 } 875 if (open my $stderr, '<', $STDERR) { 876 $err .= <$stderr>; 877 } else { 878 $err .= "Could not read STDERR '$STDERR' file: $!\n"; 879 } 880 if ($exit_code == $FAILURE_CODE) { 881 $err .= "Something went wrong. Received FAILURE_CODE as exit code.\n"; 882 } 883 if ($ENV{DEBUG_RUNENV}) { 884 print "OUT: $out\n"; 885 print "ERR: $err\n"; 886 } 887 return ($out, $err); 888 } elsif (defined $pid) { # child 889 # Just in case the order we update the environment changes how 890 # the environment is set up we sort the keys here for consistency. 891 for my $k (sort keys %$env) { 892 $ENV{$k} = $env->{$k}; 893 } 894 if ($ENV{DEBUG_RUNENV}) { 895 print "Child Process $$ Executing:\n$PERL @$args\n"; 896 } 897 open STDOUT, '>', $STDOUT 898 or do { 899 print "Failed to dup STDOUT to '$STDOUT': $!"; 900 exit $FAILURE_CODE; 901 }; 902 open STDERR, '>', $STDERR 903 or do { 904 print "Failed to dup STDERR to '$STDERR': $!"; 905 exit $FAILURE_CODE; 906 }; 907 exec $PERL, @$args 908 or print STDERR "Failed to exec: ", 909 join(" ",map { "'$_'" } $^X, @$args), 910 ": $!\n"; 911 exit $FAILURE_CODE; 912 } 913} 914 915sub DIE { 916 _print_stderr "# @_\n"; 917 exit 1; 918} 919 920# A somewhat safer version of the sometimes wrong $^X. 921sub which_perl { 922 unless (defined $Perl) { 923 $Perl = $^X; 924 925 # VMS should have 'perl' aliased properly 926 return $Perl if $is_vms; 927 928 my $exe; 929 if (! eval {require Config; 1}) { 930 warn "test.pl had problems loading Config: $@"; 931 $exe = ''; 932 } else { 933 $exe = $Config::Config{_exe}; 934 } 935 $exe = '' unless defined $exe; 936 937 # This doesn't absolutize the path: beware of future chdirs(). 938 # We could do File::Spec->abs2rel() but that does getcwd()s, 939 # which is a bit heavyweight to do here. 940 941 if ($Perl =~ /^perl\Q$exe\E$/i) { 942 my $perl = "perl$exe"; 943 if (! eval {require File::Spec; 1}) { 944 warn "test.pl had problems loading File::Spec: $@"; 945 $Perl = "./$perl"; 946 } else { 947 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl); 948 } 949 } 950 951 # Build up the name of the executable file from the name of 952 # the command. 953 954 if ($Perl !~ /\Q$exe\E$/i) { 955 $Perl = $Perl . $exe; 956 } 957 958 warn "which_perl: cannot find $Perl from $^X" unless -f $Perl; 959 960 # For subcommands to use. 961 $ENV{PERLEXE} = $Perl; 962 } 963 return $Perl; 964} 965 966sub unlink_all { 967 my $count = 0; 968 foreach my $file (@_) { 969 1 while unlink $file; 970 if( -f $file ){ 971 _print_stderr "# Couldn't unlink '$file': $!\n"; 972 }else{ 973 $count = $count + 1; # don't use ++ 974 } 975 } 976 $count; 977} 978 979# _num_to_alpha - Returns a string of letters representing a positive integer. 980# Arguments : 981# number to convert 982# maximum number of letters 983 984# returns undef if the number is negative 985# returns undef if the number of letters is greater than the maximum wanted 986 987# _num_to_alpha( 0) eq 'A'; 988# _num_to_alpha( 1) eq 'B'; 989# _num_to_alpha(25) eq 'Z'; 990# _num_to_alpha(26) eq 'AA'; 991# _num_to_alpha(27) eq 'AB'; 992 993my @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); 994 995# Avoid ++ -- ranges split negative numbers 996sub _num_to_alpha { 997 my($num,$max_char) = @_; 998 return unless $num >= 0; 999 my $alpha = ''; 1000 my $char_count = 0; 1001 $max_char = 0 if !defined($max_char) or $max_char < 0; 1002 1003 while( 1 ){ 1004 $alpha = $letters[ $num % @letters ] . $alpha; 1005 $num = int( $num / @letters ); 1006 last if $num == 0; 1007 $num = $num - 1; 1008 1009 # char limit 1010 next unless $max_char; 1011 $char_count = $char_count + 1; 1012 return if $char_count == $max_char; 1013 } 1014 return $alpha; 1015} 1016 1017my %tmpfiles; 1018sub unlink_tempfiles { 1019 unlink_all keys %tmpfiles; 1020 %tempfiles = (); 1021} 1022 1023END { unlink_tempfiles(); } 1024 1025 1026# NOTE: tempfile() may be used as a module names in our tests 1027# so the result must be restricted to only legal characters for a module 1028# name. 1029 1030# A regexp that matches the tempfile names 1031$::tempfile_regexp = 'tmp_[A-Z]+_[A-Z]+'; 1032 1033# Avoid ++, avoid ranges, avoid split // 1034my $tempfile_count = 0; 1035my $max_file_chars = 3; 1036# Note that the max number of is NOT 26**3, it is 26**3 + 26**2 + 26, 1037# as 3 character files are distinct from 2 character files, from 1 characters 1038# files, etc. 1039sub tempfile { 1040 # if you change the format returned by tempfile() you MUST change 1041 # the $::tempfile_regex define above. 1042 my $try_prefix = (-d "t" ? "t/" : "")."tmp_"._num_to_alpha($$); 1043 while (1) { 1044 my $alpha = _num_to_alpha($tempfile_count,$max_file_chars); 1045 last unless defined $alpha; 1046 my $try = $try_prefix . "_" . $alpha; 1047 $tempfile_count = $tempfile_count + 1; 1048 1049 # Need to note all the file names we allocated, as a second request 1050 # may come before the first is created. Also we are avoiding ++ here 1051 # so we aren't using the normal idiom for this kind of test. 1052 if (!$tmpfiles{$try} && !-e $try) { 1053 # We have a winner 1054 $tmpfiles{$try} = 1; 1055 return $try; 1056 } 1057 } 1058 die sprintf 1059 'panic: Too many tempfile()s with prefix "%s", limit of %d reached', 1060 $try_prefix, 26 ** $max_file_chars; 1061} 1062 1063# register_tempfile - Adds a list of files to be removed at the end of the current test file 1064# Arguments : 1065# a list of files to be removed later 1066 1067# returns a count of how many file names were actually added 1068 1069# Reuses %tmpfiles so that tempfile() will also skip any files added here 1070# even if the file doesn't exist yet. 1071 1072sub register_tempfile { 1073 my $count = 0; 1074 for( @_ ){ 1075 if( $tmpfiles{$_} ){ 1076 _print_stderr "# Temporary file '$_' already added\n"; 1077 }else{ 1078 $tmpfiles{$_} = 1; 1079 $count = $count + 1; 1080 } 1081 } 1082 return $count; 1083} 1084 1085# This is the temporary file for fresh_perl 1086my $tmpfile = tempfile(); 1087 1088sub fresh_perl { 1089 my($prog, $runperl_args) = @_; 1090 1091 # Run 'runperl' with the complete perl program contained in '$prog', and 1092 # arguments in the hash referred to by '$runperl_args'. The results are 1093 # returned, with $? set to the exit code. Unless overridden, stderr is 1094 # redirected to stdout. 1095 # 1096 # Placing the program in a file bypasses various sh vagaries 1097 1098 die sprintf "Second argument to fresh_perl_.* must be hashref of args to fresh_perl (or {})" 1099 unless !(defined $runperl_args) || ref($runperl_args) eq 'HASH'; 1100 1101 # Given the choice of the mis-parsable {} 1102 # (we want an anon hash, but a borked lexer might think that it's a block) 1103 # or relying on taking a reference to a lexical 1104 # (\ might be mis-parsed, and the reference counting on the pad may go 1105 # awry) 1106 # it feels like the least-worse thing is to assume that auto-vivification 1107 # works. At least, this is only going to be a run-time failure, so won't 1108 # affect tests using this file but not this function. 1109 my $trim= delete $runperl_args->{rtrim_result}; # hide from runperl 1110 $runperl_args->{progfile} ||= $tmpfile; 1111 $runperl_args->{stderr} = 1 unless exists $runperl_args->{stderr}; 1112 1113 open TEST, '>', $tmpfile or die "Cannot open $tmpfile: $!"; 1114 binmode TEST, ':utf8' if $runperl_args->{wide_chars}; 1115 print TEST $prog; 1116 close TEST or die "Cannot close $tmpfile: $!"; 1117 1118 my $results = runperl(%$runperl_args); 1119 my $status = $?; # Not necessary to save this, but it makes it clear to 1120 # future maintainers. 1121 $results=~s/[ \t]+\n/\n/g if $trim; 1122 # Clean up the results into something a bit more predictable. 1123 $results =~ s/\n+$//; 1124 $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g; 1125 $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g; 1126 1127 # bison says 'parse error' instead of 'syntax error', 1128 # various yaccs may or may not capitalize 'syntax'. 1129 $results =~ s/^(syntax|parse) error/syntax error/mig; 1130 1131 if ($is_vms) { 1132 # some tests will trigger VMS messages that won't be expected 1133 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//; 1134 1135 # pipes double these sometimes 1136 $results =~ s/\n\n/\n/g; 1137 } 1138 1139 $? = $status; 1140 return $results; 1141} 1142 1143 1144sub _fresh_perl { 1145 my($prog, $action, $expect, $runperl_args, $name) = @_; 1146 1147 local $Level = $Level + 1; 1148 1149 # strip trailing whitespace if requested - makes some tests easier 1150 $expect=~s/[[:blank:]]+\n/\n/g if $runperl_args->{rtrim_result}; 1151 1152 my $results = fresh_perl($prog, $runperl_args); 1153 my $status = $?; 1154 1155 # Use the first line of the program as a name if none was given 1156 unless( $name ) { 1157 (my $first_line, $name) = $prog =~ /^((.{1,50}).*)/; 1158 $name = $name . '...' if length $first_line > length $name; 1159 } 1160 1161 # Historically this was implemented using a closure, but then that means 1162 # that the tests for closures avoid using this code. Given that there 1163 # are exactly two callers, doing exactly two things, the simpler approach 1164 # feels like a better trade off. 1165 my $pass; 1166 if ($action eq 'eq') { 1167 $pass = is($results, $expect, $name); 1168 } elsif ($action eq '=~') { 1169 $pass = like($results, $expect, $name); 1170 } else { 1171 die "_fresh_perl can't process action '$action'"; 1172 } 1173 1174 unless ($pass) { 1175 _diag "# PROG: \n$prog\n"; 1176 _diag "# STATUS: $status\n"; 1177 } 1178 1179 return $pass; 1180} 1181 1182# 1183# fresh_perl_is 1184# 1185# Combination of run_perl() and is(). 1186# 1187 1188sub fresh_perl_is { 1189 my($prog, $expected, $runperl_args, $name) = @_; 1190 1191 # _fresh_perl() is going to clip the trailing newlines off the result. 1192 # This will make it so the test author doesn't have to know that. 1193 $expected =~ s/\n+$//; 1194 1195 local $Level = $Level + 1; 1196 _fresh_perl($prog, 'eq', $expected, $runperl_args, $name); 1197} 1198 1199# 1200# fresh_perl_like 1201# 1202# Combination of run_perl() and like(). 1203# 1204 1205sub fresh_perl_like { 1206 my($prog, $expected, $runperl_args, $name) = @_; 1207 local $Level = $Level + 1; 1208 _fresh_perl($prog, '=~', $expected, $runperl_args, $name); 1209} 1210 1211# Many tests use the same format in __DATA__ or external files to specify a 1212# sequence of (fresh) tests to run, extra files they may temporarily need, and 1213# what the expected output is. Putting it here allows common code to serve 1214# these multiple tests. 1215# 1216# Each program is source code to run followed by an "EXPECT" line, followed 1217# by the expected output. 1218# 1219# The first line of the code to run may be a command line switch such as -wE 1220# or -0777 (alphanumerics only; only one cluster, beginning with a minus is 1221# allowed). Later lines may contain (note the '# ' on each): 1222# # TODO reason for todo 1223# # SKIP reason for skip 1224# # SKIP ?code to test if this should be skipped 1225# # NAME name of the test (as with ok($ok, $name)) 1226# 1227# The expected output may contain: 1228# OPTION list of options 1229# OPTIONS list of options 1230# 1231# The possible options for OPTION may be: 1232# regex - the expected output is a regular expression 1233# random - all lines match but in any order 1234# fatal - the code will fail fatally (croak, die) 1235# nonfatal - the code is not expected to fail fatally 1236# 1237# If the actual output contains a line "SKIPPED" the test will be 1238# skipped. 1239# 1240# If the actual output contains a line "PREFIX", any output starting with that 1241# line will be ignored when comparing with the expected output 1242# 1243# If the global variable $FATAL is true then OPTION fatal is the 1244# default. 1245 1246our $FATAL; 1247sub _setup_one_file { 1248 my $fh = shift; 1249 # Store the filename as a program that started at line 0. 1250 # Real files count lines starting at line 1. 1251 my @these = (0, shift); 1252 my ($lineno, $current); 1253 while (<$fh>) { 1254 if ($_ eq "########\n") { 1255 if (defined $current) { 1256 push @these, $lineno, $current; 1257 } 1258 undef $current; 1259 } else { 1260 if (!defined $current) { 1261 $lineno = $.; 1262 } 1263 $current .= $_; 1264 } 1265 } 1266 if (defined $current) { 1267 push @these, $lineno, $current; 1268 } 1269 ((scalar @these) / 2 - 1, @these); 1270} 1271 1272sub setup_multiple_progs { 1273 my ($tests, @prgs); 1274 foreach my $file (@_) { 1275 next if $file =~ /(?:~|\.orig|,v)$/; 1276 next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio'); 1277 next if -d $file; 1278 1279 open my $fh, '<', $file or die "Cannot open $file: $!\n" ; 1280 my $found; 1281 while (<$fh>) { 1282 if (/^__END__/) { 1283 $found = $found + 1; # don't use ++ 1284 last; 1285 } 1286 } 1287 # This is an internal error, and should never happen. All bar one of 1288 # the files had an __END__ marker to signal the end of their preamble, 1289 # although for some it wasn't technically necessary as they have no 1290 # tests. It might be possible to process files without an __END__ by 1291 # seeking back to the start and treating the whole file as tests, but 1292 # it's simpler and more reliable just to make the rule that all files 1293 # must have __END__ in. This should never fail - a file without an 1294 # __END__ should not have been checked in, because the regression tests 1295 # would not have passed. 1296 die "Could not find '__END__' in $file" 1297 unless $found; 1298 1299 my ($t, @p) = _setup_one_file($fh, $file); 1300 $tests += $t; 1301 push @prgs, @p; 1302 1303 close $fh 1304 or die "Cannot close $file: $!\n"; 1305 } 1306 return ($tests, @prgs); 1307} 1308 1309sub run_multiple_progs { 1310 my $up = shift; 1311 my @prgs; 1312 if ($up) { 1313 # The tests in lib run in a temporary subdirectory of t, and always 1314 # pass in a list of "programs" to run 1315 @prgs = @_; 1316 } else { 1317 # The tests below t run in t and pass in a file handle. In theory we 1318 # can pass (caller)[1] as the second argument to report errors with 1319 # the filename of our caller, as the handle is always DATA. However, 1320 # line numbers in DATA count from the __END__ token, so will be wrong. 1321 # Which is more confusing than not providing line numbers. So, for now, 1322 # don't provide line numbers. No obvious clean solution - one hack 1323 # would be to seek DATA back to the start and read to the __END__ token, 1324 # but that feels almost like we should just open $0 instead. 1325 1326 # Not going to rely on undef in list assignment. 1327 my $dummy; 1328 ($dummy, @prgs) = _setup_one_file(shift); 1329 } 1330 my $taint_disabled; 1331 if (! eval {require Config; 1}) { 1332 warn "test.pl had problems loading Config: $@"; 1333 $taint_disabled = ''; 1334 } else { 1335 $taint_disabled = $Config::Config{taint_disabled}; 1336 } 1337 1338 my $tmpfile = tempfile(); 1339 1340 my $count_failures = 0; 1341 my ($file, $line); 1342 PROGRAM: 1343 while (defined ($line = shift @prgs)) { 1344 $_ = shift @prgs; 1345 unless ($line) { 1346 $file = $_; 1347 if (defined $file) { 1348 print "# From $file\n"; 1349 } 1350 next; 1351 } 1352 my $switch = ""; 1353 my @temps ; 1354 my @temp_path; 1355 if (s/^(\s*-\w+)//) { 1356 $switch = $1; 1357 } 1358 1359 s/^# NOTE.*\n//mg; # remove any NOTE comments in the content 1360 1361 # unhide conflict markers - we hide them so that naive 1362 # conflict marker detection logic doesn't get upset with our 1363 # tests. 1364 s/([<=>])CONFLICT\1/$1 x 7/ge; 1365 1366 my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2); 1367 1368 my %reason; 1369 foreach my $what (qw(skip todo)) { 1370 $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1; 1371 # If the SKIP reason starts ? then it's taken as a code snippet to 1372 # evaluate. This provides the flexibility to have conditional SKIPs 1373 if ($reason{$what} && $reason{$what} =~ s/^\?//) { 1374 my $temp = eval $reason{$what}; 1375 if ($@) { 1376 die "# In \U$what\E code reason:\n# $reason{$what}\n$@"; 1377 } 1378 $reason{$what} = $temp; 1379 } 1380 } 1381 1382 my $name = ''; 1383 if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) { 1384 $name = $1; 1385 } elsif (defined $file) { 1386 $name = "test from $file at line $line"; 1387 } 1388 1389 if ($switch=~/[Tt]/ and $taint_disabled eq "define") { 1390 $reason{skip} ||= "This perl does not support taint"; 1391 } 1392 1393 if ($reason{skip}) { 1394 SKIP: 1395 { 1396 skip($name ? "$name - $reason{skip}" : $reason{skip}, 1); 1397 } 1398 next PROGRAM; 1399 } 1400 1401 if ($prog =~ /--FILE--/) { 1402 my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ; 1403 shift @files ; 1404 die "Internal error: test $_ didn't split into pairs, got " . 1405 scalar(@files) . "[" . join("%%%%", @files) ."]\n" 1406 if @files % 2; 1407 while (@files > 2) { 1408 my $filename = shift @files; 1409 my $code = shift @files; 1410 push @temps, $filename; 1411 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) { 1412 require File::Path; 1413 File::Path::mkpath($1); 1414 push(@temp_path, $1); 1415 } 1416 open my $fh, '>', $filename or die "Cannot open $filename: $!\n"; 1417 print $fh $code; 1418 close $fh or die "Cannot close $filename: $!\n"; 1419 } 1420 shift @files; 1421 $prog = shift @files; 1422 } 1423 1424 open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!"; 1425 print $fh q{ 1426 BEGIN { 1427 push @INC, '.'; 1428 open STDERR, '>&', STDOUT 1429 or die "Can't dup STDOUT->STDERR: $!;"; 1430 } 1431 }; 1432 print $fh "\n#line 1\n"; # So the line numbers don't get messed up. 1433 print $fh $prog,"\n"; 1434 close $fh or die "Cannot close $tmpfile: $!"; 1435 my $results = runperl( stderr => 1, progfile => $tmpfile, 1436 stdin => undef, $up 1437 ? (switches => ["-I$up/lib", $switch], nolib => 1) 1438 : (switches => [$switch]) 1439 ); 1440 my $status = $?; 1441 $results =~ s/\n+$//; 1442 # allow expected output to be written as if $prog is on STDIN 1443 $results =~ s/$::tempfile_regexp/-/g; 1444 if ($^O eq 'VMS') { 1445 # some tests will trigger VMS messages that won't be expected 1446 $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//; 1447 1448 # pipes double these sometimes 1449 $results =~ s/\n\n/\n/g; 1450 } 1451 # bison says 'parse error' instead of 'syntax error', 1452 # various yaccs may or may not capitalize 'syntax'. 1453 $results =~ s/^(syntax|parse) error/syntax error/mig; 1454 # allow all tests to run when there are leaks 1455 $results =~ s/Scalars leaked: \d+\n//g; 1456 1457 $expected =~ s/\n+$//; 1458 my $prefix = ($results =~ s#^PREFIX(\n|$)##) ; 1459 # any special options? (OPTIONS foo bar zap) 1460 my $option_regex = 0; 1461 my $option_random = 0; 1462 my $fatal = $FATAL; 1463 if ($expected =~ s/^OPTIONS? (.+)(?:\n|\Z)//) { 1464 foreach my $option (split(' ', $1)) { 1465 if ($option eq 'regex') { # allow regular expressions 1466 $option_regex = 1; 1467 } 1468 elsif ($option eq 'random') { # all lines match, but in any order 1469 $option_random = 1; 1470 } 1471 elsif ($option eq 'fatal') { # perl should fail 1472 $fatal = 1; 1473 } 1474 elsif ($option eq 'nonfatal') { 1475 # used to turn off default fatal 1476 $fatal = 0; 1477 } 1478 else { 1479 die "$0: Unknown OPTION '$option'\n"; 1480 } 1481 } 1482 } 1483 die "$0: can't have OPTION regex and random\n" 1484 if $option_regex + $option_random > 1; 1485 my $ok = 0; 1486 if ($results =~ s/^SKIPPED\n//) { 1487 print "$results\n" ; 1488 $ok = 1; 1489 } 1490 else { 1491 if ($option_random) { 1492 my @got = sort split "\n", $results; 1493 my @expected = sort split "\n", $expected; 1494 1495 $ok = "@got" eq "@expected"; 1496 } 1497 elsif ($option_regex) { 1498 $ok = $results =~ /^$expected/; 1499 } 1500 elsif ($prefix) { 1501 $ok = $results =~ /^\Q$expected/; 1502 } 1503 else { 1504 $ok = $results eq $expected; 1505 } 1506 1507 if ($ok && $fatal && !($status >> 8)) { 1508 $ok = 0; 1509 } 1510 } 1511 1512 local $::TODO = $reason{todo}; 1513 1514 unless ($ok) { 1515 my $err_line = ''; 1516 $err_line .= "FILE: $file ; line $line\n" if defined $file; 1517 $err_line .= "PROG: $switch\n$prog\n" . 1518 "EXPECTED:\n$expected\n"; 1519 $err_line .= "EXIT STATUS: != 0\n" if $fatal; 1520 $err_line .= "GOT:\n$results\n"; 1521 $err_line .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal; 1522 if ($::TODO) { 1523 $err_line =~ s/^/# /mg; 1524 print $err_line; # Harness can't filter it out from STDERR. 1525 } 1526 else { 1527 print STDERR $err_line; 1528 ++$count_failures; 1529 die "PERL_TEST_ABORT_FIRST_FAILURE set Test Failure" 1530 if $ENV{PERL_TEST_ABORT_FIRST_FAILURE}; 1531 } 1532 } 1533 1534 if (defined $file) { 1535 _ok($ok, "at $file line $line", $name); 1536 } else { 1537 # We don't have file and line number data for the test, so report 1538 # errors as coming from our caller. 1539 local $Level = $Level + 1; 1540 ok($ok, $name); 1541 } 1542 1543 foreach (@temps) { 1544 unlink $_ if $_; 1545 } 1546 foreach (@temp_path) { 1547 File::Path::rmtree $_ if -d $_; 1548 } 1549 } 1550 1551 if ( $count_failures ) { 1552 print STDERR <<'EOS'; 1553# 1554# Note: 'run_multiple_progs' run has one or more failures 1555# you can consider setting the environment variable 1556# PERL_TEST_ABORT_FIRST_FAILURE=1 before running the test 1557# to stop on the first error. 1558# 1559EOS 1560 } 1561 1562 1563 return; 1564} 1565 1566sub can_ok ($@) { 1567 my($proto, @methods) = @_; 1568 my $class = ref $proto || $proto; 1569 1570 unless( @methods ) { 1571 return _ok( 0, _where(), "$class->can(...)" ); 1572 } 1573 1574 my @nok = (); 1575 foreach my $method (@methods) { 1576 local($!, $@); # don't interfere with caller's $@ 1577 # eval sometimes resets $! 1578 eval { $proto->can($method) } || push @nok, $method; 1579 } 1580 1581 my $name; 1582 $name = @methods == 1 ? "$class->can('$methods[0]')" 1583 : "$class->can(...)"; 1584 1585 _ok( !@nok, _where(), $name ); 1586} 1587 1588 1589# Call $class->new( @$args ); and run the result through object_ok. 1590# See Test::More::new_ok 1591sub new_ok { 1592 my($class, $args, $obj_name) = @_; 1593 $args ||= []; 1594 $obj_name = "The object" unless defined $obj_name; 1595 1596 local $Level = $Level + 1; 1597 1598 my $obj; 1599 my $ok = eval { $obj = $class->new(@$args); 1 }; 1600 my $error = $@; 1601 1602 if($ok) { 1603 object_ok($obj, $class, $obj_name); 1604 } 1605 else { 1606 ok( 0, "new() died" ); 1607 diag("Error was: $@"); 1608 } 1609 1610 return $obj; 1611 1612} 1613 1614 1615sub isa_ok ($$;$) { 1616 my($object, $class, $obj_name) = @_; 1617 1618 my $diag; 1619 $obj_name = 'The object' unless defined $obj_name; 1620 my $name = "$obj_name isa $class"; 1621 if( !defined $object ) { 1622 $diag = "$obj_name isn't defined"; 1623 } 1624 else { 1625 my $whatami = ref $object ? 'object' : 'class'; 1626 1627 # We can't use UNIVERSAL::isa because we want to honor isa() overrides 1628 local($@, $!); # eval sometimes resets $! 1629 my $rslt = eval { $object->isa($class) }; 1630 my $error = $@; # in case something else blows away $@ 1631 1632 if( $error ) { 1633 if( $error =~ /^Can't call method "isa" on unblessed reference/ ) { 1634 # It's an unblessed reference 1635 $obj_name = 'The reference' unless defined $obj_name; 1636 if( !UNIVERSAL::isa($object, $class) ) { 1637 my $ref = ref $object; 1638 $diag = "$obj_name isn't a '$class' it's a '$ref'"; 1639 } 1640 } 1641 elsif( $error =~ /Can't call method "isa" without a package/ ) { 1642 # It's something that can't even be a class 1643 $obj_name = 'The thing' unless defined $obj_name; 1644 $diag = "$obj_name isn't a class or reference"; 1645 } 1646 else { 1647 die <<WHOA; 1648WHOA! I tried to call ->isa on your object and got some weird error. 1649This should never happen. Please contact the author immediately. 1650Here's the error. 1651$@ 1652WHOA 1653 } 1654 } 1655 elsif( !$rslt ) { 1656 $obj_name = "The $whatami" unless defined $obj_name; 1657 my $ref = ref $object; 1658 $diag = "$obj_name isn't a '$class' it's a '$ref'"; 1659 } 1660 } 1661 1662 _ok( !$diag, _where(), $name ); 1663} 1664 1665 1666sub class_ok { 1667 my($class, $isa, $class_name) = @_; 1668 1669 # Written so as to count as one test 1670 local $Level = $Level + 1; 1671 if( ref $class ) { 1672 ok( 0, "$class is a reference, not a class name" ); 1673 } 1674 else { 1675 isa_ok($class, $isa, $class_name); 1676 } 1677} 1678 1679 1680sub object_ok { 1681 my($obj, $isa, $obj_name) = @_; 1682 1683 local $Level = $Level + 1; 1684 if( !ref $obj ) { 1685 ok( 0, "$obj is not a reference" ); 1686 } 1687 else { 1688 isa_ok($obj, $isa, $obj_name); 1689 } 1690} 1691 1692 1693# Purposefully avoiding a closure. 1694sub __capture { 1695 push @::__capture, join "", @_; 1696} 1697 1698sub capture_warnings { 1699 my $code = shift; 1700 1701 local @::__capture; 1702 local $SIG {__WARN__} = \&__capture; 1703 local $Level = 1; 1704 &$code; 1705 return @::__capture; 1706} 1707 1708# This will generate a variable number of tests. 1709# Use done_testing() instead of a fixed plan. 1710sub warnings_like { 1711 my ($code, $expect, $name) = @_; 1712 local $Level = $Level + 1; 1713 1714 my @w = capture_warnings($code); 1715 1716 cmp_ok(scalar @w, '==', scalar @$expect, $name); 1717 foreach my $e (@$expect) { 1718 if (ref $e) { 1719 like(shift @w, $e, $name); 1720 } else { 1721 is(shift @w, $e, $name); 1722 } 1723 } 1724 if (@w) { 1725 diag("Saw these additional warnings:"); 1726 diag($_) foreach @w; 1727 } 1728} 1729 1730sub _fail_excess_warnings { 1731 my($expect, $got, $name) = @_; 1732 local $Level = $Level + 1; 1733 # This will fail, and produce diagnostics 1734 is($expect, scalar @$got, $name); 1735 diag("Saw these warnings:"); 1736 diag($_) foreach @$got; 1737} 1738 1739sub warning_is { 1740 my ($code, $expect, $name) = @_; 1741 die sprintf "Expect must be a string or undef, not a %s reference", ref $expect 1742 if ref $expect; 1743 local $Level = $Level + 1; 1744 my @w = capture_warnings($code); 1745 if (@w > 1) { 1746 _fail_excess_warnings(0 + defined $expect, \@w, $name); 1747 } else { 1748 is($w[0], $expect, $name); 1749 } 1750} 1751 1752sub warning_like { 1753 my ($code, $expect, $name) = @_; 1754 die sprintf "Expect must be a regexp object" 1755 unless ref $expect eq 'Regexp'; 1756 local $Level = $Level + 1; 1757 my @w = capture_warnings($code); 1758 if (@w > 1) { 1759 _fail_excess_warnings(0 + defined $expect, \@w, $name); 1760 } else { 1761 like($w[0], $expect, $name); 1762 } 1763} 1764 1765# Set a watchdog to timeout the entire test file. The input seconds is 1766# multiplied by $ENV{PERL_TEST_TIME_OUT_FACTOR} (default 1; minimum 1). 1767# Set this in your profile for slow boxes, or use it to override the timeout 1768# temporarily for debugging. 1769# 1770# NOTE: If the test file uses 'threads', then call the watchdog() function 1771# _AFTER_ the 'threads' module is loaded. 1772{ # Closure 1773 my $watchdog; 1774 my $watchdog_thread; 1775 1776sub watchdog ($;$) 1777{ 1778 my $timeout = shift; 1779 1780 # If cancelling, use the state variables to know which method was used to 1781 # create the watchdog. 1782 if ($timeout == 0) { 1783 if ($watchdog_thread) { 1784 $watchdog_thread->kill('KILL'); 1785 undef $watch_dog_thread; 1786 } 1787 elsif ($watchdog) { 1788 kill('KILL', $watchdog); 1789 undef $watch_dog; 1790 } 1791 else { 1792 alarm(0); 1793 } 1794 1795 return; 1796 } 1797 1798 # Make sure these aren't defined. 1799 undef $watchdog; 1800 undef $watchdog_thread; 1801 1802 my $method = shift || ""; 1803 1804 my $timeout_msg = 'Test process timed out - terminating'; 1805 1806 # Accept either spelling 1807 my $timeout_factor = $ENV{PERL_TEST_TIME_OUT_FACTOR} 1808 || $ENV{PERL_TEST_TIMEOUT_FACTOR} 1809 || 1; 1810 $timeout_factor = 1 if $timeout_factor < 1; 1811 $timeout_factor = $1 if $timeout_factor =~ /^(\d+)$/; 1812 1813 # Valgrind slows perl way down so give it more time before dying. 1814 $timeout_factor = 10 if $timeout_factor < 10 && $ENV{PERL_VALGRIND}; 1815 1816 $timeout *= $timeout_factor; 1817 1818 my $pid_to_kill = $$; # PID for this process 1819 1820 if ($method eq "alarm") { 1821 goto WATCHDOG_VIA_ALARM; 1822 } 1823 1824 # shut up use only once warning 1825 my $threads_on = $threads::threads && $threads::threads; 1826 1827 # Don't use a watchdog process if 'threads' is loaded - 1828 # use a watchdog thread instead 1829 if (!$threads_on || $method eq "process") { 1830 1831 # On Windows and VMS, try launching a watchdog process 1832 # using system(1, ...) (see perlport.pod). system() returns 1833 # immediately on these platforms with effectively a pid of the new 1834 # process 1835 if ($is_mswin || $is_vms) { 1836 # On Windows, try to get the 'real' PID 1837 if ($is_mswin) { 1838 eval { require Win32; }; 1839 if (defined(&Win32::GetCurrentProcessId)) { 1840 $pid_to_kill = Win32::GetCurrentProcessId(); 1841 } 1842 } 1843 1844 # If we still have a fake PID, we can't use this method at all 1845 return if ($pid_to_kill <= 0); 1846 1847 # Launch watchdog process 1848 undef $watchdog; 1849 eval { 1850 local $SIG{'__WARN__'} = sub { 1851 _diag("Watchdog warning: $_[0]"); 1852 }; 1853 my $sig = $is_vms ? 'TERM' : 'KILL'; 1854 my $prog = "sleep($timeout);" . 1855 "warn qq/# $timeout_msg" . '\n/;' . 1856 "kill(q/$sig/, $pid_to_kill);"; 1857 1858 # If we're in taint mode PATH will be tainted 1859 $ENV{PATH} =~ /(.*)/s; 1860 local $ENV{PATH} = untaint_path($1); 1861 1862 # On Windows use the indirect object plus LIST form to guarantee 1863 # that perl is launched directly rather than via the shell (see 1864 # perlfunc.pod), and ensure that the LIST has multiple elements 1865 # since the indirect object plus COMMANDSTRING form seems to 1866 # hang (see perl #121283). Don't do this on VMS, which doesn't 1867 # support the LIST form at all. 1868 if ($is_mswin) { 1869 my $runperl = which_perl(); 1870 $runperl =~ /(.*)/; 1871 $runperl = $1; 1872 if ($runperl =~ m/\s/) { 1873 $runperl = qq{"$runperl"}; 1874 } 1875 $watchdog = system({ $runperl } 1, $runperl, '-e', $prog); 1876 } 1877 else { 1878 my $cmd = _create_runperl(prog => $prog); 1879 $watchdog = system(1, $cmd); 1880 } 1881 }; 1882 if ($@ || ($watchdog <= 0)) { 1883 _diag('Failed to start watchdog'); 1884 _diag($@) if $@; 1885 undef($watchdog); 1886 return; 1887 } 1888 1889 # Add END block to parent to terminate and 1890 # clean up watchdog process 1891 eval("END { local \$! = 0; local \$? = 0; 1892 wait() if kill('KILL', $watchdog); };"); 1893 return; 1894 } 1895 1896 # Try using fork() to generate a watchdog process 1897 undef $watchdog; 1898 eval { $watchdog = fork() }; 1899 if (defined($watchdog)) { 1900 if ($watchdog) { # Parent process 1901 # Add END block to parent to terminate and 1902 # clean up watchdog process 1903 eval "END { local \$! = 0; local \$? = 0; 1904 wait() if kill('KILL', $watchdog); };"; 1905 return; 1906 } 1907 1908 ### Watchdog process code 1909 1910 # Load POSIX if available 1911 eval { require POSIX; }; 1912 1913 # Execute the timeout 1914 sleep($timeout - 2) if ($timeout > 2); # Workaround for perlbug #49073 1915 sleep(2); 1916 1917 # Kill test process if still running 1918 if (kill(0, $pid_to_kill)) { 1919 _diag($timeout_msg); 1920 kill('KILL', $pid_to_kill); 1921 if ($is_cygwin) { 1922 # sometimes the above isn't enough on cygwin 1923 sleep 1; # wait a little, it might have worked after all 1924 system("/bin/kill -f $pid_to_kill") if kill(0, $pid_to_kill); 1925 } 1926 } 1927 1928 # Don't execute END block (added at beginning of this file) 1929 $NO_ENDING = 1; 1930 1931 # Terminate ourself (i.e., the watchdog) 1932 POSIX::_exit(1) if (defined(&POSIX::_exit)); 1933 exit(1); 1934 } 1935 1936 # fork() failed - fall through and try using a thread 1937 } 1938 1939 # Use a watchdog thread because either 'threads' is loaded, 1940 # or fork() failed 1941 if (eval {require threads; 1}) { 1942 $watchdog_thread = 'threads'->create(sub { 1943 # Load POSIX if available 1944 eval { require POSIX; }; 1945 1946 $SIG{'KILL'} = sub { threads->exit(); }; 1947 1948 # Detach after the signal handler is set up; the parent knows 1949 # not to signal until detached. 1950 'threads'->detach(); 1951 1952 # Execute the timeout 1953 my $time_left = $timeout; 1954 do { 1955 $time_left = $time_left - sleep($time_left); 1956 } while ($time_left > 0); 1957 1958 # Kill the parent (and ourself) 1959 select(STDERR); $| = 1; 1960 _diag($timeout_msg); 1961 POSIX::_exit(1) if (defined(&POSIX::_exit)); 1962 my $sig = $is_vms ? 'TERM' : 'KILL'; 1963 kill($sig, $pid_to_kill); 1964 }); 1965 1966 # Don't proceed until the watchdog has set up its signal handler. 1967 # (Otherwise there is a possibility that we will exit with threads 1968 # running.) The watchdog tells us the handler is set by detaching 1969 # itself. (The 'is_running()' is a fail-safe.) 1970 while ( $watchdog_thread->is_running() 1971 && ! $watchdog_thread->is_detached()) 1972 { 1973 'threads'->yield(); 1974 } 1975 1976 return; 1977 } 1978 1979 # If everything above fails, then just use an alarm timeout 1980WATCHDOG_VIA_ALARM: 1981 if (eval { alarm($timeout); 1; }) { 1982 # Load POSIX if available 1983 eval { require POSIX; }; 1984 1985 # Alarm handler will do the actual 'killing' 1986 $SIG{'ALRM'} = sub { 1987 select(STDERR); $| = 1; 1988 _diag($timeout_msg); 1989 POSIX::_exit(1) if (defined(&POSIX::_exit)); 1990 my $sig = $is_vms ? 'TERM' : 'KILL'; 1991 kill($sig, $pid_to_kill); 1992 }; 1993 } 1994} 1995} # End closure 1996 1997# Orphaned Docker or Linux containers do not necessarily attach to PID 1. They might attach to 0 instead. 1998sub is_linux_container { 1999 2000 if ($^O eq 'linux' && open my $fh, '<', '/proc/1/cgroup') { 2001 while(<$fh>) { 2002 if (m{^\d+:pids:(.*)} && $1 ne '/init.scope') { 2003 return 1; 2004 } 2005 } 2006 } 2007 2008 return 0; 2009} 2010 20111; 2012