6 our $VERSION = '0.78_01';
7 $VERSION = eval { $VERSION }; # make the alpha version come out as a number
9 # Make Test::Builder thread-safe for ithreads.
12 # Load threads::shared when threads are turned on.
13 # 5.8.0's threads are so busted we no longer support them.
14 if( $] >= 5.008001 && $Config{useithreads} && $INC{'threads.pm'}) {
15 require threads::shared;
17 # Hack around YET ANOTHER threads::shared bug. It would
18 # occassionally forget the contents of the variable when sharing it.
19 # So we first copy the data, then share, then put our copy back.
20 *share = sub (\[$@%]) {
24 if( $type eq 'HASH' ) {
27 elsif( $type eq 'ARRAY' ) {
30 elsif( $type eq 'SCALAR' ) {
34 die("Unknown type: ".$type);
37 $_[0] = &threads::shared::share($_[0]);
39 if( $type eq 'HASH' ) {
42 elsif( $type eq 'ARRAY' ) {
45 elsif( $type eq 'SCALAR' ) {
49 die("Unknown type: ".$type);
55 # 5.8.0's threads::shared is busted when threads are off
56 # and earlier Perls just don't have that module at all.
58 *share = sub { return $_[0] };
66 Test::Builder - Backend for building test libraries
70 package My::Test::Module;
71 use base 'Test::Builder::Module';
73 my $CLASS = __PACKAGE__;
76 my($test, $name) = @_;
77 my $tb = $CLASS->builder;
79 $tb->ok($test, $name);
85 Test::Simple and Test::More have proven to be popular testing modules,
86 but they're not always flexible enough. Test::Builder provides the a
87 building block upon which to write your own test libraries I<which can
96 my $Test = Test::Builder->new;
98 Returns a Test::Builder object representing the current state of the
101 Since you only run one test per program C<new> always returns the same
102 Test::Builder object. No matter how many times you call new(), you're
103 getting the same object. This is called a singleton. This is done so that
104 multiple modules share such global information as the test counter and
105 where test output is going.
107 If you want a completely new Test::Builder object different from the
108 singleton, use C<create>.
112 my $Test = Test::Builder->new;
115 $Test ||= $class->create;
122 my $Test = Test::Builder->create;
124 Ok, so there can be more than one Test::Builder object and this is how
125 you get it. You might use this instead of C<new()> if you're testing
126 a Test::Builder based module, but otherwise you probably want C<new>.
128 B<NOTE>: the implementation is not complete. C<level>, for example, is
129 still shared amongst B<all> Test::Builder objects, even ones created using
130 this method. Also, the method name may change in the future.
137 my $self = bless {}, $class;
147 Reinitializes the Test::Builder singleton to its original state.
148 Mostly useful for tests run in persistent environments where the same
149 test might be run multiple times in the same process.
158 # We leave this a global because it has to be localized and localizing
159 # hash keys is just asking for pain. Also, it was documented.
162 $self->{Have_Plan} = 0;
163 $self->{No_Plan} = 0;
164 $self->{Original_Pid} = $$;
166 share($self->{Curr_Test});
167 $self->{Curr_Test} = 0;
168 $self->{Test_Results} = &share([]);
170 $self->{Exported_To} = undef;
171 $self->{Expected_Tests} = 0;
173 $self->{Skip_All} = 0;
175 $self->{Use_Nums} = 1;
177 $self->{No_Header} = 0;
178 $self->{No_Ending} = 0;
180 $self->{TODO} = undef;
182 $self->_dup_stdhandles unless $^C;
189 =head2 Setting up tests
191 These methods are for setting up tests and declaring how many there
192 are. You usually only want to call one of these methods.
198 $Test->plan('no_plan');
199 $Test->plan( skip_all => $reason );
200 $Test->plan( tests => $num_tests );
202 A convenient way to set up your tests. Call this and Test::Builder
203 will print the appropriate headers and take the appropriate actions.
205 If you call plan(), don't call any of the other methods below.
210 my($self, $cmd, $arg) = @_;
214 local $Level = $Level + 1;
216 if( $self->{Have_Plan} ) {
217 $self->croak("You tried to plan twice");
220 if( $cmd eq 'no_plan' ) {
223 elsif( $cmd eq 'skip_all' ) {
224 return $self->skip_all($arg);
226 elsif( $cmd eq 'tests' ) {
228 local $Level = $Level + 1;
229 return $self->expected_tests($arg);
231 elsif( !defined $arg ) {
232 $self->croak("Got an undefined number of tests");
235 $self->croak("You said to run 0 tests");
239 my @args = grep { defined } ($cmd, $arg);
240 $self->croak("plan() doesn't understand @args");
246 =item B<expected_tests>
248 my $max = $Test->expected_tests;
249 $Test->expected_tests($max);
251 Gets/sets the # of tests we expect this test to run and prints out
252 the appropriate headers.
261 $self->croak("Number of tests must be a positive integer. You gave it '$max'")
262 unless $max =~ /^\+?\d+$/ and $max > 0;
264 $self->{Expected_Tests} = $max;
265 $self->{Have_Plan} = 1;
267 $self->_print("1..$max\n") unless $self->no_header;
269 return $self->{Expected_Tests};
277 Declares that this test will run an indeterminate # of tests.
284 $self->{No_Plan} = 1;
285 $self->{Have_Plan} = 1;
290 $plan = $Test->has_plan
292 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).
299 return($self->{Expected_Tests}) if $self->{Expected_Tests};
300 return('no_plan') if $self->{No_Plan};
308 $Test->skip_all($reason);
310 Skips all the tests, using the given $reason. Exits immediately with 0.
315 my($self, $reason) = @_;
318 $out .= " # Skip $reason" if $reason;
321 $self->{Skip_All} = 1;
323 $self->_print($out) unless $self->no_header;
330 my $pack = $Test->exported_to;
331 $Test->exported_to($pack);
333 Tells Test::Builder what package you exported your functions to.
335 This method isn't terribly useful since modules which share the same
336 Test::Builder object might get exported to different packages and only
337 the last one will be honored.
342 my($self, $pack) = @_;
344 if( defined $pack ) {
345 $self->{Exported_To} = $pack;
347 return $self->{Exported_To};
354 These actually run the tests, analogous to the functions in Test::More.
356 They all return true if the test passed, false if the test failed.
358 $name is always optional.
364 $Test->ok($test, $name);
366 Your basic test. Pass if $test is true, fail if $test is false. Just
367 like Test::Simple's ok().
372 my($self, $test, $name) = @_;
374 # $test might contain an object which we don't want to accidentally
375 # store, so we turn it into a boolean.
376 $test = $test ? 1 : 0;
380 lock $self->{Curr_Test};
381 $self->{Curr_Test}++;
383 # In case $name is a string overloaded object, force it to stringify.
384 $self->_unoverload_str(\$name);
386 $self->diag(<<ERR) if defined $name and $name =~ /^[\d\s]+$/;
387 You named your test '$name'. You shouldn't use numbers for your test names.
391 my $todo = $self->todo();
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 local $self->{TODO} = $todo;
397 $self->_unoverload_str(\$todo);
400 my $result = &share({});
404 @$result{ 'ok', 'actual_ok' } = ( ( $todo ? 1 : 0 ), 0 );
407 @$result{ 'ok', 'actual_ok' } = ( 1, $test );
411 $out .= " $self->{Curr_Test}" if $self->use_numbers;
413 if( defined $name ) {
414 $name =~ s|#|\\#|g; # # in a name can confuse Test::Harness.
416 $result->{name} = $name;
419 $result->{name} = '';
423 $out .= " # TODO $todo";
424 $result->{reason} = $todo;
425 $result->{type} = 'todo';
428 $result->{reason} = '';
429 $result->{type} = '';
432 $self->{Test_Results}[$self->{Curr_Test}-1] = $result;
438 my $msg = $todo ? "Failed (TODO)" : "Failed";
439 $self->_print_diag("\n") if $ENV{HARNESS_ACTIVE};
441 my(undef, $file, $line) = $self->caller;
442 if( defined $name ) {
443 $self->diag(qq[ $msg test '$name'\n]);
444 $self->diag(qq[ at $file line $line.\n]);
447 $self->diag(qq[ $msg test at $file line $line.\n]);
451 return $test ? 1 : 0;
459 $self->_try(sub { require overload } ) || return;
461 foreach my $thing (@_) {
462 if( $self->_is_object($$thing) ) {
463 if( my $string_meth = overload::Method($$thing, $type) ) {
464 $$thing = $$thing->$string_meth();
472 my($self, $thing) = @_;
474 return $self->_try(sub { ref $thing && $thing->isa('UNIVERSAL') }) ? 1 : 0;
478 sub _unoverload_str {
481 $self->_unoverload(q[""], @_);
484 sub _unoverload_num {
487 $self->_unoverload('0+', @_);
490 next unless $self->_is_dualvar($$val);
496 # This is a hack to detect a dualvar such as $!
498 my($self, $val) = @_;
502 return 1 if $numval != 0 and $numval ne $val;
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, $got, $type, $expect) = @_;
562 foreach my $val (\$got, \$expect) {
563 if( defined $$val ) {
564 if( $type eq 'eq' ) {
565 # quote and force string context
569 # force numeric context
570 $self->_unoverload_num($val);
578 local $Level = $Level + 1;
579 return $self->diag(sprintf <<DIAGNOSTIC, $got, $expect);
588 $Test->isnt_eq($got, $dont_expect, $name);
590 Like Test::More's isnt(). Checks if $got ne $dont_expect. This is
595 $Test->isnt_num($got, $dont_expect, $name);
597 Like Test::More's isnt(). Checks if $got ne $dont_expect. This is
603 my($self, $got, $dont_expect, $name) = @_;
604 local $Level = $Level + 1;
606 if( !defined $got || !defined $dont_expect ) {
607 # undef only matches undef and nothing else
608 my $test = defined $got || defined $dont_expect;
610 $self->ok($test, $name);
611 $self->_cmp_diag($got, 'ne', $dont_expect) unless $test;
615 return $self->cmp_ok($got, 'ne', $dont_expect, $name);
619 my($self, $got, $dont_expect, $name) = @_;
620 local $Level = $Level + 1;
622 if( !defined $got || !defined $dont_expect ) {
623 # undef only matches undef and nothing else
624 my $test = defined $got || defined $dont_expect;
626 $self->ok($test, $name);
627 $self->_cmp_diag($got, '!=', $dont_expect) unless $test;
631 return $self->cmp_ok($got, '!=', $dont_expect, $name);
637 $Test->like($this, qr/$regex/, $name);
638 $Test->like($this, '/$regex/', $name);
640 Like Test::More's like(). Checks if $this matches the given $regex.
642 You'll want to avoid qr// if you want your tests to work before 5.005.
646 $Test->unlike($this, qr/$regex/, $name);
647 $Test->unlike($this, '/$regex/', $name);
649 Like Test::More's unlike(). Checks if $this B<does not match> the
655 my($self, $this, $regex, $name) = @_;
657 local $Level = $Level + 1;
658 $self->_regex_ok($this, $regex, '=~', $name);
662 my($self, $this, $regex, $name) = @_;
664 local $Level = $Level + 1;
665 $self->_regex_ok($this, $regex, '!~', $name);
671 $Test->cmp_ok($this, $type, $that, $name);
673 Works just like Test::More's cmp_ok().
675 $Test->cmp_ok($big_num, '!=', $other_big_num);
680 my %numeric_cmps = map { ($_, 1) }
681 ("<", "<=", ">", ">=", "==", "!=", "<=>");
684 my($self, $got, $type, $expect, $name) = @_;
686 # Treat overloaded objects as numbers if we're asked to do a
687 # numeric comparison.
688 my $unoverload = $numeric_cmps{$type} ? '_unoverload_num'
691 $self->$unoverload(\$got, \$expect);
696 local($@,$!,$SIG{__DIE__}); # isolate eval
698 my $code = $self->_caller_context;
700 # Yes, it has to look like this or 5.4.5 won't see the #line
702 # Don't ask me, man, I just work here.
704 $code" . "\$got $type \$expect;";
707 local $Level = $Level + 1;
708 my $ok = $self->ok($test, $name);
711 if( $type =~ /^(eq|==)$/ ) {
712 $self->_is_diag($got, $type, $expect);
715 $self->_cmp_diag($got, $type, $expect);
722 my($self, $got, $type, $expect) = @_;
724 $got = defined $got ? "'$got'" : 'undef';
725 $expect = defined $expect ? "'$expect'" : 'undef';
727 local $Level = $Level + 1;
728 return $self->diag(sprintf <<DIAGNOSTIC, $got, $type, $expect);
736 sub _caller_context {
739 my($pack, $file, $line) = $self->caller(1);
742 $code .= "#line $line $file\n" if defined $file and defined $line;
750 =head2 Other Testing Methods
752 These are methods which are used in the course of writing a test but are not themselves tests.
758 $Test->BAIL_OUT($reason);
760 Indicates to the Test::Harness that things are going so badly all
761 testing should terminate. This includes running any additional test
764 It will exit with 255.
769 my($self, $reason) = @_;
771 $self->{Bailed_Out} = 1;
772 $self->_print("Bail out! $reason");
777 BAIL_OUT() used to be BAILOUT()
781 *BAILOUT = \&BAIL_OUT;
789 Skips the current test, reporting $why.
794 my($self, $why) = @_;
796 $self->_unoverload_str(\$why);
800 lock($self->{Curr_Test});
801 $self->{Curr_Test}++;
803 $self->{Test_Results}[$self->{Curr_Test}-1] = &share({
812 $out .= " $self->{Curr_Test}" if $self->use_numbers;
814 $out .= " $why" if length $why;
826 $Test->todo_skip($why);
828 Like skip(), only it will declare the test as failing and TODO. Similar
831 print "not ok $tnum # TODO $why\n";
836 my($self, $why) = @_;
841 lock($self->{Curr_Test});
842 $self->{Curr_Test}++;
844 $self->{Test_Results}[$self->{Curr_Test}-1] = &share({
853 $out .= " $self->{Curr_Test}" if $self->use_numbers;
854 $out .= " # TODO & SKIP $why\n";
862 =begin _unimplemented
867 $Test->skip_rest($reason);
869 Like skip(), only it skips all the rest of the tests you plan to run
870 and terminates the test.
872 If you're running under no_plan, it skips once and terminates the
880 =head2 Test building utility methods
882 These methods are useful when writing your own test methods.
888 $Test->maybe_regex(qr/$regex/);
889 $Test->maybe_regex('/$regex/');
891 Convenience method for building testing functions that take regular
892 expressions as arguments, but need to work before perl 5.005.
894 Takes a quoted regular expression produced by qr//, or a string
895 representing a regular expression.
897 Returns a Perl value which may be used instead of the corresponding
898 regular expression, or undef if it's argument is not recognised.
900 For example, a version of like(), sans the useful diagnostic messages,
904 my ($self, $this, $regex, $name) = @_;
905 my $usable_regex = $self->maybe_regex($regex);
906 die "expecting regex, found '$regex'\n"
907 unless $usable_regex;
908 $self->ok($this =~ m/$usable_regex/, $name);
915 my ($self, $regex) = @_;
916 my $usable_regex = undef;
918 return $usable_regex unless defined $regex;
924 ? re::is_regexp($regex)
925 : ref $regex eq 'Regexp'
928 $usable_regex = $regex;
930 # Check for '/foo/' or 'm,foo,'
931 elsif( ($re, $opts) = $regex =~ m{^ /(.*)/ (\w*) $ }sx or
932 (undef, $re, $opts) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
935 $usable_regex = length $opts ? "(?$opts)$re" : $re;
938 return $usable_regex;
945 # is_regexp() checks for regexes in a robust manner, say if they're
947 return re::is_regexp($regex) if defined &re::is_regexp;
948 return ref $regex eq 'Regexp';
953 my($self, $this, $regex, $cmp, $name) = @_;
956 my $usable_regex = $self->maybe_regex($regex);
957 unless (defined $usable_regex) {
958 $ok = $self->ok( 0, $name );
959 $self->diag(" '$regex' doesn't look much like a regex to me.");
965 my $code = $self->_caller_context;
967 local($@, $!, $SIG{__DIE__}); # isolate eval
969 # Yes, it has to look like this or 5.4.5 won't see the #line
971 # Don't ask me, man, I just work here.
973 $code" . q{$test = $this =~ /$usable_regex/ ? 1 : 0};
975 $test = !$test if $cmp eq '!~';
977 local $Level = $Level + 1;
978 $ok = $self->ok( $test, $name );
982 $this = defined $this ? "'$this'" : 'undef';
983 my $match = $cmp eq '=~' ? "doesn't match" : "matches";
985 local $Level = $Level + 1;
986 $self->diag(sprintf <<DIAGNOSTIC, $this, $match, $regex);
997 # I'm not ready to publish this. It doesn't deal with array return
998 # values from the code or context.
1004 my $return_from_code = $Test->try(sub { code });
1005 my($return_from_code, $error) = $Test->try(sub { code });
1007 Works like eval BLOCK except it ensures it has no effect on the rest of the test (ie. $@ is not set) nor is effected by outside interference (ie. $SIG{__DIE__}) and works around some quirks in older Perls.
1009 $error is what would normally be in $@.
1011 It is suggested you use this in place of eval BLOCK.
1016 my($self, $code) = @_;
1018 local $!; # eval can mess up $!
1019 local $@; # don't set $@ in the test
1020 local $SIG{__DIE__}; # don't trip an outside DIE handler.
1021 my $return = eval { $code->() };
1023 return wantarray ? ($return, $@) : $return;
1031 my $is_fh = $Test->is_fh($thing);
1033 Determines if the given $thing can be used as a filehandle.
1039 my $maybe_fh = shift;
1040 return 0 unless defined $maybe_fh;
1042 return 1 if ref $maybe_fh eq 'GLOB'; # its a glob ref
1043 return 1 if ref \$maybe_fh eq 'GLOB'; # its a glob
1045 return eval { $maybe_fh->isa("IO::Handle") } ||
1046 # 5.5.4's tied() and can() doesn't like getting undef
1047 eval { (tied($maybe_fh) || '')->can('TIEHANDLE') };
1061 $Test->level($how_high);
1063 How far up the call stack should $Test look when reporting where the
1068 Setting L<$Test::Builder::Level> overrides. This is typically useful
1074 local $Test::Builder::Level = $Test::Builder::Level + 1;
1078 To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
1083 my($self, $level) = @_;
1085 if( defined $level ) {
1092 =item B<use_numbers>
1094 $Test->use_numbers($on_or_off);
1096 Whether or not the test should output numbers. That is, this if true:
1108 Most useful when you can't depend on the test output order, such as
1109 when threads or forking is involved.
1116 my($self, $use_nums) = @_;
1118 if( defined $use_nums ) {
1119 $self->{Use_Nums} = $use_nums;
1121 return $self->{Use_Nums};
1127 $Test->no_diag($no_diag);
1129 If set true no diagnostics will be printed. This includes calls to
1134 $Test->no_ending($no_ending);
1136 Normally, Test::Builder does some extra diagnostics when the test
1137 ends. It also changes the exit code as described below.
1139 If this is true, none of that will be done.
1143 $Test->no_header($no_header);
1145 If set to true, no "1..N" header will be printed.
1149 foreach my $attribute (qw(No_Header No_Ending No_Diag)) {
1150 my $method = lc $attribute;
1153 my($self, $no) = @_;
1156 $self->{$attribute} = $no;
1158 return $self->{$attribute};
1161 no strict 'refs'; ## no critic
1162 *{__PACKAGE__.'::'.$method} = $code;
1170 Controlling where the test output goes.
1172 It's ok for your test to change where STDOUT and STDERR point to,
1173 Test::Builder's default output settings will not be affected.
1181 Prints out the given @msgs. Like C<print>, arguments are simply
1184 Normally, it uses the failure_output() handle, but if this is for a
1185 TODO test, the todo_output() handle is used.
1187 Output will be indented and marked with a # so as not to interfere
1188 with test output. A newline will be put on the end if there isn't one
1191 We encourage using this rather than calling print directly.
1193 Returns false. Why? Because diag() is often used in conjunction with
1194 a failing test (C<ok() || diag()>) it "passes through" the failure.
1196 return ok(...) || diag(...);
1199 Mark Fowler <mark@twoshortplanks.com>
1204 my($self, @msgs) = @_;
1206 return if $self->no_diag;
1207 return unless @msgs;
1209 # Prevent printing headers when compiling (i.e. -c)
1212 # Smash args together like print does.
1213 # Convert undef to 'undef' so its readable.
1214 my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1216 # Escape each line with a #.
1219 # Stick a newline on the end if it needs it.
1220 $msg .= "\n" unless $msg =~ /\n\Z/;
1222 local $Level = $Level + 1;
1223 $self->_print_diag($msg);
1232 $Test->_print(@msgs);
1234 Prints to the output() filehandle.
1241 my($self, @msgs) = @_;
1243 # Prevent printing headers when only compiling. Mostly for when
1244 # tests are deparsed with B::Deparse
1247 my $msg = join '', @msgs;
1249 local($\, $", $,) = (undef, ' ', '');
1250 my $fh = $self->output;
1252 # Escape each line after the first with a # so we don't
1253 # confuse Test::Harness.
1254 $msg =~ s/\n(.)/\n# $1/sg;
1256 # Stick a newline on the end if it needs it.
1257 $msg .= "\n" unless $msg =~ /\n\Z/;
1264 =item B<_print_diag>
1266 $Test->_print_diag(@msg);
1268 Like _print, but prints to the current diagnostic filehandle.
1277 local($\, $", $,) = (undef, ' ', '');
1278 my $fh = $self->todo ? $self->todo_output : $self->failure_output;
1285 $Test->output($file);
1287 Where normal "ok/not ok" test output should go.
1291 =item B<failure_output>
1293 $Test->failure_output($fh);
1294 $Test->failure_output($file);
1296 Where diagnostic output on test failures and diag() should go.
1300 =item B<todo_output>
1302 $Test->todo_output($fh);
1303 $Test->todo_output($file);
1305 Where diagnostics about todo test failures and diag() should go.
1312 my($self, $fh) = @_;
1315 $self->{Out_FH} = $self->_new_fh($fh);
1317 return $self->{Out_FH};
1320 sub failure_output {
1321 my($self, $fh) = @_;
1324 $self->{Fail_FH} = $self->_new_fh($fh);
1326 return $self->{Fail_FH};
1330 my($self, $fh) = @_;
1333 $self->{Todo_FH} = $self->_new_fh($fh);
1335 return $self->{Todo_FH};
1341 my($file_or_fh) = shift;
1344 if( $self->is_fh($file_or_fh) ) {
1348 open $fh, ">", $file_or_fh or
1349 $self->croak("Can't open test output log $file_or_fh: $!");
1359 my $old_fh = select $fh;
1365 my($Testout, $Testerr);
1366 sub _dup_stdhandles {
1369 $self->_open_testhandles;
1371 # Set everything to unbuffered else plain prints to STDOUT will
1372 # come out in the wrong order from our own prints.
1373 _autoflush($Testout);
1374 _autoflush(\*STDOUT);
1375 _autoflush($Testerr);
1376 _autoflush(\*STDERR);
1378 $self->output ($Testout);
1379 $self->failure_output($Testerr);
1380 $self->todo_output ($Testout);
1384 my $Opened_Testhandles = 0;
1385 sub _open_testhandles {
1388 return if $Opened_Testhandles;
1390 # We dup STDOUT and STDERR so people can change them in their
1391 # test suites while still getting normal test output.
1392 open( $Testout, ">&STDOUT") or die "Can't dup STDOUT: $!";
1393 open( $Testerr, ">&STDERR") or die "Can't dup STDERR: $!";
1395 # $self->_copy_io_layers( \*STDOUT, $Testout );
1396 # $self->_copy_io_layers( \*STDERR, $Testerr );
1398 $Opened_Testhandles = 1;
1402 sub _copy_io_layers {
1403 my($self, $src, $dest) = @_;
1407 my @layers = PerlIO::get_layers($src);
1409 binmode $dest, join " ", map ":$_", @layers if @layers;
1415 $tb->carp(@message);
1417 Warns with C<@message> but the message will appear to come from the
1418 point where the original test function was called (C<$tb->caller>).
1422 $tb->croak(@message);
1424 Dies with C<@message> but the message will appear to come from the
1425 point where the original test function was called (C<$tb->caller>).
1429 sub _message_at_caller {
1432 local $Level = $Level + 1;
1433 my($pack, $file, $line) = $self->caller;
1434 return join("", @_) . " at $file line $line.\n";
1439 warn $self->_message_at_caller(@_);
1444 die $self->_message_at_caller(@_);
1450 unless( $self->{Have_Plan} ) {
1451 local $Level = $Level + 2;
1452 $self->croak("You tried to run a test without a plan");
1459 =head2 Test Status and Info
1463 =item B<current_test>
1465 my $curr_test = $Test->current_test;
1466 $Test->current_test($num);
1468 Gets/sets the current test number we're on. You usually shouldn't
1471 If set forward, the details of the missing tests are filled in as 'unknown'.
1472 if set backward, the details of the intervening tests are deleted. You
1473 can erase history if you really want to.
1478 my($self, $num) = @_;
1480 lock($self->{Curr_Test});
1481 if( defined $num ) {
1482 unless( $self->{Have_Plan} ) {
1483 $self->croak("Can't change the current test number without a plan!");
1486 $self->{Curr_Test} = $num;
1488 # If the test counter is being pushed forward fill in the details.
1489 my $test_results = $self->{Test_Results};
1490 if( $num > @$test_results ) {
1491 my $start = @$test_results ? @$test_results : 0;
1492 for ($start..$num-1) {
1493 $test_results->[$_] = &share({
1496 reason => 'incrementing test number',
1502 # If backward, wipe history. Its their funeral.
1503 elsif( $num < @$test_results ) {
1504 $#{$test_results} = $num - 1;
1507 return $self->{Curr_Test};
1513 my @tests = $Test->summary;
1515 A simple summary of the tests so far. True for pass, false for fail.
1516 This is a logical pass/fail, so todos are passes.
1518 Of course, test #1 is $tests[0], etc...
1525 return map { $_->{'ok'} } @{ $self->{Test_Results} };
1530 my @tests = $Test->details;
1532 Like summary(), but with a lot more detail.
1534 $tests[$test_num - 1] =
1535 { 'ok' => is the test considered a pass?
1536 actual_ok => did it literally say 'ok'?
1537 name => name of the test (if any)
1538 type => type of test (if any, see below).
1539 reason => reason for the above (if any)
1542 'ok' is true if Test::Harness will consider the test to be a pass.
1544 'actual_ok' is a reflection of whether or not the test literally
1545 printed 'ok' or 'not ok'. This is for examining the result of 'todo'
1548 'name' is the name of the test.
1550 'type' indicates if it was a special test. Normal tests have a type
1551 of ''. Type can be one of the following:
1555 todo_skip see todo_skip()
1558 Sometimes the Test::Builder test counter is incremented without it
1559 printing any test output, for example, when current_test() is changed.
1560 In these cases, Test::Builder doesn't know the result of the test, so
1561 it's type is 'unkown'. These details for these tests are filled in.
1562 They are considered ok, but the name and actual_ok is left undef.
1564 For example "not ok 23 - hole count # TODO insufficient donuts" would
1565 result in this structure:
1567 $tests[22] = # 23 - 1, since arrays start from 0.
1568 { ok => 1, # logically, the test passed since it's todo
1569 actual_ok => 0, # in absolute terms, it failed
1570 name => 'hole count',
1572 reason => 'insufficient donuts'
1579 return @{ $self->{Test_Results} };
1584 my $todo_reason = $Test->todo;
1585 my $todo_reason = $Test->todo($pack);
1587 todo() looks for a $TODO variable in your tests. If set, all tests
1588 will be considered 'todo' (see Test::More and Test::Harness for
1589 details). Returns the reason (ie. the value of $TODO) if running as
1590 todo tests, false otherwise.
1592 todo() is about finding the right package to look for $TODO in. It's
1593 pretty good at guessing the right package to look at. It first looks for
1594 the caller based on C<$Level + 1>, since C<todo()> is usually called inside
1595 a test function. As a last resort it will use C<exported_to()>.
1597 Sometimes there is some confusion about where todo() should be looking
1598 for the $TODO variable. If you want to be sure, tell it explicitly
1604 my($self, $pack) = @_;
1606 return $self->{TODO} if defined $self->{TODO};
1608 $pack = $pack || $self->caller(1) || $self->exported_to;
1609 return 0 unless $pack;
1611 no strict 'refs'; ## no critic
1612 return defined ${$pack.'::TODO'} ? ${$pack.'::TODO'}
1618 my $package = $Test->caller;
1619 my($pack, $file, $line) = $Test->caller;
1620 my($pack, $file, $line) = $Test->caller($height);
1622 Like the normal caller(), except it reports according to your level().
1624 C<$height> will be added to the level().
1629 my($self, $height) = @_;
1632 my @caller = CORE::caller($self->level + $height + 1);
1633 return wantarray ? @caller : $caller[0];
1644 =item B<_sanity_check>
1646 $self->_sanity_check();
1648 Runs a bunch of end of test sanity checks to make sure reality came
1649 through ok. If anything is wrong it will die with a fairly friendly
1658 $self->_whoa($self->{Curr_Test} < 0, 'Says here you ran a negative number of tests!');
1659 $self->_whoa(!$self->{Have_Plan} and $self->{Curr_Test},
1660 'Somehow your tests ran without a plan!');
1661 $self->_whoa($self->{Curr_Test} != @{ $self->{Test_Results} },
1662 'Somehow you got a different number of results than tests ran!');
1667 $self->_whoa($check, $description);
1669 A sanity check, similar to assert(). If the $check is true, something
1670 has gone horribly wrong. It will die with the given $description and
1671 a note to contact the author.
1676 my($self, $check, $desc) = @_;
1678 local $Level = $Level + 1;
1679 $self->croak(<<"WHOA");
1681 This should never happen! Please contact the author immediately!
1688 _my_exit($exit_num);
1690 Perl seems to have some trouble with exiting inside an END block. 5.005_03
1691 and 5.6.1 both seem to do odd things. Instead, this function edits $?
1692 directly. It should ONLY be called from inside an END block. It
1693 doesn't actually exit, that's your job.
1713 my $real_exit_code = $?;
1714 $self->_sanity_check();
1716 # Don't bother with an ending if this is a forked copy. Only the parent
1717 # should do the ending.
1718 if( $self->{Original_Pid} != $$ ) {
1722 # Exit if plan() was never called. This is so "require Test::Simple"
1724 if( !$self->{Have_Plan} ) {
1728 # Don't do an ending if we bailed out.
1729 if( $self->{Bailed_Out} ) {
1733 # Figure out if we passed or failed and print helpful messages.
1734 my $test_results = $self->{Test_Results};
1735 if( @$test_results ) {
1736 # The plan? We have no plan.
1737 if( $self->{No_Plan} ) {
1738 $self->_print("1..$self->{Curr_Test}\n") unless $self->no_header;
1739 $self->{Expected_Tests} = $self->{Curr_Test};
1742 # Auto-extended arrays and elements which aren't explicitly
1743 # filled in with a shared reference will puke under 5.8.0
1744 # ithreads. So we have to fill them in by hand. :(
1745 my $empty_result = &share({});
1746 for my $idx ( 0..$self->{Expected_Tests}-1 ) {
1747 $test_results->[$idx] = $empty_result
1748 unless defined $test_results->[$idx];
1751 my $num_failed = grep !$_->{'ok'},
1752 @{$test_results}[0..$self->{Curr_Test}-1];
1754 my $num_extra = $self->{Curr_Test} - $self->{Expected_Tests};
1756 if( $num_extra < 0 ) {
1757 my $s = $self->{Expected_Tests} == 1 ? '' : 's';
1758 $self->diag(<<"FAIL");
1759 Looks like you planned $self->{Expected_Tests} test$s but only ran $self->{Curr_Test}.
1762 elsif( $num_extra > 0 ) {
1763 my $s = $self->{Expected_Tests} == 1 ? '' : 's';
1764 $self->diag(<<"FAIL");
1765 Looks like you planned $self->{Expected_Tests} test$s but ran $num_extra extra.
1769 if ( $num_failed ) {
1770 my $num_tests = $self->{Curr_Test};
1771 my $s = $num_failed == 1 ? '' : 's';
1773 my $qualifier = $num_extra == 0 ? '' : ' run';
1775 $self->diag(<<"FAIL");
1776 Looks like you failed $num_failed test$s of $num_tests$qualifier.
1780 if( $real_exit_code ) {
1781 $self->diag(<<"FAIL");
1782 Looks like your test died just after $self->{Curr_Test}.
1785 _my_exit( 255 ) && return;
1790 $exit_code = $num_failed <= 254 ? $num_failed : 254;
1792 elsif( $num_extra != 0 ) {
1799 _my_exit( $exit_code ) && return;
1801 elsif ( $self->{Skip_All} ) {
1802 _my_exit( 0 ) && return;
1804 elsif ( $real_exit_code ) {
1805 $self->diag(<<'FAIL');
1806 Looks like your test died before it could output anything.
1808 _my_exit( 255 ) && return;
1811 $self->diag("No tests run!\n");
1812 _my_exit( 255 ) && return;
1817 $Test->_ending if defined $Test and !$Test->no_ending;
1822 If all your tests passed, Test::Builder will exit with zero (which is
1823 normal). If anything failed it will exit with how many failed. If
1824 you run less (or more) tests than you planned, the missing (or extras)
1825 will be considered failures. If no tests were ever run Test::Builder
1826 will throw a warning and exit with 255. If the test died, even after
1827 having successfully completed all its tests, it will still be
1828 considered a failure and will exit with 255.
1830 So the exit codes are...
1832 0 all tests successful
1833 255 test died or all passed but wrong # of tests run
1834 any other number how many failed (including missing or extras)
1836 If you fail more than 254 tests, it will be reported as 254.
1841 In perl 5.8.1 and later, Test::Builder is thread-safe. The test
1842 number is shared amongst all threads. This means if one thread sets
1843 the test number using current_test() they will all be effected.
1845 While versions earlier than 5.8.1 had threads they contain too many
1848 Test::Builder is only thread-aware if threads.pm is loaded I<before>
1853 CPAN can provide the best examples. Test::Simple, Test::More,
1854 Test::Exception and Test::Differences all use Test::Builder.
1858 Test::Simple, Test::More, Test::Harness
1862 Original code by chromatic, maintained by Michael G Schwern
1863 E<lt>schwern@pobox.comE<gt>
1867 Copyright 2002, 2004 by chromatic E<lt>chromatic@wgz.orgE<gt> and
1868 Michael G Schwern E<lt>schwern@pobox.comE<gt>.
1870 This program is free software; you can redistribute it and/or
1871 modify it under the same terms as Perl itself.
1873 See F<http://www.perl.com/perl/misc/Artistic.html>