2 # $Id: /mirror/googlecode/test-more-trunk/lib/Test/Builder.pm 67223 2008-10-15T03:08:18.888155Z schwern $
8 our $VERSION = '0.82_01';
9 $VERSION = eval $VERSION; ## no critic (BuiltinFunctions::ProhibitStringyEval)
11 # Make Test::Builder thread-safe for ithreads.
14 # Load threads::shared when threads are turned on.
15 # 5.8.0's threads are so busted we no longer support them.
16 if( $] >= 5.008001 && $Config{useithreads} && $INC{'threads.pm'} ) {
17 require threads::shared;
19 # Hack around YET ANOTHER threads::shared bug. It would
20 # occassionally forget the contents of the variable when sharing it.
21 # So we first copy the data, then share, then put our copy back.
22 *share = sub (\[$@%]) {
26 if( $type eq 'HASH' ) {
29 elsif( $type eq 'ARRAY' ) {
32 elsif( $type eq 'SCALAR' ) {
36 die( "Unknown type: " . $type );
39 $_[0] = &threads::shared::share( $_[0] );
41 if( $type eq 'HASH' ) {
44 elsif( $type eq 'ARRAY' ) {
47 elsif( $type eq 'SCALAR' ) {
51 die( "Unknown type: " . $type );
57 # 5.8.0's threads::shared is busted when threads are off
58 # and earlier Perls just don't have that module at all.
60 *share = sub { return $_[0] };
67 Test::Builder - Backend for building test libraries
71 package My::Test::Module;
72 use base 'Test::Builder::Module';
74 my $CLASS = __PACKAGE__;
77 my($test, $name) = @_;
78 my $tb = $CLASS->builder;
80 $tb->ok($test, $name);
86 Test::Simple and Test::More have proven to be popular testing modules,
87 but they're not always flexible enough. Test::Builder provides the a
88 building block upon which to write your own test libraries I<which can
97 my $Test = Test::Builder->new;
99 Returns a Test::Builder object representing the current state of the
102 Since you only run one test per program C<new> always returns the same
103 Test::Builder object. No matter how many times you call new(), you're
104 getting the same object. This is called a singleton. This is done so that
105 multiple modules share such global information as the test counter and
106 where test output is going.
108 If you want a completely new Test::Builder object different from the
109 singleton, use C<create>.
113 my $Test = Test::Builder->new;
117 $Test ||= $class->create;
123 my $Test = Test::Builder->create;
125 Ok, so there can be more than one Test::Builder object and this is how
126 you get it. You might use this instead of C<new()> if you're testing
127 a Test::Builder based module, but otherwise you probably want C<new>.
129 B<NOTE>: the implementation is not complete. C<level>, for example, is
130 still shared amongst B<all> Test::Builder objects, even ones created using
131 this method. Also, the method name may change in the future.
138 my $self = bless {}, $class;
148 Reinitializes the Test::Builder singleton to its original state.
149 Mostly useful for tests run in persistent environments where the same
150 test might be run multiple times in the same process.
156 sub reset { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
159 # We leave this a global because it has to be localized and localizing
160 # hash keys is just asking for pain. Also, it was documented.
163 $self->{Have_Plan} = 0;
164 $self->{No_Plan} = 0;
165 $self->{Original_Pid} = $$;
167 share( $self->{Curr_Test} );
168 $self->{Curr_Test} = 0;
169 $self->{Test_Results} = &share( [] );
171 $self->{Exported_To} = undef;
172 $self->{Expected_Tests} = 0;
174 $self->{Skip_All} = 0;
176 $self->{Use_Nums} = 1;
178 $self->{No_Header} = 0;
179 $self->{No_Ending} = 0;
181 $self->{Todo} = undef;
182 $self->{Todo_Stack} = [];
183 $self->{Start_Todo} = 0;
185 $self->_dup_stdhandles;
192 =head2 Setting up tests
194 These methods are for setting up tests and declaring how many there
195 are. You usually only want to call one of these methods.
201 $Test->plan('no_plan');
202 $Test->plan( skip_all => $reason );
203 $Test->plan( tests => $num_tests );
205 A convenient way to set up your tests. Call this and Test::Builder
206 will print the appropriate headers and take the appropriate actions.
208 If you call plan(), don't call any of the other methods below.
213 my( $self, $cmd, $arg ) = @_;
217 local $Level = $Level + 1;
219 $self->croak("You tried to plan twice")
220 if $self->{Have_Plan};
222 if( $cmd eq 'no_plan' ) {
223 $self->carp("no_plan takes no arguments") if $arg;
226 elsif( $cmd eq 'skip_all' ) {
227 return $self->skip_all($arg);
229 elsif( $cmd eq 'tests' ) {
231 local $Level = $Level + 1;
232 return $self->expected_tests($arg);
234 elsif( !defined $arg ) {
235 $self->croak("Got an undefined number of tests");
238 $self->croak("You said to run 0 tests");
242 my @args = grep { defined } ( $cmd, $arg );
243 $self->croak("plan() doesn't understand @args");
249 =item B<expected_tests>
251 my $max = $Test->expected_tests;
252 $Test->expected_tests($max);
254 Gets/sets the # of tests we expect this test to run and prints out
255 the appropriate headers.
264 $self->croak("Number of tests must be a positive integer. You gave it '$max'")
265 unless $max =~ /^\+?\d+$/;
267 $self->{Expected_Tests} = $max;
268 $self->{Have_Plan} = 1;
270 $self->_print("1..$max\n") unless $self->no_header;
272 return $self->{Expected_Tests};
279 Declares that this test will run an indeterminate # of tests.
286 $self->{No_Plan} = 1;
287 $self->{Have_Plan} = 1;
294 $plan = $Test->has_plan
296 Find out whether a plan has been defined. $plan is either C<undef> (no plan has been set), C<no_plan> (indeterminate # of tests) or an integer (the number of expected tests).
303 return( $self->{Expected_Tests} ) if $self->{Expected_Tests};
304 return('no_plan') if $self->{No_Plan};
311 $Test->skip_all($reason);
313 Skips all the tests, using the given $reason. Exits immediately with 0.
318 my( $self, $reason ) = @_;
321 $out .= " # Skip $reason" if $reason;
324 $self->{Skip_All} = 1;
326 $self->_print($out) unless $self->no_header;
332 my $pack = $Test->exported_to;
333 $Test->exported_to($pack);
335 Tells Test::Builder what package you exported your functions to.
337 This method isn't terribly useful since modules which share the same
338 Test::Builder object might get exported to different packages and only
339 the last one will be honored.
344 my( $self, $pack ) = @_;
346 if( defined $pack ) {
347 $self->{Exported_To} = $pack;
349 return $self->{Exported_To};
356 These actually run the tests, analogous to the functions in Test::More.
358 They all return true if the test passed, false if the test failed.
360 $name is always optional.
366 $Test->ok($test, $name);
368 Your basic test. Pass if $test is true, fail if $test is false. Just
369 like Test::Simple's ok().
374 my( $self, $test, $name ) = @_;
376 # $test might contain an object which we don't want to accidentally
377 # store, so we turn it into a boolean.
378 $test = $test ? 1 : 0;
382 lock $self->{Curr_Test};
383 $self->{Curr_Test}++;
385 # In case $name is a string overloaded object, force it to stringify.
386 $self->_unoverload_str( \$name );
388 $self->diag(<<"ERR") if defined $name and $name =~ /^[\d\s]+$/;
389 You named your test '$name'. You shouldn't use numbers for your test names.
393 # Capture the value of $TODO for the rest of this ok() call
394 # so it can more easily be found by other routines.
395 my $todo = $self->todo();
396 my $in_todo = $self->in_todo;
397 local $self->{Todo} = $todo if $in_todo;
399 $self->_unoverload_str( \$todo );
402 my $result = &share( {} );
406 @$result{ 'ok', 'actual_ok' } = ( ( $self->in_todo ? 1 : 0 ), 0 );
409 @$result{ 'ok', 'actual_ok' } = ( 1, $test );
413 $out .= " $self->{Curr_Test}" if $self->use_numbers;
415 if( defined $name ) {
416 $name =~ s|#|\\#|g; # # in a name can confuse Test::Harness.
418 $result->{name} = $name;
421 $result->{name} = '';
424 if( $self->in_todo ) {
425 $out .= " # TODO $todo";
426 $result->{reason} = $todo;
427 $result->{type} = 'todo';
430 $result->{reason} = '';
431 $result->{type} = '';
434 $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = $result;
440 my $msg = $self->in_todo ? "Failed (TODO)" : "Failed";
441 $self->_print_to_fh( $self->_diag_fh, "\n" ) if $ENV{HARNESS_ACTIVE};
443 my( undef, $file, $line ) = $self->caller;
444 if( defined $name ) {
445 $self->diag(qq[ $msg test '$name'\n]);
446 $self->diag(qq[ at $file line $line.\n]);
449 $self->diag(qq[ $msg test at $file line $line.\n]);
453 return $test ? 1 : 0;
460 $self->_try( sub { require overload } ) || return;
462 foreach my $thing (@_) {
463 if( $self->_is_object($$thing) ) {
464 if( my $string_meth = overload::Method( $$thing, $type ) ) {
465 $$thing = $$thing->$string_meth();
474 my( $self, $thing ) = @_;
476 return $self->_try( sub { ref $thing && $thing->isa('UNIVERSAL') } ) ? 1 : 0;
479 sub _unoverload_str {
482 return $self->_unoverload( q[""], @_ );
485 sub _unoverload_num {
488 $self->_unoverload( '0+', @_ );
490 no warnings 'numeric';
492 next unless $self->_is_dualvar($$val);
499 # This is a hack to detect a dualvar such as $!
501 my( $self, $val ) = @_;
503 no warnings 'numeric';
504 my $numval = $val + 0;
505 return $numval != 0 and $numval ne $val ? 1 : 0;
510 $Test->is_eq($got, $expected, $name);
512 Like Test::More's is(). Checks if $got eq $expected. This is the
517 $Test->is_num($got, $expected, $name);
519 Like Test::More's is(). Checks if $got == $expected. This is the
525 my( $self, $got, $expect, $name ) = @_;
526 local $Level = $Level + 1;
528 $self->_unoverload_str( \$got, \$expect );
530 if( !defined $got || !defined $expect ) {
531 # undef only matches undef and nothing else
532 my $test = !defined $got && !defined $expect;
534 $self->ok( $test, $name );
535 $self->_is_diag( $got, 'eq', $expect ) unless $test;
539 return $self->cmp_ok( $got, 'eq', $expect, $name );
543 my( $self, $got, $expect, $name ) = @_;
544 local $Level = $Level + 1;
546 $self->_unoverload_num( \$got, \$expect );
548 if( !defined $got || !defined $expect ) {
549 # undef only matches undef and nothing else
550 my $test = !defined $got && !defined $expect;
552 $self->ok( $test, $name );
553 $self->_is_diag( $got, '==', $expect ) unless $test;
557 return $self->cmp_ok( $got, '==', $expect, $name );
561 my( $self, $type, $val ) = @_;
563 if( defined $$val ) {
564 if( $type eq 'eq' or $type eq 'ne' ) {
565 # quote and force string context
569 # force numeric context
570 $self->_unoverload_num($val);
581 my( $self, $got, $type, $expect ) = @_;
583 $self->_diag_fmt( $type, $_ ) for \$got, \$expect;
585 local $Level = $Level + 1;
586 return $self->diag(<<"DIAGNOSTIC");
594 my( $self, $got, $type ) = @_;
596 $self->_diag_fmt( $type, \$got );
598 local $Level = $Level + 1;
599 return $self->diag(<<"DIAGNOSTIC");
601 expected: anything else
607 $Test->isnt_eq($got, $dont_expect, $name);
609 Like Test::More's isnt(). Checks if $got ne $dont_expect. This is
614 $Test->isnt_num($got, $dont_expect, $name);
616 Like Test::More's isnt(). Checks if $got ne $dont_expect. This is
622 my( $self, $got, $dont_expect, $name ) = @_;
623 local $Level = $Level + 1;
625 if( !defined $got || !defined $dont_expect ) {
626 # undef only matches undef and nothing else
627 my $test = defined $got || defined $dont_expect;
629 $self->ok( $test, $name );
630 $self->_isnt_diag( $got, 'ne' ) unless $test;
634 return $self->cmp_ok( $got, 'ne', $dont_expect, $name );
638 my( $self, $got, $dont_expect, $name ) = @_;
639 local $Level = $Level + 1;
641 if( !defined $got || !defined $dont_expect ) {
642 # undef only matches undef and nothing else
643 my $test = defined $got || defined $dont_expect;
645 $self->ok( $test, $name );
646 $self->_isnt_diag( $got, '!=' ) unless $test;
650 return $self->cmp_ok( $got, '!=', $dont_expect, $name );
655 $Test->like($this, qr/$regex/, $name);
656 $Test->like($this, '/$regex/', $name);
658 Like Test::More's like(). Checks if $this matches the given $regex.
660 You'll want to avoid qr// if you want your tests to work before 5.005.
664 $Test->unlike($this, qr/$regex/, $name);
665 $Test->unlike($this, '/$regex/', $name);
667 Like Test::More's unlike(). Checks if $this B<does not match> the
673 my( $self, $this, $regex, $name ) = @_;
675 local $Level = $Level + 1;
676 return $self->_regex_ok( $this, $regex, '=~', $name );
680 my( $self, $this, $regex, $name ) = @_;
682 local $Level = $Level + 1;
683 return $self->_regex_ok( $this, $regex, '!~', $name );
688 $Test->cmp_ok($this, $type, $that, $name);
690 Works just like Test::More's cmp_ok().
692 $Test->cmp_ok($big_num, '!=', $other_big_num);
696 my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" );
699 my( $self, $got, $type, $expect, $name ) = @_;
701 # Treat overloaded objects as numbers if we're asked to do a
702 # numeric comparison.
704 = $numeric_cmps{$type}
708 $self->$unoverload( \$got, \$expect );
712 ## no critic (BuiltinFunctions::ProhibitStringyEval)
714 local( $@, $!, $SIG{__DIE__} ); # isolate eval
716 my $code = $self->_caller_context;
718 # Yes, it has to look like this or 5.4.5 won't see the #line
720 # Don't ask me, man, I just work here.
722 $code" . "\$got $type \$expect;";
725 local $Level = $Level + 1;
726 my $ok = $self->ok( $test, $name );
729 if( $type =~ /^(eq|==)$/ ) {
730 $self->_is_diag( $got, $type, $expect );
732 elsif( $type =~ /^(ne|!=)$/ ) {
733 $self->_isnt_diag( $got, $type );
736 $self->_cmp_diag( $got, $type, $expect );
743 my( $self, $got, $type, $expect ) = @_;
745 $got = defined $got ? "'$got'" : 'undef';
746 $expect = defined $expect ? "'$expect'" : 'undef';
748 local $Level = $Level + 1;
749 return $self->diag(<<"DIAGNOSTIC");
756 sub _caller_context {
759 my( $pack, $file, $line ) = $self->caller(1);
762 $code .= "#line $line $file\n" if defined $file and defined $line;
770 =head2 Other Testing Methods
772 These are methods which are used in the course of writing a test but are not themselves tests.
778 $Test->BAIL_OUT($reason);
780 Indicates to the Test::Harness that things are going so badly all
781 testing should terminate. This includes running any additional test
784 It will exit with 255.
789 my( $self, $reason ) = @_;
791 $self->{Bailed_Out} = 1;
792 $self->_print("Bail out! $reason");
797 BAIL_OUT() used to be BAILOUT()
801 *BAILOUT = \&BAIL_OUT;
808 Skips the current test, reporting $why.
813 my( $self, $why ) = @_;
815 $self->_unoverload_str( \$why );
819 lock( $self->{Curr_Test} );
820 $self->{Curr_Test}++;
822 $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = &share(
833 $out .= " $self->{Curr_Test}" if $self->use_numbers;
835 $out .= " $why" if length $why;
846 $Test->todo_skip($why);
848 Like skip(), only it will declare the test as failing and TODO. Similar
851 print "not ok $tnum # TODO $why\n";
856 my( $self, $why ) = @_;
861 lock( $self->{Curr_Test} );
862 $self->{Curr_Test}++;
864 $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = &share(
875 $out .= " $self->{Curr_Test}" if $self->use_numbers;
876 $out .= " # TODO & SKIP $why\n";
883 =begin _unimplemented
888 $Test->skip_rest($reason);
890 Like skip(), only it skips all the rest of the tests you plan to run
891 and terminates the test.
893 If you're running under no_plan, it skips once and terminates the
901 =head2 Test building utility methods
903 These methods are useful when writing your own test methods.
909 $Test->maybe_regex(qr/$regex/);
910 $Test->maybe_regex('/$regex/');
912 Convenience method for building testing functions that take regular
913 expressions as arguments, but need to work before perl 5.005.
915 Takes a quoted regular expression produced by qr//, or a string
916 representing a regular expression.
918 Returns a Perl value which may be used instead of the corresponding
919 regular expression, or undef if its argument is not recognised.
921 For example, a version of like(), sans the useful diagnostic messages,
925 my ($self, $this, $regex, $name) = @_;
926 my $usable_regex = $self->maybe_regex($regex);
927 die "expecting regex, found '$regex'\n"
928 unless $usable_regex;
929 $self->ok($this =~ m/$usable_regex/, $name);
935 my( $self, $regex ) = @_;
936 my $usable_regex = undef;
938 return $usable_regex unless defined $regex;
943 if( _is_qr($regex) ) {
944 $usable_regex = $regex;
946 # Check for '/foo/' or 'm,foo,'
947 elsif(( $re, $opts ) = $regex =~ m{^ /(.*)/ (\w*) $ }sx or
948 ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
951 $usable_regex = length $opts ? "(?$opts)$re" : $re;
954 return $usable_regex;
960 # is_regexp() checks for regexes in a robust manner, say if they're
962 return re::is_regexp($regex) if defined &re::is_regexp;
963 return ref $regex eq 'Regexp';
967 my( $self, $this, $regex, $cmp, $name ) = @_;
970 my $usable_regex = $self->maybe_regex($regex);
971 unless( defined $usable_regex ) {
972 local $Level = $Level + 1;
973 $ok = $self->ok( 0, $name );
974 $self->diag(" '$regex' doesn't look much like a regex to me.");
979 ## no critic (BuiltinFunctions::ProhibitStringyEval)
982 my $code = $self->_caller_context;
984 local( $@, $!, $SIG{__DIE__} ); # isolate eval
986 # Yes, it has to look like this or 5.4.5 won't see the #line
988 # Don't ask me, man, I just work here.
990 $code" . q{$test = $this =~ /$usable_regex/ ? 1 : 0};
992 $test = !$test if $cmp eq '!~';
994 local $Level = $Level + 1;
995 $ok = $self->ok( $test, $name );
999 $this = defined $this ? "'$this'" : 'undef';
1000 my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1002 local $Level = $Level + 1;
1003 $self->diag( sprintf <<'DIAGNOSTIC', $this, $match, $regex );
1013 # I'm not ready to publish this. It doesn't deal with array return
1014 # values from the code or context.
1020 my $return_from_code = $Test->try(sub { code });
1021 my($return_from_code, $error) = $Test->try(sub { code });
1023 Works like eval BLOCK except it ensures it has no effect on the rest
1024 of the test (ie. $@ is not set) nor is effected by outside
1025 interference (ie. $SIG{__DIE__}) and works around some quirks in older
1028 $error is what would normally be in $@.
1030 It is suggested you use this in place of eval BLOCK.
1035 my( $self, $code ) = @_;
1037 local $!; # eval can mess up $!
1038 local $@; # don't set $@ in the test
1039 local $SIG{__DIE__}; # don't trip an outside DIE handler.
1040 my $return = eval { $code->() };
1042 return wantarray ? ( $return, $@ ) : $return;
1050 my $is_fh = $Test->is_fh($thing);
1052 Determines if the given $thing can be used as a filehandle.
1058 my $maybe_fh = shift;
1059 return 0 unless defined $maybe_fh;
1061 return 1 if ref $maybe_fh eq 'GLOB'; # its a glob ref
1062 return 1 if ref \$maybe_fh eq 'GLOB'; # its a glob
1064 return eval { $maybe_fh->isa("IO::Handle") } ||
1065 # 5.5.4's tied() and can() doesn't like getting undef
1066 eval { ( tied($maybe_fh) || '' )->can('TIEHANDLE') };
1079 $Test->level($how_high);
1081 How far up the call stack should $Test look when reporting where the
1086 Setting L<$Test::Builder::Level> overrides. This is typically useful
1092 local $Test::Builder::Level = $Test::Builder::Level + 1;
1096 To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
1101 my( $self, $level ) = @_;
1103 if( defined $level ) {
1109 =item B<use_numbers>
1111 $Test->use_numbers($on_or_off);
1113 Whether or not the test should output numbers. That is, this if true:
1125 Most useful when you can't depend on the test output order, such as
1126 when threads or forking is involved.
1133 my( $self, $use_nums ) = @_;
1135 if( defined $use_nums ) {
1136 $self->{Use_Nums} = $use_nums;
1138 return $self->{Use_Nums};
1143 $Test->no_diag($no_diag);
1145 If set true no diagnostics will be printed. This includes calls to
1150 $Test->no_ending($no_ending);
1152 Normally, Test::Builder does some extra diagnostics when the test
1153 ends. It also changes the exit code as described below.
1155 If this is true, none of that will be done.
1159 $Test->no_header($no_header);
1161 If set to true, no "1..N" header will be printed.
1165 foreach my $attribute (qw(No_Header No_Ending No_Diag)) {
1166 my $method = lc $attribute;
1169 my( $self, $no ) = @_;
1172 $self->{$attribute} = $no;
1174 return $self->{$attribute};
1177 no strict 'refs'; ## no critic
1178 *{ __PACKAGE__ . '::' . $method } = $code;
1185 Controlling where the test output goes.
1187 It's ok for your test to change where STDOUT and STDERR point to,
1188 Test::Builder's default output settings will not be affected.
1196 Prints out the given @msgs. Like C<print>, arguments are simply
1199 Normally, it uses the failure_output() handle, but if this is for a
1200 TODO test, the todo_output() handle is used.
1202 Output will be indented and marked with a # so as not to interfere
1203 with test output. A newline will be put on the end if there isn't one
1206 We encourage using this rather than calling print directly.
1208 Returns false. Why? Because diag() is often used in conjunction with
1209 a failing test (C<ok() || diag()>) it "passes through" the failure.
1211 return ok(...) || diag(...);
1214 Mark Fowler <mark@twoshortplanks.com>
1221 $self->_print_comment( $self->_diag_fh, @_ );
1228 Like diag(), but it prints to the C<output()> handle so it will not
1229 normally be seen by the user except in verbose mode.
1236 $self->_print_comment( $self->output, @_ );
1242 local $Level = $Level + 1;
1243 return $self->in_todo ? $self->todo_output : $self->failure_output;
1246 sub _print_comment {
1247 my( $self, $fh, @msgs ) = @_;
1249 return if $self->no_diag;
1250 return unless @msgs;
1252 # Prevent printing headers when compiling (i.e. -c)
1255 # Smash args together like print does.
1256 # Convert undef to 'undef' so its readable.
1257 my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1259 # Escape the beginning, _print will take care of the rest.
1262 local $Level = $Level + 1;
1263 $self->_print_to_fh( $fh, $msg );
1270 my @dump = $Test->explain(@msgs);
1272 Will dump the contents of any references in a human readable format.
1273 Handy for things like...
1275 is_deeply($have, $want) || diag explain $have;
1279 is_deeply($have, $want) || note explain $have;
1289 require Data::Dumper;
1291 my $dumper = Data::Dumper->new( [$_] );
1292 $dumper->Indent(1)->Terse(1);
1293 $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1304 $Test->_print(@msgs);
1306 Prints to the output() filehandle.
1314 return $self->_print_to_fh( $self->output, @_ );
1318 my( $self, $fh, @msgs ) = @_;
1320 # Prevent printing headers when only compiling. Mostly for when
1321 # tests are deparsed with B::Deparse
1324 my $msg = join '', @msgs;
1326 local( $\, $", $, ) = ( undef, ' ', '' );
1328 # Escape each line after the first with a # so we don't
1329 # confuse Test::Harness.
1330 $msg =~ s/\n(.)/\n# $1/sg;
1332 # Stick a newline on the end if it needs it.
1333 $msg .= "\n" unless $msg =~ /\n\Z/;
1335 return print $fh $msg;
1341 $Test->output($file);
1343 Where normal "ok/not ok" test output should go.
1347 =item B<failure_output>
1349 $Test->failure_output($fh);
1350 $Test->failure_output($file);
1352 Where diagnostic output on test failures and diag() should go.
1356 =item B<todo_output>
1358 $Test->todo_output($fh);
1359 $Test->todo_output($file);
1361 Where diagnostics about todo test failures and diag() should go.
1368 my( $self, $fh ) = @_;
1371 $self->{Out_FH} = $self->_new_fh($fh);
1373 return $self->{Out_FH};
1376 sub failure_output {
1377 my( $self, $fh ) = @_;
1380 $self->{Fail_FH} = $self->_new_fh($fh);
1382 return $self->{Fail_FH};
1386 my( $self, $fh ) = @_;
1389 $self->{Todo_FH} = $self->_new_fh($fh);
1391 return $self->{Todo_FH};
1396 my($file_or_fh) = shift;
1399 if( $self->is_fh($file_or_fh) ) {
1403 open $fh, ">", $file_or_fh
1404 or $self->croak("Can't open test output log $file_or_fh: $!");
1413 my $old_fh = select $fh;
1420 my( $Testout, $Testerr );
1422 sub _dup_stdhandles {
1425 $self->_open_testhandles;
1427 # Set everything to unbuffered else plain prints to STDOUT will
1428 # come out in the wrong order from our own prints.
1429 _autoflush($Testout);
1430 _autoflush( \*STDOUT );
1431 _autoflush($Testerr);
1432 _autoflush( \*STDERR );
1434 $self->reset_outputs;
1439 my $Opened_Testhandles = 0;
1441 sub _open_testhandles {
1444 return if $Opened_Testhandles;
1446 # We dup STDOUT and STDERR so people can change them in their
1447 # test suites while still getting normal test output.
1448 open( $Testout, ">&STDOUT" ) or die "Can't dup STDOUT: $!";
1449 open( $Testerr, ">&STDERR" ) or die "Can't dup STDERR: $!";
1451 # $self->_copy_io_layers( \*STDOUT, $Testout );
1452 # $self->_copy_io_layers( \*STDERR, $Testerr );
1454 $Opened_Testhandles = 1;
1459 sub _copy_io_layers {
1460 my( $self, $src, $dst ) = @_;
1465 my @src_layers = PerlIO::get_layers($src);
1467 binmode $dst, join " ", map ":$_", @src_layers if @src_layers;
1478 Resets all the output filehandles back to their defaults.
1485 $self->output ($Testout);
1486 $self->failure_output($Testerr);
1487 $self->todo_output ($Testout);
1494 $tb->carp(@message);
1496 Warns with C<@message> but the message will appear to come from the
1497 point where the original test function was called (C<$tb->caller>).
1501 $tb->croak(@message);
1503 Dies with C<@message> but the message will appear to come from the
1504 point where the original test function was called (C<$tb->caller>).
1508 sub _message_at_caller {
1511 local $Level = $Level + 1;
1512 my( $pack, $file, $line ) = $self->caller;
1513 return join( "", @_ ) . " at $file line $line.\n";
1518 return warn $self->_message_at_caller(@_);
1523 return die $self->_message_at_caller(@_);
1529 unless( $self->{Have_Plan} ) {
1530 local $Level = $Level + 2;
1531 $self->croak("You tried to run a test without a plan");
1540 =head2 Test Status and Info
1544 =item B<current_test>
1546 my $curr_test = $Test->current_test;
1547 $Test->current_test($num);
1549 Gets/sets the current test number we're on. You usually shouldn't
1552 If set forward, the details of the missing tests are filled in as 'unknown'.
1553 if set backward, the details of the intervening tests are deleted. You
1554 can erase history if you really want to.
1559 my( $self, $num ) = @_;
1561 lock( $self->{Curr_Test} );
1562 if( defined $num ) {
1563 $self->croak("Can't change the current test number without a plan!")
1564 unless $self->{Have_Plan};
1566 $self->{Curr_Test} = $num;
1568 # If the test counter is being pushed forward fill in the details.
1569 my $test_results = $self->{Test_Results};
1570 if( $num > @$test_results ) {
1571 my $start = @$test_results ? @$test_results : 0;
1572 for( $start .. $num - 1 ) {
1573 $test_results->[$_] = &share(
1577 reason => 'incrementing test number',
1584 # If backward, wipe history. Its their funeral.
1585 elsif( $num < @$test_results ) {
1586 $#{$test_results} = $num - 1;
1589 return $self->{Curr_Test};
1594 my @tests = $Test->summary;
1596 A simple summary of the tests so far. True for pass, false for fail.
1597 This is a logical pass/fail, so todos are passes.
1599 Of course, test #1 is $tests[0], etc...
1606 return map { $_->{'ok'} } @{ $self->{Test_Results} };
1611 my @tests = $Test->details;
1613 Like summary(), but with a lot more detail.
1615 $tests[$test_num - 1] =
1616 { 'ok' => is the test considered a pass?
1617 actual_ok => did it literally say 'ok'?
1618 name => name of the test (if any)
1619 type => type of test (if any, see below).
1620 reason => reason for the above (if any)
1623 'ok' is true if Test::Harness will consider the test to be a pass.
1625 'actual_ok' is a reflection of whether or not the test literally
1626 printed 'ok' or 'not ok'. This is for examining the result of 'todo'
1629 'name' is the name of the test.
1631 'type' indicates if it was a special test. Normal tests have a type
1632 of ''. Type can be one of the following:
1636 todo_skip see todo_skip()
1639 Sometimes the Test::Builder test counter is incremented without it
1640 printing any test output, for example, when current_test() is changed.
1641 In these cases, Test::Builder doesn't know the result of the test, so
1642 its type is 'unknown'. These details for these tests are filled in.
1643 They are considered ok, but the name and actual_ok is left undef.
1645 For example "not ok 23 - hole count # TODO insufficient donuts" would
1646 result in this structure:
1648 $tests[22] = # 23 - 1, since arrays start from 0.
1649 { ok => 1, # logically, the test passed since it's todo
1650 actual_ok => 0, # in absolute terms, it failed
1651 name => 'hole count',
1653 reason => 'insufficient donuts'
1660 return @{ $self->{Test_Results} };
1665 my $todo_reason = $Test->todo;
1666 my $todo_reason = $Test->todo($pack);
1668 If the current tests are considered "TODO" it will return the reason,
1669 if any. This reason can come from a $TODO variable or the last call
1670 to C<<todo_start()>>.
1672 Since a TODO test does not need a reason, this function can return an
1673 empty string even when inside a TODO block. Use C<<$Test->in_todo>>
1674 to determine if you are currently inside a TODO block.
1676 todo() is about finding the right package to look for $TODO in. It's
1677 pretty good at guessing the right package to look at. It first looks for
1678 the caller based on C<$Level + 1>, since C<todo()> is usually called inside
1679 a test function. As a last resort it will use C<exported_to()>.
1681 Sometimes there is some confusion about where todo() should be looking
1682 for the $TODO variable. If you want to be sure, tell it explicitly
1688 my( $self, $pack ) = @_;
1690 return $self->{Todo} if defined $self->{Todo};
1692 local $Level = $Level + 1;
1693 my $todo = $self->find_TODO($pack);
1694 return $todo if defined $todo;
1701 my $todo_reason = $Test->find_TODO();
1702 my $todo_reason = $Test->find_TODO($pack):
1704 Like C<<todo()>> but only returns the value of C<<$TODO>> ignoring
1710 my( $self, $pack ) = @_;
1712 $pack = $pack || $self->caller(1) || $self->exported_to;
1713 return unless $pack;
1715 no strict 'refs'; ## no critic
1716 return ${ $pack . '::TODO' };
1721 my $in_todo = $Test->in_todo;
1723 Returns true if the test is currently inside a TODO block.
1730 local $Level = $Level + 1;
1731 return( defined $self->{Todo} || $self->find_TODO ) ? 1 : 0;
1736 $Test->todo_start();
1737 $Test->todo_start($message);
1739 This method allows you declare all subsequent tests as TODO tests, up until
1740 the C<todo_end> method has been called.
1742 The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
1743 whether or not we're in a TODO test. However, often we find that this is not
1744 possible to determine (such as when we want to use C<$TODO> but
1745 the tests are being executed in other packages which can't be inferred
1748 Note that you can use this to nest "todo" tests
1750 $Test->todo_start('working on this');
1752 $Test->todo_start('working on that');
1757 This is generally not recommended, but large testing systems often have weird
1760 We've tried to make this also work with the TODO: syntax, but it's not
1761 guaranteed and its use is also discouraged:
1764 local $TODO = 'We have work to do!';
1765 $Test->todo_start('working on this');
1767 $Test->todo_start('working on that');
1773 Pick one style or another of "TODO" to be on the safe side.
1779 my $message = @_ ? shift : '';
1781 $self->{Start_Todo}++;
1782 if( $self->in_todo ) {
1783 push @{ $self->{Todo_Stack} } => $self->todo;
1785 $self->{Todo} = $message;
1794 Stops running tests as "TODO" tests. This method is fatal if called without a
1795 preceding C<todo_start> method call.
1802 if( !$self->{Start_Todo} ) {
1803 $self->croak('todo_end() called without todo_start()');
1806 $self->{Start_Todo}--;
1808 if( $self->{Start_Todo} && @{ $self->{Todo_Stack} } ) {
1809 $self->{Todo} = pop @{ $self->{Todo_Stack} };
1812 delete $self->{Todo};
1820 my $package = $Test->caller;
1821 my($pack, $file, $line) = $Test->caller;
1822 my($pack, $file, $line) = $Test->caller($height);
1824 Like the normal caller(), except it reports according to your level().
1826 C<$height> will be added to the level().
1830 sub caller { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1831 my( $self, $height ) = @_;
1834 my @caller = CORE::caller( $self->level + $height + 1 );
1835 return wantarray ? @caller : $caller[0];
1846 =item B<_sanity_check>
1848 $self->_sanity_check();
1850 Runs a bunch of end of test sanity checks to make sure reality came
1851 through ok. If anything is wrong it will die with a fairly friendly
1860 $self->_whoa( $self->{Curr_Test} < 0, 'Says here you ran a negative number of tests!' );
1861 $self->_whoa( !$self->{Have_Plan} and $self->{Curr_Test},
1862 'Somehow your tests ran without a plan!' );
1863 $self->_whoa( $self->{Curr_Test} != @{ $self->{Test_Results} },
1864 'Somehow you got a different number of results than tests ran!' );
1871 $self->_whoa($check, $description);
1873 A sanity check, similar to assert(). If the $check is true, something
1874 has gone horribly wrong. It will die with the given $description and
1875 a note to contact the author.
1880 my( $self, $check, $desc ) = @_;
1882 local $Level = $Level + 1;
1883 $self->croak(<<"WHOA");
1885 This should never happen! Please contact the author immediately!
1894 _my_exit($exit_num);
1896 Perl seems to have some trouble with exiting inside an END block. 5.005_03
1897 and 5.6.1 both seem to do odd things. Instead, this function edits $?
1898 directly. It should ONLY be called from inside an END block. It
1899 doesn't actually exit, that's your job.
1904 $? = $_[0]; ## no critic (Variables::RequireLocalizedPunctuationVars)
1918 my $real_exit_code = $?;
1919 $self->_sanity_check();
1921 # Don't bother with an ending if this is a forked copy. Only the parent
1922 # should do the ending.
1923 if( $self->{Original_Pid} != $$ ) {
1927 # Exit if plan() was never called. This is so "require Test::Simple"
1929 if( !$self->{Have_Plan} ) {
1933 # Don't do an ending if we bailed out.
1934 if( $self->{Bailed_Out} ) {
1938 # Figure out if we passed or failed and print helpful messages.
1939 my $test_results = $self->{Test_Results};
1940 if(@$test_results) {
1941 # The plan? We have no plan.
1942 if( $self->{No_Plan} ) {
1943 $self->_print("1..$self->{Curr_Test}\n") unless $self->no_header;
1944 $self->{Expected_Tests} = $self->{Curr_Test};
1947 # Auto-extended arrays and elements which aren't explicitly
1948 # filled in with a shared reference will puke under 5.8.0
1949 # ithreads. So we have to fill them in by hand. :(
1950 my $empty_result = &share( {} );
1951 for my $idx ( 0 .. $self->{Expected_Tests} - 1 ) {
1952 $test_results->[$idx] = $empty_result
1953 unless defined $test_results->[$idx];
1956 my $num_failed = grep !$_->{'ok'}, @{$test_results}[ 0 .. $self->{Curr_Test} - 1 ];
1958 my $num_extra = $self->{Curr_Test} - $self->{Expected_Tests};
1960 if( $num_extra != 0 ) {
1961 my $s = $self->{Expected_Tests} == 1 ? '' : 's';
1962 $self->diag(<<"FAIL");
1963 Looks like you planned $self->{Expected_Tests} test$s but ran $self->{Curr_Test}.
1968 my $num_tests = $self->{Curr_Test};
1969 my $s = $num_failed == 1 ? '' : 's';
1971 my $qualifier = $num_extra == 0 ? '' : ' run';
1973 $self->diag(<<"FAIL");
1974 Looks like you failed $num_failed test$s of $num_tests$qualifier.
1978 if($real_exit_code) {
1979 $self->diag(<<"FAIL");
1980 Looks like your test exited with $real_exit_code just after $self->{Curr_Test}.
1983 _my_exit($real_exit_code) && return;
1988 $exit_code = $num_failed <= 254 ? $num_failed : 254;
1990 elsif( $num_extra != 0 ) {
1997 _my_exit($exit_code) && return;
1999 elsif( $self->{Skip_All} ) {
2000 _my_exit(0) && return;
2002 elsif($real_exit_code) {
2003 $self->diag(<<"FAIL");
2004 Looks like your test exited with $real_exit_code before it could output anything.
2006 _my_exit($real_exit_code) && return;
2009 $self->diag("No tests run!\n");
2010 _my_exit(255) && return;
2013 $self->_whoa( 1, "We fell off the end of _ending()" );
2017 $Test->_ending if defined $Test and !$Test->no_ending;
2022 If all your tests passed, Test::Builder will exit with zero (which is
2023 normal). If anything failed it will exit with how many failed. If
2024 you run less (or more) tests than you planned, the missing (or extras)
2025 will be considered failures. If no tests were ever run Test::Builder
2026 will throw a warning and exit with 255. If the test died, even after
2027 having successfully completed all its tests, it will still be
2028 considered a failure and will exit with 255.
2030 So the exit codes are...
2032 0 all tests successful
2033 255 test died or all passed but wrong # of tests run
2034 any other number how many failed (including missing or extras)
2036 If you fail more than 254 tests, it will be reported as 254.
2041 In perl 5.8.1 and later, Test::Builder is thread-safe. The test
2042 number is shared amongst all threads. This means if one thread sets
2043 the test number using current_test() they will all be effected.
2045 While versions earlier than 5.8.1 had threads they contain too many
2048 Test::Builder is only thread-aware if threads.pm is loaded I<before>
2053 CPAN can provide the best examples. Test::Simple, Test::More,
2054 Test::Exception and Test::Differences all use Test::Builder.
2058 Test::Simple, Test::More, Test::Harness
2062 Original code by chromatic, maintained by Michael G Schwern
2063 E<lt>schwern@pobox.comE<gt>
2067 Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2068 Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2070 This program is free software; you can redistribute it and/or
2071 modify it under the same terms as Perl itself.
2073 See F<http://www.perl.com/perl/misc/Artistic.html>