1 package Test::Builder::Tester;
6 use Test::Builder 0.98;
12 Test::Builder::Tester - test testsuites that have been built with
17 use Test::Builder::Tester tests => 1;
20 test_out("not ok 1 - foo");
23 test_test("fail works");
27 A module that helps you test testing modules that are built with
30 The testing system is designed to be used by performing a three step
31 process for each test you wish to test. This process starts with using
32 C<test_out> and C<test_err> in advance to declare what the testsuite you
33 are testing will output with L<Test::Builder> to stdout and stderr.
35 You then can run the test(s) from your test suite that call
36 L<Test::Builder>. At this point the output of L<Test::Builder> is
37 safely captured by L<Test::Builder::Tester> rather than being
38 interpreted as real test output.
40 The final stage is to call C<test_test> that will simply compare what you
41 predeclared to what L<Test::Builder> actually outputted, and report the
42 results back with a "ok" or "not ok" (with debugging) to the normal
51 my $t = Test::Builder->new;
58 our @ISA = qw(Exporter);
60 our @EXPORT = qw(test_out test_err test_fail test_diag test_test line_num);
68 $t->exported_to($caller);
72 foreach my $idx ( 0 .. $#plan ) {
73 if( $plan[$idx] eq 'import' ) {
74 @imports = @{ $plan[ $idx + 1 ] };
79 __PACKAGE__->export_to_level( 1, __PACKAGE__, @imports );
86 # create some private file handles
87 my $output_handle = gensym;
88 my $error_handle = gensym;
90 # and tie them to this package
91 my $out = tie *$output_handle, "Test::Builder::Tester::Tie", "STDOUT";
92 my $err = tie *$error_handle, "Test::Builder::Tester::Tie", "STDERR";
98 # for remembering that we're testing and where we're testing at
101 my $original_is_passing;
103 # remembering where the file handles were originally connected
104 my $original_output_handle;
105 my $original_failure_handle;
106 my $original_todo_handle;
108 my $original_harness_env;
110 # function that starts testing and redirects the filehandles for now
112 # even if we're running under Test::Harness pretend we're not
113 # for now. This needed so Test::Builder doesn't add extra spaces
114 $original_harness_env = $ENV{HARNESS_ACTIVE} || 0;
115 $ENV{HARNESS_ACTIVE} = 0;
117 # remember what the handles were set to
118 $original_output_handle = $t->output();
119 $original_failure_handle = $t->failure_output();
120 $original_todo_handle = $t->todo_output();
122 # switch out to our own handles
123 $t->output($output_handle);
124 $t->failure_output($error_handle);
125 $t->todo_output($output_handle);
127 # clear the expected list
131 # remember that we're testing
133 $testing_num = $t->current_test;
135 $original_is_passing = $t->is_passing;
138 # look, we shouldn't do the ending stuff
144 These are the six methods that are exported as default.
152 Procedures for predeclaring the output that your test suite is
153 expected to produce until C<test_test> is called. These procedures
154 automatically assume that each line terminates with "\n". So
156 test_out("ok 1","ok 2");
160 test_out("ok 1\nok 2");
162 which is even the same as
167 Once C<test_out> or C<test_err> (or C<test_fail> or C<test_diag>) have
168 been called, all further output from L<Test::Builder> will be
169 captured by L<Test::Builder::Tester>. This means that you will not
170 be able perform further tests to the normal output in the normal way
171 until you call C<test_test> (well, unless you manually meddle with the
177 # do we need to do any setup?
178 _start_testing() unless $testing;
184 # do we need to do any setup?
185 _start_testing() unless $testing;
192 Because the standard failure message that L<Test::Builder> produces
193 whenever a test fails will be a common occurrence in your test error
194 output, and because it has changed between Test::Builder versions, rather
195 than forcing you to call C<test_err> with the string all the time like
198 test_err("# Failed test ($0 at line ".line_num(+1).")");
200 C<test_fail> exists as a convenience function that can be called
201 instead. It takes one argument, the offset from the current line that
202 the line that causes the fail is on.
206 This means that the example in the synopsis could be rewritten
209 test_out("not ok 1 - foo");
212 test_test("fail works");
217 # do we need to do any setup?
218 _start_testing() unless $testing;
220 # work out what line we should be on
221 my( $package, $filename, $line ) = caller;
222 $line = $line + ( shift() || 0 ); # prevent warnings
224 # expect that on stderr
225 $err->expect("# Failed test ($filename at line $line)");
230 As most of the remaining expected output to the error stream will be
231 created by L<Test::Builder>'s C<diag> function, L<Test::Builder::Tester>
232 provides a convenience function C<test_diag> that you can use instead of
235 The C<test_diag> function prepends comment hashes and spacing to the
236 start and newlines to the end of the expected output passed to it and
237 adds it to the list of expected error output. So, instead of writing
239 test_err("# Couldn't open file");
243 test_diag("Couldn't open file");
245 Remember that L<Test::Builder>'s diag function will not add newlines to
246 the end of output and test_diag will. So to check
248 Test::Builder->new->diag("foo\n","bar\n");
252 test_diag("foo","bar")
254 without the newlines.
259 # do we need to do any setup?
260 _start_testing() unless $testing;
262 # expect the same thing, but prepended with "# "
264 $err->expect( map { "# $_" } @_ );
269 Actually performs the output check testing the tests, comparing the
270 data (with C<eq>) that we have captured from L<Test::Builder> against
271 what was declared with C<test_out> and C<test_err>.
273 This takes name/value pairs that effect how the test is run.
277 =item title (synonym 'name', 'label')
279 The name of the test that will be displayed after the C<ok> or C<not
284 Setting this to a true value will cause the test to ignore if the
285 output sent by the test to the output stream does not match that
286 declared with C<test_out>.
290 Setting this to a true value will cause the test to ignore if the
291 output sent by the test to the error stream does not match that
292 declared with C<test_err>.
296 As a convenience, if only one argument is passed then this argument
297 is assumed to be the name of the test (as in the above examples.)
299 Once C<test_test> has been run test output will be redirected back to
300 the original filehandles that L<Test::Builder> was connected to
301 (probably STDOUT and STDERR,) meaning any further tests you run
302 will function normally and cause success/errors for L<Test::Harness>.
307 # decode the arguments as described in the pod
315 $mess = $args{name} if exists( $args{name} );
316 $mess = $args{title} if exists( $args{title} );
317 $mess = $args{label} if exists( $args{label} );
320 # er, are we testing?
321 croak "Not testing. You must declare output with a test function first."
324 # okay, reconnect the test suite back to the saved handles
325 $t->output($original_output_handle);
326 $t->failure_output($original_failure_handle);
327 $t->todo_output($original_todo_handle);
329 # restore the test no, etc, back to the original point
330 $t->current_test($testing_num);
332 $t->is_passing($original_is_passing);
334 # re-enable the original setting of the harness
335 $ENV{HARNESS_ACTIVE} = $original_harness_env;
337 # check the output we've stashed
338 unless( $t->ok( ( $args{skip_out} || $out->check ) &&
339 ( $args{skip_err} || $err->check ), $mess )
342 # print out the diagnostic information about why this
347 $t->diag( map { "$_\n" } $out->complaint )
348 unless $args{skip_out} || $out->check;
350 $t->diag( map { "$_\n" } $err->complaint )
351 unless $args{skip_err} || $err->check;
357 A utility function that returns the line number that the function was
358 called on. You can pass it an offset which will be added to the
359 result. This is very useful for working out the correct text of
360 diagnostic functions that contain line numbers.
362 Essentially this is the same as the C<__LINE__> macro, but the
363 C<line_num(+3)> idiom is arguably nicer.
368 my( $package, $filename, $line ) = caller;
369 return $line + ( shift() || 0 ); # prevent warnings
374 In addition to the six exported functions there exists one
375 function that can only be accessed with a fully qualified function
382 When C<test_test> is called and the output that your tests generate
383 does not match that which you declared, C<test_test> will print out
384 debug information showing the two conflicting versions. As this
385 output itself is debug information it can be confusing which part of
386 the output is from C<test_test> and which was the original output from
387 your original tests. Also, it may be hard to spot things like
388 extraneous whitespace at the end of lines that may cause your test to
389 fail even though the output looks similar.
391 To assist you C<test_test> can colour the background of the debug
392 information to disambiguate the different types of output. The debug
393 output will have its background coloured green and red. The green
394 part represents the text which is the same between the executed and
395 actual output, the red shows which part differs.
397 The C<color> function determines if colouring should occur or not.
398 Passing it a true or false value will enable or disable colouring
399 respectively, and the function called with no argument will return the
402 To enable colouring from the command line, you can use the
403 L<Text::Builder::Tester::Color> module like so:
405 perl -Mlib=Text::Builder::Tester::Color test.t
407 Or by including the L<Test::Builder::Tester::Color> module directly in
415 $color = shift if @_;
423 Calls C<< Test::Builder->no_ending >> turning off the ending tests.
424 This is needed as otherwise it will trip out because we've run more
425 tests than we strictly should have and it'll register any failures we
426 had that we were testing for as real failures.
428 The color function doesn't work unless L<Term::ANSIColor> is
429 compatible with your terminal.
431 Bugs (and requests for new features) can be reported to the author
432 though the CPAN RT system:
433 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test-Builder-Tester>
437 Copyright Mark Fowler E<lt>mark@twoshortplanks.comE<gt> 2002, 2004.
439 Some code taken from L<Test::More> and L<Test::Catch>, written by
440 Michael G Schwern E<lt>schwern@pobox.comE<gt>. Hence, those parts
441 Copyright Micheal G Schwern 2001. Used and distributed with
444 This program is free software; you can redistribute it
445 and/or modify it under the same terms as Perl itself.
451 =item Chad Granum E<lt>exodist@cpan.orgE<gt>
457 Thanks to Richard Clamp E<lt>richardc@unixbeard.netE<gt> for letting
458 me use his testing system to try this module out on.
462 L<Test::Builder>, L<Test::Builder::Tester::Color>, L<Test::More>.
468 ####################################################################
469 # Helper class that is used to remember expected and received data
471 package Test::Builder::Tester::Tie;
474 # add line(s) to be expected
480 foreach my $check (@checks) {
481 $check = $self->_account_for_subtest($check);
482 $check = $self->_translate_Failed_check($check);
483 push @{ $self->{wanted} }, ref $check ? $check : "$check\n";
487 sub _account_for_subtest {
488 my( $self, $check ) = @_;
490 # Since we ship with Test::Builder, calling a private method is safe...ish.
491 return ref($check) ? $check : $t->_indent . $check;
494 sub _translate_Failed_check {
495 my( $self, $check ) = @_;
497 if( $check =~ /\A(.*)# (Failed .*test) \((.*?) at line (\d+)\)\Z(?!\n)/ ) {
498 $check = "/\Q$1\E#\\s+\Q$2\E.*?\\n?.*?\Qat $3\E line \Q$4\E.*\\n?/";
505 # return true iff the expected data matches the got data
510 # turn off warnings as these might be undef
513 my @checks = @{ $self->{wanted} };
514 my $got = $self->{got};
515 foreach my $check (@checks) {
516 $check = "\Q$check\E" unless( $check =~ s,^/(.*)/$,$1, or ref $check );
517 return 0 unless $got =~ s/^$check//;
520 return length $got == 0;
524 # a complaint message about the inputs not matching (to be
525 # used for debugging messages)
529 my $type = $self->type;
530 my $got = $self->got;
531 my $wanted = join '', @{ $self->wanted };
533 # are we running in colour mode?
534 if(Test::Builder::Tester::color) {
536 eval { require Term::ANSIColor };
540 my $green = Term::ANSIColor::color("black") . Term::ANSIColor::color("on_green");
541 my $red = Term::ANSIColor::color("black") . Term::ANSIColor::color("on_red");
542 my $reset = Term::ANSIColor::color("reset");
544 # work out where the two strings start to differ
546 $char++ while substr( $got, $char, 1 ) eq substr( $wanted, $char, 1 );
548 # get the start string and the two end strings
549 my $start = $green . substr( $wanted, 0, $char );
550 my $gotend = $red . substr( $got, $char ) . $reset;
551 my $wantedend = $red . substr( $wanted, $char ) . $reset;
553 # make the start turn green on and off
554 $start =~ s/\n/$reset\n$green/g;
556 # make the ends turn red on and off
557 $gotend =~ s/\n/$reset\n$red/g;
558 $wantedend =~ s/\n/$reset\n$red/g;
560 # rebuild the strings
561 $got = $start . $gotend;
562 $wanted = $start . $wantedend;
566 return "$type is:\n" . "$got\nnot:\n$wanted\nas expected";
570 # forget all expected and got data
575 type => $self->{type},
588 return $self->{wanted};
593 return $self->{type};
602 $self->{got} .= join '', @_;
606 my( $class, $type ) = @_;
608 my $self = bless { type => $type }, $class;