7 our $VERSION = '1.302175';
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);
33 use Test2::Event::Subtest;
34 use Test2::Hub::Subtest;
36 use Test::Builder::Formatter;
37 use Test::Builder::TodoDiag;
40 our $Test = $ENV{TB_NO_EARLY_INIT} ? undef : Test::Builder->new;
45 my $hub = $self->{Stack}->top;
47 # Take a reference to the hash key, we do this to avoid closing over $self
48 # which is the singleton. We use a reference because the value could change
50 my $epkgr = \$self->{Exported_To};
52 #$hub->add_context_aquire(sub {$_[0]->{level} += $Level - 1});
54 $hub->pre_filter(sub {
55 my ($active_hub, $e) = @_;
58 my $cpkg = $e->{trace} ? $e->{trace}->{frame}->[0] : undef;
63 $todo = ${"$cpkg\::TODO"} if $cpkg;
64 $todo = ${"$epkg\::TODO"} if $epkg && !$todo;
66 return $e unless defined($todo);
67 return $e unless length($todo);
69 # Turn a diag into a todo diag
70 return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
72 $e->set_todo($todo) if $e->can('set_todo');
73 $e->add_amnesty({tag => 'TODO', details => $todo});
76 if ($e->isa('Test2::Event::Ok')) {
77 $e->set_effective_pass(1);
79 if (my $result = $e->get_meta(__PACKAGE__)) {
80 $result->{reason} ||= $todo;
81 $result->{type} ||= 'todo';
94 Test2::API::test2_load() unless Test2::API::test2_in_preload();
101 $Test = $class->create(singleton => 1);
103 Test2::API::test2_add_callback_post_load(
105 $Test->{Original_Pid} = $$ if !$Test->{Original_Pid} || $Test->{Original_Pid} == 0;
106 $Test->reset(singleton => 1);
107 $Test->_add_ts_hooks;
111 # Non-TB tools normally expect 0 added to the level. $Level is normally 1. So
112 # we only want the level to change if $Level != 1.
113 # TB->ctx compensates for this later.
114 Test2::API::test2_add_callback_context_aquire(sub { $_[0]->{level} += $Level - 1 });
116 Test2::API::test2_add_callback_exit(sub { $Test->_ending(@_) });
118 Test2::API::test2_ipc()->set_no_fatal(1) if Test2::API::test2_has_ipc();
127 my $self = bless {}, $class;
128 if ($params{singleton}) {
129 $self->{Stack} = Test2::API::test2_stack();
132 $self->{Stack} = Test2::API::Stack->new;
133 $self->{Stack}->new_hub(
134 formatter => Test::Builder::Formatter->new,
135 ipc => Test2::API::test2_ipc(),
138 $self->reset(%params);
139 $self->_add_ts_hooks;
148 # 1 for our frame, another for the -1 off of $Level in our hook at the top.
151 stack => $self->{Stack},
160 my $ctx = $self->ctx;
161 my $chub = $self->{Hub} || $ctx->hub;
164 my $meta = $chub->meta(__PACKAGE__, {});
165 my $parent = $meta->{parent};
167 return undef unless $parent;
171 Stack => $self->{Stack},
177 my( $self, $name ) = @_;
179 $name ||= "Child of " . $self->name;
180 my $ctx = $self->ctx;
182 my $parent = $ctx->hub;
183 my $pmeta = $parent->meta(__PACKAGE__, {});
184 $self->croak("You already have a child named ($pmeta->{child}) running")
187 $pmeta->{child} = $name;
189 # Clear $TODO for the child.
190 my $orig_TODO = $self->find_TODO(undef, 1, undef);
194 my $hub = $ctx->stack->new_hub(
195 class => 'Test2::Hub::Subtest',
198 $hub->pre_filter(sub {
199 my ($active_hub, $e) = @_;
201 # Turn a diag into a todo diag
202 return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
205 }, inherit => 1) if $orig_TODO;
207 $hub->listen(sub { push @$subevents => $_[1] });
209 $hub->set_nested( $parent->nested + 1 );
211 my $meta = $hub->meta(__PACKAGE__, {});
212 $meta->{Name} = $name;
213 $meta->{TODO} = $orig_TODO;
214 $meta->{TODO_PKG} = $ctx->trace->package;
215 $meta->{parent} = $parent;
216 $meta->{Test_Results} = [];
217 $meta->{subevents} = $subevents;
218 $meta->{subtest_id} = $hub->id;
219 $meta->{subtest_uuid} = $hub->uuid;
220 $meta->{subtest_buffered} = $parent->format ? 0 : 1;
222 $self->_add_ts_hooks;
225 return bless { Original_Pid => $$, Stack => $self->{Stack}, Hub => $hub, no_log_results => $self->{no_log_results} }, blessed($self);
233 my $st_ctx = $self->ctx;
234 my $chub = $self->{Hub} || return $st_ctx->release;
236 my $meta = $chub->meta(__PACKAGE__, {});
237 if ($meta->{child}) {
238 $self->croak("Can't call finalize() with child ($meta->{child}) active");
241 local $? = 0; # don't fail if $subtests happened to set $? nonzero
243 $self->{Stack}->pop($chub);
245 $self->find_TODO($meta->{TODO_PKG}, 1, $meta->{TODO});
247 my $parent = $self->parent;
248 my $ctx = $parent->ctx;
249 my $trace = $ctx->trace;
250 delete $ctx->hub->meta(__PACKAGE__, {})->{child};
252 $chub->finalize($trace->snapshot(hid => $chub->hid, nested => $chub->nested), 1)
258 my $plan = $chub->plan || 0;
259 my $count = $chub->count;
260 my $failed = $chub->failed;
261 my $passed = $chub->is_passing;
263 my $num_extra = $plan =~ m/\D/ ? 0 : $count - $plan;
264 if ($count && $num_extra != 0) {
265 my $s = $plan == 1 ? '' : 's';
266 $st_ctx->diag(<<"FAIL");
267 Looks like you planned $plan test$s but ran $count.
272 my $s = $failed == 1 ? '' : 's';
274 my $qualifier = $num_extra == 0 ? '' : ' run';
276 $st_ctx->diag(<<"FAIL");
277 Looks like you failed $failed test$s of $count$qualifier.
281 if (!$passed && !$failed && $count && !$num_extra) {
282 $st_ctx->diag(<<"FAIL");
283 All assertions inside the subtest passed, but errors were encountered.
289 unless ($chub->bailed_out) {
290 my $plan = $chub->plan;
291 if ( $plan && $plan eq 'SKIP' ) {
292 $parent->skip($chub->skip_reason, $meta->{Name});
294 elsif ( !$chub->count ) {
295 $parent->ok( 0, sprintf q[No tests run for subtest "%s"], $meta->{Name} );
298 $parent->{subevents} = $meta->{subevents};
299 $parent->{subtest_id} = $meta->{subtest_id};
300 $parent->{subtest_uuid} = $meta->{subtest_uuid};
301 $parent->{subtest_buffered} = $meta->{subtest_buffered};
302 $parent->ok( $chub->is_passing, $meta->{Name} );
307 return $chub->is_passing;
312 my ($name, $code, @args) = @_;
313 my $ctx = $self->ctx;
314 $ctx->throw("subtest()'s second argument must be a code ref")
315 unless $code && reftype($code) eq 'CODE';
317 $name ||= "Child of " . $self->name;
320 $_->($name,$code,@args)
321 for Test2::API::test2_list_pre_subtest_callbacks();
323 $ctx->note("Subtest: $name");
325 my $child = $self->child($name);
329 my ($ok, $err, $finished, $child_error);
330 T2_SUBTEST_WRAPPER: {
331 my $ctx = $self->ctx;
332 $st_ctx = $ctx->snapshot;
334 $ok = eval { local $Level = 1; $code->(@args); 1 };
335 ($err, $child_error) = ($@, $?);
337 # They might have done 'BEGIN { skip_all => "whatever" }'
338 if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && blessed($err) eq 'Test::Builder::Exception')) {
347 if ($start_pid != $$ && !$INC{'Test2/IPC.pm'}) {
348 warn $ok ? "Forked inside subtest, but subtest never finished!\n" : $err;
352 my $trace = $ctx->trace;
355 if(my $bailed = $st_ctx->hub->bailed_out) {
356 my $chub = $child->{Hub};
357 $self->{Stack}->pop($chub);
358 $ctx->bail($bailed->reason);
360 my $code = $st_ctx->hub->exit_code;
362 $err = "Subtest ended with exit code $code" if $code;
365 my $st_hub = $st_ctx->hub;
366 my $plan = $st_hub->plan;
367 my $count = $st_hub->count;
369 if (!$count && (!defined($plan) || "$plan" ne 'SKIP')) {
370 $st_ctx->plan(0) unless defined $plan;
371 $st_ctx->diag('No tests run!');
374 $child->finalize($st_ctx->trace);
380 $? = $child_error if defined $child_error;
382 return $st_hub->is_passing;
387 my $ctx = $self->ctx;
388 release $ctx, $ctx->hub->meta(__PACKAGE__, {})->{Name};
391 sub reset { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
392 my ($self, %params) = @_;
394 Test2::API::test2_unset_is_end();
396 # We leave this a global because it has to be localized and localizing
397 # hash keys is just asking for pain. Also, it was documented.
400 $self->{no_log_results} = $ENV{TEST_NO_LOG_RESULTS} ? 1 : 0
401 unless $params{singleton};
403 $self->{Original_Pid} = Test2::API::test2_in_preload() ? -1 : $$;
405 my $ctx = $self->ctx;
408 unless ($params{singleton}) {
415 my $meta = $ctx->hub->meta(__PACKAGE__, {});
419 Done_Testing => undef,
422 parent => $meta->{parent},
425 $self->{Exported_To} = undef unless $params{singleton};
427 $self->{Orig_Handles} ||= do {
428 my $format = $ctx->hub->format;
430 if ($format && $format->isa('Test2::Formatter::TAP')) {
431 $out = $format->handles;
436 $self->use_numbers(1);
437 $self->no_header(0) unless $params{singleton};
438 $self->no_ending(0) unless $params{singleton};
439 $self->reset_outputs;
448 no_plan => \&no_plan,
449 skip_all => \&skip_all,
450 tests => \&_plan_tests,
454 my( $self, $cmd, $arg ) = @_;
458 my $ctx = $self->ctx;
461 $ctx->throw("You tried to plan twice") if $hub->plan;
463 local $Level = $Level + 1;
465 if( my $method = $plan_cmds{$cmd} ) {
466 local $Level = $Level + 1;
467 $self->$method($arg);
470 my @args = grep { defined } ( $cmd, $arg );
471 $ctx->throw("plan() doesn't understand @args");
479 my($self, $arg) = @_;
481 my $ctx = $self->ctx;
484 local $Level = $Level + 1;
485 $self->expected_tests($arg);
487 elsif( !defined $arg ) {
488 $ctx->throw("Got an undefined number of tests");
491 $ctx->throw("You said to run 0 tests");
502 my $ctx = $self->ctx;
505 $self->croak("Number of tests must be a positive integer. You gave it '$max'")
506 unless $max =~ /^\+?\d+$/;
515 my $plan = $hub->plan;
516 return 0 unless $plan;
517 return 0 if $plan =~ m/\D/;
523 my($self, $arg) = @_;
525 my $ctx = $self->ctx;
527 if (defined $ctx->hub->plan) {
528 warn "Plan already set, no_plan() is a no-op, this will change to a hard failure in the future.";
533 $ctx->alert("no_plan takes no arguments") if $arg;
535 $ctx->hub->plan('NO PLAN');
542 my($self, $num_tests) = @_;
544 my $ctx = $self->ctx;
546 my $meta = $ctx->hub->meta(__PACKAGE__, {});
548 if ($meta->{Done_Testing}) {
549 my ($file, $line) = @{$meta->{Done_Testing}}[1,2];
550 local $ctx->hub->{ended}; # OMG This is awful.
551 $self->ok(0, "done_testing() was already called at $file line $line");
555 $meta->{Done_Testing} = [$ctx->trace->call];
557 my $plan = $ctx->hub->plan;
558 my $count = $ctx->hub->count;
560 # If done_testing() specified the number of tests, shut off no_plan
561 if( defined $num_tests ) {
562 $ctx->plan($num_tests) if !$plan || $plan eq 'NO PLAN';
564 elsif ($count && defined $num_tests && $count != $num_tests) {
565 $self->ok(0, "planned to run @{[ $self->expected_tests ]} but done_testing() expects $num_tests");
568 $num_tests = $self->current_test;
571 if( $self->expected_tests && $num_tests != $self->expected_tests ) {
572 $self->ok(0, "planned to run @{[ $self->expected_tests ]} ".
573 "but done_testing() expects $num_tests");
576 $ctx->plan($num_tests) if $ctx->hub->plan && $ctx->hub->plan eq 'NO PLAN';
578 $ctx->hub->finalize($ctx->trace, 1);
587 my $ctx = $self->ctx;
588 my $plan = $ctx->hub->plan;
591 return( $plan ) if $plan && $plan !~ m/\D/;
592 return('no_plan') if $plan && $plan eq 'NO PLAN';
598 my( $self, $reason ) = @_;
600 my $ctx = $self->ctx;
602 $ctx->hub->meta(__PACKAGE__, {})->{Skip_All} = $reason || 1;
604 # Work around old perl bug
608 while (my @call = caller($level++)) {
609 last unless @call && $call[0];
610 next unless $call[3] =~ m/::BEGIN$/;
615 die 'Label not found for "last T2_SUBTEST_WRAPPER"' if $begin && $ctx->hub->meta(__PACKAGE__, {})->{parent};
618 $ctx->plan(0, SKIP => $reason);
623 my( $self, $pack ) = @_;
625 if( defined $pack ) {
626 $self->{Exported_To} = $pack;
628 return $self->{Exported_To};
633 my( $self, $test, $name ) = @_;
635 my $ctx = $self->ctx;
637 # $test might contain an object which we don't want to accidentally
638 # store, so we turn it into a boolean.
639 $test = $test ? 1 : 0;
641 # In case $name is a string overloaded object, force it to stringify.
642 no warnings qw/uninitialized numeric/;
643 $name = "$name" if defined $name;
645 # Profiling showed that the regex here was a huge time waster, doing the
646 # numeric addition first cuts our profile time from ~300ms to ~50ms
647 $self->diag(<<" ERR") if 0 + $name && $name =~ /^[\d\s]+$/;
648 You named your test '$name'. You shouldn't use numbers for your test names.
651 use warnings qw/uninitialized numeric/;
653 my $trace = $ctx->{trace};
654 my $hub = $ctx->{hub};
661 (name => defined($name) ? $name : ''),
664 $hub->{_meta}->{+__PACKAGE__}->{Test_Results}[ $hub->{count} ] = $result unless $self->{no_log_results};
666 my $orig_name = $name;
669 my $subevents = delete $self->{subevents};
670 my $subtest_id = delete $self->{subtest_id};
671 my $subtest_uuid = delete $self->{subtest_uuid};
672 my $subtest_buffered = delete $self->{subtest_buffered};
673 my $epkg = 'Test2::Event::Ok';
675 $epkg = 'Test2::Event::Subtest';
676 push @attrs => (subevents => $subevents, subtest_id => $subtest_id, subtest_uuid => $subtest_uuid, buffered => $subtest_buffered);
680 trace => bless( {%$trace}, 'Test2::EventFacet::Trace'),
683 _meta => {'Test::Builder' => $result},
684 effective_pass => $test,
689 $self->_ok_debug($trace, $orig_name) unless($test);
697 my ($trace, $orig_name) = @_;
699 my $is_todo = $self->in_todo;
701 my $msg = $is_todo ? "Failed (TODO)" : "Failed";
703 my (undef, $file, $line) = $trace->call;
704 if (defined $orig_name) {
705 $self->diag(qq[ $msg test '$orig_name'\n at $file line $line.\n]);
708 $self->diag(qq[ $msg test at $file line $line.\n]);
714 local $Level = $Level + 1;
715 return $self->in_todo ? $self->todo_output : $self->failure_output;
719 my ($self, $type, $thing) = @_;
721 return unless ref $$thing;
722 return unless blessed($$thing) || scalar $self->_try(sub{ $$thing->isa('UNIVERSAL') });
727 my $string_meth = overload::Method( $$thing, $type ) || return;
728 $$thing = $$thing->$string_meth();
731 sub _unoverload_str {
734 $self->_unoverload( q[""], $_ ) for @_;
737 sub _unoverload_num {
740 $self->_unoverload( '0+', $_ ) for @_;
743 next unless $self->_is_dualvar($$val);
748 # This is a hack to detect a dualvar such as $!
750 my( $self, $val ) = @_;
752 # Objects are not dualvars.
753 return 0 if ref $val;
755 no warnings 'numeric';
756 my $numval = $val + 0;
757 return ($numval != 0 and $numval ne $val ? 1 : 0);
762 my( $self, $got, $expect, $name ) = @_;
764 my $ctx = $self->ctx;
766 local $Level = $Level + 1;
768 if( !defined $got || !defined $expect ) {
769 # undef only matches undef and nothing else
770 my $test = !defined $got && !defined $expect;
772 $self->ok( $test, $name );
773 $self->_is_diag( $got, 'eq', $expect ) unless $test;
778 release $ctx, $self->cmp_ok( $got, 'eq', $expect, $name );
783 my( $self, $got, $expect, $name ) = @_;
784 my $ctx = $self->ctx;
785 local $Level = $Level + 1;
787 if( !defined $got || !defined $expect ) {
788 # undef only matches undef and nothing else
789 my $test = !defined $got && !defined $expect;
791 $self->ok( $test, $name );
792 $self->_is_diag( $got, '==', $expect ) unless $test;
797 release $ctx, $self->cmp_ok( $got, '==', $expect, $name );
802 my( $self, $type, $val ) = @_;
804 if( defined $$val ) {
805 if( $type eq 'eq' or $type eq 'ne' ) {
806 # quote and force string context
810 # force numeric context
811 $self->_unoverload_num($val);
823 my( $self, $got, $type, $expect ) = @_;
825 $self->_diag_fmt( $type, $_ ) for \$got, \$expect;
827 local $Level = $Level + 1;
828 return $self->diag(<<"DIAGNOSTIC");
836 my( $self, $got, $type ) = @_;
838 $self->_diag_fmt( $type, \$got );
840 local $Level = $Level + 1;
841 return $self->diag(<<"DIAGNOSTIC");
843 expected: anything else
849 my( $self, $got, $dont_expect, $name ) = @_;
850 my $ctx = $self->ctx;
851 local $Level = $Level + 1;
853 if( !defined $got || !defined $dont_expect ) {
854 # undef only matches undef and nothing else
855 my $test = defined $got || defined $dont_expect;
857 $self->ok( $test, $name );
858 $self->_isnt_diag( $got, 'ne' ) unless $test;
863 release $ctx, $self->cmp_ok( $got, 'ne', $dont_expect, $name );
867 my( $self, $got, $dont_expect, $name ) = @_;
868 my $ctx = $self->ctx;
869 local $Level = $Level + 1;
871 if( !defined $got || !defined $dont_expect ) {
872 # undef only matches undef and nothing else
873 my $test = defined $got || defined $dont_expect;
875 $self->ok( $test, $name );
876 $self->_isnt_diag( $got, '!=' ) unless $test;
881 release $ctx, $self->cmp_ok( $got, '!=', $dont_expect, $name );
886 my( $self, $thing, $regex, $name ) = @_;
887 my $ctx = $self->ctx;
889 local $Level = $Level + 1;
891 release $ctx, $self->_regex_ok( $thing, $regex, '=~', $name );
895 my( $self, $thing, $regex, $name ) = @_;
896 my $ctx = $self->ctx;
898 local $Level = $Level + 1;
900 release $ctx, $self->_regex_ok( $thing, $regex, '!~', $name );
904 my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" );
906 # Bad, these are not comparison operators. Should we include more?
907 my %cmp_ok_bl = map { ( $_, 1 ) } ( "=", "+=", ".=", "x=", "^=", "|=", "||=", "&&=", "...");
910 my( $self, $got, $type, $expect, $name ) = @_;
911 my $ctx = $self->ctx;
913 if ($cmp_ok_bl{$type}) {
914 $ctx->throw("$type is not a valid comparison operator in cmp_ok()");
920 ## no critic (BuiltinFunctions::ProhibitStringyEval)
922 local( $@, $!, $SIG{__DIE__} ); # isolate eval
924 my($pack, $file, $line) = $ctx->trace->call();
926 # This is so that warnings come out at the caller's level
928 #line $line "(eval in cmp_ok) $file"
929 \$test = (\$got $type \$expect);
934 local $Level = $Level + 1;
935 my $ok = $self->ok( $test, $name );
937 # Treat overloaded objects as numbers if we're asked to do a
938 # numeric comparison.
940 = $numeric_cmps{$type}
944 $self->diag(<<"END") unless $succ;
945 An error occurred while using $type:
946 ------------------------------------
948 ------------------------------------
952 $self->$unoverload( \$got, \$expect );
954 if( $type =~ /^(eq|==)$/ ) {
955 $self->_is_diag( $got, $type, $expect );
957 elsif( $type =~ /^(ne|!=)$/ ) {
959 my $eq = ($got eq $expect || $got == $expect)
961 (defined($got) xor defined($expect))
962 || (length($got) != length($expect))
967 $self->_cmp_diag( $got, $type, $expect );
970 $self->_isnt_diag( $got, $type );
974 $self->_cmp_diag( $got, $type, $expect );
977 return release $ctx, $ok;
981 my( $self, $got, $type, $expect ) = @_;
983 $got = defined $got ? "'$got'" : 'undef';
984 $expect = defined $expect ? "'$expect'" : 'undef';
986 local $Level = $Level + 1;
987 return $self->diag(<<"DIAGNOSTIC");
994 sub _caller_context {
997 my( $pack, $file, $line ) = $self->caller(1);
1000 $code .= "#line $line $file\n" if defined $file and defined $line;
1007 my( $self, $reason ) = @_;
1009 my $ctx = $self->ctx;
1011 $self->{Bailed_Out} = 1;
1013 $ctx->bail($reason);
1019 *BAILOUT = \&BAIL_OUT;
1023 my( $self, $why, $name ) = @_;
1025 $name = '' unless defined $name;
1026 $self->_unoverload_str( \$why );
1028 my $ctx = $self->ctx;
1030 $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1036 } unless $self->{no_log_results};
1038 $name =~ s|#|\\#|g; # # in a name can confuse Test::Harness.
1039 $name =~ s{\n}{\n# }sg;
1040 $why =~ s{\n}{\n# }sg;
1042 my $tctx = $ctx->snapshot;
1043 $tctx->skip('', $why);
1045 return release $ctx, 1;
1050 my( $self, $why ) = @_;
1053 my $ctx = $self->ctx;
1055 $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1059 type => 'todo_skip',
1061 } unless $self->{no_log_results};
1063 $why =~ s{\n}{\n# }sg;
1064 my $tctx = $ctx->snapshot;
1065 $tctx->send_event( 'Skip', todo => $why, todo_diag => 1, reason => $why, pass => 0);
1067 return release $ctx, 1;
1072 my( $self, $regex ) = @_;
1073 my $usable_regex = undef;
1075 return $usable_regex unless defined $regex;
1080 if( _is_qr($regex) ) {
1081 $usable_regex = $regex;
1083 # Check for '/foo/' or 'm,foo,'
1084 elsif(( $re, $opts ) = $regex =~ m{^ /(.*)/ (\w*) $ }sx or
1085 ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
1088 $usable_regex = length $opts ? "(?$opts)$re" : $re;
1091 return $usable_regex;
1097 # is_regexp() checks for regexes in a robust manner, say if they're
1099 return re::is_regexp($regex) if defined &re::is_regexp;
1100 return ref $regex eq 'Regexp';
1104 my( $self, $thing, $regex, $cmp, $name ) = @_;
1107 my $usable_regex = $self->maybe_regex($regex);
1108 unless( defined $usable_regex ) {
1109 local $Level = $Level + 1;
1110 $ok = $self->ok( 0, $name );
1111 $self->diag(" '$regex' doesn't look much like a regex to me.");
1117 my $context = $self->_caller_context;
1120 ## no critic (BuiltinFunctions::ProhibitStringyEval)
1122 local( $@, $!, $SIG{__DIE__} ); # isolate eval
1124 # No point in issuing an uninit warning, they'll see it in the diagnostics
1125 no warnings 'uninitialized';
1127 $test = eval $context . q{$test = $thing =~ /$usable_regex/ ? 1 : 0};
1130 $test = !$test if $cmp eq '!~';
1132 local $Level = $Level + 1;
1133 $ok = $self->ok( $test, $name );
1137 $thing = defined $thing ? "'$thing'" : 'undef';
1138 my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1140 local $Level = $Level + 1;
1141 $self->diag( sprintf <<'DIAGNOSTIC', $thing, $match, $regex );
1154 my $maybe_fh = shift;
1155 return 0 unless defined $maybe_fh;
1157 return 1 if ref $maybe_fh eq 'GLOB'; # its a glob ref
1158 return 1 if ref \$maybe_fh eq 'GLOB'; # its a glob
1160 return eval { $maybe_fh->isa("IO::Handle") } ||
1161 eval { tied($maybe_fh)->can('TIEHANDLE') };
1166 my( $self, $level ) = @_;
1168 if( defined $level ) {
1176 my( $self, $use_nums ) = @_;
1178 my $ctx = $self->ctx;
1179 my $format = $ctx->hub->format;
1180 unless ($format && $format->can('no_numbers') && $format->can('set_no_numbers')) {
1181 warn "The current formatter does not support 'use_numbers'" if $format;
1182 return release $ctx, 0;
1185 $format->set_no_numbers(!$use_nums) if defined $use_nums;
1187 return release $ctx, $format->no_numbers ? 0 : 1;
1191 for my $method (qw(no_header no_diag)) {
1192 my $set = "set_$method";
1194 my( $self, $no ) = @_;
1196 my $ctx = $self->ctx;
1197 my $format = $ctx->hub->format;
1198 unless ($format && $format->can($set)) {
1199 warn "The current formatter does not support '$method'" if $format;
1204 $format->$set($no) if defined $no;
1206 return release $ctx, $format->$method ? 1 : 0;
1209 no strict 'refs'; ## no critic
1215 my( $self, $no ) = @_;
1217 my $ctx = $self->ctx;
1219 $ctx->hub->set_no_ending($no) if defined $no;
1221 return release $ctx, $ctx->hub->no_ending;
1228 my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1230 if (Test2::API::test2_in_preload()) {
1232 $text =~ s/^/# /msg;
1233 print STDERR $text, "\n";
1237 my $ctx = $self->ctx;
1248 my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
1250 if (Test2::API::test2_in_preload()) {
1252 $text =~ s/^/# /msg;
1253 print STDOUT $text, "\n";
1257 my $ctx = $self->ctx;
1268 require Data::Dumper;
1273 my $dumper = Data::Dumper->new( [$_] );
1274 $dumper->Indent(1)->Terse(1);
1275 $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1284 my( $self, $fh ) = @_;
1286 my $ctx = $self->ctx;
1287 my $format = $ctx->hub->format;
1289 return unless $format && $format->isa('Test2::Formatter::TAP');
1291 $format->handles->[Test2::Formatter::TAP::OUT_STD()] = $self->_new_fh($fh)
1294 return $format->handles->[Test2::Formatter::TAP::OUT_STD()];
1297 sub failure_output {
1298 my( $self, $fh ) = @_;
1300 my $ctx = $self->ctx;
1301 my $format = $ctx->hub->format;
1303 return unless $format && $format->isa('Test2::Formatter::TAP');
1305 $format->handles->[Test2::Formatter::TAP::OUT_ERR()] = $self->_new_fh($fh)
1308 return $format->handles->[Test2::Formatter::TAP::OUT_ERR()];
1312 my( $self, $fh ) = @_;
1314 my $ctx = $self->ctx;
1315 my $format = $ctx->hub->format;
1317 return unless $format && $format->isa('Test::Builder::Formatter');
1319 $format->handles->[Test::Builder::Formatter::OUT_TODO()] = $self->_new_fh($fh)
1322 return $format->handles->[Test::Builder::Formatter::OUT_TODO()];
1327 my($file_or_fh) = shift;
1330 if( $self->is_fh($file_or_fh) ) {
1333 elsif( ref $file_or_fh eq 'SCALAR' ) {
1334 # Scalar refs as filehandles was added in 5.8.
1336 open $fh, ">>", $file_or_fh
1337 or $self->croak("Can't open scalar ref $file_or_fh: $!");
1339 # Emulate scalar ref filehandles with a tie.
1341 $fh = Test::Builder::IO::Scalar->new($file_or_fh)
1342 or $self->croak("Can't tie scalar ref $file_or_fh");
1346 open $fh, ">", $file_or_fh
1347 or $self->croak("Can't open test output log $file_or_fh: $!");
1356 my $old_fh = select $fh;
1367 my $ctx = $self->ctx;
1368 my $format = $ctx->hub->format;
1370 return unless $format && $format->isa('Test2::Formatter::TAP');
1371 $format->set_handles([@{$self->{Orig_Handles}}]) if $self->{Orig_Handles};
1379 my $ctx = $self->ctx;
1380 $ctx->alert(join "", @_);
1386 my $ctx = $self->ctx;
1387 $ctx->throw(join "", @_);
1393 my( $self, $num ) = @_;
1395 my $ctx = $self->ctx;
1396 my $hub = $ctx->hub;
1398 if( defined $num ) {
1399 $hub->set_count($num);
1401 unless ($self->{no_log_results}) {
1402 # If the test counter is being pushed forward fill in the details.
1403 my $test_results = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1404 if ($num > @$test_results) {
1405 my $start = @$test_results ? @$test_results : 0;
1406 for ($start .. $num - 1) {
1407 $test_results->[$_] = {
1410 reason => 'incrementing test number',
1416 # If backward, wipe history. Its their funeral.
1417 elsif ($num < @$test_results) {
1418 $#{$test_results} = $num - 1;
1422 return release $ctx, $hub->count;
1429 my $ctx = $self->ctx;
1430 my $hub = $ctx->hub;
1434 $hub->set_failed(0) if $bool;
1435 $hub->is_passing($bool);
1438 return release $ctx, $hub->is_passing;
1445 return if $self->{no_log_results};
1447 my $ctx = $self->ctx;
1448 my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1450 return map { $_ ? $_->{'ok'} : () } @$data;
1457 return if $self->{no_log_results};
1459 my $ctx = $self->ctx;
1460 my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1467 my( $self, $pack, $set, $new_value ) = @_;
1469 my $ctx = $self->ctx;
1471 $pack ||= $ctx->trace->package || $self->exported_to;
1474 return unless $pack;
1476 no strict 'refs'; ## no critic
1478 my $old_value = ${ $pack . '::TODO' };
1479 $set and ${ $pack . '::TODO' } = $new_value;
1484 my( $self, $pack ) = @_;
1486 local $Level = $Level + 1;
1487 my $ctx = $self->ctx;
1490 my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1491 return $meta->[-1]->[1] if $meta && @$meta;
1493 $pack ||= $ctx->trace->package;
1495 return unless $pack;
1497 no strict 'refs'; ## no critic
1499 return ${ $pack . '::TODO' };
1505 local $Level = $Level + 1;
1506 my $ctx = $self->ctx;
1509 my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1510 return 1 if $meta && @$meta;
1512 my $pack = $ctx->trace->package || return 0;
1514 no strict 'refs'; ## no critic
1516 my $todo = ${ $pack . '::TODO' };
1518 return 0 unless defined $todo;
1519 return 0 if "$todo" eq '';
1525 my $message = @_ ? shift : '';
1527 my $ctx = $self->ctx;
1529 my $hub = $ctx->hub;
1530 my $filter = $hub->pre_filter(sub {
1531 my ($active_hub, $e) = @_;
1533 # Turn a diag into a todo diag
1534 return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
1537 if ($hub == $active_hub && $e->isa('Test2::Event::Ok')) {
1538 $e->set_todo($message);
1539 $e->set_effective_pass(1);
1541 if (my $result = $e->get_meta(__PACKAGE__)) {
1542 $result->{reason} ||= $message;
1543 $result->{type} ||= 'todo';
1551 push @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}} => [$filter, $message];
1561 my $ctx = $self->ctx;
1563 my $set = pop @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}};
1565 $ctx->throw('todo_end() called without todo_start()') unless $set;
1567 $ctx->hub->pre_unfilter($set->[0]);
1575 sub caller { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1578 my $ctx = $self->ctx;
1580 my $trace = $ctx->trace;
1582 return wantarray ? $trace->call : $trace->package;
1587 my( $self, $code, %opts ) = @_;
1592 local $!; # eval can mess up $!
1593 local $@; # don't set $@ in the test
1594 local $SIG{__DIE__}; # don't trip an outside DIE handler.
1595 $return = eval { $code->() };
1599 die $error if $error and $opts{die_on_fail};
1601 return wantarray ? ( $return, $error ) : $return;
1606 my ($ctx, $real_exit_code, $new) = @_;
1609 my $octx = $self->ctx;
1610 $ctx = $octx->snapshot;
1614 return if $ctx->hub->no_ending;
1615 return if $ctx->hub->meta(__PACKAGE__, {})->{Ending}++;
1617 # Don't bother with an ending if this is a forked copy. Only the parent
1618 # should do the ending.
1619 return unless $self->{Original_Pid} == $$;
1621 my $hub = $ctx->hub;
1622 return if $hub->bailed_out;
1624 my $plan = $hub->plan;
1625 my $count = $hub->count;
1626 my $failed = $hub->failed;
1627 my $passed = $hub->is_passing;
1628 return unless $plan || $count || $failed;
1630 # Ran tests but never declared a plan or hit done_testing
1631 if( !$hub->plan and $hub->count ) {
1632 $self->diag("Tests were run but no plan was declared and done_testing() was not seen.");
1634 if($real_exit_code) {
1635 $self->diag(<<"FAIL");
1636 Looks like your test exited with $real_exit_code just after $count.
1638 $$new ||= $real_exit_code;
1642 # But if the tests ran, handle exit code.
1644 my $exit_code = $failed <= 254 ? $failed : 254;
1645 $$new ||= $exit_code;
1653 if ($real_exit_code && !$count) {
1654 $self->diag("Looks like your test exited with $real_exit_code before it could output anything.");
1655 $$new ||= $real_exit_code;
1659 return if $plan && "$plan" eq 'SKIP';
1662 $self->diag('No tests run!');
1667 if ($real_exit_code) {
1668 $self->diag(<<"FAIL");
1669 Looks like your test exited with $real_exit_code just after $count.
1671 $$new ||= $real_exit_code;
1675 if ($plan eq 'NO PLAN') {
1676 $ctx->plan( $count );
1680 # Figure out if we passed or failed and print helpful messages.
1681 my $num_extra = $count - $plan;
1683 if ($num_extra != 0) {
1684 my $s = $plan == 1 ? '' : 's';
1685 $self->diag(<<"FAIL");
1686 Looks like you planned $plan test$s but ran $count.
1691 my $s = $failed == 1 ? '' : 's';
1693 my $qualifier = $num_extra == 0 ? '' : ' run';
1695 $self->diag(<<"FAIL");
1696 Looks like you failed $failed test$s of $count$qualifier.
1700 if (!$passed && !$failed && $count && !$num_extra) {
1701 $ctx->diag(<<"FAIL");
1702 All assertions passed, but errors were encountered.
1708 $exit_code = $failed <= 254 ? $failed : 254;
1710 elsif ($num_extra != 0) {
1717 $$new ||= $exit_code;
1721 # Some things used this even though it was private... I am looking at you
1722 # Test::Builder::Prefix...
1723 sub _print_comment {
1724 my( $self, $fh, @msgs ) = @_;
1726 return if $self->no_diag;
1727 return unless @msgs;
1729 # Prevent printing headers when compiling (i.e. -c)
1732 # Smash args together like print does.
1733 # Convert undef to 'undef' so its readable.
1734 my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
1736 # Escape the beginning, _print will take care of the rest.
1739 local( $\, $", $, ) = ( undef, ' ', '' );
1745 # This is used by Test::SharedFork to turn on IPC after the fact. Not
1746 # documenting because I do not want it used. The method name is borrowed from
1748 # Once Test2 stuff goes stable this method will be removed and Test::SharedFork
1749 # will be made smarter.
1750 sub coordinate_forks {
1758 Test2::API::test2_ipc_enable_polling();
1759 Test2::API::test2_load();
1760 my $ipc = Test2::IPC::apply_ipc($self->{Stack});
1761 $ipc->set_no_fatal(1);
1762 Test2::API::test2_no_wait(1);
1765 sub no_log_results { $_[0]->{no_log_results} = 1 }
1773 Test::Builder - Backend for building test libraries
1777 package My::Test::Module;
1778 use base 'Test::Builder::Module';
1780 my $CLASS = __PACKAGE__;
1783 my($test, $name) = @_;
1784 my $tb = $CLASS->builder;
1786 $tb->ok($test, $name);
1792 L<Test::Simple> and L<Test::More> have proven to be popular testing modules,
1793 but they're not always flexible enough. Test::Builder provides a
1794 building block upon which to write your own test libraries I<which can
1803 my $Test = Test::Builder->new;
1805 Returns a Test::Builder object representing the current state of the
1808 Since you only run one test per program C<new> always returns the same
1809 Test::Builder object. No matter how many times you call C<new()>, you're
1810 getting the same object. This is called a singleton. This is done so that
1811 multiple modules share such global information as the test counter and
1812 where test output is going.
1814 If you want a completely new Test::Builder object different from the
1815 singleton, use C<create>.
1819 my $Test = Test::Builder->create;
1821 Ok, so there can be more than one Test::Builder object and this is how
1822 you get it. You might use this instead of C<new()> if you're testing
1823 a Test::Builder based module, but otherwise you probably want C<new>.
1825 B<NOTE>: the implementation is not complete. C<level>, for example, is still
1826 shared by B<all> Test::Builder objects, even ones created using this method.
1827 Also, the method name may change in the future.
1831 $builder->subtest($name, \&subtests, @args);
1833 See documentation of C<subtest> in Test::More.
1835 C<subtest> also, and optionally, accepts arguments which will be passed to the
1840 diag $builder->name;
1842 Returns the name of the current builder. Top level builders default to C<$0>
1843 (the name of the executable). Child builders are named via the C<child>
1844 method. If no name is supplied, will be named "Child of $parent->name".
1850 Reinitializes the Test::Builder singleton to its original state.
1851 Mostly useful for tests run in persistent environments where the same
1852 test might be run multiple times in the same process.
1856 =head2 Setting up tests
1858 These methods are for setting up tests and declaring how many there
1859 are. You usually only want to call one of these methods.
1865 $Test->plan('no_plan');
1866 $Test->plan( skip_all => $reason );
1867 $Test->plan( tests => $num_tests );
1869 A convenient way to set up your tests. Call this and Test::Builder
1870 will print the appropriate headers and take the appropriate actions.
1872 If you call C<plan()>, don't call any of the other methods below.
1874 =item B<expected_tests>
1876 my $max = $Test->expected_tests;
1877 $Test->expected_tests($max);
1879 Gets/sets the number of tests we expect this test to run and prints out
1880 the appropriate headers.
1887 Declares that this test will run an indeterminate number of tests.
1890 =item B<done_testing>
1892 $Test->done_testing();
1893 $Test->done_testing($num_tests);
1895 Declares that you are done testing, no more tests will be run after this point.
1897 If a plan has not yet been output, it will do so.
1899 $num_tests is the number of tests you planned to run. If a numbered
1900 plan was already declared, and if this contradicts, a failing test
1901 will be run to reflect the planning mistake. If C<no_plan> was declared,
1904 If C<done_testing()> is called twice, the second call will issue a
1907 If C<$num_tests> is omitted, the number of tests run will be used, like
1910 C<done_testing()> is, in effect, used when you'd want to use C<no_plan>, but
1911 safer. You'd use it like so:
1913 $Test->ok($a == $b);
1914 $Test->done_testing();
1916 Or to plan a variable number of tests:
1918 for my $test (@tests) {
1921 $Test->done_testing(scalar @tests);
1926 $plan = $Test->has_plan
1928 Find out whether a plan has been defined. C<$plan> is either C<undef> (no plan
1929 has been set), C<no_plan> (indeterminate # of tests) or an integer (the number
1935 $Test->skip_all($reason);
1937 Skips all the tests, using the given C<$reason>. Exits immediately with 0.
1939 =item B<exported_to>
1941 my $pack = $Test->exported_to;
1942 $Test->exported_to($pack);
1944 Tells Test::Builder what package you exported your functions to.
1946 This method isn't terribly useful since modules which share the same
1947 Test::Builder object might get exported to different packages and only
1948 the last one will be honored.
1952 =head2 Running tests
1954 These actually run the tests, analogous to the functions in Test::More.
1956 They all return true if the test passed, false if the test failed.
1958 C<$name> is always optional.
1964 $Test->ok($test, $name);
1966 Your basic test. Pass if C<$test> is true, fail if $test is false. Just
1967 like Test::Simple's C<ok()>.
1971 $Test->is_eq($got, $expected, $name);
1973 Like Test::More's C<is()>. Checks if C<$got eq $expected>. This is the
1976 C<undef> only ever matches another C<undef>.
1980 $Test->is_num($got, $expected, $name);
1982 Like Test::More's C<is()>. Checks if C<$got == $expected>. This is the
1985 C<undef> only ever matches another C<undef>.
1989 $Test->isnt_eq($got, $dont_expect, $name);
1991 Like L<Test::More>'s C<isnt()>. Checks if C<$got ne $dont_expect>. This is
1996 $Test->isnt_num($got, $dont_expect, $name);
1998 Like L<Test::More>'s C<isnt()>. Checks if C<$got ne $dont_expect>. This is
1999 the numeric version.
2003 $Test->like($thing, qr/$regex/, $name);
2004 $Test->like($thing, '/$regex/', $name);
2006 Like L<Test::More>'s C<like()>. Checks if $thing matches the given C<$regex>.
2010 $Test->unlike($thing, qr/$regex/, $name);
2011 $Test->unlike($thing, '/$regex/', $name);
2013 Like L<Test::More>'s C<unlike()>. Checks if $thing B<does not match> the
2018 $Test->cmp_ok($thing, $type, $that, $name);
2020 Works just like L<Test::More>'s C<cmp_ok()>.
2022 $Test->cmp_ok($big_num, '!=', $other_big_num);
2026 =head2 Other Testing Methods
2028 These are methods which are used in the course of writing a test but are not themselves tests.
2034 $Test->BAIL_OUT($reason);
2036 Indicates to the L<Test::Harness> that things are going so badly all
2037 testing should terminate. This includes running any additional test
2040 It will exit with 255.
2043 BAIL_OUT() used to be BAILOUT()
2050 Skips the current test, reporting C<$why>.
2055 $Test->todo_skip($why);
2057 Like C<skip()>, only it will declare the test as failing and TODO. Similar
2060 print "not ok $tnum # TODO $why\n";
2062 =begin _unimplemented
2067 $Test->skip_rest($reason);
2069 Like C<skip()>, only it skips all the rest of the tests you plan to run
2070 and terminates the test.
2072 If you're running under C<no_plan>, it skips once and terminates the
2080 =head2 Test building utility methods
2082 These methods are useful when writing your own test methods.
2086 =item B<maybe_regex>
2088 $Test->maybe_regex(qr/$regex/);
2089 $Test->maybe_regex('/$regex/');
2091 This method used to be useful back when Test::Builder worked on Perls
2092 before 5.6 which didn't have qr//. Now its pretty useless.
2094 Convenience method for building testing functions that take regular
2095 expressions as arguments.
2097 Takes a quoted regular expression produced by C<qr//>, or a string
2098 representing a regular expression.
2100 Returns a Perl value which may be used instead of the corresponding
2101 regular expression, or C<undef> if its argument is not recognized.
2103 For example, a version of C<like()>, sans the useful diagnostic messages,
2104 could be written as:
2107 my ($self, $thing, $regex, $name) = @_;
2108 my $usable_regex = $self->maybe_regex($regex);
2109 die "expecting regex, found '$regex'\n"
2110 unless $usable_regex;
2111 $self->ok($thing =~ m/$usable_regex/, $name);
2117 my $is_fh = $Test->is_fh($thing);
2119 Determines if the given C<$thing> can be used as a filehandle.
2134 $Test->level($how_high);
2136 How far up the call stack should C<$Test> look when reporting where the
2141 Setting C<$Test::Builder::Level> overrides. This is typically useful
2147 local $Test::Builder::Level = $Test::Builder::Level + 1;
2151 To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
2153 =item B<use_numbers>
2155 $Test->use_numbers($on_or_off);
2157 Whether or not the test should output numbers. That is, this if true:
2169 Most useful when you can't depend on the test output order, such as
2170 when threads or forking is involved.
2176 $Test->no_diag($no_diag);
2178 If set true no diagnostics will be printed. This includes calls to
2183 $Test->no_ending($no_ending);
2185 Normally, Test::Builder does some extra diagnostics when the test
2186 ends. It also changes the exit code as described below.
2188 If this is true, none of that will be done.
2192 $Test->no_header($no_header);
2194 If set to true, no "1..N" header will be printed.
2200 Controlling where the test output goes.
2202 It's ok for your test to change where STDOUT and STDERR point to,
2203 Test::Builder's default output settings will not be affected.
2211 Prints out the given C<@msgs>. Like C<print>, arguments are simply
2214 Normally, it uses the C<failure_output()> handle, but if this is for a
2215 TODO test, the C<todo_output()> handle is used.
2217 Output will be indented and marked with a # so as not to interfere
2218 with test output. A newline will be put on the end if there isn't one
2221 We encourage using this rather than calling print directly.
2223 Returns false. Why? Because C<diag()> is often used in conjunction with
2224 a failing test (C<ok() || diag()>) it "passes through" the failure.
2226 return ok(...) || diag(...);
2229 Mark Fowler <mark@twoshortplanks.com>
2235 Like C<diag()>, but it prints to the C<output()> handle so it will not
2236 normally be seen by the user except in verbose mode.
2240 my @dump = $Test->explain(@msgs);
2242 Will dump the contents of any references in a human readable format.
2243 Handy for things like...
2245 is_deeply($have, $want) || diag explain $have;
2249 is_deeply($have, $want) || note explain $have;
2253 =item B<failure_output>
2255 =item B<todo_output>
2257 my $filehandle = $Test->output;
2258 $Test->output($filehandle);
2259 $Test->output($filename);
2260 $Test->output(\$scalar);
2262 These methods control where Test::Builder will print its output.
2263 They take either an open C<$filehandle>, a C<$filename> to open and write to
2264 or a C<$scalar> reference to append to. It will always return a C<$filehandle>.
2266 B<output> is where normal "ok/not ok" test output goes.
2270 B<failure_output> is where diagnostic output on test failures and
2271 C<diag()> goes. It is normally not read by Test::Harness and instead is
2272 displayed to the user.
2276 C<todo_output> is used instead of C<failure_output()> for the
2277 diagnostics of a failing TODO test. These will not be seen by the
2286 Resets all the output filehandles back to their defaults.
2290 $tb->carp(@message);
2292 Warns with C<@message> but the message will appear to come from the
2293 point where the original test function was called (C<< $tb->caller >>).
2297 $tb->croak(@message);
2299 Dies with C<@message> but the message will appear to come from the
2300 point where the original test function was called (C<< $tb->caller >>).
2306 =head2 Test Status and Info
2310 =item B<no_log_results>
2312 This will turn off result long-term storage. Calling this method will make
2313 C<details> and C<summary> useless. You may want to use this if you are running
2314 enough tests to fill up all available memory.
2316 Test::Builder->new->no_log_results();
2318 There is no way to turn it back on.
2320 =item B<current_test>
2322 my $curr_test = $Test->current_test;
2323 $Test->current_test($num);
2325 Gets/sets the current test number we're on. You usually shouldn't
2328 If set forward, the details of the missing tests are filled in as 'unknown'.
2329 if set backward, the details of the intervening tests are deleted. You
2330 can erase history if you really want to.
2335 my $ok = $builder->is_passing;
2337 Indicates if the test suite is currently passing.
2339 More formally, it will be false if anything has happened which makes
2340 it impossible for the test suite to pass. True otherwise.
2342 For example, if no tests have run C<is_passing()> will be true because
2343 even though a suite with no tests is a failure you can add a passing
2344 test to it and start passing.
2346 Don't think about it too much.
2351 my @tests = $Test->summary;
2353 A simple summary of the tests so far. True for pass, false for fail.
2354 This is a logical pass/fail, so todos are passes.
2356 Of course, test #1 is $tests[0], etc...
2361 my @tests = $Test->details;
2363 Like C<summary()>, but with a lot more detail.
2365 $tests[$test_num - 1] =
2366 { 'ok' => is the test considered a pass?
2367 actual_ok => did it literally say 'ok'?
2368 name => name of the test (if any)
2369 type => type of test (if any, see below).
2370 reason => reason for the above (if any)
2373 'ok' is true if Test::Harness will consider the test to be a pass.
2375 'actual_ok' is a reflection of whether or not the test literally
2376 printed 'ok' or 'not ok'. This is for examining the result of 'todo'
2379 'name' is the name of the test.
2381 'type' indicates if it was a special test. Normal tests have a type
2382 of ''. Type can be one of the following:
2386 todo_skip see todo_skip()
2389 Sometimes the Test::Builder test counter is incremented without it
2390 printing any test output, for example, when C<current_test()> is changed.
2391 In these cases, Test::Builder doesn't know the result of the test, so
2392 its type is 'unknown'. These details for these tests are filled in.
2393 They are considered ok, but the name and actual_ok is left C<undef>.
2395 For example "not ok 23 - hole count # TODO insufficient donuts" would
2396 result in this structure:
2398 $tests[22] = # 23 - 1, since arrays start from 0.
2399 { ok => 1, # logically, the test passed since its todo
2400 actual_ok => 0, # in absolute terms, it failed
2401 name => 'hole count',
2403 reason => 'insufficient donuts'
2409 my $todo_reason = $Test->todo;
2410 my $todo_reason = $Test->todo($pack);
2412 If the current tests are considered "TODO" it will return the reason,
2413 if any. This reason can come from a C<$TODO> variable or the last call
2416 Since a TODO test does not need a reason, this function can return an
2417 empty string even when inside a TODO block. Use C<< $Test->in_todo >>
2418 to determine if you are currently inside a TODO block.
2420 C<todo()> is about finding the right package to look for C<$TODO> in. It's
2421 pretty good at guessing the right package to look at. It first looks for
2422 the caller based on C<$Level + 1>, since C<todo()> is usually called inside
2423 a test function. As a last resort it will use C<exported_to()>.
2425 Sometimes there is some confusion about where C<todo()> should be looking
2426 for the C<$TODO> variable. If you want to be sure, tell it explicitly
2431 my $todo_reason = $Test->find_TODO();
2432 my $todo_reason = $Test->find_TODO($pack);
2434 Like C<todo()> but only returns the value of C<$TODO> ignoring
2437 Can also be used to set C<$TODO> to a new value while returning the
2440 my $old_reason = $Test->find_TODO($pack, 1, $new_reason);
2444 my $in_todo = $Test->in_todo;
2446 Returns true if the test is currently inside a TODO block.
2450 $Test->todo_start();
2451 $Test->todo_start($message);
2453 This method allows you declare all subsequent tests as TODO tests, up until
2454 the C<todo_end> method has been called.
2456 The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
2457 whether or not we're in a TODO test. However, often we find that this is not
2458 possible to determine (such as when we want to use C<$TODO> but
2459 the tests are being executed in other packages which can't be inferred
2462 Note that you can use this to nest "todo" tests
2464 $Test->todo_start('working on this');
2466 $Test->todo_start('working on that');
2471 This is generally not recommended, but large testing systems often have weird
2474 We've tried to make this also work with the TODO: syntax, but it's not
2475 guaranteed and its use is also discouraged:
2478 local $TODO = 'We have work to do!';
2479 $Test->todo_start('working on this');
2481 $Test->todo_start('working on that');
2487 Pick one style or another of "TODO" to be on the safe side.
2494 Stops running tests as "TODO" tests. This method is fatal if called without a
2495 preceding C<todo_start> method call.
2499 my $package = $Test->caller;
2500 my($pack, $file, $line) = $Test->caller;
2501 my($pack, $file, $line) = $Test->caller($height);
2503 Like the normal C<caller()>, except it reports according to your C<level()>.
2505 C<$height> will be added to the C<level()>.
2507 If C<caller()> winds up off the top of the stack it report the highest context.
2513 If all your tests passed, Test::Builder will exit with zero (which is
2514 normal). If anything failed it will exit with how many failed. If
2515 you run less (or more) tests than you planned, the missing (or extras)
2516 will be considered failures. If no tests were ever run Test::Builder
2517 will throw a warning and exit with 255. If the test died, even after
2518 having successfully completed all its tests, it will still be
2519 considered a failure and will exit with 255.
2521 So the exit codes are...
2523 0 all tests successful
2524 255 test died or all passed but wrong # of tests run
2525 any other number how many failed (including missing or extras)
2527 If you fail more than 254 tests, it will be reported as 254.
2531 In perl 5.8.1 and later, Test::Builder is thread-safe. The test number is
2532 shared by all threads. This means if one thread sets the test number using
2533 C<current_test()> they will all be effected.
2535 While versions earlier than 5.8.1 had threads they contain too many
2538 Test::Builder is only thread-aware if threads.pm is loaded I<before>
2541 You can directly disable thread support with one of the following:
2551 Test2::API::test2_ipc_disable()
2555 An informative hash, accessible via C<details()>, is stored for each
2556 test you perform. So memory usage will scale linearly with each test
2557 run. Although this is not a problem for most test suites, it can
2558 become an issue if you do large (hundred thousands to million)
2559 combinatorics tests in the same run.
2561 In such cases, you are advised to either split the test file into smaller
2562 ones, or use a reverse approach, doing "normal" (code) compares and
2563 triggering C<fail()> should anything go unexpected.
2565 Future versions of Test::Builder will have a way to turn history off.
2570 CPAN can provide the best examples. L<Test::Simple>, L<Test::More>,
2571 L<Test::Exception> and L<Test::Differences> all use Test::Builder.
2577 L<Test2>, L<Test2::API>
2581 L<Test::Simple>, L<Test::More>
2589 Original code by chromatic, maintained by Michael G Schwern
2590 E<lt>schwern@pobox.comE<gt>
2596 =item Chad Granum E<lt>exodist@cpan.orgE<gt>
2602 Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2603 Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2605 This program is free software; you can redistribute it and/or
2606 modify it under the same terms as Perl itself.
2608 See F<http://www.perl.com/perl/misc/Artistic.html>