1use strict; 2 3package Test::Tester; 4 5BEGIN 6{ 7 if (*Test::Builder::new{CODE}) 8 { 9 warn "You should load Test::Tester before Test::Builder (or anything that loads Test::Builder)" 10 } 11} 12 13use Test::Builder; 14use Test::Tester::CaptureRunner; 15use Test::Tester::Delegate; 16 17require Exporter; 18 19use vars qw( @ISA @EXPORT $VERSION ); 20 21$VERSION = "0.114"; 22@EXPORT = qw( run_tests check_tests check_test cmp_results show_space ); 23@ISA = qw( Exporter ); 24 25my $Test = Test::Builder->new; 26my $Capture = Test::Tester::Capture->new; 27my $Delegator = Test::Tester::Delegate->new; 28$Delegator->{Object} = $Test; 29 30my $runner = Test::Tester::CaptureRunner->new; 31 32my $want_space = $ENV{TESTTESTERSPACE}; 33 34sub show_space 35{ 36 $want_space = 1; 37} 38 39my $colour = ''; 40my $reset = ''; 41 42if (my $want_colour = $ENV{TESTTESTERCOLOUR} || $ENV{TESTTESTERCOLOUR}) 43{ 44 if (eval "require Term::ANSIColor") 45 { 46 my ($f, $b) = split(",", $want_colour); 47 $colour = Term::ANSIColor::color($f).Term::ANSIColor::color("on_$b"); 48 $reset = Term::ANSIColor::color("reset"); 49 } 50 51} 52 53sub new_new 54{ 55 return $Delegator; 56} 57 58sub capture 59{ 60 return Test::Tester::Capture->new; 61} 62 63sub fh 64{ 65 # experiment with capturing output, I don't like it 66 $runner = Test::Tester::FHRunner->new; 67 68 return $Test; 69} 70 71sub find_run_tests 72{ 73 my $d = 1; 74 my $found = 0; 75 while ((not $found) and (my ($sub) = (caller($d))[3]) ) 76 { 77# print "$d: $sub\n"; 78 $found = ($sub eq "Test::Tester::run_tests"); 79 $d++; 80 } 81 82# die "Didn't find 'run_tests' in caller stack" unless $found; 83 return $d; 84} 85 86sub run_tests 87{ 88 local($Delegator->{Object}) = $Capture; 89 90 $runner->run_tests(@_); 91 92 return ($runner->get_premature, $runner->get_results); 93} 94 95sub check_test 96{ 97 my $test = shift; 98 my $expect = shift; 99 my $name = shift; 100 $name = "" unless defined($name); 101 102 @_ = ($test, [$expect], $name); 103 goto &check_tests; 104} 105 106sub check_tests 107{ 108 my $test = shift; 109 my $expects = shift; 110 my $name = shift; 111 $name = "" unless defined($name); 112 113 my ($prem, @results) = eval { run_tests($test, $name) }; 114 115 $Test->ok(! $@, "Test '$name' completed") || $Test->diag($@); 116 $Test->ok(! length($prem), "Test '$name' no premature diagnostication") || 117 $Test->diag("Before any testing anything, your tests said\n$prem"); 118 119 local $Test::Builder::Level = $Test::Builder::Level + 1; 120 cmp_results(\@results, $expects, $name); 121 return ($prem, @results); 122} 123 124sub cmp_field 125{ 126 my ($result, $expect, $field, $desc) = @_; 127 128 if (defined $expect->{$field}) 129 { 130 $Test->is_eq($result->{$field}, $expect->{$field}, 131 "$desc compare $field"); 132 } 133} 134 135sub cmp_result 136{ 137 my ($result, $expect, $name) = @_; 138 139 my $sub_name = $result->{name}; 140 $sub_name = "" unless defined($name); 141 142 my $desc = "subtest '$sub_name' of '$name'"; 143 144 { 145 local $Test::Builder::Level = $Test::Builder::Level + 1; 146 147 cmp_field($result, $expect, "ok", $desc); 148 149 cmp_field($result, $expect, "actual_ok", $desc); 150 151 cmp_field($result, $expect, "type", $desc); 152 153 cmp_field($result, $expect, "reason", $desc); 154 155 cmp_field($result, $expect, "name", $desc); 156 } 157 158 # if we got no depth then default to 1 159 my $depth = 1; 160 if (exists $expect->{depth}) 161 { 162 $depth = $expect->{depth}; 163 } 164 165 # if depth was explicitly undef then don't test it 166 if (defined $depth) 167 { 168 $Test->is_eq($result->{depth}, $depth, "checking depth") || 169 $Test->diag('You need to change $Test::Builder::Level'); 170 } 171 172 if (defined(my $exp = $expect->{diag})) 173 { 174 # if there actually is some diag then put a \n on the end if it's not 175 # there already 176 177 $exp .= "\n" if (length($exp) and $exp !~ /\n$/); 178 if (not $Test->ok($result->{diag} eq $exp, 179 "subtest '$sub_name' of '$name' compare diag") 180 ) 181 { 182 my $got = $result->{diag}; 183 my $glen = length($got); 184 my $elen = length($exp); 185 for ($got, $exp) 186 { 187 my @lines = split("\n", $_); 188 $_ = join("\n", map { 189 if ($want_space) 190 { 191 $_ = $colour.escape($_).$reset; 192 } 193 else 194 { 195 "'$colour$_$reset'" 196 } 197 } @lines); 198 } 199 200 $Test->diag(<<EOM); 201Got diag ($glen bytes): 202$got 203Expected diag ($elen bytes): 204$exp 205EOM 206 207 } 208 } 209} 210 211sub escape 212{ 213 my $str = shift; 214 my $res = ''; 215 for my $char (split("", $str)) 216 { 217 my $c = ord($char); 218 if(($c>32 and $c<125) or $c == 10) 219 { 220 $res .= $char; 221 } 222 else 223 { 224 $res .= sprintf('\x{%x}', $c) 225 } 226 } 227 return $res; 228} 229 230sub cmp_results 231{ 232 my ($results, $expects, $name) = @_; 233 234 $Test->is_num(scalar @$results, scalar @$expects, "Test '$name' result count"); 235 236 for (my $i = 0; $i < @$expects; $i++) 237 { 238 my $expect = $expects->[$i]; 239 my $result = $results->[$i]; 240 241 local $Test::Builder::Level = $Test::Builder::Level + 1; 242 cmp_result($result, $expect, $name); 243 } 244} 245 246######## nicked from Test::More 247sub plan { 248 my(@plan) = @_; 249 250 my $caller = caller; 251 252 $Test->exported_to($caller); 253 254 my @imports = (); 255 foreach my $idx (0..$#plan) { 256 if( $plan[$idx] eq 'import' ) { 257 my($tag, $imports) = splice @plan, $idx, 2; 258 @imports = @$imports; 259 last; 260 } 261 } 262 263 $Test->plan(@plan); 264 265 __PACKAGE__->_export_to_level(1, __PACKAGE__, @imports); 266} 267 268sub import { 269 my($class) = shift; 270 { 271 no warnings 'redefine'; 272 *Test::Builder::new = \&new_new; 273 } 274 goto &plan; 275} 276 277sub _export_to_level 278{ 279 my $pkg = shift; 280 my $level = shift; 281 (undef) = shift; # redundant arg 282 my $callpkg = caller($level); 283 $pkg->export($callpkg, @_); 284} 285 286 287############ 288 2891; 290 291__END__ 292 293=head1 NAME 294 295Test::Tester - Ease testing test modules built with Test::Builder 296 297=head1 SYNOPSIS 298 299 use Test::Tester tests => 6; 300 301 use Test::MyStyle; 302 303 check_test( 304 sub { 305 is_mystyle_eq("this", "that", "not eq"); 306 }, 307 { 308 ok => 0, # expect this to fail 309 name => "not eq", 310 diag => "Expected: 'this'\nGot: 'that'", 311 } 312 ); 313 314or 315 316 use Test::Tester; 317 318 use Test::More tests => 3; 319 use Test::MyStyle; 320 321 my ($premature, @results) = run_tests( 322 sub { 323 is_database_alive("dbname"); 324 } 325 ); 326 327 # now use Test::More::like to check the diagnostic output 328 329 like($results[0]->{diag}, "/^Database ping took \\d+ seconds$"/, "diag"); 330 331=head1 DESCRIPTION 332 333If you have written a test module based on Test::Builder then Test::Tester 334allows you to test it with the minimum of effort. 335 336=head1 HOW TO USE (THE EASY WAY) 337 338From version 0.08 Test::Tester no longer requires you to included anything 339special in your test modules. All you need to do is 340 341 use Test::Tester; 342 343in your test script B<before> any other Test::Builder based modules and away 344you go. 345 346Other modules based on Test::Builder can be used to help with the 347testing. In fact you can even use functions from your module to test 348other functions from the same module (while this is possible it is 349probably not a good idea, if your module has bugs, then 350using it to test itself may give the wrong answers). 351 352The easiest way to test is to do something like 353 354 check_test( 355 sub { is_mystyle_eq("this", "that", "not eq") }, 356 { 357 ok => 0, # we expect the test to fail 358 name => "not eq", 359 diag => "Expected: 'this'\nGot: 'that'", 360 } 361 ); 362 363this will execute the is_mystyle_eq test, capturing it's results and 364checking that they are what was expected. 365 366You may need to examine the test results in a more flexible way, for 367example, the diagnostic output may be quite long or complex or it may involve 368something that you cannot predict in advance like a timestamp. In this case 369you can get direct access to the test results: 370 371 my ($premature, @results) = run_tests( 372 sub { 373 is_database_alive("dbname"); 374 } 375 ); 376 377 like($result[0]->{diag}, "/^Database ping took \\d+ seconds$"/, "diag"); 378 379 380We cannot predict how long the database ping will take so we use 381Test::More's like() test to check that the diagnostic string is of the right 382form. 383 384=head1 HOW TO USE (THE HARD WAY) 385 386I<This is here for backwards compatibility only> 387 388Make your module use the Test::Tester::Capture object instead of the 389Test::Builder one. How to do this depends on your module but assuming that 390your module holds the Test::Builder object in $Test and that all your test 391routines access it through $Test then providing a function something like this 392 393 sub set_builder 394 { 395 $Test = shift; 396 } 397 398should allow your test scripts to do 399 400 Test::YourModule::set_builder(Test::Tester->capture); 401 402and after that any tests inside your module will captured. 403 404=head1 TEST RESULTS 405 406The result of each test is captured in a hash. These hashes are the same as 407the hashes returned by Test::Builder->details but with a couple of extra 408fields. 409 410These fields are documented in L<Test::Builder> in the details() function 411 412=over 2 413 414=item ok 415 416Did the test pass? 417 418=item actual_ok 419 420Did the test really pass? That is, did the pass come from 421Test::Builder->ok() or did it pass because it was a TODO test? 422 423=item name 424 425The name supplied for the test. 426 427=item type 428 429What kind of test? Possibilities include, skip, todo etc. See 430L<Test::Builder> for more details. 431 432=item reason 433 434The reason for the skip, todo etc. See L<Test::Builder> for more details. 435 436=back 437 438These fields are exclusive to Test::Tester. 439 440=over 2 441 442=item diag 443 444Any diagnostics that were output for the test. This only includes 445diagnostics output B<after> the test result is declared. 446 447Note that Test::Builder ensures that any diagnostics end in a \n and 448it in earlier versions of Test::Tester it was essential that you have 449the final \n in your expected diagnostics. From version 0.10 onwards, 450Test::Tester will add the \n if you forgot it. It will not add a \n if 451you are expecting no diagnostics. See below for help tracking down 452hard to find space and tab related problems. 453 454=item depth 455 456This allows you to check that your test module is setting the correct value 457for $Test::Builder::Level and thus giving the correct file and line number 458when a test fails. It is calculated by looking at caller() and 459$Test::Builder::Level. It should count how many subroutines there are before 460jumping into the function you are testing. So for example in 461 462 run_tests( sub { my_test_function("a", "b") } ); 463 464the depth should be 1 and in 465 466 sub deeper { my_test_function("a", "b") } 467 468 run_tests(sub { deeper() }); 469 470depth should be 2, that is 1 for the sub {} and one for deeper(). This 471might seem a little complex but if your tests look like the simple 472examples in this doc then you don't need to worry as the depth will 473always be 1 and that's what Test::Tester expects by default. 474 475B<Note>: if you do not specify a value for depth in check_test() then it 476automatically compares it against 1, if you really want to skip the depth 477test then pass in undef. 478 479B<Note>: depth will not be correctly calculated for tests that run from a 480signal handler or an END block or anywhere else that hides the call stack. 481 482=back 483 484Some of Test::Tester's functions return arrays of these hashes, just 485like Test::Builder->details. That is, the hash for the first test will 486be array element 1 (not 0). Element 0 will not be a hash it will be a 487string which contains any diagnostic output that came before the first 488test. This should usually be empty, if it's not, it means something 489output diagnostics before any test results showed up. 490 491=head1 SPACES AND TABS 492 493Appearances can be deceptive, especially when it comes to emptiness. If you 494are scratching your head trying to work out why Test::Tester is saying that 495your diagnostics are wrong when they look perfectly right then the answer is 496probably whitespace. From version 0.10 on, Test::Tester surrounds the 497expected and got diag values with single quotes to make it easier to spot 498trailing whitesapce. So in this example 499 500 # Got diag (5 bytes): 501 # 'abcd ' 502 # Expected diag (4 bytes): 503 # 'abcd' 504 505it is quite clear that there is a space at the end of the first string. 506Another way to solve this problem is to use colour and inverse video on an 507ANSI terminal, see below COLOUR below if you want this. 508 509Unfortunately this is sometimes not enough, neither colour nor quotes will 510help you with problems involving tabs, other non-printing characters and 511certain kinds of problems inherent in Unicode. To deal with this, you can 512switch Test::Tester into a mode whereby all "tricky" characters are shown as 513\{xx}. Tricky characters are those with ASCII code less than 33 or higher 514than 126. This makes the output more difficult to read but much easier to 515find subtle differences between strings. To turn on this mode either call 516show_space() in your test script or set the TESTTESTERSPACE environment 517variable to be a true value. The example above would then look like 518 519 # Got diag (5 bytes): 520 # abcd\x{20} 521 # Expected diag (4 bytes): 522 # abcd 523 524=head1 COLOUR 525 526If you prefer to use colour as a means of finding tricky whitespace 527characters then you can set the TESTTESTCOLOUR environment variable to a 528comma separated pair of colours, the first for the foreground, the second 529for the background. For example "white,red" will print white text on a red 530background. This requires the Term::ANSIColor module. You can specify any 531colour that would be acceptable to the Term::ANSIColor::color function. 532 533If you spell colour differently, that's no problem. The TESTTESTERCOLOR 534variable also works (if both are set then the British spelling wins out). 535 536=head1 EXPORTED FUNCTIONS 537 538=head3 ($premature, @results) = run_tests(\&test_sub) 539 540\&test_sub is a reference to a subroutine. 541 542run_tests runs the subroutine in $test_sub and captures the results of any 543tests inside it. You can run more than 1 test inside this subroutine if you 544like. 545 546$premature is a string containing any diagnostic output from before 547the first test. 548 549@results is an array of test result hashes. 550 551=head3 cmp_result(\%result, \%expect, $name) 552 553\%result is a ref to a test result hash. 554 555\%expect is a ref to a hash of expected values for the test result. 556 557cmp_result compares the result with the expected values. If any differences 558are found it outputs diagnostics. You may leave out any field from the 559expected result and cmp_result will not do the comparison of that field. 560 561=head3 cmp_results(\@results, \@expects, $name) 562 563\@results is a ref to an array of test results. 564 565\@expects is a ref to an array of hash refs. 566 567cmp_results checks that the results match the expected results and if any 568differences are found it outputs diagnostics. It first checks that the 569number of elements in \@results and \@expects is the same. Then it goes 570through each result checking it against the expected result as in 571cmp_result() above. 572 573=head3 ($premature, @results) = check_tests(\&test_sub, \@expects, $name) 574 575\&test_sub is a reference to a subroutine. 576 577\@expect is a ref to an array of hash refs which are expected test results. 578 579check_tests combines run_tests and cmp_tests into a single call. It also 580checks if the tests died at any stage. 581 582It returns the same values as run_tests, so you can further examine the test 583results if you need to. 584 585=head3 ($premature, @results) = check_test(\&test_sub, \%expect, $name) 586 587\&test_sub is a reference to a subroutine. 588 589\%expect is a ref to an hash of expected values for the test result. 590 591check_test is a wrapper around check_tests. It combines run_tests and 592cmp_tests into a single call, checking if the test died. It assumes 593that only a single test is run inside \&test_sub and include a test to 594make sure this is true. 595 596It returns the same values as run_tests, so you can further examine the test 597results if you need to. 598 599=head3 show_space() 600 601Turn on the escaping of characters as described in the SPACES AND TABS 602section. 603 604=head1 HOW IT WORKS 605 606Normally, a test module (let's call it Test:MyStyle) calls 607Test::Builder->new to get the Test::Builder object. Test::MyStyle calls 608methods on this object to record information about test results. When 609Test::Tester is loaded, it replaces Test::Builder's new() method with one 610which returns a Test::Tester::Delegate object. Most of the time this object 611behaves as the real Test::Builder object. Any methods that are called are 612delegated to the real Test::Builder object so everything works perfectly. 613However once we go into test mode, the method calls are no longer passed to 614the real Test::Builder object, instead they go to the Test::Tester::Capture 615object. This object seems exactly like the real Test::Builder object, 616except, instead of outputting test results and diagnostics, it just records 617all the information for later analysis. 618 619=head1 CAVEATS 620 621Support for calling Test::Builder->note is minimal. It's implemented 622as an empty stub, so modules that use it will not crash but the calls 623are not recorded for testing purposes like the others. Patches 624welcome. 625 626=head1 SEE ALSO 627 628L<Test::Builder> the source of testing goodness. L<Test::Builder::Tester> 629for an alternative approach to the problem tackled by Test::Tester - 630captures the strings output by Test::Builder. This means you cannot get 631separate access to the individual pieces of information and you must predict 632B<exactly> what your test will output. 633 634=head1 AUTHOR 635 636This module is copyright 2005 Fergal Daly <fergal@esatclear.ie>, some parts 637are based on other people's work. 638 639Plan handling lifted from Test::More. written by Michael G Schwern 640<schwern@pobox.com>. 641 642Test::Tester::Capture is a cut down and hacked up version of Test::Builder. 643Test::Builder was written by chromatic <chromatic@wgz.org> and Michael G 644Schwern <schwern@pobox.com>. 645 646=head1 LICENSE 647 648Under the same license as Perl itself 649 650See http://www.perl.com/perl/misc/Artistic.html 651 652=cut 653