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