File Coverage

blib/lib/Test/Builder.pm
Criterion Covered Total %
statement 943 996 94.6
branch 354 436 81.1
condition 169 252 67.0
subroutine 165 168 98.2
pod 48 53 90.5
total 1679 1905 88.1


line stmt bran cond sub pod time code
1             package Test::Builder;
2              
3 166     166   83538 use 5.006;
  166         955  
4 166     166   1048 use strict;
  166         471  
  166         3701  
5 166     166   998 use warnings;
  165         455  
  165         13797  
6              
7             our $VERSION = '1.302181';
8              
9             BEGIN {
10 164 50   166   5782 if( $] < 5.008 ) {
11 2         99 require Test::Builder::IO::Scalar;
12             }
13             }
14              
15 164     166   1131 use Scalar::Util qw/blessed reftype weaken/;
  164         530  
  164         23302  
16              
17 164     166   55452 use Test2::Util qw/USE_THREADS try get_tid/;
  164         456  
  164         11823  
18 164     165   79080 use Test2::API qw/context release/;
  164         574  
  164         24133  
19             # Make Test::Builder thread-safe for ithreads.
20             BEGIN {
21 164 100 66 165   1090 warn "Test::Builder was loaded after Test2 initialization, this is not recommended."
22             if Test2::API::test2_init_done() || Test2::API::test2_load_done();
23              
24 164         3392 if (USE_THREADS && ! Test2::API::test2_ipc_disabled()) {
25             require Test2::IPC;
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             }
31             }
32              
33 164     164   1179 use Test2::Event::Subtest;
  164         400  
  164         4584  
34 164     164   938 use Test2::Hub::Subtest;
  164         421  
  164         5258  
35              
36 164     164   67105 use Test::Builder::Formatter;
  164         524  
  164         1258  
37 164     164   67877 use Test::Builder::TodoDiag;
  164         495  
  164         19960  
