File Coverage

blib/lib/Test/Builder/Tester.pm
Criterion Covered Total %
statement 113 121 93.3
branch 27 32 84.3
condition 7 13 53.8
subroutine 22 26 84.6
pod 7 7 100.0
total 176 199 88.4


line stmt bran cond sub pod time code
1             package Test::Builder::Tester;
2              
3 7     7   126938 use strict;
  7         20  
  7         379  
4 7     7   53 use vars qw(@EXPORT $VERSION @ISA);
  7         13  
  7         3301  
5             $VERSION = "1.01";
6              
7 7     7   55933 use Test::Builder;
  7         176178  
  7         231  
8 7     7   42339 use Symbol;
  7         16186  
  7         2855  
9 7     7   66 use Carp;
  7         11  
  7         1343  
10              
11             =head1 NAME
12              
13             Test::Builder::Tester - test testsuites that have been built with
14             Test::Builder
15              
16             =head1 SYNOPSIS
17              
18             use Test::Builder::Tester tests => 1;
19             use Test::More;
20              
21             test_out("not ok 1 - foo");
22             test_err("# Failed test ($0 at line ".line_num(+1).")");
23             fail("foo");
24             test_test("fail works");
25              
26             =head1 DESCRIPTION
27              
28             A module that helps you test testing modules that are built with
29             B.
30              
31             The testing system is designed to be used by performing a three step
32             process for each test you wish to test. This process starts with using
33             C and C in advance to declare what the testsuite you
34             are testing will output with B to stdout and stderr.
35              
36             You then can run the test(s) from your test suite that call
37             B. At this point the output of B is
38             safely captured by B rather than being
39             interpreted as real test output.
40              
41             The final stage is to call C that will simply compare what you
42             predeclared to what B actually outputted, and report the
43             results back with a "ok" or "not ok" (with debugging) to the normal
44             output.
45              
46             =cut
47              
48             ####
49             # set up testing
50             ####
51              
52             my $t = Test::Builder->new;
53              
54             ###
55             # make us an exporter
56             ###
57              
58 7     7   42 use Exporter;
  7         17  
  7         20685  
