2 # $Id: /mirror/googlecode/test-more-trunk/lib/Test/Builder.pm 67223 2008-10-15T03:08:18.888155Z schwern $
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+', @_ );
491 next unless $self->_is_dualvar($$val);
498 # This is a hack to detect a dualvar such as $!
500 my( $self, $val ) = @_;
502 no warnings 'numeric';
503 my $numval = $val + 0;
504 return $numval != 0 and $numval ne $val ? 1 : 0;
509 $Test->is_eq($got, $expected, $name);
511 Like Test::More's is(). Checks if $got eq $expected. This is the
516 $Test->is_num($got, $expected, $name);
518 Like Test::More's is(). Checks if $got == $expected. This is the
524 my( $self, $got, $expect, $name ) = @_;
525 local $Level = $Level + 1;
527 $self->_unoverload_str( \$got, \$expect );
529 if( !defined $got || !defined $expect ) {
530 # undef only matches undef and nothing else
531 my $test = !defined $got && !defined $expect;
533 $self->ok( $test, $name );
534 $self->_is_diag( $got, 'eq', $expect ) unless $test;
538 return $self->cmp_ok( $got, 'eq', $expect, $name );
542 my( $self, $got, $expect, $name ) = @_;
543 local $Level = $Level + 1;
545 $self->_unoverload_num( \$got, \$expect );
547 if( !defined $got || !defined $expect ) {
548 # undef only matches undef and nothing else
549 my $test = !defined $got && !defined $expect;
551 $self->ok( $test, $name );
552 $self->_is_diag( $got, '==', $expect ) unless $test;
556 return $self->cmp_ok( $got, '==', $expect, $name );
560 my( $self, $type, $val ) = @_;
562 if( defined $$val ) {
563 if( $type eq 'eq' or $type eq 'ne' ) {
564 # quote and force string context
568 # force numeric context
569 $self->_unoverload_num($val);
580 my( $self, $got, $type, $expect ) = @_;
582 $self->_diag_fmt( $type, $_ ) for \$got, \$expect;
584 local $Level = $Level + 1;
585 return $self->diag(<<"DIAGNOSTIC");
593 my( $self, $got, $type ) = @_;
595 $self->_diag_fmt( $type, \$got );
597 local $Level = $Level + 1;
598 return $self->diag(<<"DIAGNOSTIC");
600 expected: anything else
606 $Test->isnt_eq($got, $dont_expect, $name);
608 Like Test::More's isnt(). Checks if $got ne $dont_expect. This is
613 $Test->isnt_num($got, $dont_expect, $name);
615 Like Test::More's isnt(). Checks if $got ne $dont_expect. This is
621 my( $self, $got, $dont_expect, $name ) = @_;
622 local $Level = $Level + 1;
624 if( !defined $got || !defined $dont_expect ) {
625 # undef only matches undef and nothing else
626 my $test = defined $got || defined $dont_expect;
628 $self->ok( $test, $name );
629 $self->_isnt_diag( $got, 'ne' ) unless $test;
633 return $self->cmp_ok( $got, 'ne', $dont_expect, $name );
637 my( $self, $got, $dont_expect, $name ) = @_;
638 local $Level = $Level + 1;
640 if( !defined $got || !defined $dont_expect ) {
641 # undef only matches undef and nothing else
642 my $test = defined $got || defined $dont_expect;
644 $self->ok( $test, $name );
645 $self->_isnt_diag( $got, '!=' ) unless $test;
649 return $self->cmp_ok( $got, '!=', $dont_expect, $name );
654 $Test->like($this, qr/$regex/, $name);
655 $Test->like($this, '/$regex/', $name);
657 Like Test::More's like(). Checks if $this matches the given $regex.
659 You'll want to avoid qr// if you want your tests to work before 5.005.
663 $Test->unlike($this, qr/$regex/, $name);
664 $Test->unlike($this, '/$regex/', $name);
666 Like Test::More's unlike(). Checks if $this B<does not match> the
672 my( $self, $this, $regex, $name ) = @_;
674 local $Level = $Level + 1;
675 return $self->_regex_ok( $this, $regex, '=~', $name );
679 my( $self, $this, $regex, $name ) = @_;
681 local $Level = $Level + 1;
682 return $self->_regex_ok( $this, $regex, '!~', $name );
687 $Test->cmp_ok($this, $type, $that, $name);
689 Works just like Test::More's cmp_ok().
691 $Test->cmp_ok($big_num, '!=', $other_big_num);
695 my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" );
698 my( $self, $got, $type, $expect, $name ) = @_;
700 # Treat overloaded objects as numbers if we're asked to do a
701 # numeric comparison.
703 = $numeric_cmps{$type}
707 $self->$unoverload( \$got, \$expect );
711 ## no critic (BuiltinFunctions::ProhibitStringyEval)
713 local( $@, $!, $SIG{__DIE__} ); # isolate eval
715 my $code = $self->_caller_context;
717 # Yes, it has to look like this or 5.4.5 won't see the #line
719 # Don't ask me, man, I just work here.
721 $code" . "\$got $type \$expect;";
724 local $Level = $Level + 1;
725 my $ok = $self->ok( $test, $name );
728 if( $type =~ /^(eq|==)$/ ) {
729 $self->_is_diag( $got, $type, $expect );
731 elsif( $type =~ /^(ne|!=)$/ ) {
732 $self->_isnt_diag( $got, $type );
735 $self->_cmp_diag( $got, $type, $expect );
742 my( $self, $got, $type, $expect ) = @_;
744 $got = defined $got ? "'$got'" : 'undef';
745 $expect = defined $expect ? "'$expect'" : 'undef';
747 local $Level = $Level + 1;
748 return $self->diag(<<"DIAGNOSTIC");
755 sub _caller_context {
758 my( $pack, $file, $line ) = $self->caller(1);
761 $code .= "#line $line $file\n" if defined $file and defined $line;
769 =head2 Other Testing Methods
771 These are methods which are used in the course of writing a test but are not themselves tests.
777 $Test->BAIL_OUT($reason);
779 Indicates to the Test::Harness that things are going so badly all
780 testing should terminate. This includes running any additional test
783 It will exit with 255.
788 my( $self, $reason ) = @_;
790 $self->{Bailed_Out} = 1;
791 $self->_print("Bail out! $reason");
796 BAIL_OUT() used to be BAILOUT()
800 *BAILOUT = \&BAIL_OUT;
807 Skips the current test, reporting $why.
812 my( $self, $why ) = @_;
814 $self->_unoverload_str( \$why );
818 lock( $self->{Curr_Test} );
819 $self->{Curr_Test}++;
821 $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = &share(
832 $out .= " $self->{Curr_Test}" if $self->use_numbers;
834 $out .= " $why" if length $why;
845 $Test->todo_skip($why);
847 Like skip(), only it will declare the test as failing and TODO. Similar
850 print "not ok $tnum # TODO $why\n";
855 my( $self, $why ) = @_;
860 lock( $self->{Curr_Test} );
861 $self->{Curr_Test}++;
863 $self->{Test_Results}[ $self->{Curr_Test} - 1 ] = &share(
874 $out .= " $self->{Curr_Test}" if $self->use_numbers;
875 $out .= " # TODO & SKIP $why\n";
882 =begin _unimplemented
887 $Test->skip_rest($reason);
889 Like skip(), only it skips all the rest of the tests you plan to run
890 and terminates the test.
892 If you're running under no_plan, it skips once and terminates the
900 =head2 Test building utility methods
902 These methods are useful when writing your own test methods.
908 $Test->maybe_regex(qr/$regex/);
909 $Test->maybe_regex('/$regex/');
911 Convenience method for building testing functions that take regular
912 expressions as arguments, but need to work before perl 5.005.
914 Takes a quoted regular expression produced by qr//, or a string
915 representing a regular expression.
917 Returns a Perl value which may be used instead of the corresponding
918 regular expression, or undef if its argument is not recognised.
920 For example, a version of like(), sans the useful diagnostic messages,
924 my ($self, $this, $regex, $name) = @_;
925 my $usable_regex = $self->maybe_regex($regex);
926 die "expecting regex, found '$regex'\n"
927 unless $usable_regex;
928 $self->ok($this =~ m/$usable_regex/, $name);
934 my( $self, $regex ) = @_;
935 my $usable_regex = undef;
937 return $usable_regex unless defined $regex;
942 if( _is_qr($regex) ) {
943 $usable_regex = $regex;
945 # Check for '/foo/' or 'm,foo,'
946 elsif(( $re, $opts ) = $regex =~ m{^ /(.*)/ (\w*) $ }sx or
947 ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
950 $usable_regex = length $opts ? "(?$opts)$re" : $re;
953 return $usable_regex;
959 # is_regexp() checks for regexes in a robust manner, say if they're
961 return re::is_regexp($regex) if defined &re::is_regexp;
962 return ref $regex eq 'Regexp';
966 my( $self, $this, $regex, $cmp, $name ) = @_;
969 my $usable_regex = $self->maybe_regex($regex);
970 unless( defined $usable_regex ) {
971 local $Level = $Level + 1;
972 $ok = $self->ok( 0, $name );
973 $self->diag(" '$regex' doesn't look much like a regex to me.");
978 ## no critic (BuiltinFunctions::ProhibitStringyEval)
981 my $code = $self->_caller_context;
983 local( $@, $!, $SIG{__DIE__} ); # isolate eval
985 # Yes, it has to look like this or 5.4.5 won't see the #line
987 # Don't ask me, man, I just work here.
989 $code" . q{$test = $this =~ /$usable_regex/ ? 1 : 0};
991 $test = !$test if $cmp eq '!~';
993 local $Level = $Level + 1;
994 $ok = $self->ok( $test, $name );
998 $this = defined $this ? "'$this'" : 'undef';
999 my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1001 local $Level = $Level + 1;
1002 $self->diag( sprintf <<'DIAGNOSTIC', $this, $match, $regex );
1012 # I'm not ready to publish this. It doesn't deal with array return
1013 # values from the code or context.
1019 my $return_from_code = $Test->try(sub { code });
1020 my($return_from_code, $error) = $Test->try(sub { code });
1022 Works like eval BLOCK except it ensures it has no effect on the rest
1023 of the test (ie. $@ is not set) nor is effected by outside
1024 interference (ie. $SIG{__DIE__}) and works around some quirks in older
1027 $error is what would normally be in $@.
1029 It is suggested you use this in place of eval BLOCK.
1034 my( $self, $code ) = @_;
1036 local $!; # eval can mess up $!
1037 local $@; # don't set $@ in the test
1038 local $SIG{__DIE__}; # don't trip an outside DIE handler.
1039 my $return = eval { $code->() };
1041 return wantarray ? ( $return, $@ ) : $return;
1049 my $is_fh = $Test->is_fh($thing);
1051 Determines if the given $thing can be used as a filehandle.
1057 my $maybe_fh = shift;
1058 return 0 unless defined $maybe_fh;
1060 return 1 if ref $maybe_fh eq 'GLOB'; # its a glob ref
1061 return 1 if ref \$maybe_fh eq 'GLOB'; # its a glob
1063 return eval { $maybe_fh->isa("IO::Handle") } ||
1064 # 5.5.4's tied() and can() doesn't like getting undef
1065 eval { ( tied($maybe_fh) || '' )->can('TIEHANDLE') };
1078 $Test->level($how_high);
1080 How far up the call stack should $Test look when reporting where the
1085 Setting L<$Test::Builder::Level> overrides. This is typically useful
1091 local $Test::Builder::Level = $Test::Builder::Level + 1;
1095 To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
1100 my( $self, $level ) = @_;
1102 if( defined $level ) {
1108 =item B<use_numbers>
1110 $Test->use_numbers($on_or_off);
1112 Whether or not the test should output numbers. That is, this if true:
1124 Most useful when you can't depend on the test output order, such as
1125 when threads or forking is involved.
1132 my( $self, $use_nums ) = @_;
1134 if( defined $use_nums ) {
1135 $self->{Use_Nums} = $use_nums;
1137 return $self->{Use_Nums};
1142 $Test->no_diag($no_diag);
1144 If set true no diagnostics will be printed. This includes calls to
1149 $Test->no_ending($no_ending);
1151 Normally, Test::Builder does some extra diagnostics when the test
1152 ends. It also changes the exit code as described below.
1154 If this is true, none of that will be done.
1158 $Test->no_header($no_header);
1160 If set to true, no "1..N" header will be printed.
1164 foreach my $attribute (qw(No_Header No_Ending No_Diag)) {
1165 my $method = lc $attribute;
1168 my( $self, $no ) = @_;
1171 $self->{$attribute} = $no;
1173 return $self->{$attribute};
1176 no strict 'refs'; ## no critic
1177 *{ __PACKAGE__ . '::' . $method } = $code;
1184 Controlling where the test output goes.
1186 It's ok for your test to change where STDOUT and STDERR point to,
1187 Test::Builder's default output settings will not be affected.
1195 Prints out the given @msgs. Like C<print>, arguments are simply
1198 Normally, it uses the failure_output() handle, but if this is for a
1199 TODO test, the todo_output() handle is used.
1201 Output will be indented and marked with a # so as not to interfere
1202 with test output. A newline will be put on the end if there isn't one
1205 We encourage using this rather than calling print directly.
1207 Returns false. Why? Because diag() is often used in conjunction with
1208 a failing test (C<ok() || diag()>) it "passes through" the failure.
1210 return ok(...) || diag(...);
1213 Mark Fowler <mark@twoshortplanks.com>
1220 $self->_print_comment( $self->_diag_fh, @_ );
1227 Like diag(), but it prints to the C<output()> handle so it will not
1228 normally be seen by the user except in verbose mode.
1235 $self->_print_comment( $self->output, @_ );
1241 local $Level = $Level + 1;
1242 return $self->in_todo ? $self->todo_output : $self->failure_output;
1245 sub _print_comment {
1246 my( $self, $fh, @msgs ) = @_;
1248 return if $self->no_diag;
1249 return unless @msgs;
1251 # Prevent printing headers when compiling (i.e. -c)
1254 # Smash args together like print does.
1255 # Convert undef to 'undef' so its readable.
1256 my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1258 # Escape the beginning, _print will take care of the rest.
1261 local $Level = $Level + 1;
1262 $self->_print_to_fh( $fh, $msg );
1269 my @dump = $Test->explain(@msgs);
1271 Will dump the contents of any references in a human readable format.
1272 Handy for things like...
1274 is_deeply($have, $want) || diag explain $have;
1278 is_deeply($have, $want) || note explain $have;
1288 require Data::Dumper;
1290 my $dumper = Data::Dumper->new( [$_] );
1291 $dumper->Indent(1)->Terse(1);
1292 $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1303 $Test->_print(@msgs);
1305 Prints to the output() filehandle.
1313 return $self->_print_to_fh( $self->output, @_ );
1317 my( $self, $fh, @msgs ) = @_;
1319 # Prevent printing headers when only compiling. Mostly for when
1320 # tests are deparsed with B::Deparse
1323 my $msg = join '', @msgs;
1325 local( $\, $", $, ) = ( undef, ' ', '' );
1327 # Escape each line after the first with a # so we don't
1328 # confuse Test::Harness.
1329 $msg =~ s/\n(.)/\n# $1/sg;
1331 # Stick a newline on the end if it needs it.
1332 $msg .= "\n" unless $msg =~ /\n\Z/;
1334 return print $fh $msg;
1340 $Test->output($file);
1342 Where normal "ok/not ok" test output should go.
1346 =item B<failure_output>
1348 $Test->failure_output($fh);
1349 $Test->failure_output($file);
1351 Where diagnostic output on test failures and diag() should go.
1355 =item B<todo_output>
1357 $Test->todo_output($fh);
1358 $Test->todo_output($file);
1360 Where diagnostics about todo test failures and diag() should go.
1367 my( $self, $fh ) = @_;
1370 $self->{Out_FH} = $self->_new_fh($fh);
1372 return $self->{Out_FH};
1375 sub failure_output {
1376 my( $self, $fh ) = @_;
1379 $self->{Fail_FH} = $self->_new_fh($fh);
1381 return $self->{Fail_FH};
1385 my( $self, $fh ) = @_;
1388 $self->{Todo_FH} = $self->_new_fh($fh);
1390 return $self->{Todo_FH};
1395 my($file_or_fh) = shift;
1398 if( $self->is_fh($file_or_fh) ) {
1402 open $fh, ">", $file_or_fh
1403 or $self->croak("Can't open test output log $file_or_fh: $!");
1412 my $old_fh = select $fh;
1419 my( $Testout, $Testerr );
1421 sub _dup_stdhandles {
1424 $self->_open_testhandles;
1426 # Set everything to unbuffered else plain prints to STDOUT will
1427 # come out in the wrong order from our own prints.
1428 _autoflush($Testout);
1429 _autoflush( \*STDOUT );
1430 _autoflush($Testerr);
1431 _autoflush( \*STDERR );
1433 $self->reset_outputs;
1438 my $Opened_Testhandles = 0;
1440 sub _open_testhandles {
1443 return if $Opened_Testhandles;
1445 # We dup STDOUT and STDERR so people can change them in their
1446 # test suites while still getting normal test output.
1447 open( $Testout, ">&STDOUT" ) or die "Can't dup STDOUT: $!";
1448 open( $Testerr, ">&STDERR" ) or die "Can't dup STDERR: $!";
1450 # $self->_copy_io_layers( \*STDOUT, $Testout );
1451 # $self->_copy_io_layers( \*STDERR, $Testerr );
1453 $Opened_Testhandles = 1;
1458 sub _copy_io_layers {
1459 my( $self, $src, $dst ) = @_;
1464 my @src_layers = PerlIO::get_layers($src);
1466 binmode $dst, join " ", map ":$_", @src_layers if @src_layers;
1477 Resets all the output filehandles back to their defaults.
1484 $self->output ($Testout);
1485 $self->failure_output($Testerr);
1486 $self->todo_output ($Testout);
1493 $tb->carp(@message);
1495 Warns with C<@message> but the message will appear to come from the
1496 point where the original test function was called (C<$tb->caller>).
1500 $tb->croak(@message);
1502 Dies with C<@message> but the message will appear to come from the
1503 point where the original test function was called (C<$tb->caller>).
1507 sub _message_at_caller {
1510 local $Level = $Level + 1;
1511 my( $pack, $file, $line ) = $self->caller;
1512 return join( "", @_ ) . " at $file line $line.\n";
1517 return warn $self->_message_at_caller(@_);
1522 return die $self->_message_at_caller(@_);
1528 unless( $self->{Have_Plan} ) {
1529 local $Level = $Level + 2;
1530 $self->croak("You tried to run a test without a plan");
1539 =head2 Test Status and Info
1543 =item B<current_test>
1545 my $curr_test = $Test->current_test;
1546 $Test->current_test($num);
1548 Gets/sets the current test number we're on. You usually shouldn't
1551 If set forward, the details of the missing tests are filled in as 'unknown'.
1552 if set backward, the details of the intervening tests are deleted. You
1553 can erase history if you really want to.
1558 my( $self, $num ) = @_;
1560 lock( $self->{Curr_Test} );
1561 if( defined $num ) {
1562 $self->croak("Can't change the current test number without a plan!")
1563 unless $self->{Have_Plan};
1565 $self->{Curr_Test} = $num;
1567 # If the test counter is being pushed forward fill in the details.
1568 my $test_results = $self->{Test_Results};
1569 if( $num > @$test_results ) {
1570 my $start = @$test_results ? @$test_results : 0;
1571 for( $start .. $num - 1 ) {
1572 $test_results->[$_] = &share(
1576 reason => 'incrementing test number',
1583 # If backward, wipe history. Its their funeral.
1584 elsif( $num < @$test_results ) {
1585 $#{$test_results} = $num - 1;
1588 return $self->{Curr_Test};
1593 my @tests = $Test->summary;
1595 A simple summary of the tests so far. True for pass, false for fail.
1596 This is a logical pass/fail, so todos are passes.
1598 Of course, test #1 is $tests[0], etc...
1605 return map { $_->{'ok'} } @{ $self->{Test_Results} };
1610 my @tests = $Test->details;
1612 Like summary(), but with a lot more detail.
1614 $tests[$test_num - 1] =
1615 { 'ok' => is the test considered a pass?
1616 actual_ok => did it literally say 'ok'?
1617 name => name of the test (if any)
1618 type => type of test (if any, see below).
1619 reason => reason for the above (if any)
1622 'ok' is true if Test::Harness will consider the test to be a pass.
1624 'actual_ok' is a reflection of whether or not the test literally
1625 printed 'ok' or 'not ok'. This is for examining the result of 'todo'
1628 'name' is the name of the test.
1630 'type' indicates if it was a special test. Normal tests have a type
1631 of ''. Type can be one of the following:
1635 todo_skip see todo_skip()
1638 Sometimes the Test::Builder test counter is incremented without it
1639 printing any test output, for example, when current_test() is changed.
1640 In these cases, Test::Builder doesn't know the result of the test, so
1641 its type is 'unknown'. These details for these tests are filled in.
1642 They are considered ok, but the name and actual_ok is left undef.
1644 For example "not ok 23 - hole count # TODO insufficient donuts" would
1645 result in this structure:
1647 $tests[22] = # 23 - 1, since arrays start from 0.
1648 { ok => 1, # logically, the test passed since it's todo
1649 actual_ok => 0, # in absolute terms, it failed
1650 name => 'hole count',
1652 reason => 'insufficient donuts'
1659 return @{ $self->{Test_Results} };
1664 my $todo_reason = $Test->todo;
1665 my $todo_reason = $Test->todo($pack);
1667 If the current tests are considered "TODO" it will return the reason,
1668 if any. This reason can come from a $TODO variable or the last call
1669 to C<<todo_start()>>.
1671 Since a TODO test does not need a reason, this function can return an
1672 empty string even when inside a TODO block. Use C<<$Test->in_todo>>
1673 to determine if you are currently inside a TODO block.
1675 todo() is about finding the right package to look for $TODO in. It's
1676 pretty good at guessing the right package to look at. It first looks for
1677 the caller based on C<$Level + 1>, since C<todo()> is usually called inside
1678 a test function. As a last resort it will use C<exported_to()>.
1680 Sometimes there is some confusion about where todo() should be looking
1681 for the $TODO variable. If you want to be sure, tell it explicitly
1687 my( $self, $pack ) = @_;
1689 return $self->{Todo} if defined $self->{Todo};
1691 local $Level = $Level + 1;
1692 my $todo = $self->find_TODO($pack);
1693 return $todo if defined $todo;
1700 my $todo_reason = $Test->find_TODO();
1701 my $todo_reason = $Test->find_TODO($pack):
1703 Like C<<todo()>> but only returns the value of C<<$TODO>> ignoring
1709 my( $self, $pack ) = @_;
1711 $pack = $pack || $self->caller(1) || $self->exported_to;
1712 return unless $pack;
1714 no strict 'refs'; ## no critic
1715 return ${ $pack . '::TODO' };
1720 my $in_todo = $Test->in_todo;
1722 Returns true if the test is currently inside a TODO block.
1729 local $Level = $Level + 1;
1730 return( defined $self->{Todo} || $self->find_TODO ) ? 1 : 0;
1735 $Test->todo_start();
1736 $Test->todo_start($message);
1738 This method allows you declare all subsequent tests as TODO tests, up until
1739 the C<todo_end> method has been called.
1741 The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
1742 whether or not we're in a TODO test. However, often we find that this is not
1743 possible to determine (such as when we want to use C<$TODO> but
1744 the tests are being executed in other packages which can't be inferred
1747 Note that you can use this to nest "todo" tests
1749 $Test->todo_start('working on this');
1751 $Test->todo_start('working on that');
1756 This is generally not recommended, but large testing systems often have weird
1759 We've tried to make this also work with the TODO: syntax, but it's not
1760 guaranteed and its use is also discouraged:
1763 local $TODO = 'We have work to do!';
1764 $Test->todo_start('working on this');
1766 $Test->todo_start('working on that');
1772 Pick one style or another of "TODO" to be on the safe side.
1778 my $message = @_ ? shift : '';
1780 $self->{Start_Todo}++;
1781 if( $self->in_todo ) {
1782 push @{ $self->{Todo_Stack} } => $self->todo;
1784 $self->{Todo} = $message;
1793 Stops running tests as "TODO" tests. This method is fatal if called without a
1794 preceding C<todo_start> method call.
1801 if( !$self->{Start_Todo} ) {
1802 $self->croak('todo_end() called without todo_start()');
1805 $self->{Start_Todo}--;
1807 if( $self->{Start_Todo} && @{ $self->{Todo_Stack} } ) {
1808 $self->{Todo} = pop @{ $self->{Todo_Stack} };
1811 delete $self->{Todo};
1819 my $package = $Test->caller;
1820 my($pack, $file, $line) = $Test->caller;
1821 my($pack, $file, $line) = $Test->caller($height);
1823 Like the normal caller(), except it reports according to your level().
1825 C<$height> will be added to the level().
1829 sub caller { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1830 my( $self, $height ) = @_;
1833 my @caller = CORE::caller( $self->level + $height + 1 );
1834 return wantarray ? @caller : $caller[0];
1845 =item B<_sanity_check>
1847 $self->_sanity_check();
1849 Runs a bunch of end of test sanity checks to make sure reality came
1850 through ok. If anything is wrong it will die with a fairly friendly
1859 $self->_whoa( $self->{Curr_Test} < 0, 'Says here you ran a negative number of tests!' );
1860 $self->_whoa( !$self->{Have_Plan} and $self->{Curr_Test},
1861 'Somehow your tests ran without a plan!' );
1862 $self->_whoa( $self->{Curr_Test} != @{ $self->{Test_Results} },
1863 'Somehow you got a different number of results than tests ran!' );
1870 $self->_whoa($check, $description);
1872 A sanity check, similar to assert(). If the $check is true, something
1873 has gone horribly wrong. It will die with the given $description and
1874 a note to contact the author.
1879 my( $self, $check, $desc ) = @_;
1881 local $Level = $Level + 1;
1882 $self->croak(<<"WHOA");
1884 This should never happen! Please contact the author immediately!
1893 _my_exit($exit_num);
1895 Perl seems to have some trouble with exiting inside an END block. 5.005_03
1896 and 5.6.1 both seem to do odd things. Instead, this function edits $?
1897 directly. It should ONLY be called from inside an END block. It
1898 doesn't actually exit, that's your job.
1903 $? = $_[0]; ## no critic (Variables::RequireLocalizedPunctuationVars)
1917 my $real_exit_code = $?;
1918 $self->_sanity_check();
1920 # Don't bother with an ending if this is a forked copy. Only the parent
1921 # should do the ending.
1922 if( $self->{Original_Pid} != $$ ) {
1926 # Exit if plan() was never called. This is so "require Test::Simple"
1928 if( !$self->{Have_Plan} ) {
1932 # Don't do an ending if we bailed out.
1933 if( $self->{Bailed_Out} ) {
1937 # Figure out if we passed or failed and print helpful messages.
1938 my $test_results = $self->{Test_Results};
1939 if(@$test_results) {
1940 # The plan? We have no plan.
1941 if( $self->{No_Plan} ) {
1942 $self->_print("1..$self->{Curr_Test}\n") unless $self->no_header;
1943 $self->{Expected_Tests} = $self->{Curr_Test};
1946 # Auto-extended arrays and elements which aren't explicitly
1947 # filled in with a shared reference will puke under 5.8.0
1948 # ithreads. So we have to fill them in by hand. :(
1949 my $empty_result = &share( {} );
1950 for my $idx ( 0 .. $self->{Expected_Tests} - 1 ) {
1951 $test_results->[$idx] = $empty_result
1952 unless defined $test_results->[$idx];
1955 my $num_failed = grep !$_->{'ok'}, @{$test_results}[ 0 .. $self->{Curr_Test} - 1 ];
1957 my $num_extra = $self->{Curr_Test} - $self->{Expected_Tests};
1959 if( $num_extra != 0 ) {
1960 my $s = $self->{Expected_Tests} == 1 ? '' : 's';
1961 $self->diag(<<"FAIL");
1962 Looks like you planned $self->{Expected_Tests} test$s but ran $self->{Curr_Test}.
1967 my $num_tests = $self->{Curr_Test};
1968 my $s = $num_failed == 1 ? '' : 's';
1970 my $qualifier = $num_extra == 0 ? '' : ' run';
1972 $self->diag(<<"FAIL");
1973 Looks like you failed $num_failed test$s of $num_tests$qualifier.
1977 if($real_exit_code) {
1978 $self->diag(<<"FAIL");
1979 Looks like your test exited with $real_exit_code just after $self->{Curr_Test}.
1982 _my_exit($real_exit_code) && return;
1987 $exit_code = $num_failed <= 254 ? $num_failed : 254;
1989 elsif( $num_extra != 0 ) {
1996 _my_exit($exit_code) && return;
1998 elsif( $self->{Skip_All} ) {
1999 _my_exit(0) && return;
2001 elsif($real_exit_code) {
2002 $self->diag(<<"FAIL");
2003 Looks like your test exited with $real_exit_code before it could output anything.
2005 _my_exit($real_exit_code) && return;
2008 $self->diag("No tests run!\n");
2009 _my_exit(255) && return;
2012 $self->_whoa( 1, "We fell off the end of _ending()" );
2016 $Test->_ending if defined $Test and !$Test->no_ending;
2021 If all your tests passed, Test::Builder will exit with zero (which is
2022 normal). If anything failed it will exit with how many failed. If
2023 you run less (or more) tests than you planned, the missing (or extras)
2024 will be considered failures. If no tests were ever run Test::Builder
2025 will throw a warning and exit with 255. If the test died, even after
2026 having successfully completed all its tests, it will still be
2027 considered a failure and will exit with 255.
2029 So the exit codes are...
2031 0 all tests successful
2032 255 test died or all passed but wrong # of tests run
2033 any other number how many failed (including missing or extras)
2035 If you fail more than 254 tests, it will be reported as 254.
2040 In perl 5.8.1 and later, Test::Builder is thread-safe. The test
2041 number is shared amongst all threads. This means if one thread sets
2042 the test number using current_test() they will all be effected.
2044 While versions earlier than 5.8.1 had threads they contain too many
2047 Test::Builder is only thread-aware if threads.pm is loaded I<before>
2052 CPAN can provide the best examples. Test::Simple, Test::More,
2053 Test::Exception and Test::Differences all use Test::Builder.
2057 Test::Simple, Test::More, Test::Harness
2061 Original code by chromatic, maintained by Michael G Schwern
2062 E<lt>schwern@pobox.comE<gt>
2066 Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2067 Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2069 This program is free software; you can redistribute it and/or
2070 modify it under the same terms as Perl itself.
2072 See F<http://www.perl.com/perl/misc/Artistic.html>