38              
39             our $Level = 1;
40             our $Test = $ENV{TB_NO_EARLY_INIT} ? undef : Test::Builder->new;
41              
42             sub _add_ts_hooks {
43 361     362   729 my $self = shift;
44              
45 361         1391 my $hub = $self->{Stack}->top;
46              
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
49             # in rare cases.
50 361         902 my $epkgr = \$self->{Exported_To};
51              
52             #$hub->add_context_aquire(sub {$_[0]->{level} += $Level - 1});
53              
54             $hub->pre_filter(
55             sub {
56 4416     4417   8579 my ($active_hub, $e) = @_;
57              
58 4416         7217 my $epkg = $$epkgr;
59 4416 50       11891 my $cpkg = $e->{trace} ? $e->{trace}->{frame}->[0] : undef;
60              
61 164     164   1215 no strict 'refs';
  164         428  
  163         6283  
62 163     164   1044 no warnings 'once';
  163         387  
  163         43954  
63 4416         6164 my $todo;
64 4416 50       8671 $todo = ${"$cpkg\::TODO"} if $cpkg;
  4416         15816  
65 4416 100 100     14377 $todo = ${"$epkg\::TODO"} if $epkg && !$todo;
  2961         5673  
66              
67 4416 100       13416 return $e unless defined($todo);
68 324 100       682 return $e unless length($todo);
69              
70             # Turn a diag into a todo diag
71 322 100       1137 return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
72              
73 208 100       1151 $e->set_todo($todo) if $e->can('set_todo');
74 208         980 $e->add_amnesty({tag => 'TODO', details => $todo});
75              
76             # Set todo on ok's
77 208 100       906 if ($e->isa('Test2::Event::Ok')) {
78 133         379 $e->set_effective_pass(1);
79              
80 133 100       388 if (my $result = $e->get_meta(__PACKAGE__)) {
81 131   100     527 $result->{reason} ||= $todo;
82 131   100     442 $result->{type} ||= 'todo';
83 131         220 $result->{ok} = 1;
84             }
85             }
86              
87 208         558 return $e;
88             },
89              
90             inherit => 1,
91              
92             intercept_inherit => {
93             clean => sub {
94 23     24   73 my %params = @_;
95              
96 23         73 my $state = $params{state};
97 23         50 my $trace = $params{trace};
98              
99 23         54 my $epkg = $$epkgr;
100 23         114 my $cpkg = $trace->{frame}->[0];
101              
102 163     164   1314 no strict 'refs';
  163         452  
  163         6457  
103 163     164   1046 no warnings 'once';
  163         362  
  163         30703  
104              
105 23         75 $state->{+__PACKAGE__} = {};
106 23 50       71 $state->{+__PACKAGE__}->{"$cpkg\::TODO"} = ${"$cpkg\::TODO"} if $cpkg;
  23         133  
107 23 100       70 $state->{+__PACKAGE__}->{"$epkg\::TODO"} = ${"$epkg\::TODO"} if $epkg;
  13         56  
108              
109 23 50       75 ${"$cpkg\::TODO"} = undef if $cpkg;
  23         81  
110 23 100       91 ${"$epkg\::TODO"} = undef if $epkg;
  13         66  
111             },
112             restore => sub {
113 25     26   93 my %params = @_;
114 25         61 my $state = $params{state};
115              
116 163     164   1188 no strict 'refs';
  163         413  
  163         6480  
117 163     164   1105 no warnings 'once';
  163         383  
  163         10367  
118              
119 25         46 for my $item (keys %{$state->{+__PACKAGE__}}) {
  25         120  
120 163     164   1146 no strict 'refs';
  163         436  
  163         5647  
121 163     164   1028 no warnings 'once';
  163         465  
  163         17180  
122              
123 25         59 ${"$item"} = $state->{+__PACKAGE__}->{$item};
  25         142  
124             }
125             },
126             },
127 361         5979 );
128             }
129              
130             {
131 163     164   1235 no warnings;
  163         426  
  162         7416  
132             INIT {
133 162     164   1050 use warnings;
  162         372  
  162         557552  
134 151 100   152   887 Test2::API::test2_load() unless Test2::API::test2_in_preload();
135             }
136             }
137              
138             sub new {
139 2136     2137 1 90142 my($class) = shift;
140 2136 100       5750 unless($Test) {
141 157         547 $Test = $class->create(singleton => 1);
142              
143             Test2::API::test2_add_callback_post_load(
144             sub {
145 157 50 33 158   1507 $Test->{Original_Pid} = $$ if !$Test->{Original_Pid} || $Test->{Original_Pid} == 0;
146 157         797 $Test->reset(singleton => 1);
147 157         669 $Test->_add_ts_hooks;
148             }
149 157         1189 );
150              
151             # Non-TB tools normally expect 0 added to the level. $Level is normally 1. So
152             # we only want the level to change if $Level != 1.
153             # TB->ctx compensates for this later.
154 157     10495   906 Test2::API::test2_add_callback_context_aquire(sub { $_[0]->{level} += $Level - 1 });
  10494         29066  
155              
156 157     136   912 Test2::API::test2_add_callback_exit(sub { $Test->_ending(@_) });
  135         820  
157              
158 157 50       645 Test2::API::test2_ipc()->set_no_fatal(1) if Test2::API::test2_has_ipc();
159             }
160 2136         5415 return $Test;
161             }
162              
163             sub create {
164 209     210 1 957 my $class = shift;
165 209         728 my %params = @_;
166              
167 209         629 my $self = bless {}, $class;
168 209 100       728 if ($params{singleton}) {
169 162         800 $self->{Stack} = Test2::API::test2_stack();
170             }
171             else {
172 47         357 $self->{Stack} = Test2::API::Stack->new;
173             $self->{Stack}->new_hub(
174 47         351 formatter => Test::Builder::Formatter->new,
175             ipc => Test2::API::test2_ipc(),
176             );
177              
178 47         344 $self->reset(%params);
179 47         242 $self->_add_ts_hooks;
180             }
181              
182 209         708 return $self;
183             }
184              
185             sub ctx {
186 10810     10811 0 18618 my $self = shift;
187             context(
188             # 1 for our frame, another for the -1 off of $Level in our hook at the top.
189             level => 2,
190             fudge => 1,
191             stack => $self->{Stack},
192             hub => $self->{Hub},
193 10810         55871 wrapped => 1,
194             @_
195             );
196             }
197              
198             sub parent {
199 148     149 0 250 my $self = shift;
200 148         312 my $ctx = $self->ctx;
201 148   66     526 my $chub = $self->{Hub} || $ctx->hub;
202 148         1011 $ctx->release;
203              
204 148         572 my $meta = $chub->meta(__PACKAGE__, {});
205 148         322 my $parent = $meta->{parent};
206              
207 148 100       357 return undef unless $parent;
208              
209             return bless {
210             Original_Pid => $$,
211             Stack => $self->{Stack},
212 147         1171 Hub => $parent,
213             }, blessed($self);
214             }
215              
216             sub child {
217 151     152 0 426 my( $self, $name ) = @_;
218              
219 151   66     374 $name ||= "Child of " . $self->name;
220 151         350 my $ctx = $self->ctx;
221              
222 151         630 my $parent = $ctx->hub;
223 151         591 my $pmeta = $parent->meta(__PACKAGE__, {});
224             $self->croak("You already have a child named ($pmeta->{child}) running")
225 151 50       498 if $pmeta->{child};
226              
227 151         332 $pmeta->{child} = $name;
228              
229             # Clear $TODO for the child.
230 151         437 my $orig_TODO = $self->find_TODO(undef, 1, undef);
231              
232 151         334 my $subevents = [];
233              
234 151         552 my $hub = $ctx->stack->new_hub(
235             class => 'Test2::Hub::Subtest',
236             );
237              
238             $hub->pre_filter(sub {
239 114     115   206 my ($active_hub, $e) = @_;
240              
241             # Turn a diag into a todo diag
242 114 100       405 return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
243              
244 78         153 return $e;
245 151 100       691 }, inherit => 1) if $orig_TODO;
246              
247 151     603   932 $hub->listen(sub { push @$subevents => $_[1] });
  602         1738  
248              
249 151         373 $hub->set_nested( $parent->nested + 1 );
250              
251 151         514 my $meta = $hub->meta(__PACKAGE__, {});
252 151         354 $meta->{Name} = $name;
253 151         296 $meta->{TODO} = $orig_TODO;
254 151         403 $meta->{TODO_PKG} = $ctx->trace->package;
255 151         379 $meta->{parent} = $parent;
256 151         313 $meta->{Test_Results} = [];
257 151         291 $meta->{subevents} = $subevents;
258 151         412 $meta->{subtest_id} = $hub->id;
259 151         527 $meta->{subtest_uuid} = $hub->uuid;
260 151 100       438 $meta->{subtest_buffered} = $parent->format ? 0 : 1;
261              
262 151         496 $self->_add_ts_hooks;
263              
264 151         594 $ctx->release;
265 151         1453 return bless { Original_Pid => $$, Stack => $self->{Stack}, Hub => $hub, no_log_results => $self->{no_log_results} }, blessed($self);
266             }
267              
268             sub finalize {
269 147     148 0 306 my $self = shift;
270 147         256 my $ok = 1;
271 147 100       404 ($ok) = @_ if @_;
272              
273 147         385 my $st_ctx = $self->ctx;
274 147   50     476 my $chub = $self->{Hub} || return $st_ctx->release;
275              
276 147         576 my $meta = $chub->meta(__PACKAGE__, {});
277 147 50       445 if ($meta->{child}) {
278 0         0 $self->croak("Can't call finalize() with child ($meta->{child}) active");
279             }
280              
281 147         485 local $? = 0; # don't fail if $subtests happened to set $? nonzero
282              
283 147         677 $self->{Stack}->pop($chub);
284              
285 147         528 $self->find_TODO($meta->{TODO_PKG}, 1, $meta->{TODO});
286              
287 147         519 my $parent = $self->parent;
288 147         387 my $ctx = $parent->ctx;
289 147         726 my $trace = $ctx->trace;
290 147         383 delete $ctx->hub->meta(__PACKAGE__, {})->{child};
291              
292 147 100 66     640 $chub->finalize($trace->snapshot(hid => $chub->hid, nested => $chub->nested), 1)
      100        
      100        
293             if $ok
294             && $chub->count
295             && !$chub->no_ending
296             && !$chub->ended;
297              
298 147   100     469 my $plan = $chub->plan || 0;
299 147         427 my $count = $chub->count;
300 147         444 my $failed = $chub->failed;
301 147         584 my $passed = $chub->is_passing;
302              
303 147 100       619 my $num_extra = $plan =~ m/\D/ ? 0 : $count - $plan;
304 147 100 100     573 if ($count && $num_extra != 0) {
305 12 50       27 my $s = $plan == 1 ? '' : 's';
306 12         54 $st_ctx->diag(<<"FAIL");
307             Looks like you planned $plan test$s but ran $count.
308             FAIL
309             }
310              
311 147 100       376 if ($failed) {
312 61 100       144 my $s = $failed == 1 ? '' : 's';
313              
314 61 100       137 my $qualifier = $num_extra == 0 ? '' : ' run';
315              
316 61         326 $st_ctx->diag(<<"FAIL");
317             Looks like you failed $failed test$s of $count$qualifier.
318             FAIL
319             }
320              
321 147 50 100     668 if (!$passed && !$failed && $count && !$num_extra) {
      66        
      33        
322 0         0 $st_ctx->diag(<<"FAIL");
323             All assertions inside the subtest passed, but errors were encountered.
324             FAIL
325             }
326              
327 147         534 $st_ctx->release;
328              
329 147 50       501 unless ($chub->bailed_out) {
330 147         415 my $plan = $chub->plan;
331 147 100 100     875 if ( $plan && $plan eq 'SKIP' ) {
    100          
332 2         19 $parent->skip($chub->skip_reason, $meta->{Name});
333             }
334             elsif ( !$chub->count ) {
335 54         374 $parent->ok( 0, sprintf q[No tests run for subtest "%s"], $meta->{Name} );
336             }
337             else {
338 91         234 $parent->{subevents} = $meta->{subevents};
339 91         202 $parent->{subtest_id} = $meta->{subtest_id};
340 91         208 $parent->{subtest_uuid} = $meta->{subtest_uuid};
341 91         188 $parent->{subtest_buffered} = $meta->{subtest_buffered};
342 91         302 $parent->ok( $chub->is_passing, $meta->{Name} );
343             }
344             }
345              
346 147         487 $ctx->release;
347 147         501 return $chub->is_passing;
348             }
349              
350             sub subtest {
351 142     143 1 264 my $self = shift;
352 142         339 my ($name, $code, @args) = @_;
353 142         367 my $ctx = $self->ctx;
354 142 100 66     989 $ctx->throw("subtest()'s second argument must be a code ref")
355             unless $code && reftype($code) eq 'CODE';
356              
357 140   33     369 $name ||= "Child of " . $self->name;
358              
359              
360             $_->($name,$code,@args)
361 140         391 for Test2::API::test2_list_pre_subtest_callbacks();
362              
363 140         728 $ctx->note("Subtest: $name");
364              
365 140         536 my $child = $self->child($name);
366              
367 140         362 my $start_pid = $$;
368 140         222 my $st_ctx;
369 140         250 my ($ok, $err, $finished, $child_error);
370             T2_SUBTEST_WRAPPER: {
371 140         225 my $ctx = $self->ctx;
  140         324  
372 140         587 $st_ctx = $ctx->snapshot;
373 140         504 $ctx->release;
374 140         257 $ok = eval { local $Level = 1; $code->(@args); 1 };
  140         283  
  140         528  
  134         365  
375 135         404 ($err, $child_error) = ($@, $?);
376              
377             # They might have done 'BEGIN { skip_all => "whatever" }'
378 135 50 66     905 if (!$ok && $err =~ m/Label not found for "last T2_SUBTEST_WRAPPER"/ || (blessed($err) && blessed($err) eq 'Test::Builder::Exception')) {
      33        
      33        
379 0         0 $ok = undef;
380 0         0 $err = undef;
381             }
382             else {
383 135         393 $finished = 1;
384             }
385             }
386              
387 139 50 33     506 if ($start_pid != $$ && !$INC{'Test2/IPC.pm'}) {
388 0 0       0 warn $ok ? "Forked inside subtest, but subtest never finished!\n" : $err;
389 0         0 exit 255;
390             }
391              
392 139         371 my $trace = $ctx->trace;
393              
394 139 100       341 if (!$finished) {
395 4 100       13 if(my $bailed = $st_ctx->hub->bailed_out) {
396 2         5 my $chub = $child->{Hub};
397 2         10 $self->{Stack}->pop($chub);
398 2         11 $ctx->bail($bailed->reason);
399             }
400 2         6 my $code = $st_ctx->hub->exit_code;
401 2         6 $ok = !$code;
402 2 50       6 $err = "Subtest ended with exit code $code" if $code;
403             }
404              
405 137         342 my $st_hub = $st_ctx->hub;
406 137         440 my $plan = $st_hub->plan;
407 137         456 my $count = $st_hub->count;
408              
409 137 100 100     512 if (!$count && (!defined($plan) || "$plan" ne 'SKIP')) {
      100        
410 50 100       126 $st_ctx->plan(0) unless defined $plan;
411 50         150 $st_ctx->diag('No tests run!');
412             }
413              
414 137         359 $child->finalize($st_ctx->trace);
415              
416 137         481 $ctx->release;
417              
418 137 100       347 die $err unless $ok;
419              
420 136 100       376 $? = $child_error if defined $child_error;
421              
422 136         350 return $st_hub->is_passing;
423             }
424              
425             sub name {
426 6     7 1 12 my $self = shift;
427 6         15 my $ctx = $self->ctx;
428 6         22 release $ctx, $ctx->hub->meta(__PACKAGE__, {})->{Name};
429             }
430              
431             sub reset { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
432 217     218 1 801 my ($self, %params) = @_;
433              
434 217         943 Test2::API::test2_unset_is_end();
435              
436             # We leave this a global because it has to be localized and localizing
437             # hash keys is just asking for pain. Also, it was documented.
438 217         400 $Level = 1;
439              
440             $self->{no_log_results} = $ENV{TEST_NO_LOG_RESULTS} ? 1 : 0
441 217 50       888 unless $params{singleton};
    100          
442              
443 217 50       754 $self->{Original_Pid} = Test2::API::test2_in_preload() ? -1 : $$;
444              
445 217         819 my $ctx = $self->ctx;
446 217         1356 my $hub = $ctx->hub;
447 217         1305 $ctx->release;
448 217 100       1083 unless ($params{singleton}) {
449 55         331 $hub->reset_state();
450 55         210 $hub->_tb_reset();
451             }
452              
453 217         792 $ctx = $self->ctx;
454              
455 217         1121 my $meta = $ctx->hub->meta(__PACKAGE__, {});
456             %$meta = (
457             Name => $0,
458             Ending => 0,
459             Done_Testing => undef,
460             Skip_All => 0,
461             Test_Results => [],
462             parent => $meta->{parent},
463 217         1742 );
464              
465 217 100       912 $self->{Exported_To} = undef unless $params{singleton};
466              
467 217   66     1189 $self->{Orig_Handles} ||= do {
468 209         845 my $format = $ctx->hub->format;
469 209         465 my $out;
470 209 100 66     2941 if ($format && $format->isa('Test2::Formatter::TAP')) {
471 208         2198 $out = $format->handles;
472             }
473 209 100       1388 $out ? [@$out] : [];
474             };
475              
476 217         940 $self->use_numbers(1);
477 217 100       1033 $self->no_header(0) unless $params{singleton};
478 217 100       927 $self->no_ending(0) unless $params{singleton};
479 217         1056 $self->reset_outputs;
480              
481 217         778 $ctx->release;
482              
483 217         561 return;
484             }
485              
486              
487             my %plan_cmds = (
488             no_plan => \&no_plan,
489             skip_all => \&skip_all,
490             tests => \&_plan_tests,
491             );
492              
493             sub plan {
494 282     283 1 1135 my( $self, $cmd, $arg ) = @_;
495              
496 282 100       868 return unless $cmd;
497              
498 208         606 my $ctx = $self->ctx;
499 208         973 my $hub = $ctx->hub;
500              
501 208 100       937 $ctx->throw("You tried to plan twice") if $hub->plan;
502              
503 206         566 local $Level = $Level + 1;
504              
505 206 100       810 if( my $method = $plan_cmds{$cmd} ) {
506 203         443 local $Level = $Level + 1;
507 203         652 $self->$method($arg);
508             }
509             else {
510 3         9 my @args = grep { defined } ( $cmd, $arg );
  6         18  
511 3         17 $ctx->throw("plan() doesn't understand @args");
512             }
513              
514 185         1735 release $ctx, 1;
515             }
516              
517              
518             sub _plan_tests {
519 166     167   453 my($self, $arg) = @_;
520              
521 166         508 my $ctx = $self->ctx;
522              
523 166 100       757 if($arg) {
    100          
524 163         403 local $Level = $Level + 1;
525 163         642 $self->expected_tests($arg);
526             }
527             elsif( !defined $arg ) {
528 1         5 $ctx->throw("Got an undefined number of tests");
529             }
530             else {
531 2         9 $ctx->throw("You said to run 0 tests");
532             }
533              
534 159         557 $ctx->release;
535             }
536              
537              
538             sub expected_tests {
539 252     253 1 543 my $self = shift;
540 252         588 my($max) = @_;
541              
542 252         764 my $ctx = $self->ctx;
543              
544 252 100       1140 if(@_) {
545 163 100       1413 $self->croak("Number of tests must be a positive integer. You gave it '$max'")
546             unless $max =~ /^\+?\d+$/;
547              
548 159         818 $ctx->plan($max);
549             }
550              
551 248         1006 my $hub = $ctx->hub;
552              
553 248         1084 $ctx->release;
554              
555 248         897 my $plan = $hub->plan;
556 248 100       1048 return 0 unless $plan;
557 202 100       1034 return 0 if $plan =~ m/\D/;
558 201         789 return $plan;
559             }
560              
561              
562             sub no_plan {
563 27     27 1 94 my($self, $arg) = @_;
564              
565 27         109 my $ctx = $self->ctx;
566              
567 27 100       173 if (defined $ctx->hub->plan) {
568 1         16 warn "Plan already set, no_plan() is a no-op, this will change to a hard failure in the future.";
569 1         9 $ctx->release;
570 1         3 return;
571             }
572              
573 26 100       85 $ctx->alert("no_plan takes no arguments") if $arg;
574              
575 26         92 $ctx->hub->plan('NO PLAN');
576              
577 26         98 release $ctx, 1;
578             }
579              
580              
581             sub done_testing {
582 68     68 1 323 my($self, $num_tests) = @_;
583              
584 68         413 my $ctx = $self->ctx;
585              
586 68         472 my $meta = $ctx->hub->meta(__PACKAGE__, {});
587              
588 68 100       444 if ($meta->{Done_Testing}) {
589 2         5 my ($file, $line) = @{$meta->{Done_Testing}}[1,2];
  2         8  
590 2         6 local $ctx->hub->{ended}; # OMG This is awful.
591 2         12 $self->ok(0, "done_testing() was already called at $file line $line");
592 2         8 $ctx->release;
593 2         7 return;
594             }
595 66         417 $meta->{Done_Testing} = [$ctx->trace->call];
596              
597 66         320 my $plan = $ctx->hub->plan;
598 66         305 my $count = $ctx->hub->count;
599              
600             # If done_testing() specified the number of tests, shut off no_plan
601 66 100 66     1062 if( defined $num_tests ) {
    50 33        
602 19 100 100     312 $ctx->plan($num_tests) if !$plan || $plan eq 'NO PLAN';
603             }
604             elsif ($count && defined $num_tests && $count != $num_tests) {
605 0         0 $self->ok(0, "planned to run @{[ $self->expected_tests ]} but done_testing() expects $num_tests");
  0         0  
606             }
607             else {
608 47         315 $num_tests = $self->current_test;
609             }
610              
611 66 100 100     347 if( $self->expected_tests && $num_tests != $self->expected_tests ) {
612 2         6 $self->ok(0, "planned to run @{[ $self->expected_tests ]} ".
  2         17  
613             "but done_testing() expects $num_tests");
614             }
615              
616 66 100 100     365 $ctx->plan($num_tests) if $ctx->hub->plan && $ctx->hub->plan eq 'NO PLAN';
617              
618 66         243 $ctx->hub->finalize($ctx->trace, 1);
619              
620 66         274 release $ctx, 1;
621             }
622              
623              
624             sub has_plan {
625 11     11 1 23 my $self = shift;
626              
627 11         32 my $ctx = $self->ctx;
628 11         50 my $plan = $ctx->hub->plan;
629 11         55 $ctx->release;
630              
631 11 100 100     91 return( $plan ) if $plan && $plan !~ m/\D/;
632 7 100 66     44 return('no_plan') if $plan && $plan eq 'NO PLAN';
633 2         8 return(undef);
634             }
635              
636              
637             sub skip_all {
638 12     12 1 45 my( $self, $reason ) = @_;
639              
640 12         39 my $ctx = $self->ctx;
641              
642 12   100     88 $ctx->hub->meta(__PACKAGE__, {})->{Skip_All} = $reason || 1;
643              
644             # Work around old perl bug
645 12 50       55 if ($] < 5.020000) {
646 0         0 my $begin = 0;
647 0         0 my $level = 0;
648 0         0 while (my @call = caller($level++)) {
649 0 0 0     0 last unless @call && $call[0];
650 0 0       0 next unless $call[3] =~ m/::BEGIN$/;
651 0         0 $begin++;
652 0         0 last;
653             }
654             # HACK!
655 0 0 0     0 die 'Label not found for "last T2_SUBTEST_WRAPPER"' if $begin && $ctx->hub->meta(__PACKAGE__, {})->{parent};
656             }
657              
658 12         70 $ctx->plan(0, SKIP => $reason);
659             }
660              
661              
662             sub exported_to {
663 251     251 1 758 my( $self, $pack ) = @_;
664              
665 251 100       732 if( defined $pack ) {
666 141         400 $self->{Exported_To} = $pack;
667             }
668 251         637 return $self->{Exported_To};
669             }
670              
671              
672             sub ok {
673 2130     2130 1 517800 my( $self, $test, $name ) = @_;
674              
675 2130         5125 my $ctx = $self->ctx;
676              
677             # $test might contain an object which we don't want to accidentally
678             # store, so we turn it into a boolean.
679 2130 100       6676 $test = $test ? 1 : 0;
680              
681             # In case $name is a string overloaded object, force it to stringify.
682 162     164   1573 no warnings qw/uninitialized numeric/;
  162         455  
  162         23104  
683 2130 100       5717 $name = "$name" if defined $name;
684              
685             # Profiling showed that the regex here was a huge time waster, doing the
686             # numeric addition first cuts our profile time from ~300ms to ~50ms
687 2130 100 100     11769 $self->diag(<<" ERR") if 0 + $name && $name =~ /^[\d\s]+$/;
688             You named your test '$name'. You shouldn't use numbers for your test names.
689             Very confusing.
690             ERR
691 162     164   1294 use warnings qw/uninitialized numeric/;
  162         371  
  162         119534  
692              
693 2130         4661 my $trace = $ctx->{trace};
694 2130         4787 my $hub = $ctx->{hub};
695              
696 2130 100       17757 my $result = {
697             ok => $test,
698             actual_ok => $test,
699             reason => '',
700             type => '',
701             (name => defined($name) ? $name : ''),
702             };
703              
704 2130 100       9504 $hub->{_meta}->{+__PACKAGE__}->{Test_Results}[ $hub->{count} ] = $result unless $self->{no_log_results};
705              
706 2130         3872 my $orig_name = $name;
707              
708 2130         3279 my @attrs;
709 2130         3783 my $subevents = delete $self->{subevents};
710 2130         3305 my $subtest_id = delete $self->{subtest_id};
711 2130         3387 my $subtest_uuid = delete $self->{subtest_uuid};
712 2130         3207 my $subtest_buffered = delete $self->{subtest_buffered};
713 2130         4719 my $epkg = 'Test2::Event::Ok';
714 2130 100       4694 if ($subevents) {
715 88         155 $epkg = 'Test2::Event::Subtest';
716 88         272 push @attrs => (subevents => $subevents, subtest_id => $subtest_id, subtest_uuid => $subtest_uuid, buffered => $subtest_buffered);
717             }
718              
719 2130         26915 my $e = bless {
720             trace => bless( {%$trace}, 'Test2::EventFacet::Trace'),
721             pass => $test,
722             name => $name,
723             _meta => {'Test::Builder' => $result},
724             effective_pass => $test,
725             @attrs,
726             }, $epkg;
727 2130         13956 $hub->send($e);
728              
729 2130 100       6006 $self->_ok_debug($trace, $orig_name) unless($test);
730              
731 2130         8853 $ctx->release;
732 2130         17665 return $test;
733             }
734              
735             sub _ok_debug {
736 476     476   724 my $self = shift;
737 476         1001 my ($trace, $orig_name) = @_;
738              
739 476         1182 my $is_todo = $self->in_todo;
740              
741 476 100       1211 my $msg = $is_todo ? "Failed (TODO)" : "Failed";
742              
743 476         1317 my (undef, $file, $line) = $trace->call;
744 476 100       1128 if (defined $orig_name) {
745 447         1898 $self->diag(qq[ $msg test '$orig_name'\n at $file line $line.\n]);
746             }
747             else {
748 29         202 $self->diag(qq[ $msg test at $file line $line.\n]);
749             }
750             }
751              
752             sub _diag_fh {
753 0     0   0 my $self = shift;
754 0         0 local $Level = $Level + 1;
755 0 0       0 return $self->in_todo ? $self->todo_output : $self->failure_output;
756             }
757              
758             sub _unoverload {
759 646     646   2161 my ($self, $type, $thing) = @_;
760              
761 646 100       1492 return unless ref $$thing;
762 500 50 100 455   2651 return unless blessed($$thing) || scalar $self->_try(sub{ $$thing->isa('UNIVERSAL') });
  455         2484  
763             {
764 45         87 local ($!, $@);
  45         141  
765 45         359 require overload;
766             }
767 45   100     164 my $string_meth = overload::Method( $$thing, $type ) || return;
768 8         419 $$thing = $$thing->$string_meth();
769             }
770              
771             sub _unoverload_str {
772 320     320   521 my $self = shift;
773              
774 320         827 $self->_unoverload( q[""], $_ ) for @_;
775             }
776              
777             sub _unoverload_num {
778 17     17   34 my $self = shift;
779              
780 17         88 $self->_unoverload( '0+', $_ ) for @_;
781              
782 17         29 for my $val (@_) {
783 23 100       47 next unless $self->_is_dualvar($$val);
784 1         4 $$val = $$val + 0;
785             }
786             }
787              
788             # This is a hack to detect a dualvar such as $!
789             sub _is_dualvar {
790 23     23   41 my( $self, $val ) = @_;
791              
792             # Objects are not dualvars.
793 23 50       43 return 0 if ref $val;
794              
795 162     164   1462 no warnings 'numeric';
  162         445  
  162         202245  
796 23         36 my $numval = $val + 0;
797 23   66     112 return ($numval != 0 and $numval ne $val ? 1 : 0);
798             }
799              
800              
801             sub is_eq {
802 506     506 1 2866 my( $self, $got, $expect, $name ) = @_;
803              
804 506         1346 my $ctx = $self->ctx;
805              
806 506         1338 local $Level = $Level + 1;
807              
808 506 100 100     2142 if( !defined $got || !defined $expect ) {
809             # undef only matches undef and nothing else
810 13   100     77 my $test = !defined $got && !defined $expect;
811              
812 13         50 $self->ok( $test, $name );
813 13 100       53 $self->_is_diag( $got, 'eq', $expect ) unless $test;
814 13         101 $ctx->release;
815 13         45 return $test;
816             }
817              
818 493         1522 release $ctx, $self->cmp_ok( $got, 'eq', $expect, $name );
819             }
820              
821              
822             sub is_num {
823 65     65 1 1542221 my( $self, $got, $expect, $name ) = @_;
824 65         480 my $ctx = $self->ctx;
825 65         303 local $Level = $Level + 1;
826              
827 65 100 66     596 if( !defined $got || !defined $expect ) {
828             # undef only matches undef and nothing else
829 1   33     6 my $test = !defined $got && !defined $expect;
830              
831 1         4 $self->ok( $test, $name );
832 1 50       4 $self->_is_diag( $got, '==', $expect ) unless $test;
833 1         4 $ctx->release;
834 1         4 return $test;
835             }
836              
837 64         389 release $ctx, $self->cmp_ok( $got, '==', $expect, $name );
838             }
839              
840              
841             sub _diag_fmt {
842 51     51   99 my( $self, $type, $val ) = @_;
843              
844 51 100       101 if( defined $$val ) {
845 46 100 100     325 if( $type eq 'eq' or $type eq 'ne' ) {
846             # quote and force string context
847 35         93 $$val = "'$$val'";
848             }
849             else {
850             # force numeric context
851 11         22 $self->_unoverload_num($val);
852             }
853             }
854             else {
855 5         12 $$val = 'undef';
856             }
857              
858 51         101 return;
859             }
860              
861              
862             sub _is_diag {
863 23     23   71 my( $self, $got, $type, $expect ) = @_;
864              
865 23         80 $self->_diag_fmt( $type, $_ ) for \$got, \$expect;
866              
867 23         59 local $Level = $Level + 1;
868 23         89 return $self->diag(<<"DIAGNOSTIC");
869             got: $got
870             expected: $expect
871             DIAGNOSTIC
872              
873             }
874              
875             sub _isnt_diag {
876 5     5   12 my( $self, $got, $type ) = @_;
877              
878 5         12 $self->_diag_fmt( $type, \$got );
879              
880 5         9 local $Level = $Level + 1;
881 5         16 return $self->diag(<<"DIAGNOSTIC");
882             got: $got
883             expected: anything else
884             DIAGNOSTIC
885             }
886              
887              
888             sub isnt_eq {
889 11     11 1 38 my( $self, $got, $dont_expect, $name ) = @_;
890 11         28 my $ctx = $self->ctx;
891 11         43 local $Level = $Level + 1;
892              
893 11 100 66     70 if( !defined $got || !defined $dont_expect ) {
894             # undef only matches undef and nothing else
895 4   66     15 my $test = defined $got || defined $dont_expect;
896              
897 4         14 $self->ok( $test, $name );
898 4 100       14 $self->_isnt_diag( $got, 'ne' ) unless $test;
899 4         11 $ctx->release;
900 4         10 return $test;
901             }
902              
903 7         27 release $ctx, $self->cmp_ok( $got, 'ne', $dont_expect, $name );
904             }
905              
906             sub isnt_num {
907 2     2 1 101924 my( $self, $got, $dont_expect, $name ) = @_;
908 2         75 my $ctx = $self->ctx;
909 2         33 local $Level = $Level + 1;
910              
911 2 100 66     56 if( !defined $got || !defined $dont_expect ) {
912             # undef only matches undef and nothing else
913 1   33     4 my $test = defined $got || defined $dont_expect;
914              
915 1         3 $self->ok( $test, $name );
916 1 50       4 $self->_isnt_diag( $got, '!=' ) unless $test;
917 1         3 $ctx->release;
918 1         2 return $test;
919             }
920              
921 1         44 release $ctx, $self->cmp_ok( $got, '!=', $dont_expect, $name );
922             }
923              
924              
925             sub like {
926 315     315 1 4753209 my( $self, $thing, $regex, $name ) = @_;
927 315         5436 my $ctx = $self->ctx;
928              
929 315         2744 local $Level = $Level + 1;
930              
931 315         4692 release $ctx, $self->_regex_ok( $thing, $regex, '=~', $name );
932             }
933              
934             sub unlike {
935 5     5 1 18 my( $self, $thing, $regex, $name ) = @_;
936 5         12 my $ctx = $self->ctx;
937              
938 5         15 local $Level = $Level + 1;
939              
940 5         13 release $ctx, $self->_regex_ok( $thing, $regex, '!~', $name );
941             }
942              
943              
944             my %numeric_cmps = map { ( $_, 1 ) } ( "<", "<=", ">", ">=", "==", "!=", "<=>" );
945              
946             # Bad, these are not comparison operators. Should we include more?
947             my %cmp_ok_bl = map { ( $_, 1 ) } ( "=", "+=", ".=", "x=", "^=", "|=", "||=", "&&=", "...");
948              
949             sub cmp_ok {
950 601     601 1 1652 my( $self, $got, $type, $expect, $name ) = @_;
951 601         1370 my $ctx = $self->ctx;
952              
953 601 100       2212 if ($cmp_ok_bl{$type}) {
954 2         10 $ctx->throw("$type is not a valid comparison operator in cmp_ok()");
955             }
956              
957 599         1720 my ($test, $succ);
958 599         0 my $error;
959             {
960             ## no critic (BuiltinFunctions::ProhibitStringyEval)
961              
962 599         959 local( $@, $!, $SIG{__DIE__} ); # isolate eval
  599         3347  
963              
964 599         2404 my($pack, $file, $line) = $ctx->trace->call();
965 599         1748 my $warning_bits = $ctx->trace->warning_bits;
966              
967             # This is so that warnings come out at the caller's level
968 599     96   52322 $succ = eval qq[
  96     53   3898  
  73     36   2350  
  56     26   1667  
  26     21   1554  
  21     18   985  
  18     12   796  
  12     12   517  
  12     11   533  
  11     11   508  
  11     11   487  
  11     10   524  
  10     8   396  
  8     8   402  
  8     8   393  
  8     8   537  
  8     7   359  
  7     6   245  
  6     6   239  
  6     6   241  
  6     6   233  
  6     6   253  
  6     6   220  
  6     6   209  
  6     6   224  
  6     6   245  
  6     6   275  
  6     5   239  
  5     5   187  
  5     5   181  
  5     5   212  
  5     5   190  
  5     5   181  
  5     5   193  
  5     5   180  
  5     5   189  
  5     5   212  
  5     5   200  
  5     5   212  
  5     5   217  
  5     5   181  
  5     5   186  
  5     5   193  
  5     5   204  
  5     5   179  
  5     5   184  
  5         204  
969             BEGIN {\${^WARNING_BITS} = \$warning_bits};
970             #line $line "(eval in cmp_ok) $file"
971             \$test = (\$got $type \$expect);
972             1;
973             ];
974 599         9756 $error = $@;
975             }
976 599         1444 local $Level = $Level + 1;
977 599         2022 my $ok = $self->ok( $test, $name );
978              
979             # Treat overloaded objects as numbers if we're asked to do a
980             # numeric comparison.
981             my $unoverload
982 599 100       2058 = $numeric_cmps{$type}
983             ? '_unoverload_num'
984             : '_unoverload_str';
985              
986 599 100       1439 $self->diag(<<"END") unless $succ;
987             An error occurred while using $type:
988             ------------------------------------
989             $error
990             ------------------------------------
991             END
992              
993 599 100       1278 unless($ok) {
994 28         137 $self->$unoverload( \$got, \$expect );
995              
996 28 100       199 if( $type =~ /^(eq|==)$/ ) {
    100          
997 19         59 $self->_is_diag( $got, $type, $expect );
998             }
999             elsif( $type =~ /^(ne|!=)$/ ) {
1000 162     164   1467 no warnings;
  162         414  
  162         11312  
1001 6   66     70 my $eq = ($got eq $expect || $got == $expect)
1002             && (
1003             (defined($got) xor defined($expect))
1004             || (length($got) != length($expect))
1005             );
1006 162     164   1145 use warnings;
  162         418  
  162         58794  
1007              
1008 6 100       15 if ($eq) {
1009 2         10 $self->_cmp_diag( $got, $type, $expect );
1010             }
1011             else {
1012 4         11 $self->_isnt_diag( $got, $type );
1013             }
1014             }
1015             else {
1016 3         21 $self->_cmp_diag( $got, $type, $expect );
1017             }
1018             }
1019 599         2030 return release $ctx, $ok;
1020             }
1021              
1022             sub _cmp_diag {
1023 5     5   17 my( $self, $got, $type, $expect ) = @_;
1024              
1025 5 100       24 $got = defined $got ? "'$got'" : 'undef';
1026 5 50       20 $expect = defined $expect ? "'$expect'" : 'undef';
1027              
1028 5         12 local $Level = $Level + 1;
1029 5         28 return $self->diag(<<"DIAGNOSTIC");
1030             $got
1031             $type
1032             $expect
1033             DIAGNOSTIC
1034             }
1035              
1036             sub _caller_context {
1037 319     319   881 my $self = shift;
1038              
1039 319         3171 my( $pack, $file, $line ) = $self->caller(1);
1040              
1041 319         2376 my $code = '';
1042 319 50 33     2617 $code .= "#line $line $file\n" if defined $file and defined $line;
1043              
1044 319         1393 return $code;
1045             }
1046              
1047              
1048             sub BAIL_OUT {
1049 2     2 1 5 my( $self, $reason ) = @_;
1050              
1051 2         7 my $ctx = $self->ctx;
1052              
1053 2         8 $self->{Bailed_Out} = 1;
1054              
1055 2         10 $ctx->bail($reason);
1056             }
1057              
1058              
1059             {
1060 162     164   1341 no warnings 'once';
  162         384  
  162         117720  
1061             *BAILOUT = \&BAIL_OUT;
1062             }
1063              
1064             sub skip {
1065 17     17 1 64 my( $self, $why, $name ) = @_;
1066 17   50     58 $why ||= '';
1067 17 100       54 $name = '' unless defined $name;
1068 17         80 $self->_unoverload_str( \$why );
1069              
1070 17         73 my $ctx = $self->ctx;
1071              
1072             $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1073             'ok' => 1,
1074             actual_ok => 1,
1075             name => $name,
1076             type => 'skip',
1077             reason => $why,
1078 17 50       168 } unless $self->{no_log_results};
1079              
1080 17         122 $name =~ s|#|\\#|g; # # in a name can confuse Test::Harness.
1081 17         59 $name =~ s{\n}{\n# }sg;
1082 17         48 $why =~ s{\n}{\n# }sg;
1083              
1084 17         74 my $tctx = $ctx->snapshot;
1085 17         82 $tctx->skip('', $why);
1086              
1087 17         87 return release $ctx, 1;
1088             }
1089              
1090              
1091             sub todo_skip {
1092 6     6 1 27 my( $self, $why ) = @_;
1093 6   50     17 $why ||= '';
1094              
1095 6         17 my $ctx = $self->ctx;
1096              
1097             $ctx->hub->meta(__PACKAGE__, {})->{Test_Results}[ $ctx->hub->count ] = {
1098             'ok' => 1,
1099             actual_ok => 0,
1100             name => '',
1101             type => 'todo_skip',
1102             reason => $why,
1103 6 50       58 } unless $self->{no_log_results};
1104              
1105 6         26 $why =~ s{\n}{\n# }sg;
1106 6         41 my $tctx = $ctx->snapshot;
1107 6         30 $tctx->send_event( 'Skip', todo => $why, todo_diag => 1, reason => $why, pass => 0);
1108              
1109 6         29 return release $ctx, 1;
1110             }
1111              
1112              
1113             sub maybe_regex {
1114 327     327 1 897 my( $self, $regex ) = @_;
1115 327         654 my $usable_regex = undef;
1116              
1117 327 100       1996 return $usable_regex unless defined $regex;
1118              
1119 326         818 my( $re, $opts );
1120              
1121             # Check for qr/foo/
1122 326 100 100     857 if( _is_qr($regex) ) {
    100          
1123 302         701 $usable_regex = $regex;
1124             }
1125             # Check for '/foo/' or 'm,foo,'
1126             elsif(( $re, $opts ) = $regex =~ m{^ /(.*)/ (\w*) $ }sx or
1127             ( undef, $re, $opts ) = $regex =~ m,^ m([^\w\s]) (.+) \1 (\w*) $,sx
1128             )
1129             {
1130 22 100       88 $usable_regex = length $opts ? "(?$opts)$re" : $re;
1131             }
1132              
1133 326         1033 return $usable_regex;
1134             }
1135              
1136             sub _is_qr {
1137 326     326   762 my $regex = shift;
1138              
1139             # is_regexp() checks for regexes in a robust manner, say if they're
1140             # blessed.
1141 326 50       2386 return re::is_regexp($regex) if defined &re::is_regexp;
1142 0         0 return ref $regex eq 'Regexp';
1143             }
1144              
1145             sub _regex_ok {
1146 320     320   3532 my( $self, $thing, $regex, $cmp, $name ) = @_;
1147              
1148 320         881 my $ok = 0;
1149 320         1162 my $usable_regex = $self->maybe_regex($regex);
1150 320 100       986 unless( defined $usable_regex ) {
1151 1         2 local $Level = $Level + 1;
1152 1         3 $ok = $self->ok( 0, $name );
1153 1         6 $self->diag(" '$regex' doesn't look much like a regex to me.");
1154 1         4 return $ok;
1155             }
1156              
1157             {
1158 319         618 my $test;
  319         543  
1159 319         3360 my $context = $self->_caller_context;
1160              
1161             {
1162             ## no critic (BuiltinFunctions::ProhibitStringyEval)
1163              
1164 319         886 local( $@, $!, $SIG{__DIE__} ); # isolate eval
  319         6840  
1165              
1166             # No point in issuing an uninit warning, they'll see it in the diagnostics
1167 162     164   1334 no warnings 'uninitialized';
  162         391  
  162         91535  
1168              
1169 319         35944 $test = eval $context . q{$test = $thing =~ /$usable_regex/ ? 1 : 0};
1170             }
1171              
1172 319 100       12627 $test = !$test if $cmp eq '!~';
1173              
1174 319         867 local $Level = $Level + 1;
1175 319         4498 $ok = $self->ok( $test, $name );
1176             }
1177              
1178 319 100       1019 unless($ok) {
1179 5 50       20 $thing = defined $thing ? "'$thing'" : 'undef';
1180 5 100       14 my $match = $cmp eq '=~' ? "doesn't match" : "matches";
1181              
1182 5         9 local $Level = $Level + 1;
1183 5         33 $self->diag( sprintf <<'DIAGNOSTIC', $thing, $match, $regex );
1184             %s
1185             %13s '%s'
1186             DIAGNOSTIC
1187              
1188             }
1189              
1190 319         4057 return $ok;
1191             }
1192              
1193              
1194             sub is_fh {
1195 1167     1167 1 1828 my $self = shift;
1196 1167         1601 my $maybe_fh = shift;
1197 1167 100       2286 return 0 unless defined $maybe_fh;
1198              
1199 1166 100       3624 return 1 if ref $maybe_fh eq 'GLOB'; # its a glob ref
1200 182 100       466 return 1 if ref \$maybe_fh eq 'GLOB'; # its a glob
1201              
1202             return eval { $maybe_fh->isa("IO::Handle") } ||
1203 180   66     319 eval { tied($maybe_fh)->can('TIEHANDLE') };
1204             }
1205              
1206              
1207             sub level {
1208 20     20 1 134 my( $self, $level ) = @_;
1209              
1210 20 100       64 if( defined $level ) {
1211 18         38 $Level = $level;
1212             }
1213 20         51 return $Level;
1214             }
1215              
1216              
1217             sub use_numbers {
1218 221     221 1 626 my( $self, $use_nums ) = @_;
1219              
1220 221         728 my $ctx = $self->ctx;
1221 221         1110 my $format = $ctx->hub->format;
1222 221 50 66     3502 unless ($format && $format->can('no_numbers') && $format->can('set_no_numbers')) {
      66        
1223 3 50       9 warn "The current formatter does not support 'use_numbers'" if $format;
1224 3         13 return release $ctx, 0;
1225             }
1226              
1227 218 100       1509 $format->set_no_numbers(!$use_nums) if defined $use_nums;
1228              
1229 218 100       771 return release $ctx, $format->no_numbers ? 0 : 1;
1230             }
1231              
1232             BEGIN {
1233 162     164   601 for my $method (qw(no_header no_diag)) {
1234 324         1042 my $set = "set_$method";
1235             my $code = sub {
1236 61     61   191 my( $self, $no ) = @_;
1237              
1238 61         176 my $ctx = $self->ctx;
1239 61         312 my $format = $ctx->hub->format;
1240 61 100 66     565 unless ($format && $format->can($set)) {
1241 1 50       3 warn "The current formatter does not support '$method'" if $format;
1242 1         4 $ctx->release;
1243             return
1244 1         4 }
1245              
1246 60 100       359 $format->$set($no) if defined $no;
1247              
1248 60 100       254 return release $ctx, $format->$method ? 1 : 0;
1249 324         1970 };
1250              
1251 162     164   1314 no strict 'refs'; ## no critic
  162         449  
  162         5498  
1252 324         266735 *$method = $code;
1253             }
1254             }
1255              
1256             sub no_ending {
1257 198     198 1 511 my( $self, $no ) = @_;
1258              
1259 198         542 my $ctx = $self->ctx;
1260              
1261 198 100       985 $ctx->hub->set_no_ending($no) if defined $no;
1262              
1263 198         595 return release $ctx, $ctx->hub->no_ending;
1264             }
1265              
1266             sub diag {
1267 616     616 1 1134 my $self = shift;
1268 616 100       1416 return unless @_;
1269              
1270 608 100       1318 my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
  613         2372  
1271              
1272 608 100       1757 if (Test2::API::test2_in_preload()) {
1273 1         3 chomp($text);
1274 1         8 $text =~ s/^/# /msg;
1275 1         6 print STDERR $text, "\n";
1276 1         3 return 0;
1277             }
1278              
1279 607         1386 my $ctx = $self->ctx;
1280 607         2589 $ctx->diag($text);
1281 607         2190 $ctx->release;
1282 607         1857 return 0;
1283             }
1284              
1285              
1286             sub note {
1287 13     13 1 35 my $self = shift;
1288 13 50       35 return unless @_;
1289              
1290 13 50       33 my $text = join '' => map {defined($_) ? $_ : 'undef'} @_;
  14         70  
1291              
1292 13 100       36 if (Test2::API::test2_in_preload()) {
1293 1         3 chomp($text);
1294 1         14 $text =~ s/^/# /msg;
1295 1         3 print STDOUT $text, "\n";
1296 1         5 return 0;
1297             }
1298              
1299 12         30 my $ctx = $self->ctx;
1300 12         55 $ctx->note($text);
1301 12         109 $ctx->release;
1302 12         48 return 0;
1303             }
1304              
1305              
1306             sub explain {
1307 5     5 1 12 my $self = shift;
1308              
1309 5         16 local ($@, $!);
1310 5         1269 require Data::Dumper;
1311              
1312             return map {
1313 5         13778 ref $_
1314 9 100       94 ? do {
1315 4         21 my $dumper = Data::Dumper->new( [$_] );
1316 4         109 $dumper->Indent(1)->Terse(1);
1317 4 50       98 $dumper->Sortkeys(1) if $dumper->can("Sortkeys");
1318 4         26 $dumper->Dump;
1319             }
1320             : $_
1321             } @_;
1322             }
1323              
1324              
1325             sub output {
1326 491     491 1 1767 my( $self, $fh ) = @_;
1327              
1328 491         1247 my $ctx = $self->ctx;
1329 491         1824 my $format = $ctx->hub->format;
1330 491         1642 $ctx->release;
1331 491 50 33     2722 return unless $format && $format->isa('Test2::Formatter::TAP');
1332              
1333 491 100       1600 $format->handles->[Test2::Formatter::TAP::OUT_STD()] = $self->_new_fh($fh)
1334             if defined $fh;
1335              
1336 491         1148 return $format->handles->[Test2::Formatter::TAP::OUT_STD()];
1337             }
1338              
1339             sub failure_output {
1340 484     484 1 1117 my( $self, $fh ) = @_;
1341              
1342 484         994 my $ctx = $self->ctx;
1343 484         1621 my $format = $ctx->hub->format;
1344 484         1610 $ctx->release;
1345 484 50 33     2268 return unless $format && $format->isa('Test2::Formatter::TAP');
1346              
1347 484 100       1456 $format->handles->[Test2::Formatter::TAP::OUT_ERR()] = $self->_new_fh($fh)
1348             if defined $fh;
1349              
1350 484         1165 return $format->handles->[Test2::Formatter::TAP::OUT_ERR()];
1351             }
1352              
1353             sub todo_output {
1354 482     482 1 1179 my( $self, $fh ) = @_;
1355              
1356 482         979 my $ctx = $self->ctx;
1357 482         1633 my $format = $ctx->hub->format;
1358 482         1455 $ctx->release;
1359 482 50 33     2454 return unless $format && $format->isa('Test::Builder::Formatter');
1360              
1361 482 100       1374 $format->handles->[Test::Builder::Formatter::OUT_TODO()] = $self->_new_fh($fh)
1362             if defined $fh;
1363              
1364 482         1093 return $format->handles->[Test::Builder::Formatter::OUT_TODO()];
1365             }
1366              
1367             sub _new_fh {
1368 1157     1157   4228 my $self = shift;
1369 1157         1741 my($file_or_fh) = shift;
1370              
1371 1157         1654 my $fh;
1372 1157 100       2509 if( $self->is_fh($file_or_fh) ) {
    100          
1373 986         1513 $fh = $file_or_fh;
1374             }
1375             elsif( ref $file_or_fh eq 'SCALAR' ) {
1376             # Scalar refs as filehandles was added in 5.8.
1377 170 50       368 if( $] >= 5.008 ) {
1378 170 50       1774 open $fh, ">>", $file_or_fh
1379             or $self->croak("Can't open scalar ref $file_or_fh: $!");
1380             }
1381             # Emulate scalar ref filehandles with a tie.
1382             else {
1383 0 0       0 $fh = Test::Builder::IO::Scalar->new($file_or_fh)
1384             or $self->croak("Can't tie scalar ref $file_or_fh");
1385             }
1386             }
1387             else {
1388 1 50       138 open $fh, ">", $file_or_fh
1389             or $self->croak("Can't open test output log $file_or_fh: $!");
1390 1         15 _autoflush($fh);
1391             }
1392              
1393 1157         19090 return $fh;
1394             }
1395              
1396             sub _autoflush {
1397 1     1   3 my($fh) = shift;
1398 1         5 my $old_fh = select $fh;
1399 1         4 $| = 1;
1400 1         3 select $old_fh;
1401              
1402 1         3 return;
1403             }
1404              
1405              
1406             sub reset_outputs {
1407 221     221 1 650 my $self = shift;
1408              
1409 221         751 my $ctx = $self->ctx;
1410 221         1082 my $format = $ctx->hub->format;
1411 221         951 $ctx->release;
1412 221 100 66     1708 return unless $format && $format->isa('Test2::Formatter::TAP');
1413 219 50       867 $format->set_handles([@{$self->{Orig_Handles}}]) if $self->{Orig_Handles};
  219         1818  
1414              
1415 219         798 return;
1416             }
1417              
1418              
1419             sub carp {
1420 1     1 1 18 my $self = shift;
1421 1         4 my $ctx = $self->ctx;
1422 1         12 $ctx->alert(join "", @_);
1423 1         10 $ctx->release;
1424             }
1425              
1426             sub croak {
1427 7     7 1 26 my $self = shift;
1428 7         18 my $ctx = $self->ctx;
1429 7         44 $ctx->throw(join "", @_);
1430 0         0 $ctx->release;
1431             }
1432              
1433              
1434             sub current_test {
1435 506     506 1 1119 my( $self, $num ) = @_;
1436              
1437 506         1318 my $ctx = $self->ctx;
1438 506         1633 my $hub = $ctx->hub;
1439              
1440 506 100       1255 if( defined $num ) {
1441 307         911 $hub->set_count($num);
1442              
1443 307 50       717 unless ($self->{no_log_results}) {
1444             # If the test counter is being pushed forward fill in the details.
1445 307         645 my $test_results = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1446 307 100       1014 if ($num > @$test_results) {
    100          
1447 136 100       367 my $start = @$test_results ? @$test_results : 0;
1448 136         401 for ($start .. $num - 1) {
1449 4528         10667 $test_results->[$_] = {
1450             'ok' => 1,
1451             actual_ok => undef,
1452             reason => 'incrementing test number',
1453             type => 'unknown',
1454             name => undef
1455             };
1456             }
1457             }
1458             # If backward, wipe history. Its their funeral.
1459             elsif ($num < @$test_results) {
1460 147         235 $#{$test_results} = $num - 1;
  147         2513  
1461             }
1462             }
1463             }
1464 506         1424 return release $ctx, $hub->count;
1465             }
1466              
1467              
1468             sub is_passing {
1469 411     411 1 649 my $self = shift;
1470              
1471 411         791 my $ctx = $self->ctx;
1472 411         1308 my $hub = $ctx->hub;
1473              
1474 411 100       960 if( @_ ) {
1475 264         445 my ($bool) = @_;
1476 264 100       886 $hub->set_failed(0) if $bool;
1477 264         734 $hub->is_passing($bool);
1478             }
1479              
1480 411         1009 return release $ctx, $hub->is_passing;
1481             }
1482              
1483              
1484             sub summary {
1485 6     6 1 36 my($self) = shift;
1486              
1487 6 50       21 return if $self->{no_log_results};
1488              
1489 6         19 my $ctx = $self->ctx;
1490 6         27 my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1491 6         27 $ctx->release;
1492 6 50       18 return map { $_ ? $_->{'ok'} : () } @$data;
  14         47  
1493             }
1494              
1495              
1496             sub details {
1497 5     5 1 23 my $self = shift;
1498              
1499 5 100       24 return if $self->{no_log_results};
1500              
1501 3         9 my $ctx = $self->ctx;
1502 3         14 my $data = $ctx->hub->meta(__PACKAGE__, {})->{Test_Results};
1503 3         21 $ctx->release;
1504 3         12 return @$data;
1505             }
1506              
1507              
1508             sub find_TODO {
1509 298     298 1 724 my( $self, $pack, $set, $new_value ) = @_;
1510              
1511 298         651 my $ctx = $self->ctx;
1512              
1513 298   33     1307 $pack ||= $ctx->trace->package || $self->exported_to;
      66        
1514 298         1046 $ctx->release;
1515              
1516 298 50       722 return unless $pack;
1517              
1518 162     164   1489 no strict 'refs'; ## no critic
  162         429  
  162         6180  
1519 162     164   1114 no warnings 'once';
  162         431  
  162         27824  
1520 298         456 my $old_value = ${ $pack . '::TODO' };
  298         879  
1521 298 50       655 $set and ${ $pack . '::TODO' } = $new_value;
  298         654  
1522 298         970 return $old_value;
1523             }
1524              
1525             sub todo {
1526 29     29 1 78 my( $self, $pack ) = @_;
1527              
1528 29         54 local $Level = $Level + 1;
1529 29         61 my $ctx = $self->ctx;
1530 29         117 $ctx->release;
1531              
1532 29         96 my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1533 29 100 100     137 return $meta->[-1]->[1] if $meta && @$meta;
1534              
1535 24   33     174 $pack ||= $ctx->trace->package;
1536              
1537 24 50       65 return unless $pack;
1538              
1539 162     164   1250 no strict 'refs'; ## no critic
  162         386  
  162         5990  
1540 162     164   1012 no warnings 'once';
  162         429  
  162         24441  
1541 24         42 return ${ $pack . '::TODO' };
  24         132  
1542             }
1543              
1544             sub in_todo {
1545 478     478 1 717 my $self = shift;
1546              
1547 478         836 local $Level = $Level + 1;
1548 478         1052 my $ctx = $self->ctx;
1549 478         2205 $ctx->release;
1550              
1551 478         1458 my $meta = $ctx->hub->meta(__PACKAGE__, {todo => []})->{todo};
1552 478 100 100     2226 return 1 if $meta && @$meta;
1553              
1554 314   50     802 my $pack = $ctx->trace->package || return 0;
1555              
1556 162     163   1229 no strict 'refs'; ## no critic
  162         394  
  162         5880  
1557 162     163   948 no warnings 'once';
  162         388  
  162         217589  
1558 314         583 my $todo = ${ $pack . '::TODO' };
  314         1010  
1559              
1560 314 100       1172 return 0 unless defined $todo;
1561 89 100       256 return 0 if "$todo" eq '';
1562 87         324 return 1;
1563             }
1564              
1565             sub todo_start {
1566 90     90 1 201 my $self = shift;
1567 90 100       240 my $message = @_ ? shift : '';
1568              
1569 90         200 my $ctx = $self->ctx;
1570              
1571 90         320 my $hub = $ctx->hub;
1572             my $filter = $hub->pre_filter(sub {
1573 729     729   1276 my ($active_hub, $e) = @_;
1574              
1575             # Turn a diag into a todo diag
1576 729 100       2711 return Test::Builder::TodoDiag->new(%$e) if ref($e) eq 'Test2::Event::Diag';
1577              
1578             # Set todo on ok's
1579 435 100 100     2002 if ($hub == $active_hub && $e->isa('Test2::Event::Ok')) {
1580 176         593 $e->set_todo($message);
1581 176         530 $e->set_effective_pass(1);
1582              
1583 176 50       465 if (my $result = $e->get_meta(__PACKAGE__)) {
1584 176   100     687 $result->{reason} ||= $message;
1585 176   100     629 $result->{type} ||= 'todo';
1586 176         295 $result->{ok} = 1;
1587             }
1588             }
1589              
1590 435         924 return $e;
1591 90         675 }, inherit => 1);
1592              
1593 90         147 push @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}} => [$filter, $message];
  90         221  