59             @ISA = qw(Exporter);
60              
61             @EXPORT = qw(test_out test_err test_fail test_diag test_test line_num);
62              
63             # _export_to_level and import stolen directly from Test::More. I am
64             # the king of cargo cult programming ;-)
65              
66             # 5.004's Exporter doesn't have export_to_level.
67             sub _export_to_level
68             {
69 7     7   14 my $pkg = shift;
70 7         14 my $level = shift;
71 7         15 (undef) = shift; # XXX redundant arg
72 7         19 my $callpkg = caller($level);
73 7         3786 $pkg->export($callpkg, @_);
74             }
75              
76             sub import {
77 7     7   73 my $class = shift;
78 7         24 my(@plan) = @_;
79              
80 7         30 my $caller = caller;
81              
82 7         41 $t->exported_to($caller);
83 7         91 $t->plan(@plan);
84              
85 7         4058 my @imports = ();
86 7         54 foreach my $idx (0..$#plan) {
87 8 50       43 if( $plan[$idx] eq 'import' ) {
88 0         0 @imports = @{$plan[$idx+1]};
  0         0  
89 0         0 last;
90             }
91             }
92              
93 7         42 __PACKAGE__->_export_to_level(1, __PACKAGE__, @imports);
94             }
95              
96             ###
97             # set up file handles
98             ###
99              
100             # create some private file handles
101             my $output_handle = gensym;
102             my $error_handle = gensym;
103              
104             # and tie them to this package
105             my $out = tie *$output_handle, "Test::Tester::Tie", "STDOUT";
106             my $err = tie *$error_handle, "Test::Tester::Tie", "STDERR";
107              
108             ####
109             # exported functions
110             ####
111              
112             # for remembering that we're testing and where we're testing at
113             my $testing = 0;
114             my $testing_num;
115              
116             # remembering where the file handles were originally connected
117             my $original_output_handle;
118             my $original_failure_handle;
119             my $original_todo_handle;
120              
121             my $original_test_number;
122             my $original_harness_state;
123              
124             my $original_harness_env;
125              
126             # function that starts testing and redirects the filehandles for now
127             sub _start_testing
128             {
129             # even if we're running under Test::Harness pretend we're not
130             # for now. This needed so Test::Builder doesn't add extra spaces
131 21     21   55 $original_harness_env = $ENV{HARNESS_ACTIVE};
132 21         66 $ENV{HARNESS_ACTIVE} = 0;
133              
134             # remember what the handles were set to
135 21         63 $original_output_handle = $t->output();
136 21         146 $original_failure_handle = $t->failure_output();
137 21         127 $original_todo_handle = $t->todo_output();
138              
139             # switch out to our own handles
140 21         124 $t->output($output_handle);
141 21         311 $t->failure_output($error_handle);
142 21         1059 $t->todo_output($error_handle);
143              
144             # clear the expected list
145 21         562 $out->reset();
146 21         46 $err->reset();
147              
148             # remeber that we're testing
149 21         27 $testing = 1;
150 21         64 $testing_num = $t->current_test;
151 21         167 $t->current_test(0);
152              
153             # look, we shouldn't do the ending stuff
154 21         276 $t->no_ending(1);
155             }
156              
157             =head2 Methods
158              
159             These are the six methods that are exported as default.
160              
161             =over 4
162              
163             =item test_out
164              
165             =item test_err
166              
167             Procedures for predeclaring the output that your test suite is
168             expected to produce until C is called. These procedures
169             automatically assume that each line terminates with "\n". So
170              
171             test_out("ok 1","ok 2");
172              
173             is the same as
174              
175             test_out("ok 1\nok 2");
176              
177             which is even the same as
178              
179             test_out("ok 1");
180             test_out("ok 2");
181              
182             Once C or C (or C or C) have
183             been called once all further output from B will be
184             captured by B. This means that your will not
185             be able perform further tests to the normal output in the normal way
186             until you call C (well, unless you manually meddle with the
187             output filehandles)
188              
189             =cut
190              
191             sub test_out(@)
192             {
193             # do we need to do any setup?
194 20 100   20 1 4352 _start_testing() unless $testing;
195              
196 20         137 $out->expect(@_)
197             }
198              
199             sub test_err(@)
200             {
201             # do we need to do any setup?
202 8 50   8 1 919 _start_testing() unless $testing;
203              
204 8         23 $err->expect(@_)
205             }
206              
207             =item test_fail
208              
209             Because the standard failure message that B produces
210             whenever a test fails will be a common occurrence in your test error
211             output, rather than forcing you to call C with the string
212             all the time like so
213              
214             test_err("# Failed test ($0 at line ".line_num(+1).")");
215              
216             C exists as a convenience method that can be called
217             instead. It takes one argument, the offset from the current line that
218             the line that causes the fail is on.
219              
220             test_fail(+1);
221              
222             This means that the example in the synopsis could be rewritten
223             more simply as:
224              
225             test_out("not ok 1 - foo");
226             test_fail(+1);
227             fail("foo");
228             test_test("fail works");
229              
230             =cut
231              
232             sub test_fail
233             {
234             # do we need to do any setup?
235 4 100   4 1 152 _start_testing() unless $testing;
236              
237             # work out what line we should be on
238 4         602 my ($package, $filename, $line) = caller;
239 4   50     14 $line = $line + (shift() || 0); # prevent warnings
240              
241             # expect that on stderr
242 4         23 $err->expect("# Failed test ($0 at line $line)");
243             }
244              
245             =item test_diag
246              
247             As most of the remaining expected output to the error stream will be
248             created by Test::Builder's C function, B
249             provides a convience function C that you can use instead of
250             C.
251              
252             The C function prepends comment hashes and spacing to the
253             start and newlines to the end of the expected output passed to it and
254             adds it to the list of expected error output. So, instead of writing
255              
256             test_err("# Couldn't open file");
257              
258             you can write
259              
260             test_diag("Couldn't open file");
261              
262             Remember that B's diag function will not add newlines to
263             the end of output and test_diag will. So to check
264              
265             Test::Builder->new->diag("foo\n","bar\n");
266              
267             You would do
268              
269             test_diag("foo","bar")
270              
271             without the newlines.
272              
273             =cut
274              
275             sub test_diag
276             {
277             # do we need to do any setup?
278 4 100   4 1 917 _start_testing() unless $testing;
279              
280             # expect the same thing, but prepended with "# "
281 4         17 local $_;
282 4         7 $err->expect(map {"# $_"} @_)
  6         18  
283             }
284              
285             =item test_test
286              
287             Actually performs the output check testing the tests, comparing the
288             data (with C) that we have captured from B against
289             that that was declared with C and C.
290              
291             This takes name/value pairs that effect how the test is run.
292              
293             =over
294              
295             =item title (synonym 'name', 'label')
296              
297             The name of the test that will be displayed after the C or C
298             ok>.
299              
300             =item skip_out
301              
302             Setting this to a true value will cause the test to ignore if the
303             output sent by the test to the output stream does not match that
304             declared with C.
305              
306             =item skip_err
307              
308             Setting this to a true value will cause the test to ignore if the
309             output sent by the test to the error stream does not match that
310             declared with C.
311              
312             =back
313              
314             As a convience, if only one argument is passed then this argument
315             is assumed to be the name of the test (as in the above examples.)
316              
317             Once C has been run test output will be redirected back to
318             the original filehandles that B was connected to
319             (probably STDOUT and STDERR,) meaning any further tests you run
320             will function normally and cause success/errors for B.
321              
322             =cut
323              
324             sub test_test
325             {
326             # decode the arguements as described in the pod
327 22     22 1 229 my $mess;
328             my %args;
329 22 100       66 if (@_ == 1)
330 17         31 { $mess = shift }
331             else
332             {
333 5         14 %args = @_;
334 5 100       15 $mess = $args{name} if exists($args{name});
335 5 100       10 $mess = $args{title} if exists($args{title});
336 5 100       12 $mess = $args{label} if exists($args{label});
337             }
338              
339             # er, are we testing?
340 22 100       296 croak "Not testing. You must declare output with a test function first."
341             unless $testing;
342              
343             # okay, reconnect the test suite back to the saved handles
344 21         61 $t->output($original_output_handle);
345 21         493 $t->failure_output($original_failure_handle);
346 21         275 $t->todo_output($original_todo_handle);
347              
348             # restore the test no, etc, back to the original point
349 21         340 $t->current_test($testing_num);
350 21         326 $testing = 0;
351              
352             # re-enable the original setting of the harness
353 21         69 $ENV{HARNESS_ACTIVE} = $original_harness_env;
354              
355             # check the output we've stashed
356 21 100 33     108 unless ($t->ok( ($args{skip_out} || $out->check)
357             && ($args{skip_err} || $err->check),
358             $mess))
359             {
360             # print out the diagnostic information about why this
361             # test failed
362              
363 8         5311 local $_;
364              
365 8 50 66     41 $t->diag(map {"$_\n"} $out->complaint)
  0         0  
366             unless $args{skip_out} || $out->check;
367              
368 8 50 33     34 $t->diag(map {"$_\n"} $err->complaint)
  8         38  
369             unless $args{skip_err} || $err->check;
370             }
371             }
372              
373             =item line_num
374              
375             A utility function that returns the line number that the function was
376             called on. You can pass it an offset which will be added to the
377             result. This is very useful for working out the correct text of
378             diagnostic methods that contain line numbers.
379              
380             Essentially this is the same as the C<__LINE__> macro, but the
381             C idiom is arguably nicer.
382              
383             =cut
384              
385             sub line_num
386             {
387 15     15 1 3608 my ($package, $filename, $line) = caller;
388 15   100     123 return $line + (shift() || 0); # prevent warnings
389             }
390              
391             =back
392              
393             In addition to the six exported functions there there exists one
394             function that can only be accessed with a fully qualified function
395             call.
396              
397             =over 4
398              
399             =item color
400              
401             When C is called and the output that your tests generate
402             does not match that which you declared, C will print out
403             debug information showing the two conflicting versions. As this
404             output itself is debug information it can be confusing which part of
405             the output is from C and which was the original output from
406             your original tests. Also, it may be hard to spot things like
407             extraneous whitespace at the end of lines that may cause your test to
408             fail even though the output looks similar.
409              
410             To assist you, if you have the B module installed
411             (which you should do by default from perl 5.005 onwards), C
412             can colour the background of the debug information to disambiguate the
413             different types of output. The debug output will have it's background
414             coloured green and red. The green part represents the text which is
415             the same between the executed and actual output, the red shows which
416             part differs.
417              
418             The C function determines if colouring should occur or not.
419             Passing it a true or false value will enable or disable colouring
420             respectively, and the function called with no argument will return the
421             current setting.
422              
423             To enable colouring from the command line, you can use the
424             B module like so:
425              
426             perl -Mlib=Text::Builder::Tester::Color test.t
427              
428             Or by including the B module directly in
429             the PERL5LIB.
430              
431             =cut
432              
433             my $color;
434             sub color
435             {
436 10 100   10 1 10090 $color = shift if @_;
437 10         31 $color;
438             }
439              
440             =back
441              
442             =head1 BUGS
443              
444             Calls B's C method turning off the ending
445             tests. This is needed as otherwise it will trip out because we've run
446             more tests than we strictly should have and it'll register any
447             failures we had that we were testing for as real failures.
448              
449             The color function doesn't work unless B is installed
450             and is compatible with your terminal.
451              
452             Bugs (and requests for new features) can be reported to the author
453             though the CPAN RT system:
454             L
455              
456             =head1 AUTHOR
457              
458             Copyright Mark Fowler Emark@twoshortplanks.comE 2002, 2004.
459              
460             Some code taken from B and B, written by by
461             Michael G Schwern Eschwern@pobox.comE. Hence, those parts
462             Copyright Micheal G Schwern 2001. Used and distributed with
463             permission.
464              
465             This program is free software; you can redistribute it
466             and/or modify it under the same terms as Perl itself.
467              
468             =head1 NOTES
469              
470             This code has been tested explicitly on the following versions
471             of perl: 5.7.3, 5.6.1, 5.6.0, 5.005_03, 5.004_05 and 5.004.
472              
473             Thanks to Richard Clamp Erichardc@unixbeard.netE for letting
474             me use his testing system to try this module out on.
475              
476             =head1 SEE ALSO
477              
478             L, L, L.
479              
480             =cut
481              
482             1;
483              
484             ####################################################################
485             # Helper class that is used to remember expected and received data
486              
487             package Test::Tester::Tie;
488              
489             ##
490             # add line(s) to be expected
491              
492             sub expect
493             {
494 36     36   601 my $self = shift;
495 36         77 $self->[2] .= join '', map { "$_\n" } @_;
  42         174  
496             }
497              
498             ##
499             # return true iff the expected data matches the got data
500              
501             sub check
502             {
503 55     55   96 my $self = shift;
504              
505             # turn off warnings as these might be undef
506 55         127 local $^W = 0;
507              
508 55         398 $self->[1] eq $self->[2];
509             }
510              
511             ##
512             # a complaint message about the inputs not matching (to be
513             # used for debugging messages)
514              
515             sub complaint
516             {
517 8     8   12 my $self = shift;
518 8         21 my ($type, $got, $wanted) = @$self;
519              
520             # are we running in colour mode?
521 8 100       36 if (Test::Builder::Tester::color)
522             {
523             # get color
524 1         68 eval "require Term::ANSIColor";
525 1 50       5 unless ($@)
526             {
527             # colours
528              
529 1         4 my $green = Term::ANSIColor::color("black").
530             Term::ANSIColor::color("on_green");
531 1         33 my $red = Term::ANSIColor::color("black").
532             Term::ANSIColor::color("on_red");
533 1         27 my $reset = Term::ANSIColor::color("reset");
534              
535             # work out where the two strings start to differ
536 1         14 my $char = 0;
537 1         11 $char++ while substr($got, $char, 1) eq substr($wanted, $char, 1);
538              
539             # get the start string and the two end strings
540 1         3 my $start = $green . substr($wanted, 0, $char);
541 1         3 my $gotend = $red . substr($got , $char) . $reset;
542 1         4 my $wantedend = $red . substr($wanted, $char) . $reset;
543              
544             # make the start turn green on and off
545 1         2 $start =~ s/\n/$reset\n$green/g;
546              
547             # make the ends turn red on and off
548 1         8 $gotend =~ s/\n/$reset\n$red/g;
549 1         7 $wantedend =~ s/\n/$reset\n$red/g;
550              
551             # rebuild the strings
552 1         3 $got = $start . $gotend;
553 1         4 $wanted = $start . $wantedend;
554             }
555             }
556              
557 8         38 return "$type is:\n" .
558             "$got\nnot:\n$wanted\nas expected"
559             }
560              
561             ##
562             # forget all expected and got data
563              
564             sub reset
565             {
566 42     42   53 my $self = shift;
567 42         197 @$self = ($self->[0]);
568             }
569              
570             ###
571             # tie interface
572             ###
573              
574             sub PRINT {
575 48     48   13722 my $self = shift;
576 48         320 $self->[1] .= join '', @_;
577             }
578              
579             sub TIEHANDLE {
580 14     14   303 my $class = shift;
581 14         41 my $self = [shift()];
582 14         117 return bless $self, $class;
583             }
584              
585 0     0     sub READ {}
586 0     0     sub READLINE {}
587 0     0     sub GETC {}
588 0     0     sub FILENO {}
589              
590             1;