7 our $VERSION = '1.302141';
11 require Test::Builder::IO::Scalar;
15 use Scalar::Util qw/blessed reftype weaken/;
17 use Test2::Util qw/USE_THREADS try get_tid/;
18 use Test2::API qw/context release/;
19 # Make Test::Builder thread-safe for ithreads.
21 warn "Test::Builder was loaded after Test2 initialization, this is not recommended."
22 if Test2::API::test2_init_done() || Test2::API::test2_load_done();
24 if (USE_THREADS && ! Test2::API::test2_ipc_disabled()) {
26 require Test2::IPC::Driver::Files;
27 Test2::IPC::Driver::Files->import;
28 Test2::API::test2_ipc_enable_polling();
29 Test2::API::test2_no_wait(1);
30 Test2::API::test2_ipc_enable_shm();
34 use Test2::Event::Subtest;
35 use Test2::Hub::Subtest;
37 use Test::Builder::Formatter;
38 use Test::Builder::TodoDiag;
41 our $Test = $ENV{TB_NO_EARLY_INIT} ? undef : Test::Builder->new;
46 my $hub = $self->{Stack}->top;
48 # Take a reference to the hash key, we do this to avoid closing over $self
49 # which is the singleton. We use a reference because the value could change
51 my $epkgr = \$self->{Exported_To};
53 #$hub->add_context_aquire(sub {$_[0]->{level} += $Level - 1});
55 $hub->pre_filter(sub {
56 my ($active_hub, $e) = @_;
59 my $cpkg = $e->{trace} ? $e->{trace}->{frame}->[0] : undef;
64 $todo = ${"$cpkg\::TODO"} if $cpkg;
65 $todo = ${"$epkg\::TODO"} if $epkg && !$todo;
67 return $e unless $todo;
69 # Turn a diag into a todo diag
70 return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
72 if ($active_hub == $hub) {
73 $e->set_todo($todo) if $e->can('set_todo');
74 $e->add_amnesty({tag => 'TODO', details => $todo});
77 $e->add_amnesty({tag => 'TODO', details => $todo, inherited => 1});
81 if ($e->isa('Test2::Event::Ok')) {
82 $e->set_effective_pass(1);
84 if (my $result = $e->get_meta(__PACKAGE__)) {
85 $result->{reason} ||= $todo;
86 $result->{type} ||= 'todo';
99 Test2::API::test2_load() unless Test2::API::test2_in_preload();
106 $Test = $class->create(singleton => 1);
108 Test2::API::test2_add_callback_post_load(
110 $Test->{Original_Pid} = $$ if !$Test->{Original_Pid} || $Test->{Original_Pid} == 0;
111 $Test->reset(singleton => 1);
112 $Test->_add_ts_hooks;
116 # Non-TB tools normally expect 0 added to the level. $Level is normally 1. So
117 # we only want the level to change if $Level != 1.
118 # TB->ctx compensates for this later.
119 Test2::API::test2_add_callback_context_aquire(sub { $_[0]->{level} += $Level - 1 });
121 Test2::API::test2_add_callback_exit(sub { $Test->_ending(@_) });
123 Test2::API::test2_ipc()->set_no_fatal(1) if Test2::API::test2_has_ipc();
132 my $self = bless {}, $class;
133 if ($params{singleton}) {
134 $self->{Stack} = Test2::API::test2_stack();
137 $self->{Stack} = Test2::API::Stack->new;
138 $self->{Stack}->new_hub(
139 formatter => Test::Builder::Formatter->new,
140 ipc => Test2::API::test2_ipc(),
143 $self->reset(%params);
144 $self->_add_ts_hooks;
153 # 1 for our frame, another for the -1 off of $Level in our hook at the top.
156 stack => $self->{Stack},
165 my $ctx = $self->ctx;
166 my $chub = $self->{Hub} || $ctx->hub;
169 my $meta = $chub->meta(__PACKAGE__, {});
170 my $parent = $meta->{parent};
172 return undef unless $parent;
176 Stack => $self->{Stack},
182 my( $self, $name ) = @_;
184 $name ||= "Child of " . $self->name;
185 my $ctx = $self->ctx;
187 my $parent = $ctx->hub;
188 my $pmeta = $parent->meta(__PACKAGE__, {});
189 $self->croak("You already have a child named ($pmeta->{child}) running")
192 $pmeta->{child} = $name;
194 # Clear $TODO for the child.
195 my $orig_TODO = $self->find_TODO(undef, 1, undef);
199 my $hub = $ctx->stack->new_hub(
200 class => 'Test2::Hub::Subtest',
203 $hub->pre_filter(sub {
204 my ($active_hub, $e) = @_;
206 # Turn a diag into a todo diag
207 return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
210 }, inherit => 1) if $orig_TODO;
212 $hub->listen(sub { push @$subevents => $_[1] });
214 $hub->set_nested( $parent->nested + 1 );
216 my $meta = $hub->meta(__PACKAGE__, {});
217 $meta->{Name} = $name;
218 $meta->{TODO} = $orig_TODO;
219 $meta->{TODO_PKG} = $ctx->trace->package;
220 $meta->{parent} = $parent;
221 $meta->{Test_Results} = [];
222 $meta->{subevents} = $subevents;
223 $meta->{subtest_id} = $hub->id;
224 $meta->{subtest_uuid} = $hub->uuid;
225 $meta->{subtest_buffered} = $parent->format ? 0 : 1;
227 $self->_add_ts_hooks;
230 return bless { Original_Pid => $$, Stack => $self->{Stack}, Hub => $hub, no_log_results => $self->{no_log_results} }, blessed($self);
238 my $st_ctx = $self->ctx;
239 my $chub = $self->{Hub} || return $st_ctx->release;
241 my $meta = $chub->meta(__PACKAGE__, {});
242 if ($meta->{child}) {
243 $self->croak("Can't call finalize() with child ($meta->{child}) active");
246 local $? = 0; # don't fail if $subtests happened to set $? nonzero
248 $self->{Stack}->pop($chub);
250 $self->find_TODO($meta->{TODO_PKG}, 1, $meta->{TODO});
252 my $parent = $self->parent;
253 my $ctx = $parent->ctx;
254 my $trace = $ctx->trace;
255 delete $ctx->hub->meta(__PACKAGE__, {})->{child};
257 $chub->finalize($trace->snapshot(hid => $chub->hid, nested => $chub->nested), 1)
263 my $plan = $chub->plan || 0;
264 my $count = $chub->count;
265 my $failed = $chub->failed;
266 my $passed = $chub->is_passing;
268 my $num_extra = $plan =~ m/\D/ ? 0 : $count - $plan;
269 if ($count && $num_extra != 0) {
270 my $s = $plan == 1 ? '' : 's';
271 $st_ctx->diag(<<"FAIL");
272 Looks like you planned $plan test$s but ran $count.
277 my $s = $failed == 1 ? '' : 's';
279 my $qualifier = $num_extra == 0 ? '' : ' run';
281 $st_ctx->diag(<<"FAIL");
282 Looks like you failed $failed test$s of $count$qualifier.
286 if (!$passed && !$failed && $count && !$num_extra) {
287 $st_ctx->diag(<<"FAIL");
288 All assertions inside the subtest passed, but errors were encountered.
294 unless ($chub->bailed_out) {
295 my $plan = $chub->plan;
296 if ( $plan && $plan eq 'SKIP' ) {
297 $parent->skip($chub->skip_reason, $meta->{Name});
299 elsif ( !$chub->count ) {
300 $parent->ok( 0, sprintf q[No tests run for subtest "%s"], $meta->{Name} );
303 $parent->{subevents} = $meta->{subevents};
304 $parent->{subtest_id} = $meta->{subtest_id};
305 $parent->{subtest_uuid} = $meta->{subtest_uuid};
306 $parent->{subtest_buffered} = $meta->{subtest_buffered};
307 $parent->ok( $chub->is_passing, $meta->{Name} );
312 return $chub->is_passing;
317 my ($name, $code, @args) = @_;
318 my $ctx = $self->ctx;
319 $ctx->throw("subtest()'s second argument must be a code ref")
320 unless $code && reftype($code) eq 'CODE';
322 $name ||= "Child of " . $self->name;
325 $_->($name,$code,@args)
326 for Test2::API::test2_list_pre_subtest_callbacks();
328 $ctx->note("Subtest: $name");
330 my $child = $self->child($name);
334 my ($ok, $err, $finished, $child_error);
335 T2_SUBTEST_WRAPPER: {
336 my $ctx = $self->ctx;
337 $st_ctx = $ctx->snapshot;
339 $ok = eval { local $Level = 1; $code->(@args); 1 };
340 ($err, $child_error) = ($@, $?);
342 # They might have done 'BEGIN { skip_all => "whatever" }'
343 if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && blessed($err) eq 'Test::Builder::Exception')) {
352 if ($start_pid != $$ && !$INC{'Test2/IPC.pm'}) {
353 warn $ok ? "Forked inside subtest, but subtest never finished!\n" : $err;
357 my $trace = $ctx->trace;
360 if(my $bailed = $st_ctx->hub->bailed_out) {
361 my $chub = $child->{Hub};
362 $self->{Stack}->pop($chub);
363 $ctx->bail($bailed->reason);
365 my $code = $st_ctx->hub->exit_code;
367 $err = "Subtest ended with exit code $code" if $code;
370 my $st_hub = $st_ctx->hub;
371 my $plan = $st_hub->plan;
372 my $count = $st_hub->count;
374 if (!$count && (!defined($plan) || "$plan" ne 'SKIP')) {
375 $st_ctx->plan(0) unless defined $plan;
376 $st_ctx->diag('No tests run!');
379 $child->finalize($st_ctx->trace);
385 $? = $child_error if defined $child_error;
387 return $st_hub->is_passing;
392 my $ctx = $self->ctx;
393 release $ctx, $ctx->hub->meta(__PACKAGE__, {})->{Name};
396 sub reset { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
397 my ($self, %params) = @_;
399 Test2::API::test2_set_is_end(0);
401 # We leave this a global because it has to be localized and localizing
402 # hash keys is just asking for pain. Also, it was documented.
405 $self->{no_log_results} = $ENV{TEST_NO_LOG_RESULTS} ? 1 : 0
406 unless $params{singleton};
408 $self->{Original_Pid} = Test2::API::test2_in_preload() ? -1 : $$;
410 my $ctx = $self->ctx;
413 unless ($params{singleton}) {
420 my $meta = $ctx->hub->meta(__PACKAGE__, {});
424 Done_Testing => undef,
427 parent => $meta->{parent},
430 $self->{Exported_To} = undef unless $params{singleton};
432 $self->{Orig_Handles} ||= do {
433 my $format = $ctx->hub->format;
435 if ($format && $format->isa('Test2::Formatter::TAP')) {
436 $out = $format->handles;
441 $self->use_numbers(1);
442 $self->no_header(0) unless $params{singleton};
443 $self->no_ending(0) unless $params{singleton};
444 $self->reset_outputs;
453 no_plan => \&no_plan,
454 skip_all => \&skip_all,
455 tests => \&_plan_tests,
459 my( $self, $cmd, $arg ) = @_;
463 my $ctx = $self->ctx;
466 $ctx->throw("You tried to plan twice") if $hub->plan;
468 local $Level = $Level + 1;
470 if( my $method = $plan_cmds{$cmd} ) {
471 local $Level = $Level + 1;
472 $self->$method($arg);
475 my @args = grep { defined } ( $cmd, $arg );
476 $ctx->throw("plan() doesn't understand @args");
484 my($self, $arg) = @_;
486 my $ctx = $self->ctx;
489 local $Level = $Level + 1;
490 $self->expected_tests($arg);
492 elsif( !defined $arg ) {
493 $ctx->throw("Got an undefined number of tests");
496 $ctx->throw("You said to run 0 tests");
507 my $ctx = $self->ctx;
510 $self->croak("Number of tests must be a positive integer. You gave it '$max'")
511 unless $max =~ /^\+?\d+$/;
520 my $plan = $hub->plan;
521 return 0 unless $plan;
522 return 0 if $plan =~ m/\D/;
528 my($self, $arg) = @_;
530 my $ctx = $self->ctx;
532 if (defined $ctx->hub->plan) {
533 warn "Plan already set, no_plan() is a no-op, this will change to a hard failure in the future.";
538 $ctx->alert("no_plan takes no arguments") if $arg;
540 $ctx->hub->plan('NO PLAN');
547 my($self, $num_tests) = @_;
549 my $ctx = $self->ctx;
551 my $meta = $ctx->hub->meta(__PACKAGE__, {});
553 if ($meta->{Done_Testing}) {
554 my ($file, $line) = @{$meta->{Done_Testing}}[1,2];
555 local $ctx->hub->{ended}; # OMG This is awful.
556 $self->ok(0, "done_testing() was already called at $file line $line");
560 $meta->{Done_Testing} = [$ctx->trace->call];
562 my $plan = $ctx->hub->plan;
563 my $count = $ctx->hub->count;
565 # If done_testing() specified the number of tests, shut off no_plan
566 if( defined $num_tests ) {
567 $ctx->plan($num_tests) if !$plan || $plan eq 'NO PLAN';
569 elsif ($count && defined $num_tests && $count != $num_tests) {
570 $self->ok(0, "planned to run @{[ $self->expected_tests ]} but done_testing() expects $num_tests");
573 $num_tests = $self->current_test;
576 if( $self->expected_tests && $num_tests != $self->expected_tests ) {
577 $self->ok(0, "planned to run @{[ $self->expected_tests ]} ".
578 "but done_testing() expects $num_tests");
581 $ctx->plan($num_tests) if $ctx->hub->plan && $ctx->hub->plan eq 'NO PLAN';
583 $ctx->hub->finalize($ctx->trace, 1);
592 my $ctx = $self->ctx;
593 my $plan = $ctx->hub->plan;
596 return( $plan ) if $plan && $plan !~ m/\D/;
597 return('no_plan') if $plan && $plan eq 'NO PLAN';
603 my( $self, $reason ) = @_;
605 my $ctx = $self->ctx;
607 $ctx->hub->meta(__PACKAGE__, {})->{Skip_All} = $reason || 1;
609 # Work around old perl bug
613 while (my @call = caller($level++)) {
614 last unless @call && $call[0];
615 next unless $call[3] =~ m/::BEGIN$/;
620 die 'Label not found for "last T2_SUBTEST_WRAPPER"' if $begin && $ctx->hub->meta(__PACKAGE__, {})->{parent};
623 $ctx->plan(0, SKIP => $reason);
628 my( $self, $pack ) = @_;
630 if( defined $pack ) {
631 $self->{Exported_To} = $pack;
633 return $self->{Exported_To};
638 my( $self, $test, $name ) = @_;
640 my $ctx = $self->ctx;
642 # $test might contain an object which we don't want to accidentally
643 # store, so we turn it into a boolean.
644 $test = $test ? 1 : 0;
646 # In case $name is a string overloaded object, force it to stringify.
647 no warnings qw/uninitialized numeric/;
648 $name = "$name" if defined $name;
650 # Profiling showed that the regex here was a huge time waster, doing the
651 # numeric addition first cuts our profile time from ~300ms to ~50ms
652 $self->diag(<<" ERR") if 0 + $name && $name =~ /^[\d\s]+$/;
653 You named your test '$name'. You shouldn't use numbers for your test names.
656 use warnings qw/uninitialized numeric/;
658 my $trace = $ctx->{trace};
659 my $hub = $ctx->{hub};
666 (name => defined($name) ? $name : ''),
669 $hub->{_meta}->{+__PACKAGE__}->{Test_Results}[ $hub->{count} ] = $result unless $self->{no_log_results};
671 my $orig_name = $name;
674 my $subevents = delete $self->{subevents};
675 my $subtest_id = delete $self->{subtest_id};
676 my $subtest_uuid = delete $self->{subtest_uuid};
677 my $subtest_buffered = delete $self->{subtest_buffered};
678 my $epkg = 'Test2::Event::Ok';
680 $epkg = 'Test2::Event::Subtest';
681 push @attrs => (subevents => $subevents, subtest_id => $subtest_id, subtest_uuid => $subtest_uuid, buffered => $subtest_buffered);
685 trace => bless( {%$trace}, 'Test2::EventFacet::Trace'),
688 _meta => {'Test::Builder' => $result},
689 effective_pass => $test,
694 $self->_ok_debug($trace, $orig_name) unless($test);
702 my ($trace, $orig_name) = @_;
704 my $is_todo = defined($self->todo);
706 my $msg = $is_todo ? "Failed (TODO)" : "Failed";
708 my (undef, $file, $line) = $trace->call;
709 if (defined $orig_name) {
710 $self->diag(qq[ $msg test '$orig_name'\n at $file line $line.\n]);
713 $self->diag(qq[ $msg test at $file line $line.\n]);
719 local $Level = $Level + 1;
720 return $self->in_todo ? $self->todo_output : $self->failure_output;
724 my ($self, $type, $thing) = @_;
726 return unless ref $$thing;
727 return unless blessed($$thing) || scalar $self->_try(sub{ $$thing->isa('UNIVERSAL') });
732 my $string_meth = overload::Method( $$thing, $type ) || return;
733 $$thing = $$thing->$string_meth();
736 sub _unoverload_str {
739 $self->_unoverload( q[""], $_ ) for @_;
742 sub _unoverload_num {
745 $self->_unoverload( '0+', $_ ) for @_;
748 next unless $self->_is_dualvar($$val);
753 # This is a hack to detect a dualvar such as $!
755 my( $self, $val ) = @_;
757 # Objects are not dualvars.
758 return 0 if ref $val;
760 no warnings 'numeric';
761 my $numval = $val + 0;
762 return ($numval != 0 and $numval ne $val ? 1 : 0);
767 my( $self, $got, $expect, $name ) = @_;
769 my $ctx = $self->ctx;
771 local $Level = $Level + 1;
773 if( !defined $got || !defined $expect ) {
774 # undef only matches undef and nothing else
775 my $test = !defined $got && !defined $expect;
777 $self->ok( $test, $name );
778 $self->_is_diag( $got, 'eq', $expect ) unless $test;
783 release $ctx, $self->cmp_ok( $got, 'eq', $expect, $name );
788 my( $self, $got, $expect, $name ) = @_;
789 my $ctx = $self->ctx;
790 local $Level = $Level + 1;
792 if( !defined $got || !defined $expect ) {
793 # undef only matches undef and nothing else
794 my $test = !defined $got && !defined $expect;
796 $self->ok( $test, $name );
797 $self->_is_diag( $got, '==', $expect ) unless $test;
802 release $ctx, $self->cmp_ok( $got, '==', $expect, $name );
807 my( $self, $type, $val ) = @_;
809 if( defined $$val ) {
810 if( $type eq 'eq' or $type eq 'ne' ) {
811 # quote and force string context
815 # force numeric context
816 $self->_unoverload_num($val);
828 my( $self, $got, $type, $expect ) = @_;
830 $self->_diag_fmt( $type, $_ ) for \$got, \$expect;
832 local $Level = $Level + 1;
833 return $self->diag(<<"DIAGNOSTIC");
841 my( $self, $got, $type ) = @_;
843 $self->_diag_fmt( $type, \$got );
845 local $Level = $Level + 1;
846 return $self->diag(<<"DIAGNOSTIC");
848 expected: anything else
854 my( $self, $got, $dont_expect, $name ) = @_;
855 my $ctx = $self->ctx;
856 local $Level = $Level + 1;
858 if( !defined $got || !defined $dont_expect ) {
859 # undef only matches undef and nothing else
860 my $test = defined $got || defined $dont_expect;
862 $self->ok( $test, $name );
863 $self->_isnt_diag( $got, 'ne' ) unless $test;
868 release $ctx, $self->cmp_ok( $got, 'ne', $dont_expect, $name );
872 my( $self, $got, $dont_expect, $name ) = @_;
873 my $ctx = $self->ctx;
874 local $Level = $Level + 1;
876 if( !defined $got || !defined $dont_expect ) {
877 # undef only matches undef and nothing else
878 my $test = defined $got || defined $dont_expect;
880 $self->ok( $test, $name );
881 $self->_isnt_diag( $got, '!=' ) unless $test;
886 release $ctx, $self->cmp_ok( $got, '!=', $dont_expect, $name );
891 my( $self, $thing, $regex, $name ) = @_;
892 my $ctx = $self->ctx;
894 local $Level = $Level + 1;
896 release $ctx, $self->_regex_ok( $thing, $regex, '=~', $name );
900 my( $self, $thing, $regex, $name ) = @_;
901 my $ctx = $self->ctx;
903 local $Level = $Level + 1;
905 release $ctx, $self->_regex_ok( $thing, $regex, '!~', $name );
909 my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" );
911 # Bad, these are not comparison operators. Should we include more?
912 my %cmp_ok_bl = map { ( $_, 1 ) } ( "=", "+=", ".=", "x=", "^=", "|=", "||=", "&&=", "...");
915 my( $self, $got, $type, $expect, $name ) = @_;
916 my $ctx = $self->ctx;
918 if ($cmp_ok_bl{$type}) {
919 $ctx->throw("$type is not a valid comparison operator in cmp_ok()");
925 ## no critic (BuiltinFunctions::ProhibitStringyEval)
927 local( $@, $!, $SIG{__DIE__} ); # isolate eval
929 my($pack, $file, $line) = $ctx->trace->call();
931 # This is so that warnings come out at the caller's level
933 #line $line "(eval in cmp_ok) $file"
934 \$test = (\$got $type \$expect);
939 local $Level = $Level + 1;
940 my $ok = $self->ok( $test, $name );
942 # Treat overloaded objects as numbers if we're asked to do a
943 # numeric comparison.
945 = $numeric_cmps{$type}
949 $self->diag(<<"END") unless $succ;
950 An error occurred while using $type:
951 ------------------------------------
953 ------------------------------------
957 $self->$unoverload( \$got, \$expect );
959 if( $type =~ /^(eq|==)$/ ) {
960 $self->_is_diag( $got, $type, $expect );
962 elsif( $type =~ /^(ne|!=)$/ ) {
964 my $eq = ($got eq $expect || $got == $expect)
966 (defined($got) xor defined($expect))
967 || (length($got) != length($expect))
972 $self->_cmp_diag( $got, $type, $expect );
975 $self->_isnt_diag( $got, $type );
979 $self->_cmp_diag( $got, $type, $expect );
982 return release $ctx, $ok;
986 my( $self, $got, $type, $expect ) = @_;
988 $got = defined $got ? "'$got'" : 'undef';
989 $expect = defined $expect ? "'$expect'" : 'undef';
991 local $Level = $Level + 1;
992 return $self->diag(<<"DIAGNOSTIC");
999 sub _caller_context {
1002 my( $pack, $file, $line ) = $self->caller(1);
1005 $code .= "#line $line $file\n" if defined $file and defined $line;
1012 my( $self, $reason ) = @_;
1014 my $ctx = $self->ctx;
1016 $self->{Bailed_Out} = 1;
1018 $ctx->bail($reason);
1024 *BAILOUT = \&BAIL_OUT;
1028 my( $self, $why, $name ) = @_;
1030 $name = '' unless defined $name;
1031 $self->_unoverload_str( \$why );
1033 my $ctx = $self->ctx;
1035 $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1041 } unless $self->{no_log_results};
1043 $name =~ s|#|\\#|g; # # in a name can confuse Test::Harness.
1044 $name =~ s{\n}{\n# }sg;
1045 $why =~ s{\n}{\n# }sg;
1047 my $tctx = $ctx->snapshot;
1048 $tctx->skip('', $why);
1050 return release $ctx, 1;
1055 my( $self, $why ) = @_;
1058 my $ctx = $self->ctx;
1060 $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1064 type => 'todo_skip',
1066 } unless $self->{no_log_results};
1068 $why =~ s{\n}{\n# }sg;
1069 my $tctx = $ctx->snapshot;
1070 $tctx->send_event( 'Skip', todo => $why, todo_diag => 1, reason => $why, pass => 0);
1072 return release $ctx, 1;
1077 my( $self, $regex ) = @_;
1078 my $usable_regex = undef;
1080 return $usable_regex unless defined $regex;
1085 if( _is_qr($regex) ) {
1086 $usable_regex = $regex;
1088 # Check for '/foo/' or 'm,foo,'
1089 elsif(( $re, $opts ) = $regex =~ m{^ /(.*)/ (\w*) $ }sx or
1090 ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
1093 $usable_regex = length $opts ? "(?$opts)$re" : $re;
1096 return $usable_regex;
1102 # is_regexp() checks for regexes in a robust manner, say if they're
1104 return re::is_regexp($regex) if defined &re::is_regexp;
1105 return ref $regex eq 'Regexp';
1109 my( $self, $thing, $regex, $cmp, $name ) = @_;
1112 my $usable_regex = $self->maybe_regex($regex);
1113 unless( defined $usable_regex ) {
1114 local $Level = $Level + 1;
1115 $ok = $self->ok( 0, $name );
1116 $self->diag(" '$regex' doesn't look much like a regex to me.");
1122 my $context = $self->_caller_context;
1125 ## no critic (BuiltinFunctions::ProhibitStringyEval)
1127 local( $@, $!, $SIG{__DIE__} ); # isolate eval
1129 # No point in issuing an uninit warning, they'll see it in the diagnostics
1130 no warnings 'uninitialized';
1132 $test = eval $context . q{$test = $thing =~ /$usable_regex/ ? 1 : 0};
1135 $test = !$test if $cmp eq '!~';
1137 local $Level = $Level + 1;
1138 $ok = $self->ok( $test, $name );
1142 $thing = defined $thing ? "'$thing'" : 'undef';
1143 my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1145 local $Level = $Level + 1;
1146 $self->diag( sprintf <<'DIAGNOSTIC', $thing, $match, $regex );
1159 my $maybe_fh = shift;
1160 return 0 unless defined $maybe_fh;
1162 return 1 if ref $maybe_fh eq 'GLOB'; # its a glob ref
1163 return 1 if ref \$maybe_fh eq 'GLOB'; # its a glob
1165 return eval { $maybe_fh->isa("IO::Handle") } ||
1166 eval { tied($maybe_fh)->can('TIEHANDLE') };
1171 my( $self, $level ) = @_;
1173 if( defined $level ) {
1181 my( $self, $use_nums ) = @_;
1183 my $ctx = $self->ctx;
1184 my $format = $ctx->hub->format;
1185 unless ($format && $format->can('no_numbers') && $format->can('set_no_numbers')) {
1186 warn "The current formatter does not support 'use_numbers'" if $format;
1187 return release $ctx, 0;
1190 $format->set_no_numbers(!$use_nums) if defined $use_nums;
1192 return release $ctx, $format->no_numbers ? 0 : 1;
1196 for my $method (qw(no_header no_diag)) {
1197 my $set = "set_$method";
1199 my( $self, $no ) = @_;
1201 my $ctx = $self->ctx;
1202 my $format = $ctx->hub->format;
1203 unless ($format && $format->can($set)) {
1204 warn "The current formatter does not support '$method'" if $format;
1209 $format->$set($no) if defined $no;
1211 return release $ctx, $format->$method ? 1 : 0;
1214 no strict 'refs'; ## no critic
1220 my( $self, $no ) = @_;
1222 my $ctx = $self->ctx;
1224 $ctx->hub->set_no_ending($no) if defined $no;
1226 return release $ctx, $ctx->hub->no_ending;
1233 my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1235 if (Test2::API::test2_in_preload()) {
1237 $text =~ s/^/# /msg;
1238 print STDERR $text, "\n";
1242 my $ctx = $self->ctx;
1253 my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1255 if (Test2::API::test2_in_preload()) {
1257 $text =~ s/^/# /msg;
1258 print STDOUT $text, "\n";
1262 my $ctx = $self->ctx;
1273 require Data::Dumper;
1278 my $dumper = Data::Dumper->new( [$_] );
1279 $dumper->Indent(1)->Terse(1);
1280 $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1289 my( $self, $fh ) = @_;
1291 my $ctx = $self->ctx;
1292 my $format = $ctx->hub->format;
1294 return unless $format && $format->isa('Test2::Formatter::TAP');
1296 $format->handles->[Test2::Formatter::TAP::OUT_STD()] = $self->_new_fh($fh)
1299 return $format->handles->[Test2::Formatter::TAP::OUT_STD()];
1302 sub failure_output {
1303 my( $self, $fh ) = @_;
1305 my $ctx = $self->ctx;
1306 my $format = $ctx->hub->format;
1308 return unless $format && $format->isa('Test2::Formatter::TAP');
1310 $format->handles->[Test2::Formatter::TAP::OUT_ERR()] = $self->_new_fh($fh)
1313 return $format->handles->[Test2::Formatter::TAP::OUT_ERR()];
1317 my( $self, $fh ) = @_;
1319 my $ctx = $self->ctx;
1320 my $format = $ctx->hub->format;
1322 return unless $format && $format->isa('Test::Builder::Formatter');
1324 $format->handles->[Test::Builder::Formatter::OUT_TODO()] = $self->_new_fh($fh)
1327 return $format->handles->[Test::Builder::Formatter::OUT_TODO()];
1332 my($file_or_fh) = shift;
1335 if( $self->is_fh($file_or_fh) ) {
1338 elsif( ref $file_or_fh eq 'SCALAR' ) {
1339 # Scalar refs as filehandles was added in 5.8.
1341 open $fh, ">>", $file_or_fh
1342 or $self->croak("Can't open scalar ref $file_or_fh: $!");
1344 # Emulate scalar ref filehandles with a tie.
1346 $fh = Test::Builder::IO::Scalar->new($file_or_fh)
1347 or $self->croak("Can't tie scalar ref $file_or_fh");
1351 open $fh, ">", $file_or_fh
1352 or $self->croak("Can't open test output log $file_or_fh: $!");
1361 my $old_fh = select $fh;
1372 my $ctx = $self->ctx;
1373 my $format = $ctx->hub->format;
1375 return unless $format && $format->isa('Test2::Formatter::TAP');
1376 $format->set_handles([@{$self->{Orig_Handles}}]) if $self->{Orig_Handles};
1384 my $ctx = $self->ctx;
1385 $ctx->alert(join "", @_);
1391 my $ctx = $self->ctx;
1392 $ctx->throw(join "", @_);
1398 my( $self, $num ) = @_;
1400 my $ctx = $self->ctx;
1401 my $hub = $ctx->hub;
1403 if( defined $num ) {
1404 $hub->set_count($num);
1406 unless ($self->{no_log_results}) {
1407 # If the test counter is being pushed forward fill in the details.
1408 my $test_results = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1409 if ($num > @$test_results) {
1410 my $start = @$test_results ? @$test_results : 0;
1411 for ($start .. $num - 1) {
1412 $test_results->[$_] = {
1415 reason => 'incrementing test number',
1421 # If backward, wipe history. Its their funeral.
1422 elsif ($num < @$test_results) {
1423 $#{$test_results} = $num - 1;
1427 return release $ctx, $hub->count;
1434 my $ctx = $self->ctx;
1435 my $hub = $ctx->hub;
1439 $hub->set_failed(0) if $bool;
1440 $hub->is_passing($bool);
1443 return release $ctx, $hub->is_passing;
1450 return if $self->{no_log_results};
1452 my $ctx = $self->ctx;
1453 my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1455 return map { $_ ? $_->{'ok'} : () } @$data;
1462 return if $self->{no_log_results};
1464 my $ctx = $self->ctx;
1465 my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1472 my( $self, $pack, $set, $new_value ) = @_;
1474 my $ctx = $self->ctx;
1476 $pack ||= $ctx->trace->package || $self->exported_to;
1479 return unless $pack;
1481 no strict 'refs'; ## no critic
1483 my $old_value = ${ $pack . '::TODO' };
1484 $set and ${ $pack . '::TODO' } = $new_value;
1489 my( $self, $pack ) = @_;
1491 local $Level = $Level + 1;
1492 my $ctx = $self->ctx;
1495 my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1496 return $meta->[-1]->[1] if $meta && @$meta;
1498 $pack ||= $ctx->trace->package;
1500 return unless $pack;
1502 no strict 'refs'; ## no critic
1504 return ${ $pack . '::TODO' };
1510 local $Level = $Level + 1;
1511 my $ctx = $self->ctx;
1514 my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1515 return 1 if $meta && @$meta;
1517 my $pack = $ctx->trace->package || return 0;
1519 no strict 'refs'; ## no critic
1521 my $todo = ${ $pack . '::TODO' };
1523 return 0 unless defined $todo;
1524 return 0 if "$todo" eq '';
1530 my $message = @_ ? shift : '';
1532 my $ctx = $self->ctx;
1534 my $hub = $ctx->hub;
1535 my $filter = $hub->pre_filter(sub {
1536 my ($active_hub, $e) = @_;
1538 # Turn a diag into a todo diag
1539 return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
1542 if ($hub == $active_hub && $e->isa('Test2::Event::Ok')) {
1543 $e->set_todo($message);
1544 $e->set_effective_pass(1);
1546 if (my $result = $e->get_meta(__PACKAGE__)) {
1547 $result->{reason} ||= $message;
1548 $result->{type} ||= 'todo';
1556 push @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}} => [$filter, $message];
1566 my $ctx = $self->ctx;
1568 my $set = pop @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}};
1570 $ctx->throw('todo_end() called without todo_start()') unless $set;
1572 $ctx->hub->pre_unfilter($set->[0]);
1580 sub caller { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1583 my $ctx = $self->ctx;
1585 my $trace = $ctx->trace;
1587 return wantarray ? $trace->call : $trace->package;
1592 my( $self, $code, %opts ) = @_;
1597 local $!; # eval can mess up $!
1598 local $@; # don't set $@ in the test
1599 local $SIG{__DIE__}; # don't trip an outside DIE handler.
1600 $return = eval { $code->() };
1604 die $error if $error and $opts{die_on_fail};
1606 return wantarray ? ( $return, $error ) : $return;
1611 my ($ctx, $real_exit_code, $new) = @_;
1614 my $octx = $self->ctx;
1615 $ctx = $octx->snapshot;
1619 return if $ctx->hub->no_ending;
1620 return if $ctx->hub->meta(__PACKAGE__, {})->{Ending}++;
1622 # Don't bother with an ending if this is a forked copy. Only the parent
1623 # should do the ending.
1624 return unless $self->{Original_Pid} == $$;
1626 my $hub = $ctx->hub;
1627 return if $hub->bailed_out;
1629 my $plan = $hub->plan;
1630 my $count = $hub->count;
1631 my $failed = $hub->failed;
1632 my $passed = $hub->is_passing;
1633 return unless $plan || $count || $failed;
1635 # Ran tests but never declared a plan or hit done_testing
1636 if( !$hub->plan and $hub->count ) {
1637 $self->diag("Tests were run but no plan was declared and done_testing() was not seen.");
1639 if($real_exit_code) {
1640 $self->diag(<<"FAIL");
1641 Looks like your test exited with $real_exit_code just after $count.
1643 $$new ||= $real_exit_code;
1647 # But if the tests ran, handle exit code.
1649 my $exit_code = $failed <= 254 ? $failed : 254;
1650 $$new ||= $exit_code;
1658 if ($real_exit_code && !$count) {
1659 $self->diag("Looks like your test exited with $real_exit_code before it could output anything.");
1660 $$new ||= $real_exit_code;
1664 return if $plan && "$plan" eq 'SKIP';
1667 $self->diag('No tests run!');
1672 if ($real_exit_code) {
1673 $self->diag(<<"FAIL");
1674 Looks like your test exited with $real_exit_code just after $count.
1676 $$new ||= $real_exit_code;
1680 if ($plan eq 'NO PLAN') {
1681 $ctx->plan( $count );
1685 # Figure out if we passed or failed and print helpful messages.
1686 my $num_extra = $count - $plan;
1688 if ($num_extra != 0) {
1689 my $s = $plan == 1 ? '' : 's';
1690 $self->diag(<<"FAIL");
1691 Looks like you planned $plan test$s but ran $count.
1696 my $s = $failed == 1 ? '' : 's';
1698 my $qualifier = $num_extra == 0 ? '' : ' run';
1700 $self->diag(<<"FAIL");
1701 Looks like you failed $failed test$s of $count$qualifier.
1705 if (!$passed && !$failed && $count && !$num_extra) {
1706 $ctx->diag(<<"FAIL");
1707 All assertions passed, but errors were encountered.
1713 $exit_code = $failed <= 254 ? $failed : 254;
1715 elsif ($num_extra != 0) {
1722 $$new ||= $exit_code;
1726 # Some things used this even though it was private... I am looking at you
1727 # Test::Builder::Prefix...
1728 sub _print_comment {
1729 my( $self, $fh, @msgs ) = @_;
1731 return if $self->no_diag;
1732 return unless @msgs;
1734 # Prevent printing headers when compiling (i.e. -c)
1737 # Smash args together like print does.
1738 # Convert undef to 'undef' so its readable.
1739 my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1741 # Escape the beginning, _print will take care of the rest.
1744 local( $\, $", $, ) = ( undef, ' ', '' );
1750 # This is used by Test::SharedFork to turn on IPC after the fact. Not
1751 # documenting because I do not want it used. The method name is borrowed from
1753 # Once Test2 stuff goes stable this method will be removed and Test::SharedFork
1754 # will be made smarter.
1755 sub coordinate_forks {
1763 Test2::API::test2_ipc_enable_polling();
1764 Test2::API::test2_load();
1765 my $ipc = Test2::IPC::apply_ipc($self->{Stack});
1766 $ipc->set_no_fatal(1);
1767 Test2::API::test2_no_wait(1);
1768 Test2::API::test2_ipc_enable_shm();
1771 sub no_log_results { $_[0]->{no_log_results} = 1 }
1779 Test::Builder - Backend for building test libraries
1783 package My::Test::Module;
1784 use base 'Test::Builder::Module';
1786 my $CLASS = __PACKAGE__;
1789 my($test, $name) = @_;
1790 my $tb = $CLASS->builder;
1792 $tb->ok($test, $name);
1798 L<Test::Simple> and L<Test::More> have proven to be popular testing modules,
1799 but they're not always flexible enough. Test::Builder provides a
1800 building block upon which to write your own test libraries I<which can
1809 my $Test = Test::Builder->new;
1811 Returns a Test::Builder object representing the current state of the
1814 Since you only run one test per program C<new> always returns the same
1815 Test::Builder object. No matter how many times you call C<new()>, you're
1816 getting the same object. This is called a singleton. This is done so that
1817 multiple modules share such global information as the test counter and
1818 where test output is going.
1820 If you want a completely new Test::Builder object different from the
1821 singleton, use C<create>.
1825 my $Test = Test::Builder->create;
1827 Ok, so there can be more than one Test::Builder object and this is how
1828 you get it. You might use this instead of C<new()> if you're testing
1829 a Test::Builder based module, but otherwise you probably want C<new>.
1831 B<NOTE>: the implementation is not complete. C<level>, for example, is still
1832 shared by B<all> Test::Builder objects, even ones created using this method.
1833 Also, the method name may change in the future.
1837 $builder->subtest($name, \&subtests, @args);
1839 See documentation of C<subtest> in Test::More.
1841 C<subtest> also, and optionally, accepts arguments which will be passed to the
1846 diag $builder->name;
1848 Returns the name of the current builder. Top level builders default to C<$0>
1849 (the name of the executable). Child builders are named via the C<child>
1850 method. If no name is supplied, will be named "Child of $parent->name".
1856 Reinitializes the Test::Builder singleton to its original state.
1857 Mostly useful for tests run in persistent environments where the same
1858 test might be run multiple times in the same process.
1862 =head2 Setting up tests
1864 These methods are for setting up tests and declaring how many there
1865 are. You usually only want to call one of these methods.
1871 $Test->plan('no_plan');
1872 $Test->plan( skip_all => $reason );
1873 $Test->plan( tests => $num_tests );
1875 A convenient way to set up your tests. Call this and Test::Builder
1876 will print the appropriate headers and take the appropriate actions.
1878 If you call C<plan()>, don't call any of the other methods below.
1880 =item B<expected_tests>
1882 my $max = $Test->expected_tests;
1883 $Test->expected_tests($max);
1885 Gets/sets the number of tests we expect this test to run and prints out
1886 the appropriate headers.
1893 Declares that this test will run an indeterminate number of tests.
1896 =item B<done_testing>
1898 $Test->done_testing();
1899 $Test->done_testing($num_tests);
1901 Declares that you are done testing, no more tests will be run after this point.
1903 If a plan has not yet been output, it will do so.
1905 $num_tests is the number of tests you planned to run. If a numbered
1906 plan was already declared, and if this contradicts, a failing test
1907 will be run to reflect the planning mistake. If C<no_plan> was declared,
1910 If C<done_testing()> is called twice, the second call will issue a
1913 If C<$num_tests> is omitted, the number of tests run will be used, like
1916 C<done_testing()> is, in effect, used when you'd want to use C<no_plan>, but
1917 safer. You'd use it like so:
1919 $Test->ok($a == $b);
1920 $Test->done_testing();
1922 Or to plan a variable number of tests:
1924 for my $test (@tests) {
1927 $Test->done_testing(scalar @tests);
1932 $plan = $Test->has_plan
1934 Find out whether a plan has been defined. C<$plan> is either C<undef> (no plan
1935 has been set), C<no_plan> (indeterminate # of tests) or an integer (the number
1941 $Test->skip_all($reason);
1943 Skips all the tests, using the given C<$reason>. Exits immediately with 0.
1945 =item B<exported_to>
1947 my $pack = $Test->exported_to;
1948 $Test->exported_to($pack);
1950 Tells Test::Builder what package you exported your functions to.
1952 This method isn't terribly useful since modules which share the same
1953 Test::Builder object might get exported to different packages and only
1954 the last one will be honored.
1958 =head2 Running tests
1960 These actually run the tests, analogous to the functions in Test::More.
1962 They all return true if the test passed, false if the test failed.
1964 C<$name> is always optional.
1970 $Test->ok($test, $name);
1972 Your basic test. Pass if C<$test> is true, fail if $test is false. Just
1973 like Test::Simple's C<ok()>.
1977 $Test->is_eq($got, $expected, $name);
1979 Like Test::More's C<is()>. Checks if C<$got eq $expected>. This is the
1982 C<undef> only ever matches another C<undef>.
1986 $Test->is_num($got, $expected, $name);
1988 Like Test::More's C<is()>. Checks if C<$got == $expected>. This is the
1991 C<undef> only ever matches another C<undef>.
1995 $Test->isnt_eq($got, $dont_expect, $name);
1997 Like L<Test::More>'s C<isnt()>. Checks if C<$got ne $dont_expect>. This is
2002 $Test->isnt_num($got, $dont_expect, $name);
2004 Like L<Test::More>'s C<isnt()>. Checks if C<$got ne $dont_expect>. This is
2005 the numeric version.
2009 $Test->like($thing, qr/$regex/, $name);
2010 $Test->like($thing, '/$regex/', $name);
2012 Like L<Test::More>'s C<like()>. Checks if $thing matches the given C<$regex>.
2016 $Test->unlike($thing, qr/$regex/, $name);
2017 $Test->unlike($thing, '/$regex/', $name);
2019 Like L<Test::More>'s C<unlike()>. Checks if $thing B<does not match> the
2024 $Test->cmp_ok($thing, $type, $that, $name);
2026 Works just like L<Test::More>'s C<cmp_ok()>.
2028 $Test->cmp_ok($big_num, '!=', $other_big_num);
2032 =head2 Other Testing Methods
2034 These are methods which are used in the course of writing a test but are not themselves tests.
2040 $Test->BAIL_OUT($reason);
2042 Indicates to the L<Test::Harness> that things are going so badly all
2043 testing should terminate. This includes running any additional test
2046 It will exit with 255.
2049 BAIL_OUT() used to be BAILOUT()
2056 Skips the current test, reporting C<$why>.
2061 $Test->todo_skip($why);
2063 Like C<skip()>, only it will declare the test as failing and TODO. Similar
2066 print "not ok $tnum # TODO $why\n";
2068 =begin _unimplemented
2073 $Test->skip_rest($reason);
2075 Like C<skip()>, only it skips all the rest of the tests you plan to run
2076 and terminates the test.
2078 If you're running under C<no_plan>, it skips once and terminates the
2086 =head2 Test building utility methods
2088 These methods are useful when writing your own test methods.
2092 =item B<maybe_regex>
2094 $Test->maybe_regex(qr/$regex/);
2095 $Test->maybe_regex('/$regex/');
2097 This method used to be useful back when Test::Builder worked on Perls
2098 before 5.6 which didn't have qr//. Now its pretty useless.
2100 Convenience method for building testing functions that take regular
2101 expressions as arguments.
2103 Takes a quoted regular expression produced by C<qr//>, or a string
2104 representing a regular expression.
2106 Returns a Perl value which may be used instead of the corresponding
2107 regular expression, or C<undef> if its argument is not recognized.
2109 For example, a version of C<like()>, sans the useful diagnostic messages,
2110 could be written as:
2113 my ($self, $thing, $regex, $name) = @_;
2114 my $usable_regex = $self->maybe_regex($regex);
2115 die "expecting regex, found '$regex'\n"
2116 unless $usable_regex;
2117 $self->ok($thing =~ m/$usable_regex/, $name);
2123 my $is_fh = $Test->is_fh($thing);
2125 Determines if the given C<$thing> can be used as a filehandle.
2140 $Test->level($how_high);
2142 How far up the call stack should C<$Test> look when reporting where the
2147 Setting C<$Test::Builder::Level> overrides. This is typically useful
2153 local $Test::Builder::Level = $Test::Builder::Level + 1;
2157 To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
2159 =item B<use_numbers>
2161 $Test->use_numbers($on_or_off);
2163 Whether or not the test should output numbers. That is, this if true:
2175 Most useful when you can't depend on the test output order, such as
2176 when threads or forking is involved.
2182 $Test->no_diag($no_diag);
2184 If set true no diagnostics will be printed. This includes calls to
2189 $Test->no_ending($no_ending);
2191 Normally, Test::Builder does some extra diagnostics when the test
2192 ends. It also changes the exit code as described below.
2194 If this is true, none of that will be done.
2198 $Test->no_header($no_header);
2200 If set to true, no "1..N" header will be printed.
2206 Controlling where the test output goes.
2208 It's ok for your test to change where STDOUT and STDERR point to,
2209 Test::Builder's default output settings will not be affected.
2217 Prints out the given C<@msgs>. Like C<print>, arguments are simply
2220 Normally, it uses the C<failure_output()> handle, but if this is for a
2221 TODO test, the C<todo_output()> handle is used.
2223 Output will be indented and marked with a # so as not to interfere
2224 with test output. A newline will be put on the end if there isn't one
2227 We encourage using this rather than calling print directly.
2229 Returns false. Why? Because C<diag()> is often used in conjunction with
2230 a failing test (C<ok() || diag()>) it "passes through" the failure.
2232 return ok(...) || diag(...);
2235 Mark Fowler <mark@twoshortplanks.com>
2241 Like C<diag()>, but it prints to the C<output()> handle so it will not
2242 normally be seen by the user except in verbose mode.
2246 my @dump = $Test->explain(@msgs);
2248 Will dump the contents of any references in a human readable format.
2249 Handy for things like...
2251 is_deeply($have, $want) || diag explain $have;
2255 is_deeply($have, $want) || note explain $have;
2259 =item B<failure_output>
2261 =item B<todo_output>
2263 my $filehandle = $Test->output;
2264 $Test->output($filehandle);
2265 $Test->output($filename);
2266 $Test->output(\$scalar);
2268 These methods control where Test::Builder will print its output.
2269 They take either an open C<$filehandle>, a C<$filename> to open and write to
2270 or a C<$scalar> reference to append to. It will always return a C<$filehandle>.
2272 B<output> is where normal "ok/not ok" test output goes.
2276 B<failure_output> is where diagnostic output on test failures and
2277 C<diag()> goes. It is normally not read by Test::Harness and instead is
2278 displayed to the user.
2282 C<todo_output> is used instead of C<failure_output()> for the
2283 diagnostics of a failing TODO test. These will not be seen by the
2292 Resets all the output filehandles back to their defaults.
2296 $tb->carp(@message);
2298 Warns with C<@message> but the message will appear to come from the
2299 point where the original test function was called (C<< $tb->caller >>).
2303 $tb->croak(@message);
2305 Dies with C<@message> but the message will appear to come from the
2306 point where the original test function was called (C<< $tb->caller >>).
2312 =head2 Test Status and Info
2316 =item B<no_log_results>
2318 This will turn off result long-term storage. Calling this method will make
2319 C<details> and C<summary> useless. You may want to use this if you are running
2320 enough tests to fill up all available memory.
2322 Test::Builder->new->no_log_results();
2324 There is no way to turn it back on.
2326 =item B<current_test>
2328 my $curr_test = $Test->current_test;
2329 $Test->current_test($num);
2331 Gets/sets the current test number we're on. You usually shouldn't
2334 If set forward, the details of the missing tests are filled in as 'unknown'.
2335 if set backward, the details of the intervening tests are deleted. You
2336 can erase history if you really want to.
2341 my $ok = $builder->is_passing;
2343 Indicates if the test suite is currently passing.
2345 More formally, it will be false if anything has happened which makes
2346 it impossible for the test suite to pass. True otherwise.
2348 For example, if no tests have run C<is_passing()> will be true because
2349 even though a suite with no tests is a failure you can add a passing
2350 test to it and start passing.
2352 Don't think about it too much.
2357 my @tests = $Test->summary;
2359 A simple summary of the tests so far. True for pass, false for fail.
2360 This is a logical pass/fail, so todos are passes.
2362 Of course, test #1 is $tests[0], etc...
2367 my @tests = $Test->details;
2369 Like C<summary()>, but with a lot more detail.
2371 $tests[$test_num - 1] =
2372 { 'ok' => is the test considered a pass?
2373 actual_ok => did it literally say 'ok'?
2374 name => name of the test (if any)
2375 type => type of test (if any, see below).
2376 reason => reason for the above (if any)
2379 'ok' is true if Test::Harness will consider the test to be a pass.
2381 'actual_ok' is a reflection of whether or not the test literally
2382 printed 'ok' or 'not ok'. This is for examining the result of 'todo'
2385 'name' is the name of the test.
2387 'type' indicates if it was a special test. Normal tests have a type
2388 of ''. Type can be one of the following:
2392 todo_skip see todo_skip()
2395 Sometimes the Test::Builder test counter is incremented without it
2396 printing any test output, for example, when C<current_test()> is changed.
2397 In these cases, Test::Builder doesn't know the result of the test, so
2398 its type is 'unknown'. These details for these tests are filled in.
2399 They are considered ok, but the name and actual_ok is left C<undef>.
2401 For example "not ok 23 - hole count # TODO insufficient donuts" would
2402 result in this structure:
2404 $tests[22] = # 23 - 1, since arrays start from 0.
2405 { ok => 1, # logically, the test passed since its todo
2406 actual_ok => 0, # in absolute terms, it failed
2407 name => 'hole count',
2409 reason => 'insufficient donuts'
2415 my $todo_reason = $Test->todo;
2416 my $todo_reason = $Test->todo($pack);
2418 If the current tests are considered "TODO" it will return the reason,
2419 if any. This reason can come from a C<$TODO> variable or the last call
2422 Since a TODO test does not need a reason, this function can return an
2423 empty string even when inside a TODO block. Use C<< $Test->in_todo >>
2424 to determine if you are currently inside a TODO block.
2426 C<todo()> is about finding the right package to look for C<$TODO> in. It's
2427 pretty good at guessing the right package to look at. It first looks for
2428 the caller based on C<$Level + 1>, since C<todo()> is usually called inside
2429 a test function. As a last resort it will use C<exported_to()>.
2431 Sometimes there is some confusion about where C<todo()> should be looking
2432 for the C<$TODO> variable. If you want to be sure, tell it explicitly
2437 my $todo_reason = $Test->find_TODO();
2438 my $todo_reason = $Test->find_TODO($pack);
2440 Like C<todo()> but only returns the value of C<$TODO> ignoring
2443 Can also be used to set C<$TODO> to a new value while returning the
2446 my $old_reason = $Test->find_TODO($pack, 1, $new_reason);
2450 my $in_todo = $Test->in_todo;
2452 Returns true if the test is currently inside a TODO block.
2456 $Test->todo_start();
2457 $Test->todo_start($message);
2459 This method allows you declare all subsequent tests as TODO tests, up until
2460 the C<todo_end> method has been called.
2462 The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
2463 whether or not we're in a TODO test. However, often we find that this is not
2464 possible to determine (such as when we want to use C<$TODO> but
2465 the tests are being executed in other packages which can't be inferred
2468 Note that you can use this to nest "todo" tests
2470 $Test->todo_start('working on this');
2472 $Test->todo_start('working on that');
2477 This is generally not recommended, but large testing systems often have weird
2480 We've tried to make this also work with the TODO: syntax, but it's not
2481 guaranteed and its use is also discouraged:
2484 local $TODO = 'We have work to do!';
2485 $Test->todo_start('working on this');
2487 $Test->todo_start('working on that');
2493 Pick one style or another of "TODO" to be on the safe side.
2500 Stops running tests as "TODO" tests. This method is fatal if called without a
2501 preceding C<todo_start> method call.
2505 my $package = $Test->caller;
2506 my($pack, $file, $line) = $Test->caller;
2507 my($pack, $file, $line) = $Test->caller($height);
2509 Like the normal C<caller()>, except it reports according to your C<level()>.
2511 C<$height> will be added to the C<level()>.
2513 If C<caller()> winds up off the top of the stack it report the highest context.
2519 If all your tests passed, Test::Builder will exit with zero (which is
2520 normal). If anything failed it will exit with how many failed. If
2521 you run less (or more) tests than you planned, the missing (or extras)
2522 will be considered failures. If no tests were ever run Test::Builder
2523 will throw a warning and exit with 255. If the test died, even after
2524 having successfully completed all its tests, it will still be
2525 considered a failure and will exit with 255.
2527 So the exit codes are...
2529 0 all tests successful
2530 255 test died or all passed but wrong # of tests run
2531 any other number how many failed (including missing or extras)
2533 If you fail more than 254 tests, it will be reported as 254.
2537 In perl 5.8.1 and later, Test::Builder is thread-safe. The test number is
2538 shared by all threads. This means if one thread sets the test number using
2539 C<current_test()> they will all be effected.
2541 While versions earlier than 5.8.1 had threads they contain too many
2544 Test::Builder is only thread-aware if threads.pm is loaded I<before>
2547 You can directly disable thread support with one of the following:
2557 Test2::API::test2_ipc_disable()
2561 An informative hash, accessible via C<details()>, is stored for each
2562 test you perform. So memory usage will scale linearly with each test
2563 run. Although this is not a problem for most test suites, it can
2564 become an issue if you do large (hundred thousands to million)
2565 combinatorics tests in the same run.
2567 In such cases, you are advised to either split the test file into smaller
2568 ones, or use a reverse approach, doing "normal" (code) compares and
2569 triggering C<fail()> should anything go unexpected.
2571 Future versions of Test::Builder will have a way to turn history off.
2576 CPAN can provide the best examples. L<Test::Simple>, L<Test::More>,
2577 L<Test::Exception> and L<Test::Differences> all use Test::Builder.
2581 L<Test::Simple>, L<Test::More>, L<Test::Harness>
2585 Original code by chromatic, maintained by Michael G Schwern
2586 E<lt>schwern@pobox.comE<gt>
2592 =item Chad Granum E<lt>exodist@cpan.orgE<gt>
2598 Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2599 Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2601 This program is free software; you can redistribute it and/or
2602 modify it under the same terms as Perl itself.
2604 See F<http://www.perl.com/perl/misc/Artistic.html>