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