1594              
1595 90         367 $ctx->release;
1596              
1597 90         280 return;
1598             }
1599              
1600             sub todo_end {
1601 91     91 1 170 my $self = shift;
1602              
1603 91         192 my $ctx = $self->ctx;
1604              
1605 91         207 my $set = pop @{$ctx->hub->meta(__PACKAGE__, {todo => []})->{todo}};
  91         336  
1606              
1607 91 100       293 $ctx->throw('todo_end() called without todo_start()') unless $set;
1608              
1609 90         218 $ctx->hub->pre_unfilter($set->[0]);
1610              
1611 90         312 $ctx->release;
1612              
1613 90         726 return;
1614             }
1615              
1616              
1617             sub caller { ## no critic (Subroutines::ProhibitBuiltinHomonyms)
1618 340     340 1 1094 my( $self ) = @_;
1619              
1620 340         996 my $ctx = $self->ctx;
1621              
1622 340         5143 my $trace = $ctx->trace;
1623 340         5800 $ctx->release;
1624 340 50       5967 return wantarray ? $trace->call : $trace->package;
1625             }
1626              
1627              
1628             sub _try {
1629 544     544   1276 my( $self, $code, %opts ) = @_;
1630              
1631 544         815 my $error;
1632             my $return;
1633             {
1634 544         720 local $!; # eval can mess up $!
  544         1478  
1635 544         727 local $@; # don't set $@ in the test
1636 544         1385 local $SIG{__DIE__}; # don't trip an outside DIE handler.
1637 544         881 $return = eval { $code->() };
  544         884  
1638 544         2072 $error = $@;
1639             }
1640              
1641 544 100 100     1875 die $error if $error and $opts{die_on_fail};
1642              
1643 543 100       2963 return wantarray ? ( $return, $error ) : $return;
1644             }
1645              
1646             sub _ending {
1647 149     149   846 my $self = shift;
1648 149         500 my ($ctx, $real_exit_code, $new) = @_;
1649              
1650 149 100       800 unless ($ctx) {
1651 9         28 my $octx = $self->ctx;
1652 9         49 $ctx = $octx->snapshot;
1653 9         31 $octx->release;
1654             }
1655              
1656 149 50       979 return if $ctx->hub->no_ending;
1657 149 50       859 return if $ctx->hub->meta(__PACKAGE__, {})->{Ending}++;
1658              
1659             # Don't bother with an ending if this is a forked copy. Only the parent
1660             # should do the ending.
1661 149 50       1477 return unless $self->{Original_Pid} == $$;
1662              
1663 149         731 my $hub = $ctx->hub;
1664 149 50       713 return if $hub->bailed_out;
1665              
1666 149         728 my $plan = $hub->plan;
1667 149         664 my $count = $hub->count;
1668 149         720 my $failed = $hub->failed;
1669 149         703 my $passed = $hub->is_passing;
1670 149 100 100     954 return unless $plan || $count || $failed;
      66        
1671              
1672             # Ran tests but never declared a plan or hit done_testing
1673 146 100 66     634 if( !$hub->plan and $hub->count ) {
1674 1         13 $self->diag("Tests were run but no plan was declared and done_testing() was not seen.");
1675              
1676 1 50       3 if($real_exit_code) {
1677 0         0 $self->diag(<<"FAIL");
1678             Looks like your test exited with $real_exit_code just after $count.
1679             FAIL
1680 0   0     0 $$new ||= $real_exit_code;
1681 0         0 return;
1682             }
1683              
1684             # But if the tests ran, handle exit code.
1685 1 50       4 if($failed > 0) {
1686 0 0       0 my $exit_code = $failed <= 254 ? $failed : 254;
1687 0   0     0 $$new ||= $exit_code;
1688 0         0 return;
1689             }
1690              
1691 1   50     5 $$new ||= 254;
1692 1         3 return;
1693             }
1694              
1695 145 100 66     800 if ($real_exit_code && !$count) {
1696 1         13 $self->diag("Looks like your test exited with $real_exit_code before it could output anything.");
1697 1   33     4 $$new ||= $real_exit_code;
1698 1         5 return;
1699             }
1700              
1701 144 100 66     1235 return if $plan && "$plan" eq 'SKIP';
1702              
1703 136 100       608 if (!$count) {
1704 1         4 $self->diag('No tests run!');
1705 1   50     6 $$new ||= 255;
1706 1         4 return;
1707             }
1708              
1709 135 50       613 if ($real_exit_code) {
1710 0         0 $self->diag(<<"FAIL");
1711             Looks like your test exited with $real_exit_code just after $count.
1712             FAIL
1713 0   0     0 $$new ||= $real_exit_code;
1714 0         0 return;
1715             }
1716              
1717 135 100       576 if ($plan eq 'NO PLAN') {
1718 3         13 $ctx->plan( $count );
1719 3         11 $plan = $hub->plan;
1720             }
1721              
1722             # Figure out if we passed or failed and print helpful messages.
1723 135         435 my $num_extra = $count - $plan;
1724              
1725 135 100       620 if ($num_extra != 0) {
1726 4 100       16 my $s = $plan == 1 ? '' : 's';
1727 4         26 $self->diag(<<"FAIL");
1728             Looks like you planned $plan test$s but ran $count.
1729             FAIL
1730             }
1731              
1732 135 100       569 if ($failed) {
1733 7 100       31 my $s = $failed == 1 ? '' : 's';
1734              
1735 7 100       26 my $qualifier = $num_extra == 0 ? '' : ' run';
1736              
1737 7         45 $self->diag(<<"FAIL");
1738             Looks like you failed $failed test$s of $count$qualifier.
1739             FAIL
1740             }
1741              
1742 135 50 100     957 if (!$passed && !$failed && $count && !$num_extra) {
      66        
      66        
1743 0         0 $ctx->diag(<<"FAIL");
1744             All assertions passed, but errors were encountered.
1745             FAIL
1746             }
1747              
1748 135         373 my $exit_code = 0;
1749 135 100       992 if ($failed) {
    100          
    50          
1750 7 50       50 $exit_code = $failed <= 254 ? $failed : 254;
1751             }
1752             elsif ($num_extra != 0) {
1753 1         2 $exit_code = 255;
1754             }
1755             elsif (!$passed) {
1756 0         0 $exit_code = 255;
1757             }
1758              
1759 135   66     1008 $$new ||= $exit_code;
1760 135         893 return;
1761             }
1762              
1763             # Some things used this even though it was private... I am looking at you
1764             # Test::Builder::Prefix...
1765             sub _print_comment {
1766 0     0   0 my( $self, $fh, @msgs ) = @_;
1767              
1768 0 0       0 return if $self->no_diag;
1769 0 0       0 return unless @msgs;
1770              
1771             # Prevent printing headers when compiling (i.e. -c)
1772 0 0       0 return if $^C;
1773              
1774             # Smash args together like print does.
1775             # Convert undef to 'undef' so its readable.
1776 0 0       0 my $msg = join '', map { defined($_) ? $_ : 'undef' } @msgs;
  0         0  
1777              
1778             # Escape the beginning, _print will take care of the rest.
1779 0         0 $msg =~ s/^/# /;
1780              
1781 0         0 local( $\, $", $, ) = ( undef, ' ', '' );
1782 0         0 print $fh $msg;
1783              
1784 0         0 return 0;
1785             }
1786              
1787             # This is used by Test::SharedFork to turn on IPC after the fact. Not
1788             # documenting because I do not want it used. The method name is borrowed from
1789             # Test::Builder 2
1790             # Once Test2 stuff goes stable this method will be removed and Test::SharedFork
1791             # will be made smarter.
1792             sub coordinate_forks {
1793 0     0 0 0 my $self = shift;
1794              
1795             {
1796 0         0 local ($@, $!);
  0         0  
1797 0         0 require Test2::IPC;
1798             }
1799 0         0 Test2::IPC->import;
1800 0         0 Test2::API::test2_ipc_enable_polling();
1801 0         0 Test2::API::test2_load();
1802 0         0 my $ipc = Test2::IPC::apply_ipc($self->{Stack});
1803 0         0 $ipc->set_no_fatal(1);
1804 0         0 Test2::API::test2_no_wait(1);
1805             }
1806              
1807 2     2 1 13 sub no_log_results { $_[0]->{no_log_results} = 1 }
1808              
1809             1;
1810              
1811             __END__
1812              
1813             =head1 NAME
1814              
1815             Test::Builder - Backend for building test libraries
1816              
1817             =head1 SYNOPSIS
1818              
1819             package My::Test::Module;
1820             use base 'Test::Builder::Module';
1821              
1822             my $CLASS = __PACKAGE__;
1823              
1824             sub ok {
1825             my($test, $name) = @_;
1826             my $tb = $CLASS->builder;
1827              
1828             $tb->ok($test, $name);
1829             }
1830              
1831              
1832             =head1 DESCRIPTION
1833              
1834             L<Test::Simple> and L<Test::More> have proven to be popular testing modules,
1835             but they're not always flexible enough. Test::Builder provides a
1836             building block upon which to write your own test libraries I<which can
1837             work together>.
1838              
1839             =head2 Construction
1840              
1841             =over 4
1842              
1843             =item B<new>
1844              
1845             my $Test = Test::Builder->new;
1846              
1847             Returns a Test::Builder object representing the current state of the
1848             test.
1849              
1850             Since you only run one test per program C<new> always returns the same
1851             Test::Builder object. No matter how many times you call C<new()>, you're
1852             getting the same object. This is called a singleton. This is done so that
1853             multiple modules share such global information as the test counter and
1854             where test output is going.
1855              
1856             If you want a completely new Test::Builder object different from the
1857             singleton, use C<create>.
1858              
1859             =item B<create>
1860              
1861             my $Test = Test::Builder->create;
1862              
1863             Ok, so there can be more than one Test::Builder object and this is how
1864             you get it. You might use this instead of C<new()> if you're testing
1865             a Test::Builder based module, but otherwise you probably want C<new>.
1866              
1867             B<NOTE>: the implementation is not complete. C<level>, for example, is still
1868             shared by B<all> Test::Builder objects, even ones created using this method.
1869             Also, the method name may change in the future.
1870              
1871             =item B<subtest>
1872              
1873             $builder->subtest($name, \&subtests, @args);
1874              
1875             See documentation of C<subtest> in Test::More.
1876              
1877             C<subtest> also, and optionally, accepts arguments which will be passed to the
1878             subtests reference.
1879              
1880             =item B<name>
1881              
1882             diag $builder->name;
1883              
1884             Returns the name of the current builder. Top level builders default to C<$0>
1885             (the name of the executable). Child builders are named via the C<child>
1886             method. If no name is supplied, will be named "Child of $parent->name".
1887              
1888             =item B<reset>
1889              
1890             $Test->reset;
1891              
1892             Reinitializes the Test::Builder singleton to its original state.
1893             Mostly useful for tests run in persistent environments where the same
1894             test might be run multiple times in the same process.
1895              
1896             =back
1897              
1898             =head2 Setting up tests
1899              
1900             These methods are for setting up tests and declaring how many there
1901             are. You usually only want to call one of these methods.
1902              
1903             =over 4
1904              
1905             =item B<plan>
1906              
1907             $Test->plan('no_plan');
1908             $Test->plan( skip_all => $reason );
1909             $Test->plan( tests => $num_tests );
1910              
1911             A convenient way to set up your tests. Call this and Test::Builder
1912             will print the appropriate headers and take the appropriate actions.
1913              
1914             If you call C<plan()>, don't call any of the other methods below.
1915              
1916             =item B<expected_tests>
1917              
1918             my $max = $Test->expected_tests;
1919             $Test->expected_tests($max);
1920              
1921             Gets/sets the number of tests we expect this test to run and prints out
1922             the appropriate headers.
1923              
1924              
1925             =item B<no_plan>
1926              
1927             $Test->no_plan;
1928              
1929             Declares that this test will run an indeterminate number of tests.
1930              
1931              
1932             =item B<done_testing>
1933              
1934             $Test->done_testing();
1935             $Test->done_testing($num_tests);
1936              
1937             Declares that you are done testing, no more tests will be run after this point.
1938              
1939             If a plan has not yet been output, it will do so.
1940              
1941             $num_tests is the number of tests you planned to run. If a numbered
1942             plan was already declared, and if this contradicts, a failing test
1943             will be run to reflect the planning mistake. If C<no_plan> was declared,
1944             this will override.
1945              
1946             If C<done_testing()> is called twice, the second call will issue a
1947             failing test.
1948              
1949             If C<$num_tests> is omitted, the number of tests run will be used, like
1950             no_plan.
1951              
1952             C<done_testing()> is, in effect, used when you'd want to use C<no_plan>, but
1953             safer. You'd use it like so:
1954              
1955             $Test->ok($a == $b);
1956             $Test->done_testing();
1957              
1958             Or to plan a variable number of tests:
1959              
1960             for my $test (@tests) {
1961             $Test->ok($test);
1962             }
1963             $Test->done_testing(scalar @tests);
1964              
1965              
1966             =item B<has_plan>
1967              
1968             $plan = $Test->has_plan
1969              
1970             Find out whether a plan has been defined. C<$plan> is either C<undef> (no plan
1971             has been set), C<no_plan> (indeterminate # of tests) or an integer (the number
1972             of expected tests).
1973              
1974             =item B<skip_all>
1975              
1976             $Test->skip_all;
1977             $Test->skip_all($reason);
1978              
1979             Skips all the tests, using the given C<$reason>. Exits immediately with 0.
1980              
1981             =item B<exported_to>
1982              
1983             my $pack = $Test->exported_to;
1984             $Test->exported_to($pack);
1985              
1986             Tells Test::Builder what package you exported your functions to.
1987              
1988             This method isn't terribly useful since modules which share the same
1989             Test::Builder object might get exported to different packages and only
1990             the last one will be honored.
1991              
1992             =back
1993              
1994             =head2 Running tests
1995              
1996             These actually run the tests, analogous to the functions in Test::More.
1997              
1998             They all return true if the test passed, false if the test failed.
1999              
2000             C<$name> is always optional.
2001              
2002             =over 4
2003              
2004             =item B<ok>
2005              
2006             $Test->ok($test, $name);
2007              
2008             Your basic test. Pass if C<$test> is true, fail if $test is false. Just
2009             like Test::Simple's C<ok()>.
2010              
2011             =item B<is_eq>
2012              
2013             $Test->is_eq($got, $expected, $name);
2014              
2015             Like Test::More's C<is()>. Checks if C<$got eq $expected>. This is the
2016             string version.
2017              
2018             C<undef> only ever matches another C<undef>.
2019              
2020             =item B<is_num>
2021              
2022             $Test->is_num($got, $expected, $name);
2023              
2024             Like Test::More's C<is()>. Checks if C<$got == $expected>. This is the
2025             numeric version.
2026              
2027             C<undef> only ever matches another C<undef>.
2028              
2029             =item B<isnt_eq>
2030              
2031             $Test->isnt_eq($got, $dont_expect, $name);
2032              
2033             Like L<Test::More>'s C<isnt()>. Checks if C<$got ne $dont_expect>. This is
2034             the string version.
2035              
2036             =item B<isnt_num>
2037              
2038             $Test->isnt_num($got, $dont_expect, $name);
2039              
2040             Like L<Test::More>'s C<isnt()>. Checks if C<$got ne $dont_expect>. This is
2041             the numeric version.
2042              
2043             =item B<like>
2044              
2045             $Test->like($thing, qr/$regex/, $name);
2046             $Test->like($thing, '/$regex/', $name);
2047              
2048             Like L<Test::More>'s C<like()>. Checks if $thing matches the given C<$regex>.
2049              
2050             =item B<unlike>
2051              
2052             $Test->unlike($thing, qr/$regex/, $name);
2053             $Test->unlike($thing, '/$regex/', $name);
2054              
2055             Like L<Test::More>'s C<unlike()>. Checks if $thing B<does not match> the
2056             given C<$regex>.
2057              
2058             =item B<cmp_ok>
2059              
2060             $Test->cmp_ok($thing, $type, $that, $name);
2061              
2062             Works just like L<Test::More>'s C<cmp_ok()>.
2063              
2064             $Test->cmp_ok($big_num, '!=', $other_big_num);
2065              
2066             =back
2067              
2068             =head2 Other Testing Methods
2069              
2070             These are methods which are used in the course of writing a test but are not themselves tests.
2071              
2072             =over 4
2073              
2074             =item B<BAIL_OUT>
2075              
2076             $Test->BAIL_OUT($reason);
2077              
2078             Indicates to the L<Test::Harness> that things are going so badly all
2079             testing should terminate. This includes running any additional test
2080             scripts.
2081              
2082             It will exit with 255.
2083              
2084             =for deprecated
2085             BAIL_OUT() used to be BAILOUT()
2086              
2087             =item B<skip>
2088              
2089             $Test->skip;
2090             $Test->skip($why);
2091              
2092             Skips the current test, reporting C<$why>.
2093              
2094             =item B<todo_skip>
2095              
2096             $Test->todo_skip;
2097             $Test->todo_skip($why);
2098              
2099             Like C<skip()>, only it will declare the test as failing and TODO. Similar
2100             to
2101              
2102             print "not ok $tnum # TODO $why\n";
2103              
2104             =begin _unimplemented
2105              
2106             =item B<skip_rest>
2107              
2108             $Test->skip_rest;
2109             $Test->skip_rest($reason);
2110              
2111             Like C<skip()>, only it skips all the rest of the tests you plan to run
2112             and terminates the test.
2113              
2114             If you're running under C<no_plan>, it skips once and terminates the
2115             test.
2116              
2117             =end _unimplemented
2118              
2119             =back
2120              
2121              
2122             =head2 Test building utility methods
2123              
2124             These methods are useful when writing your own test methods.
2125              
2126             =over 4
2127              
2128             =item B<maybe_regex>
2129              
2130             $Test->maybe_regex(qr/$regex/);
2131             $Test->maybe_regex('/$regex/');
2132              
2133             This method used to be useful back when Test::Builder worked on Perls
2134             before 5.6 which didn't have qr//. Now its pretty useless.
2135              
2136             Convenience method for building testing functions that take regular
2137             expressions as arguments.
2138              
2139             Takes a quoted regular expression produced by C<qr//>, or a string
2140             representing a regular expression.
2141              
2142             Returns a Perl value which may be used instead of the corresponding
2143             regular expression, or C<undef> if its argument is not recognized.
2144              
2145             For example, a version of C<like()>, sans the useful diagnostic messages,
2146             could be written as:
2147              
2148             sub laconic_like {
2149             my ($self, $thing, $regex, $name) = @_;
2150             my $usable_regex = $self->maybe_regex($regex);
2151             die "expecting regex, found '$regex'\n"
2152             unless $usable_regex;
2153             $self->ok($thing =~ m/$usable_regex/, $name);
2154             }
2155              
2156              
2157             =item B<is_fh>
2158              
2159             my $is_fh = $Test->is_fh($thing);
2160              
2161             Determines if the given C<$thing> can be used as a filehandle.
2162              
2163             =cut
2164              
2165              
2166             =back
2167              
2168              
2169             =head2 Test style
2170              
2171              
2172             =over 4
2173              
2174             =item B<level>
2175              
2176             $Test->level($how_high);
2177              
2178             How far up the call stack should C<$Test> look when reporting where the
2179             test failed.
2180              
2181             Defaults to 1.
2182              
2183             Setting C<$Test::Builder::Level> overrides. This is typically useful
2184             localized:
2185              
2186             sub my_ok {
2187             my $test = shift;
2188              
2189             local $Test::Builder::Level = $Test::Builder::Level + 1;
2190             $TB->ok($test);
2191             }
2192              
2193             To be polite to other functions wrapping your own you usually want to increment C<$Level> rather than set it to a constant.
2194              
2195             =item B<use_numbers>
2196              
2197             $Test->use_numbers($on_or_off);
2198              
2199             Whether or not the test should output numbers. That is, this if true:
2200              
2201             ok 1
2202             ok 2
2203             ok 3
2204              
2205             or this if false
2206              
2207             ok
2208             ok
2209             ok
2210              
2211             Most useful when you can't depend on the test output order, such as
2212             when threads or forking is involved.
2213              
2214             Defaults to on.
2215              
2216             =item B<no_diag>
2217              
2218             $Test->no_diag($no_diag);
2219              
2220             If set true no diagnostics will be printed. This includes calls to
2221             C<diag()>.
2222              
2223             =item B<no_ending>
2224              
2225             $Test->no_ending($no_ending);
2226              
2227             Normally, Test::Builder does some extra diagnostics when the test
2228             ends. It also changes the exit code as described below.
2229              
2230             If this is true, none of that will be done.
2231              
2232             =item B<no_header>
2233              
2234             $Test->no_header($no_header);
2235              
2236             If set to true, no "1..N" header will be printed.
2237              
2238             =back
2239              
2240             =head2 Output
2241              
2242             Controlling where the test output goes.
2243              
2244             It's ok for your test to change where STDOUT and STDERR point to,
2245             Test::Builder's default output settings will not be affected.
2246              
2247             =over 4
2248              
2249             =item B<diag>
2250              
2251             $Test->diag(@msgs);
2252              
2253             Prints out the given C<@msgs>. Like C<print>, arguments are simply
2254             appended together.
2255              
2256             Normally, it uses the C<failure_output()> handle, but if this is for a
2257             TODO test, the C<todo_output()> handle is used.
2258              
2259             Output will be indented and marked with a # so as not to interfere
2260             with test output. A newline will be put on the end if there isn't one
2261             already.
2262              
2263             We encourage using this rather than calling print directly.
2264              
2265             Returns false. Why? Because C<diag()> is often used in conjunction with
2266             a failing test (C<ok() || diag()>) it "passes through" the failure.
2267              
2268             return ok(...) || diag(...);
2269              
2270             =for blame transfer
2271             Mark Fowler <mark@twoshortplanks.com>
2272              
2273             =item B<note>
2274              
2275             $Test->note(@msgs);
2276              
2277             Like C<diag()>, but it prints to the C<output()> handle so it will not
2278             normally be seen by the user except in verbose mode.
2279              
2280             =item B<explain>
2281              
2282             my @dump = $Test->explain(@msgs);
2283              
2284             Will dump the contents of any references in a human readable format.
2285             Handy for things like...
2286              
2287             is_deeply($have, $want) || diag explain $have;
2288              
2289             or
2290              
2291             is_deeply($have, $want) || note explain $have;
2292              
2293             =item B<output>
2294              
2295             =item B<failure_output>
2296              
2297             =item B<todo_output>
2298              
2299             my $filehandle = $Test->output;
2300             $Test->output($filehandle);
2301             $Test->output($filename);
2302             $Test->output(\$scalar);
2303              
2304             These methods control where Test::Builder will print its output.
2305             They take either an open C<$filehandle>, a C<$filename> to open and write to
2306             or a C<$scalar> reference to append to. It will always return a C<$filehandle>.
2307              
2308             B<output> is where normal "ok/not ok" test output goes.
2309              
2310             Defaults to STDOUT.
2311              
2312             B<failure_output> is where diagnostic output on test failures and
2313             C<diag()> goes. It is normally not read by Test::Harness and instead is
2314             displayed to the user.
2315              
2316             Defaults to STDERR.
2317              
2318             C<todo_output> is used instead of C<failure_output()> for the
2319             diagnostics of a failing TODO test. These will not be seen by the
2320             user.
2321              
2322             Defaults to STDOUT.
2323              
2324             =item reset_outputs
2325              
2326             $tb->reset_outputs;
2327              
2328             Resets all the output filehandles back to their defaults.
2329              
2330             =item carp
2331              
2332             $tb->carp(@message);
2333              
2334             Warns with C<@message> but the message will appear to come from the
2335             point where the original test function was called (C<< $tb->caller >>).
2336              
2337             =item croak
2338              
2339             $tb->croak(@message);
2340              
2341             Dies with C<@message> but the message will appear to come from the
2342             point where the original test function was called (C<< $tb->caller >>).
2343              
2344              
2345             =back
2346              
2347              
2348             =head2 Test Status and Info
2349              
2350             =over 4
2351              
2352             =item B<no_log_results>
2353              
2354             This will turn off result long-term storage. Calling this method will make
2355             C<details> and C<summary> useless. You may want to use this if you are running
2356             enough tests to fill up all available memory.
2357              
2358             Test::Builder->new->no_log_results();
2359              
2360             There is no way to turn it back on.
2361              
2362             =item B<current_test>
2363              
2364             my $curr_test = $Test->current_test;
2365             $Test->current_test($num);
2366              
2367             Gets/sets the current test number we're on. You usually shouldn't
2368             have to set this.
2369              
2370             If set forward, the details of the missing tests are filled in as 'unknown'.
2371             if set backward, the details of the intervening tests are deleted. You
2372             can erase history if you really want to.
2373              
2374              
2375             =item B<is_passing>
2376              
2377             my $ok = $builder->is_passing;
2378              
2379             Indicates if the test suite is currently passing.
2380              
2381             More formally, it will be false if anything has happened which makes
2382             it impossible for the test suite to pass. True otherwise.
2383              
2384             For example, if no tests have run C<is_passing()> will be true because
2385             even though a suite with no tests is a failure you can add a passing
2386             test to it and start passing.
2387              
2388             Don't think about it too much.
2389              
2390              
2391             =item B<summary>
2392              
2393             my @tests = $Test->summary;
2394              
2395             A simple summary of the tests so far. True for pass, false for fail.
2396             This is a logical pass/fail, so todos are passes.
2397              
2398             Of course, test #1 is $tests[0], etc...
2399              
2400              
2401             =item B<details>
2402              
2403             my @tests = $Test->details;
2404              
2405             Like C<summary()>, but with a lot more detail.
2406              
2407             $tests[$test_num - 1] =
2408             { 'ok' => is the test considered a pass?
2409             actual_ok => did it literally say 'ok'?
2410             name => name of the test (if any)
2411             type => type of test (if any, see below).
2412             reason => reason for the above (if any)
2413             };
2414              
2415             'ok' is true if Test::Harness will consider the test to be a pass.
2416              
2417             'actual_ok' is a reflection of whether or not the test literally
2418             printed 'ok' or 'not ok'. This is for examining the result of 'todo'
2419             tests.
2420              
2421             'name' is the name of the test.
2422              
2423             'type' indicates if it was a special test. Normal tests have a type
2424             of ''. Type can be one of the following:
2425              
2426             skip see skip()
2427             todo see todo()
2428             todo_skip see todo_skip()
2429             unknown see below
2430              
2431             Sometimes the Test::Builder test counter is incremented without it
2432             printing any test output, for example, when C<current_test()> is changed.
2433             In these cases, Test::Builder doesn't know the result of the test, so
2434             its type is 'unknown'. These details for these tests are filled in.
2435             They are considered ok, but the name and actual_ok is left C<undef>.
2436              
2437             For example "not ok 23 - hole count # TODO insufficient donuts" would
2438             result in this structure:
2439              
2440             $tests[22] = # 23 - 1, since arrays start from 0.
2441             { ok => 1, # logically, the test passed since its todo
2442             actual_ok => 0, # in absolute terms, it failed
2443             name => 'hole count',
2444             type => 'todo',
2445             reason => 'insufficient donuts'
2446             };
2447              
2448              
2449             =item B<todo>
2450              
2451             my $todo_reason = $Test->todo;
2452             my $todo_reason = $Test->todo($pack);
2453              
2454             If the current tests are considered "TODO" it will return the reason,
2455             if any. This reason can come from a C<$TODO> variable or the last call
2456             to C<todo_start()>.
2457              
2458             Since a TODO test does not need a reason, this function can return an
2459             empty string even when inside a TODO block. Use C<< $Test->in_todo >>
2460             to determine if you are currently inside a TODO block.
2461              
2462             C<todo()> is about finding the right package to look for C<$TODO> in. It's
2463             pretty good at guessing the right package to look at. It first looks for
2464             the caller based on C<$Level + 1>, since C<todo()> is usually called inside
2465             a test function. As a last resort it will use C<exported_to()>.
2466              
2467             Sometimes there is some confusion about where C<todo()> should be looking
2468             for the C<$TODO> variable. If you want to be sure, tell it explicitly
2469             what $pack to use.
2470              
2471             =item B<find_TODO>
2472              
2473             my $todo_reason = $Test->find_TODO();
2474             my $todo_reason = $Test->find_TODO($pack);
2475              
2476             Like C<todo()> but only returns the value of C<$TODO> ignoring
2477             C<todo_start()>.
2478              
2479             Can also be used to set C<$TODO> to a new value while returning the
2480             old value:
2481              
2482             my $old_reason = $Test->find_TODO($pack, 1, $new_reason);
2483              
2484             =item B<in_todo>
2485              
2486             my $in_todo = $Test->in_todo;
2487              
2488             Returns true if the test is currently inside a TODO block.
2489              
2490             =item B<todo_start>
2491              
2492             $Test->todo_start();
2493             $Test->todo_start($message);
2494              
2495             This method allows you declare all subsequent tests as TODO tests, up until
2496             the C<todo_end> method has been called.
2497              
2498             The C<TODO:> and C<$TODO> syntax is generally pretty good about figuring out
2499             whether or not we're in a TODO test. However, often we find that this is not
2500             possible to determine (such as when we want to use C<$TODO> but
2501             the tests are being executed in other packages which can't be inferred
2502             beforehand).
2503              
2504             Note that you can use this to nest "todo" tests
2505              
2506             $Test->todo_start('working on this');
2507             # lots of code
2508             $Test->todo_start('working on that');
2509             # more code
2510             $Test->todo_end;
2511             $Test->todo_end;
2512              
2513             This is generally not recommended, but large testing systems often have weird
2514             internal needs.
2515              
2516             We've tried to make this also work with the TODO: syntax, but it's not
2517             guaranteed and its use is also discouraged:
2518              
2519             TODO: {
2520             local $TODO = 'We have work to do!';
2521             $Test->todo_start('working on this');
2522             # lots of code
2523             $Test->todo_start('working on that');
2524             # more code
2525             $Test->todo_end;
2526             $Test->todo_end;
2527             }
2528              
2529             Pick one style or another of "TODO" to be on the safe side.
2530              
2531              
2532             =item C<todo_end>
2533              
2534             $Test->todo_end;
2535              
2536             Stops running tests as "TODO" tests. This method is fatal if called without a
2537             preceding C<todo_start> method call.
2538              
2539             =item B<caller>
2540              
2541             my $package = $Test->caller;
2542             my($pack, $file, $line) = $Test->caller;
2543             my($pack, $file, $line) = $Test->caller($height);
2544              
2545             Like the normal C<caller()>, except it reports according to your C<level()>.
2546              
2547             C<$height> will be added to the C<level()>.
2548              
2549             If C<caller()> winds up off the top of the stack it report the highest context.
2550              
2551             =back
2552              
2553             =head1 EXIT CODES
2554              
2555             If all your tests passed, Test::Builder will exit with zero (which is
2556             normal). If anything failed it will exit with how many failed. If
2557             you run less (or more) tests than you planned, the missing (or extras)
2558             will be considered failures. If no tests were ever run Test::Builder
2559             will throw a warning and exit with 255. If the test died, even after
2560             having successfully completed all its tests, it will still be
2561             considered a failure and will exit with 255.
2562              
2563             So the exit codes are...
2564              
2565             0 all tests successful
2566             255 test died or all passed but wrong # of tests run
2567             any other number how many failed (including missing or extras)
2568              
2569             If you fail more than 254 tests, it will be reported as 254.
2570              
2571             =head1 THREADS
2572              
2573             In perl 5.8.1 and later, Test::Builder is thread-safe. The test number is
2574             shared by all threads. This means if one thread sets the test number using
2575             C<current_test()> they will all be effected.
2576              
2577             While versions earlier than 5.8.1 had threads they contain too many
2578             bugs to support.
2579              
2580             Test::Builder is only thread-aware if threads.pm is loaded I<before>
2581             Test::Builder.
2582              
2583             You can directly disable thread support with one of the following:
2584              
2585             $ENV{T2_NO_IPC} = 1
2586              
2587             or
2588              
2589             no Test2::IPC;
2590              
2591             or
2592              
2593             Test2::API::test2_ipc_disable()
2594              
2595             =head1 MEMORY
2596              
2597             An informative hash, accessible via C<details()>, is stored for each
2598             test you perform. So memory usage will scale linearly with each test
2599             run. Although this is not a problem for most test suites, it can
2600             become an issue if you do large (hundred thousands to million)
2601             combinatorics tests in the same run.
2602              
2603             In such cases, you are advised to either split the test file into smaller
2604             ones, or use a reverse approach, doing "normal" (code) compares and
2605             triggering C<fail()> should anything go unexpected.
2606              
2607             Future versions of Test::Builder will have a way to turn history off.
2608              
2609              
2610             =head1 EXAMPLES
2611              
2612             CPAN can provide the best examples. L<Test::Simple>, L<Test::More>,
2613             L<Test::Exception> and L<Test::Differences> all use Test::Builder.
2614              
2615             =head1 SEE ALSO
2616              
2617             =head2 INTERNALS
2618              
2619             L<Test2>, L<Test2::API>
2620              
2621             =head2 LEGACY
2622              
2623             L<Test::Simple>, L<Test::More>
2624              
2625             =head2 EXTERNAL
2626              
2627             L<Test::Harness>
2628              
2629             =head1 AUTHORS
2630              
2631             Original code by chromatic, maintained by Michael G Schwern
2632             E<lt>schwern@pobox.comE<gt>
2633              
2634             =head1 MAINTAINERS
2635              
2636             =over 4
2637              
2638             =item Chad Granum E<lt>exodist@cpan.orgE<gt>
2639              
2640             =back
2641              
2642             =head1 COPYRIGHT
2643              
2644             Copyright 2002-2008 by chromatic E<lt>chromatic@wgz.orgE<gt> and
2645             Michael G Schwern E<lt>schwern@pobox.comE<gt>.
2646              
2647             This program is free software; you can redistribute it and/or
2648             modify it under the same terms as Perl itself.
2649              
2650             See F<http://www.perl.com/perl/misc/Artistic.html>