blib/lib/Test/Group.pm

filter: Statementstmt 96.5% 279 / 289 Branchbran 80.5% 95 / 118 Conditioncond 81.0% 30 / 37 MC/DCmcdc 68.1% 15 / 22 Subroutinesub 93.7% 60 / 64 Podpod 100% 13 / 13 totaltotal 90.6% 492 / 543 CC 73 SCAR 17.8
CC
73
Cov
91%
ok
16.0
as_Test_Builder_params
11.1
test
11.0
CRAP 6.0
« blib/lib/Test/Group/Tester.pm ↑ Summary blib/lib/Test/Group/Plan.pm »
1 #!/usr/bin/perl -w
2 # -*- coding: utf-8; -*-
3 #
4 # (C)-IDEALX
5  
6 package Test::Group;
7 76 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 76 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Test::Group - Group together related tests in a test suite
13  
14 =head1 VERSION
15  
16 Test::Group version 0.20
17  
18 =cut
19  
20 76 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 76 $VERSION = '0.20';
22  
23 =head1 SYNOPSIS
24  
25 Basics:
26  
27 =for tests "synopsis-success" begin
28  
29 use Test::More no_plan => 1;
30 use Test::Group;
31  
32 test "hammering the server" => sub {
33 ok(I_can_connect);
34 for(1..1000) {
35 ok(I_can_make_a_request);
36 }
37 }; # Don't forget the semicolon here!
38  
39 =for tests "synopsis-success" end
40  
41 Failed subtests are displayed I<before> the result of the test they belong to.
42 For instance,
43  
44 =for tests "synopsis-fail" begin
45  
46 use Test::More no_plan => 1;
47 use Test::Group;
48  
49 test "this test group will fail", sub {
50 ok 1, "sub test blah";
51 is "foo", "bar", "I so wish they were the same...";
52 ok 1;
53 like "blah blah blah", qr/bla/;
54 };
55  
56 =for tests "synopsis-fail" end
57  
58 produces something like this:
59  
60 # Failed test 'I so wish they were the same...'
61 # in test.pl at line 6.
62 # got: 'foo'
63 # expected: 'bar'
64 not ok 1 - this test group will fail
65 # Failed test 'this test group will fail'
66 # in test.pl at line 9.
67 1..1
68  
69 Exceptions in tests are not fatal:
70  
71 =for tests "synopsis-die" begin
72  
73 test "this test will fail but the suite will proceed", sub {
74 pass;
75 die;
76 };
77  
78  
79 =for tests "synopsis-die" end
80  
81 Test::More style TODO support:
82  
83 =for tests "synopsis-TODO" begin
84  
85 test "a test with TODO in the name is marked TODO" => sub {
86 pass("this part is done");
87 fail("but I'm not finished with this one yet");
88 };
89  
90 {
91 local $TODO = "Test::More's good old method also works";
92 test "this test is not finished yet" => sub {
93 pass;
94 fail;
95 };
96 };
97  
98 =for tests "synopsis-TODO" end
99  
100 Misc:
101  
102 =for tests "synopsis-misc" begin
103  
104 # Don't catch exceptions raised in test groups later on
105 Test::Group->dont_catch_exceptions;
106  
107 # log caught exceptions in /tmp/log
108 Test::Group->logfile("/tmp/log");
109  
110 # skip the next group of test
111 skip_next_test "network not available" if (! Network->available());
112 test "bla", sub {
113 my $ftp = Net::FTP->new("some.host.name");
114 # ...
115 };
116  
117 begin_skipping_tests "reason";
118  
119 test "this test will not run" => sub {
120 # ...
121 };
122  
123 end_skipping_tests;
124  
125 # from now on, skip all tests whose names do not match /bla/
126 test_only qr/bla/;
127  
128 =for tests "synopsis-misc" end
129  
130 =head1 DESCRIPTION
131  
132 Fed up with counting tests to discover what went wrong in your last
133 test run? Tired of squinting at your test source to find out where on
134 earth the faulty test predicate is called, and what it is supposed to
135 check for? Then this module is for you!
136  
137 I<Test::Group> allows for grouping together related tests in a
138 standard I<Test::More>-style script. (If you are not already familiar
139 with L<Test::More>, now would be the time to go take a look.)
140 I<Test::Group> provides a bunch of maintainability and scalability
141 advantages to large test suites:
142  
143 =over
144  
145 =item *
146  
147 related tests can be grouped and given a name. The intent of the test
148 author is therefore made explicit with much less effort than would be
149 needed to name all the individual tests;
150  
151 =item *
152  
153 the test output is much shorter and more readable: only failed
154 subtests show a diagnostic, while test groups with no problems inside
155 produce a single friendly C<ok> line;
156  
157 =item *
158  
159 no more tedious test counting: running an arbitrarily large or
160 variable number of tests (e.g. in loops) is now hassle-free and
161 doesn't clutter the test output.
162  
163 =back
164  
165 Authors of I<Test::*> modules may also find I<Test::Group> of
166 interest, because it allows for composing several L<Test::More>
167 predicates into a single one (see L</Reflexivity>).
168  
169  
170 =head1 FEATURES
171  
172 =head2 Blocking Exceptions
173  
174 By default, calls to L<perlfunc/die> and other exceptions from within
175 a test group cause it to fail and terminates execution of the group,
176 but does not terminate whole script. This relieves the programmer
177 from having to worry about code that may throw in tests.
178  
179 This behavior can be disabled totally using L</dont_catch_exceptions>.
180 Exceptions can also be trapped as usual using L<perlfunc/eval> or
181 otherwise from inside a group, in which case the test code of course
182 has full control on what to do next (this is how one should test error
183 management, by the way).
184  
185 When Test::Group is set to block errors (the default setting, see also
186 L</catch_exceptions>), the error messages are displayed as part of the
187 test name, which some may not find very readable. Therefore, one can
188 use a L</logfile> instead.
189  
190 =head2 Skipping Groups
191  
192 I<Test::Group> can skip single test groups or a range of them
193 (consecutive or matched by a regex), which helps shortening the debug
194 cycle even more in test-driven programming. When a test group is
195 skipped, the code within it is simply not executed, and the test is
196 marked as skipped wrt L<Test::Builder>. See L</skip_next_test>,
197 L</skip_next_tests>, L</begin_skipping_tests>, L</end_skipping_tests>
198 and L</test_only> for details.
199  
200 =head2 Reflexivity
201  
202 Test groups integrate with L<Test::Builder> by acting as a single big
203 test; therefore, I<Test::Group> is fully reflexive. A particularly
204 attractive consequence is that constructing new L<Test::More>
205 predicates is straightforward with I<Test::Group>. For example,
206  
207 =for tests "foobar_ok" begin
208  
209 use Test::Builder;
210 use Test::Group;
211  
212 sub foobar_ok {
213 my ($text, $name) = @_;
214 $name ||= "foobar_ok";
215 local $Test::Builder::Level = $Test::Builder::Level + 1;
216 test $name => sub {
217 local $Test::Group::InPredicate = 1;
218 like($text, qr/foo/, "foo ok");
219 like($text, qr/bar/, "bar ok");
220 };
221 }
222  
223 =for tests "foobar_ok" end
224  
225 defines a new test predicate I<foobar_ok> that will DWIM regardless of
226 the caller's testing style: for "classical" L<Test::Simple> or
227 L<Test::More> users, I<foobar_ok> will act as just another I<*_ok>
228 predicate (in particular, it always counts for a single test, honors
229 L<Test::More/TODO: BLOCK> constructs, etc); and of course, users of
230 I<Test::Group> can freely call I<foobar_ok> from within a group.
231  
232 Adding 1 to C<$Test::Builder::Level> causes the location of the call
233 to foobar_ok() to be shown if a test fails, see L<Test::Builder>.
234  
235 Setting C<$Test::Group::InPredicate> to a true value prevents the
236 location of individual failing tests within test groups from being
237 shown.
238  
239 =head2 TODO Tests
240  
241 As shown in L</SYNOPSIS>, L<Test::More>'s concept of TODO tests is
242 supported by I<Test::Group>: a group is in TODO state if the $TODO
243 variable is set by the time it starts, or if the test name contains
244 the word C<TODO>. Note, however, that setting $TODO from B<inside>
245 the test group (that is, B<after> the group starts) will not do what
246 you mean:
247  
248 =for tests "TODO gotcha" begin
249  
250 test "something" => sub {
251 local $TODO = "this test does not work yet";
252 pass; # GOTCHA!
253 fail;
254 };
255  
256 =for tests "TODO gotcha" end
257  
258 Here C<pass> is an unexpected success, and therefore the whole test
259 group will report a TODO success despite the test not actually being a
260 success (that is, it would B<also> be defective if one were to comment
261 out the C<local $TODO> line). This semantics, on the other hand,
262 DWIMs for marking a B<portion> of the test group as TODO:
263  
264 =for tests "TODO correct" begin
265  
266 test "something" => sub {
267 pass;
268 {
269 local $TODO = "this part does not work yet";
270 fail;
271 }
272 };
273  
274 =for tests "TODO correct" end
275  
276 Finally, there is a subtle gotcha to be aware of when setting $TODO
277 outside a test group (that's the second one, so maybe you should not
278 do that to begin with). In this case, the value of $TODO is set to
279 undef B<inside> the group. In other words, this test (similar to the
280 one to be found in L</SYNOPSIS>) will succeed as expected:
281  
282 =for tests "TODO gotcha 2" begin
283  
284 {
285 local $TODO = "not quite done yet";
286 test "foo" => sub {
287 fail;
288 pass; # NOT an unexpected success, as
289 # this is simply a subtest of the whole
290 # test "foo", which will fail.
291 };
292 }
293  
294 =for tests "TODO gotcha 2" end
295  
296 =head2 OUTPUT FORMAT
297  
298 As seen briefly in L</SYNOPSIS>, only top-level test groups (and toplevel
299 Test::More tests if any) produce a single "ok" or "not ok" summary line. Failed
300 sub-tests produce non-scoring comment messages (prefixed with "#"); successful
301 sub-tests are silent. This is different from, and predates, the
302 L<Test::More/subtest> functionality.
303  
304 However, if you enable the experimental L</use_subtest> feature then
305 I<Test::Group> will use the same underlying mechanism as
306 L<Test::More/subtest> and produce very similar output.
307  
308 =head2 PLUGIN INTERFACE
309  
310 A simple plugin interface allows module authors to write extensions
311 to I<Test::Group>. See L<Test::Group::Extending> for details.
312  
313 The following extensions are distributed with I<Test::Group>:
314  
315 L<Test::Group::Plan>, L<Test::Group::NoWarnings>
316  
317 =cut
318  
319 76 ▶use 5.004;
Subroutine BEGIN: called CC=1 SCAR=0.0
320  
321 76 ▶use Test::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
322 76 ▶use Test::Builder;
Subroutine BEGIN: called CC=1 SCAR=0.0
323 76 ▶BEGIN { die "Need Test::Simple version 0.59 or later, sorry"
Subroutine BEGIN: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
unless "Test::Builder"->can("create") 0 76 76
324 unless Test::Builder->can("create"); }
325 76 ▶use IO::File;
Subroutine BEGIN: called CC=1 SCAR=0.0
326 76 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
327  
328 76 my $classstate_verbose = $ENV{PERL_TEST_GROUP_VERBOSE};
329 76 my $classstate_skipcounter;
330 my $classstate_skipreason;
331 76 my $classstate_testonly_reason;
332 351 ▶my $classstate_testonly_criteria = sub { 1 };
Subroutine __ANON__: called CC=1 SCAR=0.0
333 76 my $classstate_catchexceptions = 1;
334 76 my $classstate_logfile;
335 my $classstate_logfd;
336 76 my @classstate_plugins;
337 76 my $classstate_use_subtest;
338  
339 76 our $Level = 0;
340 # $Test::Group::Level is effectively added to $Test::Builder::Level.
341 # Do not use it, it is present for backward compatibility only.
342 # Use $Test::Builder::Level instead.
343  
344 76 our $InPredicate;
345  
346 =head2 FUNCTIONS
347  
348 All functions below are intended to be called from the test
349 script. They are all exported by default.
350  
351 =cut
352  
353 76 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
354 76 ▶use vars qw(@ISA @EXPORT @EXPORT_OK);
Subroutine BEGIN: called CC=1 SCAR=0.0
355 76 @ISA = qw(Exporter);
356 76 @EXPORT = qw(test skip_next_test skip_next_tests
357 begin_skipping_tests end_skipping_tests
358 test_only);
359 76 @EXPORT_OK = qw(next_test_plugin);
360  
361 =head3 test ($name, $groupsub)
362  
363 Executes I<$groupsub>, which must be a reference to a subroutine, in a
364 controlled environment and groups the results of all
365 L<Test::Builder>-style subtests launched inside into a single call to
366 L<Test::Builder/ok>, regardless of their number. If the test group is
367 to be skipped (as discussed in L</Skipping Groups>), calls
368 L<Test::Builder/skip> once instead.
369  
370 In case the test group is B<not> skipped, the first parameter to
371 L<Test::Builder/ok> and the value of the TODO string during same (see
372 L<Test::More/TODO: BLOCK>) are determined according to the following
373 algorithm:
374  
375 =over
376  
377 =item 1
378  
379 if the test group terminates by throwing an exception, or terminates
380 normally but without calling any subtest, it fails.
381  
382 =item 2
383  
384 otherwise, if any subtest failed outside of a TODO block, the group
385 fails.
386  
387 =item 3
388  
389 otherwise, if any subtest B<succeeds> inside of a TODO block, the
390 group is flagged as an unexpected success.
391  
392 =item 4
393  
394 otherwise, if any subtest fails inside of a TODO block, the group
395 results in a TODO (excused) failure.
396  
397 =item 5
398  
399 otherwise, the test group managed to avert all hazards and is a
400 straight success (tada!!).
401  
402 =back
403  
404 If any sub-tests failed in I<$groupsub>, diagnostics will be
405 propagated using L<Test::Builder/diag> as usual.
406  
407 The return value of I<test> is 1 if the test group is a success
408 (including a TODO unexpected success), 0 if it is a failure (including
409 a TODO excused failure), and undef if the test group was skipped.
410  
411 =cut
412  
413 349 ▶sub test ($&) {
Subroutine test: called CC=11 SCAR=24.0
Pod documented
414 349 my ($name, $code) = @_;
415  
416 349 my ($callerpackage) = caller(0);
417  
418 349 my $Test = Test::Builder->new; # This is a singleton actually -
419 # it should read "Test::Builder->the()" with permission from
420 # Michael Schwern :-)
421  
422 349 my $subTest = Test::Group::_Runner->new($name, $callerpackage, $code);
423 349 $subTest->run();
424  
425 348 ▶ if ($subTest->is_skipped) {
Branch: 1 branch
BranchTrueFalseTotal
if ($subTest->is_skipped) 21 327 348
426 21 $Test->skip($subTest->skip_reason);
427 21 return;
428 }
429  
430 327 ▶ if ($subTest->got_exception) {
Branch: 1 branch
BranchTrueFalseTotal
if ($subTest->got_exception) 6 321 327
431 6 my $exn = $subTest->exception();
432 my $exntext =
433 ( ! defined $exn ? "an undefined exception" :
434 6 ▶ eval { $exn->can("stringify") } ? $exn->stringify :
Branch: 1 branch
BranchTrueFalseTotal
ref $exn && $Data::Dumper::VERSION ? : 1 5 6
Condition100%3/3
ref $exn and $Data::Dumper::VERSION
!ll&&!rl&&r
411
MC/DC100%2/2
ref $exn and $Data::Dumper::VERSION
ref $exn $Data::Dumper::VERSION
Truth table100%3/3
A and B
A= ref $exnB= $Data::Dumper::VERSION
ABresult
0X0
100
111
435 6 ▶ (ref($exn) && $Data::Dumper::VERSION ) ? do {
Branch: 2 branches
BranchTrueFalseTotal
!defined($exn) ? : 0 6 6
eval { do { $exn->can('stringify') } } ? : 0 6 6
436 76 ▶ no warnings "once";
Subroutine BEGIN: called CC=1 SCAR=0.0
437 1 local $Data::Dumper::Indent = 1;
438 1 local $Data::Dumper::Terse = 1;
439 1 ▶ Data::Dumper::Dumper($exn) } :
Branch: 1 branch
BranchTrueFalseTotal
"$exn" ? : 5 0 5
440 "$exn" ? "$exn" : "a blank exception" );
441 6 { local $/ = ""; chomp($exntext); }
442 6 my $message = <<"MESSAGE";
443 Test ``$name'' died:
444 $exntext
445 MESSAGE
446 6 ▶ if ($classstate_logfd) {
Branch: 1 branch
BranchTrueFalseTotal
if ($classstate_logfd) { } 2 4 6
447 2 print $classstate_logfd $message;
448 2 $Test->diag("test ``$name'' died - "
449 . "see log file: ``$classstate_logfile''");
450 } else {
451 4 $Test->diag($message);
452 };
453 6 $name = "*died* $name";
454 }
455  
456 327 ▶ return $subTest->{result} if exists $subTest->{result};
Branch: 1 branch
BranchTrueFalseTotal
if exists $subTest->{"result"} 49 278 327
457  
458 76 ▶ no warnings "redefine";
Subroutine BEGIN: called CC=1 SCAR=0.0
459 278 my ($OK, $TODO_string) = $subTest->as_Test_Builder_params;
460 # I tried to put a "local $TODO = " here, but that didn't work and
461 # I lack the patience to dig up the whole story about
462 # Test::Builder->caller not doing The Right Thing here (yet
463 # elsewhere it does when it apparently shouldn't, e.g. in
464 # L</run>). So here goes a sleazy local-method trick to get the
465 # TODO status across to Test::Builder; the trick has an adherence
466 # in L</ok>, which see.
467 278 ▶ local *Test::Builder::todo = sub { $TODO_string };
Subroutine __ANON__: called CC=1 SCAR=0.0
468 278 ▶ local *Test::Builder::in_todo = sub { defined($TODO_string) };
Subroutine __ANON__: called CC=1 SCAR=0.0
469 278 local $Test::Builder::Level = $Test::Builder::Level + $Level;
470 278 $Test->ok($OK, $name);
471 278 ▶ return $OK ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$OK ? : 155 123 278
472 }
473  
474 =head3 skip_next_tests ($number)
475  
476 =head3 skip_next_tests ($number, $reason)
477  
478 Skips the $number following groups of tests with reason $reason. Dies
479 if we are currently skipping tests already.
480  
481 =head3 skip_next_test ()
482  
483 =head3 skip_next_test ($reason)
484  
485 Equivalent to:
486  
487 skip_next_tests 1;
488 skip_next_tests 1, $reason;
489  
490 =head3 begin_skipping_tests ()
491  
492 begin_skipping_tests;
493 begin_skipping_tests "reason";
494  
495 Skips all subsequent groups of tests until blocked by
496 L</end_skipping_tests>.
497  
498 =head3 end_skipping_tests ()
499  
500 Cancels the effect of L</begin_skipping_tests>. Has no effect if we
501 are not currently skipping tests.
502  
503 =cut
504  
505 7 ▶sub skip_next_tests {
Subroutine skip_next_tests: called CC=3 SCAR=12.0
Pod documented
506 7 my ($counter, $reason) = @_;
507 7 ▶ $classstate_skipcounter = $counter unless
Branch: 1 branch
BranchTrueFalseTotal
unless $classstate_skipcounter and $classstate_skipcounter > $counter 7 0 7
Condition33%1/3
$classstate_skipcounter and $classstate_skipcounter > $counter
!ll&&!rl&&r
700
MC/DC0%0/2
$classstate_skipcounter and $classstate_skipcounter > $counter
$classstate_skipcounter $classstate_skipcounter > $counter
Truth table33%1/3
A and B
A= $classstate_skipcounterB= $classstate_skipcounter > $counter
ABresult
0X0
100
111
508 ($classstate_skipcounter && $classstate_skipcounter > $counter);
509 7 $classstate_skipreason = $reason;
510 7 return 1;
511 }
512  
513 5 ▶sub skip_next_test {
Subroutine skip_next_test: called CC=1 SCAR=0.0
Pod documented
514 5 skip_next_tests 1, @_;
515 }
516  
517 5 ▶sub begin_skipping_tests {
Subroutine begin_skipping_tests: called CC=1 SCAR=0.0
Pod documented
518 5 my ($reason) = @_;
519 5 $classstate_skipcounter = -1;
520 5 $classstate_skipreason = $reason;
521 5 return 1;
522 }
523  
524 5 ▶sub end_skipping_tests {
Subroutine end_skipping_tests: called CC=1 SCAR=0.0
Pod documented
525 5 $classstate_skipcounter = 0;
526 5 return 1;
527 }
528  
529 =head3 test_only ()
530  
531 test_only "bla()", "reason";
532 test_only qr/^bla/;
533 test_only sub { /bla/ };
534  
535 Skip all groups of tests whose name does not match the criteria. The
536 criteria can be a plain string, a regular expression or a function.
537  
538 test_only;
539  
540 Resets to normal behavior.
541  
542 =cut
543  
544 5 ▶sub test_only (;$$) {
Subroutine test_only: called CC=5 SCAR=18.7
Pod documented
545 5 my ($criteria, $reason) = @_;
546  
547 5 $classstate_testonly_reason = $reason;
548  
549 5 ▶ if (!defined $criteria) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $criteria) { } 0 5 5
elsif (not ref $criteria) { } 2 3 5
elsif (ref $criteria eq 'Regexp') { } 3 0 3
elsif (ref $criteria eq 'CODE') { } 0 0 0
550 0 ▶ $classstate_testonly_criteria = sub { 1 };
Subroutine __ANON__: not called CC=1 SCAR=6.9
551 } elsif (!ref $criteria) {
552 2 ▶ $classstate_testonly_criteria = sub { $_[0] eq $criteria };
Subroutine __ANON__: called CC=1 SCAR=0.0
553 } elsif (ref $criteria eq "Regexp") {
554 3 ▶ $classstate_testonly_criteria = sub { $_[0] =~ /$criteria/ };
Subroutine __ANON__: called CC=1 SCAR=0.0
555 } elsif (ref $criteria eq "CODE") {
556 0 $classstate_testonly_criteria = $criteria;
557 }
558 }
559  
560 =head2 PLUGIN FUNCTIONS
561  
562 The following function relates to the plugin interface. It is not
563 exported by default. See L<Test::Group::Extending> for details.
564  
565 =head3 next_test_plugin ($plugin)
566  
567 Installs a plugin for the next test group. I<$plugin> must be a
568 subroutine reference.
569  
570 =cut
571  
572 56 ▶sub next_test_plugin (&) {
Subroutine next_test_plugin: called CC=1 SCAR=0.0
Pod documented
573 56 my $plugin = shift;
574  
575 56 push @classstate_plugins, $plugin;
576 }
577  
578 =head1 CLASS METHODS
579  
580 A handful of class methods are available to tweak the behavior of this
581 module on a global basis. They are to be invoked like this:
582  
583 Test::Group->foo(@args);
584  
585 =head2 verbose ($level)
586  
587 Sets verbosity level to $level, where 0 means quietest.
588  
589 At level 1 and above there is a diagnostic line for the start of each
590 test group.
591  
592 At level 2 there is a diagnostic line showing the result of each
593 subtest within top-level test groups. At level 3, the subtests of test
594 groups nested within top level test groups also get diagnostic lines,
595 and so on.
596  
597 The default verbosity level is 0, or the value of the
598 C<PERL_TEST_GROUP_VERBOSE> environment variable if it is set.
599  
600 =cut
601  
602 36 ▶sub verbose { shift; $classstate_verbose = shift }
Subroutine verbose: called CC=1 SCAR=0.0
Pod documented
603  
604 =head2 catch_exceptions ()
605  
606 Causes exceptions thrown from within the sub reference passed to
607 L</test> to be blocked; in this case, the test currently running will
608 fail but the suite will proceed. This is the default behavior.
609  
610 Note that I<catch_exceptions> only deals with exceptions arising
611 inside I<test> blocks; those thrown by surrounding code (if any) still
612 cause the test script to terminate as usual unless other appropriate
613 steps are taken.
614  
615 =head2 dont_catch_exceptions ()
616  
617 Reverses the effect of L</catch_exceptions>, and causes exceptions
618 thrown from a L</test> sub reference to be fatal to the whole suite.
619 This only takes effect for test subs that run after
620 I<dont_catch_exceptions()> returns; in other words this is B<not> a
621 whole-script pragma.
622  
623 =cut
624  
625 0 ▶sub catch_exceptions { $classstate_catchexceptions = 1; }
Subroutine catch_exceptions: not called CC=1 SCAR=6.9
Pod documented
626 2 ▶sub dont_catch_exceptions { $classstate_catchexceptions = 0; }
Subroutine dont_catch_exceptions: called CC=1 SCAR=0.0
Pod documented
627  
628 =head2 logfile ($classstate_logfile)
629  
630 Sets the log file for caught exceptions to F<$classstate_logfile>.
631 From this point on, all exceptions thrown from within a text group
632 (assuming they are caught, see L</catch_exceptions>) will be written
633 to F<$classstate_logfile> instead of being passed on to
634 L<Test::More/diag>. This is very convenient with exceptions with a
635 huge text representation (say an instance of L<Error> containing a
636 stack trace).
637  
638 =cut
639  
640 3 ▶sub logfile {
Subroutine logfile: called CC=2 SCAR=7.1
Pod documented
641 3 my $class = shift;
642 3 $classstate_logfile = shift;
643 3 ▶ $classstate_logfd = new IO::File("> $classstate_logfile") or
Branch: 1 branch
BranchTrueFalseTotal
$classstate_logfd = "IO::File"->new("> $classstate_logfile") or die "Cannot open $classstate_logfile" 3 0 3
644 die "Cannot open $classstate_logfile";
645 }
646  
647 =head2 use_subtest ()
648  
649 This feature is experimental.
650  
651 Causes I<Test::Group> to use L<Test::Builder>'s subtest() feature as
652 the test aggregation method, rather than doing black magic behind the
653 scenes.
654  
655 It is a fatal error to call use_subtest() if L<Test::Builder> is too
656 old to support subtests. To use subtests if they are available but
657 fall back to normal operation if they are not, you can do:
658  
659 eval { Test::Group->use_subtest };
660  
661 I<Test::Group>'s exception handling mechanism is bypassed under
662 use_subtest(), since Test::Builder::subtest() has its own exception
663 handling system.
664  
665 =cut
666  
667 10 ▶sub use_subtest {
Subroutine use_subtest: called CC=2 SCAR=7.2
Pod documented
668 10 ▶ Test::Builder->new->can('subtest') or die
Branch: 1 branch
BranchTrueFalseTotal
"Test::Builder"->new->can("subtest") or die "Test::Builder too old for use_subtest()\n" 10 0 10
669 "Test::Builder too old for use_subtest()\n";
670 10 $classstate_use_subtest = 1;
671 }
672
673 =head2 no_subtest ()
674  
675 Turns off use_subtest.
676  
677 =cut
678  
679 0 ▶sub no_subtest {
Subroutine no_subtest: not called CC=1 SCAR=6.9
Pod documented
680 0 $classstate_use_subtest = 0;
681 }
682  
683 =begin internals
684  
685 =head1 INTERNALS
686  
687 =head2 Test::Group::_Runner internal class
688  
689 This is an internal class whose job is to observe the tests in lieu of
690 the real I<Test::Builder> singleton (see L<Test::Builder/new>) during
691 the time the I<$groupsub> argument to L</test> is being run.
692 Short-circuiting L<Test::Builder> involves a fair amount of black
693 magic, which is performed using the
694 L</Test::Builder::_HijackedByTestGroup internal class> as an
695 accomplice.
696  
697 =cut
698  
699 package Test::Group::_Runner;
700  
701 =head3 new ($name, $callerpackage, $sub)
702  
703 Object constructor; constructs an object that models only the state of
704 the test group $sub that is about to be run as if L</test> had been
705 invoked from $callerpackage. This I<Test::Group::_Runner> object is
706 available by calling L</current> from $sub, while it is being executed
707 by L</run>. Afterwards, it can be queried using L</subtests> and
708 other methods to discover how the test group run went.
709  
710 =cut
711  
712 381 ▶sub new {
Subroutine new: called CC=4 SCAR=13.9
713 381 my ($class, $name, $callerpackage, $code) = @_;
714  
715 381 my $self = bless {
716 name => $name,
717 callerpackage => $callerpackage,
718 code => $code,
719 subtests => [],
720 }, $class;
721 # Stash the TODO state on behalf of L</as_Test_Builder_params>,
722 # coz we're going to muck with $TODO soon. Warning, ->todo
723 # returns 0 instead of undef if there is no TODO block active:
724 381 my $T = Test::Builder->new;
725 381 my $current_todo = $T->todo($callerpackage);
726 381 ▶ $self->{in_todo} = $current_todo if $current_todo;
Branch: 1 branch
BranchTrueFalseTotal
if $current_todo 8 373 381
727  
728 # For testability: test groups run inside a mute group are mute as
729 # well.
730 381 ▶ $self->mute(1) if ($class->current &&
Branch: 1 branch
BranchTrueFalseTotal
if $class->current and $class->current->mute 13 368 381
Condition100%3/3
$class->current and $class->current->mute
!ll&&!rl&&r
2888013
MC/DC100%2/2
$class->current and $class->current->mute
$class->current $class->current->mute
Truth table100%3/3
A and B
A= $class->currentB= $class->current->mute
ABresult
0X0
100
111
731 $class->current->mute);
732  
733 381 return $self;
734 }
735  
736 =head3 run ()
737  
738 Executes the $sub test group passed as the second parameter to
739 L</new>, monitoring the results of the sub-tests and stashing them
740 into L</subtests>. Invoking C<< ->new($name, $sub) >> then C<<
741 ->run() >> is the same as running </test> with the same parameters,
742 except that I<test()> additionally passes along the test group results
743 to L<Test::Builder>.
744  
745 If any plugins have been set, they are applied to the test group and
746 the list of plugins is cleared.
747  
748 =cut
749  
750 381 ▶sub run {
Subroutine run: called CC=9 SCAR=22.0
751 381 my ($self) = @_;
752  
753 381 ▶ if ($classstate_skipcounter) {
Branch: 2 branches
BranchTrueFalseTotal
if ($classstate_skipcounter) { } 20 361 381
elsif (not &$classstate_testonly_criteria($self->{'name'})) { } 4 357 361
754 20 $classstate_skipcounter--;
755 20 $self->_skip($classstate_skipreason);
756 20 ▶ undef $classstate_skipreason unless $classstate_skipcounter;
Branch: 1 branch
BranchTrueFalseTotal
unless $classstate_skipcounter 7 13 20
757 20 return $self;
758 } elsif (! $classstate_testonly_criteria->($self->{name})) {
759 4 $self->_skip($classstate_testonly_reason);
760 4 return $self;
761 }
762  
763 357 ▶ Test::Builder->new->diag("Running group of tests - $self->{name}")
Branch: 1 branch
BranchTrueFalseTotal
if $classstate_verbose 96 261 357
764 if ($classstate_verbose);
765  
766 357 my $code = $self->{code};
767 357 ▶ if (my @plugins = @classstate_plugins) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@plugins) = @classstate_plugins) 44 313 357
768 44 ▶ $code = sub { $self->_run_code_via_plugins(@plugins) };
Subroutine __ANON__: called CC=1 SCAR=0.0
769 44 @classstate_plugins = ();
770 }
771  
772 357 ▶ if ($classstate_use_subtest) {
Branch: 1 branch
BranchTrueFalseTotal
if ($classstate_use_subtest) { } 49 308 357
773 49 my $level = $Test::Builder::Level + $Level + 1;
774 49 local $Test::Builder::Level = $level;
775 $self->{result} = Test::Builder->new->subtest(
776 49 ▶ $self->{name} => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
777 49 $code->();
778 49 Test::Builder->new->done_testing;
779  
780 # Work around a flaw in Test::Builder 0.94, see
781 # http://code.google.com/p/test-more/issues/detail?id=58
782 49 $Test::Builder::Level = $level + 2;
783 }
784 49 );
785 } else {
786 # Reset $Test::Builder::Level to the default when running the inner
787 # test code. Otherwise, the file/line diagnostics of failing tests
788 # within the group would be messed up if test() is called with a
789 # non-default $Test::Builder::Level value.
790 308 local $Test::Builder::Level = 1;
791  
792 308 $self->_hijack(); # BEGIN CRITICAL SECTION
793 my $exception_raised = !
794 308 $self->_run_with_local_TODO($self->{callerpackage}, $code);
795 308 $self->_unhijack(); # END CRITICAL SECTION
796  
797 308 ▶ if ($exception_raised) {
Branch: 1 branch
BranchTrueFalseTotal
if ($exception_raised) 11 297 308
798 11 ▶ if ($classstate_catchexceptions) {
Branch: 1 branch
BranchTrueFalseTotal
if ($classstate_catchexceptions) { } 10 1 11
799 10 $self->_record_exception();
800 } else {
801 1 die $@; # Rethrow
802 }
803 }
804 }
805  
806 356 return; # No useful return value yet
807 }
808  
809 =head3 current ()
810  
811 =head3 current ($newcurrent)
812  
813 Class method, gets or sets the current instance of
814 I<Test::Group::_Runner> w.r.t. the current state of the L</_hijack>
815 / L</_unhijack> call stack. If the stack is empty, returns undef.
816  
817 =cut
818  
819 {
820 76 my $current;
821  
822 4010 ▶ sub current {
Subroutine current: called CC=2 SCAR=6.9
823 4010 ▶ if (@_ == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1) { } 3394 616 4010
824 3394 return $current;
825 } else {
826 616 $current = $_[1];
827 }
828 }
829 }
830  
831 =head3 orig_blessed ()
832  
833 Returns the class in which C<< Test::Builder->new >> was originally
834 blessed just before it got L</_hijack>ed: this will usually be
835 C<Test::Builder>, unless something really big happens to Perl's
836 testing infrastructure.
837  
838 =cut
839  
840 76 ▶sub orig_blessed {
Subroutine orig_blessed: not called CC=3 SCAR=22.3
841 0 my $self = shift;
842 0 ▶ return $self->{reblessed_from} if defined $self->{reblessed_from};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"reblessed_from"} 0 0 0
843 # Calls recursively:
844 0 ▶ return $self->{parent}->orig_blessed if defined $self->{parent};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"parent"} 0 0 0
845 0 return; # Object not completely constructed, should not happen
846 }
847  
848 =head3 mute ()
849  
850 =head3 mute ($bool)
851  
852 Gets or sets the mute status (false by default). This method is not
853 (yet) made visible from L<Test::Group> proper; it is used in the test
854 suite (see L<testlib/tg_test_test>) so as not to scare the systems
855 administrator with lots of (expected) failure messages at C<Build
856 test> time.
857  
858 =cut
859  
860 299 ▶sub mute {
Subroutine mute: called CC=2 SCAR=6.9
861 299 my ($self, @mute) = @_;
862 299 ▶ if (@mute) {
Branch: 1 branch
BranchTrueFalseTotal
if (@mute) { } 45 254 299
863 45 $self->{mute} = $mute[0];
864 } else {
865 254 return $self->{mute};
866 }
867 }
868  
869 =head3 ok ($status)
870  
871 =head3 ok ($status, $testname)
872  
873 =head3 skip ($reason)
874  
875 Called from within the group subs by virtue of
876 L</Test::Builder::_HijackedByTestGroup internal class> delegating both
877 methods to us. Works like L<Test::Builder/ok>
878 resp. L<Test::Builder/skip>, except that the test results are stashed
879 away as part of the group result instead of being printed at once.
880  
881 =cut
882  
883 # The code was copied over from L<Test::Builder/ok>, and then
884 # simplified and refactored.
885 1655 ▶sub ok {
Subroutine ok: called CC=16 SCAR=27.7
886 1655 my ($self, $status, $testname) = @_;
887  
888 # Coerce the arguments into being actual scalars (not objects)
889 1655 ▶ $status = $status ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$status ? : 1494 161 1655
890 1655 ▶ $testname = substr($testname, 0) if defined $testname; # Stringifies
Branch: 1 branch
BranchTrueFalseTotal
if defined $testname 589 1066 1655
891  
892 # Use the actual Test::Builder->todo to get at the TODO status.
893 # This is both elegant and necessary for recursion, because
894 # L</test> localizes this same method in order to fool
895 # Test::Builder about the TODO state.
896 1655 my $T = Test::Builder->new;
897 1655 my($pack, $file, $line) = $T->caller;
898  
899 1655 ▶ my $todo = $T->todo($pack) || undef;
Condition100%2/2
$T->todo($pack) || undef
l!l
51650
MC/DC100%1/1
$T->todo($pack) || undef
$T->todo($pack)
Truth table100%2/2
A
A= $T->todo($pack)
Aresult
11
00
900 1655 ▶ $todo = substr($todo, 0) if $todo; # Stringifies
Branch: 1 branch
BranchTrueFalseTotal
if $todo 5 1650 1655
901  
902 1655 my $result = { status => $status };
903 1655 ▶ $result->{todo} = $todo if defined($todo);
Branch: 1 branch
BranchTrueFalseTotal
if defined $todo 5 1650 1655
904 1655 push @{$self->{subtests}}, $result;
905  
906 1655 ▶ if ($classstate_verbose and $classstate_verbose >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($classstate_verbose and $classstate_verbose >= 2) 264 1391 1655
Condition66%2/3
$classstate_verbose and $classstate_verbose >= 2
!ll&&!rl&&r
13910264
MC/DC50%1/2
$classstate_verbose and $classstate_verbose >= 2
$classstate_verbose $classstate_verbose >= 2
Truth table66%2/3
A and B
A= $classstate_verboseB= $classstate_verbose >= 2
ABresult
0X0
100
111
907 264 my $nums .= $self->_fully_qualified_test_number;
908 264 ▶ if ($nums =~ tr/.// < $classstate_verbose) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nums =~ tr/.// < $classstate_verbose) 228 36 264
909 228 ▶ my $line = ($status ? '' : 'not ') . "ok $nums";
Branch: 1 branch
BranchTrueFalseTotal
$status ? : 198 30 228
910 228 ▶ $line .= " $testname" if defined $testname;
Branch: 1 branch
BranchTrueFalseTotal
if defined $testname 228 0 228
911 228 $T->diag($line);
912 }
913 }
914  
915 # Report failures only, as Test::Builder would
916 1655 ▶ if( ! $status && ! $self->mute ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($status or $self->mute) 134 1521 1655
Condition100%3/3
$status or $self->mute
l!l&&r!l&&!r
149427134
MC/DC100%2/2
$status or $self->mute
$status $self->mute
Truth table100%3/3
A or B
A= $statusB= $self->mute
ABresult
1X1
011
000
917 134 ▶ my $msg = $todo ? "Failed (TODO)" : "Failed";
Branch: 1 branch
BranchTrueFalseTotal
$todo ? : 0 134 134
918  
919 134 ▶ if( defined $testname ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $testname) { } 128 6 134
920 128 $T->diag(qq[ $msg test '$testname'\n]);
921 128 ▶ unless ($InPredicate) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Test::Group::InPredicate) 88 40 128
922 88 $T->diag(qq[ in $file at line $line.\n]);
923 }
924 } else {
925 6 $T->diag(qq[ $msg test in $file at line $line.\n]);
926 }
927 }
928  
929 1655 return $status;
930 }
931  
932  
933 6 ▶sub skip {
Subroutine skip: called CC=1 SCAR=0.0
934 6 my ($self, $reason) = @_;
935 6 push @{$self->{subtests}}, { status => 1 };
936 }
937  
938 =head3 diag (@messages)
939  
940 Called from within the group subs by virtue of
941 L</Test::Builder::_HijackedByTestGroup internal class> delegating it
942 to us. If this runner object is L</mute>, does nothing; otherwise,
943 works like L<Test::Builder/diag>.
944  
945 =cut
946  
947 552 ▶sub diag {
Subroutine diag: called CC=2 SCAR=6.9
948 552 my ($self, @msgs) = @_;
949 552 ▶ return if ($self->{mute});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"mute"} 3 549 552
950 549 my $origdiag = Test::Builder->can("diag");
951 549 $origdiag->(Test::Builder->new, @msgs);
952 }
953  
954 =head3 subtests ()
955  
956 After the test is run, returns a list of hash references, each
957 indicating the status of a subtest that ran during L</run>. The
958 following keys may be set in each returned hash:
959  
960 =over
961  
962 =item I<status> (always)
963  
964 A boolean indicating whether the subtest was successful.
965  
966 =item I<todo> (may not exist)
967  
968 A string indicating an excuse why the test might have failed.
969  
970 =back
971  
972 In scalar context, returns the number of subtests that occured in the
973 group run.
974  
975 The list of I<subtests()> is appended to by L</ok> as the test group
976 progresses.
977  
978 =cut
979  
980 1598 ▶sub subtests { @{shift->{subtests}} }
Subroutine subtests: called CC=1 SCAR=0.0
981  
982 =head3 unexcused_failure_subtests ()
983  
984 Returns the subset of the L</subtests> that have a false I<status> and
985 no I<todo>. Such tests cause the test group to fail as a whole. In
986 scalar context, returns the number of such unexcused failures.
987  
988 =cut
989  
990 345 ▶sub unexcused_failure_subtests {
Subroutine unexcused_failure_subtests: called CC=2 SCAR=6.9
991 345 ▶ grep { (! $_->{status}) && ! exists($_->{todo}) }
Condition100%3/3
$_->{'status'} || exists $_->{'todo'}
l!l&&r!l&&!r
354512191
MC/DC100%2/2
$_->{'status'} || exists $_->{'todo'}
$_->{'status'} exists $_->{'todo'}
Truth table100%3/3
A || B
A= $_->{'status'}B= exists $_->{'todo'}
ABresult
1X1
011
000
992 (shift->subtests);
993 }
994  
995 =head3 unexpected_success_subtests ()
996  
997 Returns the subset of the L</subtests> that have a true I<status> and
998 also a I<todo>. Such tests are called B<unexpected successes> and are
999 signaled both by L<Test::Harness> and I<Test::Group> (see respectively
1000 L<Test::More/TODO: BLOCK> and L</TODO Tests>). In scalar context,
1001 returns the number of such unexpected successes.
1002  
1003 =cut
1004  
1005 186 ▶sub unexpected_success_subtests {
Subroutine unexpected_success_subtests: called CC=2 SCAR=6.9
1006 186 ▶ grep { $_->{status} && exists($_->{todo}) } (shift->subtests);
Condition100%3/3
$_->{'status'} && exists $_->{'todo'}
!ll&&!rl&&r
1233556
MC/DC100%2/2
$_->{'status'} && exists $_->{'todo'}
$_->{'status'} exists $_->{'todo'}
Truth table100%3/3
A && B
A= $_->{'status'}B= exists $_->{'todo'}
ABresult
0X0
100
111
1007 }
1008  
1009 =head3 todo_subtests ()
1010  
1011 Returns the subset of the L</subtests> that have a I<todo>, regardless
1012 of whether they are L</unexpected_success_subtests>.
1013  
1014 =cut
1015  
1016 189 ▶sub todo_subtests {
Subroutine todo_subtests: called CC=1 SCAR=0.0
1017 189 grep { exists $_->{todo} } (shift->subtests)
1018 }
1019  
1020 =head3 got_exception ()
1021  
1022 Returns true iff there was an exception raised while the test group
1023 sub ran (that is, whether L</_record_exception> was called once for
1024 this object).
1025  
1026 =cut
1027  
1028 699 ▶sub got_exception { defined shift->{exception} }
Subroutine got_exception: called CC=1 SCAR=0.0
1029  
1030 =head3 exception ()
1031  
1032 Returns the value of the exception passed to L</_record_exception>.
1033 Note that it is possible for I<exception()> to return undef, yet
1034 I<got_exception()> to return true (that is, an exception whose value
1035 is undef): this can happen when a DESTROY block that runs after the
1036 initial exception in turn throws another exception (remedy: one should
1037 use "local $@;" at the beginning of every sub DESTROY).
1038  
1039 =cut
1040  
1041 6 ▶sub exception { shift->{exception} }
Subroutine exception: called CC=1 SCAR=0.0
1042  
1043 =head3 is_skipped ()
1044  
1045 Returns true iff this test was skipped and did not actually run.
1046  
1047 =head3 skip_reason ()
1048  
1049 Returns the reason that was stipulated by the test writer for skipping
1050 this test. Note that I<skip_reason()> may be undef even if
1051 L</skipped> is true.
1052  
1053 =cut
1054  
1055 819 ▶sub is_skipped { exists shift->{skipreason} }
Subroutine is_skipped: called CC=1 SCAR=0.0
1056 21 ▶sub skip_reason { shift->{skipreason} }
Subroutine skip_reason: called CC=1 SCAR=0.0
1057  
1058 =head3 as_Test_Builder_params ()
1059  
1060 Returns a ($OK_status, $TODO_string) pair that sums up what we should
1061 tell L<Test::Builder> about this test (assuming that it actually ran,
1062 as opposed to L</is_skipped> tests). The returned values implement
1063 the algorithm detailed in L</test>; they are designed to be used
1064 respectively as the first parameter to L<Test::Builder/ok>, and as
1065 what L<Test::Builder/todo> should be tricked into returning during the
1066 call to said I<< Test::Builder->ok >> (have a look at the source code
1067 for L</test> if you want to see that trick in action).
1068  
1069 I<as_Test_Builder_params> will do its best to sum up the status of the
1070 multiple tests ran inside this group into what amounts to a single
1071 call to L<Test::Builder/ok>, according to the following table:
1072  
1073 Situation $OK_status defined($TODO_string)
1074  
1075 Real success true false
1076  
1077 Success, but TODOs seen false true
1078 within the group
1079  
1080 Unexpected TODO success(es) true true
1081 within the group
1082  
1083 Failed test in group, false false
1084 or no tests run at all
1085  
1086 Finally, if the test group as a whole is running in a TODO context (by
1087 virtue of $TODO being defined at L</test> invocation time, or the test
1088 having the word TODO in the name, as discussed in L</TODO Tests>),
1089 $TODO_string will be set if it isn't already, possibly transforming
1090 the fate of the test group accordingly.
1091  
1092 =cut
1093  
1094 370 ▶sub as_Test_Builder_params {
Subroutine as_Test_Builder_params: called CC=11 SCAR=24.0
1095 370 my ($self) = @_;
1096  
1097 370 ▶ die <<"MESSAGE" if ! wantarray;
Branch: 1 branch
BranchTrueFalseTotal
unless wantarray 0 370 370
1098 INCORRECT CALL: array context only for this method.
1099 MESSAGE
1100  
1101 370 my ($OK, $TODO_string);
1102 370 ▶ if ($self->is_skipped) {
Branch: 4 branches
BranchTrueFalseTotal
if ($self->is_skipped) { } 0 370 370
elsif ($self->got_exception or not $self->subtests or $self->unexcused_failure_subtests) { } 187 183 370
elsif ($self->unexpected_success_subtests) { } 3 180 183
elsif ($self->todo_subtests) { } 9 171 180
1103 0 die <<"MESSAGE";
1104 INCORRECT CALL: this method should not be called for skipped tests
1105 MESSAGE
1106 ▶ } elsif ($self->got_exception ||
Condition100%6/6
$self->got_exception or not $self->subtests or $self->unexcused_failure_subtests
l!l&&r!l&&!r
25162183
$self->got_exception or not $self->subtests
l!l&&r!l&&!r
205345
MC/DC100%3/3
$self->got_exception or not $self->subtests or $self->unexcused_failure_subtests
$self->got_exception not $self->subtests $self->unexcused_failure_subtests
Truth table100%4/4
A or not(B) or C
A= $self->got_exceptionB= not $self->subtestsC= $self->unexcused_failure_subtests
ABCresult
1XX1
01X1
0011
0000
1107 !($self->subtests) ||
1108 $self->unexcused_failure_subtests) {
1109 187 ($OK, $TODO_string) = (0, undef);
1110 } elsif ($self->unexpected_success_subtests) {
1111 3 ($OK, $TODO_string) = (1, $self->_make_todo_string
1112 ($self->unexpected_success_subtests));
1113 } elsif ($self->todo_subtests) {
1114 9 ($OK, $TODO_string) =
1115 (0, $self->_make_todo_string($self->todo_subtests));
1116 } else {
1117 171 ($OK, $TODO_string) = (1, undef); # Hurray!
1118 }
1119 370 ▶ if (! defined $TODO_string) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $TODO_string) 358 12 370
1120 358 ▶ $TODO_string = $self->{name} if $self->{name} =~ m/\bTODO\b/;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"name"} =~ /\bTODO\b/ 13 345 358
1121 358 ▶ $TODO_string = $self->{in_todo} if $self->{in_todo};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"in_todo"} 15 343 358
1122 }
1123 370 return ($OK, $TODO_string);
1124 }
1125  
1126 =head3 _hijack ()
1127  
1128 Hijacks L<Test::Builder> for the time the test group sub is being run,
1129 so that we may capture the calls to L<Test::Builder/ok> and friends
1130 made from within the group sub. L</_unhijack> cancels this behavior.
1131  
1132 When called while L</current> is undef, C<< Test::Builder->new >> is
1133 (ahem) temporarily reblessed into the
1134 I<Test::Builder::_HijackedByTestGroup> package, so that any method
1135 calls performed subsequently against it will be routed through
1136 L</Test::Builder::_HijackedByTestGroup internal class> where they can
1137 be tampered with at will. This works even if third-party code
1138 happened to hold a reference to C<< Test::Builder->new >> before
1139 I<_hijack> was called.
1140  
1141 If on the other hand L</current> was already defined before entering
1142 I<_hijack>, then a B<nested hijack> is performed: this is to support
1143 nested L</test> group subs. In this case, the returned object behaves
1144 mostly like the first return value of I<_hijack> except that its
1145 L</_unhijack> method has no effect.
1146  
1147 =cut
1148  
1149 308 ▶sub _hijack {
Subroutine _hijack: called CC=2 SCAR=6.9
1150 308 my ($self) = @_;
1151  
1152 308 my $class = ref($self);
1153 308 ▶ if (defined $class->current) { # Nested hijack
Branch: 1 branch
BranchTrueFalseTotal
if (defined $class->current) { } 87 221 308
1154 87 $self->{parent} = $class->current;
1155 } else { # Top-level hijack
1156 221 $self->{orig_testbuilder} = Test::Builder->new;
1157 221 $self->{reblessed_from} = ref($self->{orig_testbuilder});
1158 bless($self->{orig_testbuilder},
1159 221 "Test::Builder::_HijackedByTestGroup");
1160 }
1161  
1162 # The following line of code must be executed immediately after
1163 # the reblessing above, as the delegating stubs (L</ok>, L</skip>
1164 # and L</diag> below) need ->current() to be set to work:
1165 308 $class->current($self);
1166 }
1167  
1168 =head3 _unhijack ()
1169  
1170 Unbuggers the C<< Test::Builder->new >> singleton that was reblessed
1171 by L</_hijack>, so that it may resume being itself, or pops one item
1172 from the L</current> stack in case of a nested hijack.
1173  
1174 =cut
1175  
1176 308 ▶sub _unhijack {
Subroutine _unhijack: called CC=2 SCAR=6.9
1177 308 my ($self) = @_;
1178 308 ▶ if (defined($self->{orig_testbuilder})) { # Top-level unhijack
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{'orig_testbuilder'}) { } 221 87 308
1179 221 $self->current(undef);
1180 221 bless $self->{orig_testbuilder}, $self->{reblessed_from};
1181 } else {
1182 # Nested unhijack
1183 87 $self->current($self->{parent});
1184 }
1185 308 1;
1186 }
1187  
1188 =head3 _fully_qualified_test_number ()
1189  
1190 Returns the compound number of the current test, fully qualified
1191 from the outer L<Test::Builder> test down into the current test
1192 group, with numbers joined with dots.
1193  
1194 =cut
1195  
1196 264 ▶sub _fully_qualified_test_number {
Subroutine _fully_qualified_test_number: called CC=3 SCAR=11.0
1197 264 my $self = shift;
1198  
1199 264 my @nums;
1200 264 my $runner = $self->current;
1201 264 ▶ while ($runner) {
Branch: 1 branch
BranchTrueFalseTotal
if ($runner) 480 264 744
1202 480 unshift @nums, 1+scalar $runner->subtests;
1203 480 $runner = $runner->{parent};
1204 }
1205 264 ▶ --$nums[-1] if @nums;
Branch: 1 branch
BranchTrueFalseTotal
if @nums 264 0 264
1206 264 return join '.', 1+Test::Builder->new->current_test, @nums;
1207 }
1208  
1209 =head3 _run_with_local_TODO ($callerpackage, $sub)
1210  
1211 Invokes the test sub $sub while temporarily setting the variable
1212 C<${${callerpackage}::TODO}> to undef, thereby implementing the
1213 local-TODO semantics described in L</TODO Tests>. Returns true if
1214 $sub completed, and false if $sub threw an exception (that is
1215 thereafter available in $@ as usual).
1216  
1217 I<_run_with_local_TODO> is guaranteed not to throw an exception
1218 itself, so that it is safe to use it in a critical section opened by
1219 calling L</_hijack> and closed by calling L</_unhijack>.
1220  
1221 =cut
1222  
1223 308 ▶sub _run_with_local_TODO {
Subroutine _run_with_local_TODO: called CC=1 SCAR=0.0
1224 308 my ($self, $callerpackage, $sub) = @_;
1225 ## Locally sets $TODO to undef, see POD snippet "TODO gotcha 2".
1226 ## I used to do
1227 # no strict 'refs';
1228 # local ${$callerpackage . '::TODO' };
1229 ## but this doesn't work in 5.6 ("Can't localize through a reference")
1230 76 ▶ my $TODOref = do { no strict "refs"; \${$callerpackage . '::TODO' } };
Subroutine BEGIN: called CC=1 SCAR=0.0
1231 308 my $TODOorig = $$TODOref;
1232 308 $$TODOref = undef;
1233  
1234 308 my $retval = eval { $sub->(); 1; };
1235 308 $$TODOref = $TODOorig;
1236 308 return $retval;
1237 }
1238  
1239 =head3 _run_code_via_plugins (@plugins)
1240  
1241 Invokes the subroutine reference stored as C<$self->{code}> via
1242 the chain of plugins in C<@plugins>.
1243  
1244 =cut
1245  
1246 134 ▶sub _run_code_via_plugins {
Subroutine _run_code_via_plugins: called CC=2 SCAR=6.9
1247 134 my ($self, $plugin, @more) = @_;
1248  
1249 134 ▶ if ($plugin) {
Branch: 1 branch
BranchTrueFalseTotal
if ($plugin) { } 68 66 134
1250 68 my $old_inp = $InPredicate;
1251 68 local $InPredicate = 1;
1252 90 ▶ $plugin->(sub{
Subroutine __ANON__: called CC=1 SCAR=0.0
1253 90 local $InPredicate = $old_inp;
1254 90 $self->_run_code_via_plugins(@more);
1255 68 });
1256 } else {
1257 66 $self->{code}->();
1258 }
1259 }
1260  
1261 =head3 _skip ($reason)
1262  
1263 Private setter called from L</run> when the test sub is not to be
1264 called at all. $reason is the reason why the test is being skipped
1265 (probable causes are L</skip_next_test>, L</skip_next_tests>,
1266 L</test_only> and friends).
1267  
1268 =cut
1269  
1270 24 ▶sub _skip {
Subroutine _skip: called CC=1 SCAR=0.0
1271 24 my ($self, $reason) = @_;
1272  
1273 24 $self->{skipreason} = $reason;
1274 }
1275  
1276 =head3 _record_exception ()
1277  
1278 Memorizes the exception that was raised by the group sub that just
1279 run. The exception is looked for in variables C<$@> and
1280 C<$Error::THROWN>. TODO: add support for other popular exception
1281 management classes.
1282  
1283 =cut
1284  
1285 10 ▶sub _record_exception {
Subroutine _record_exception: called CC=5 SCAR=20.9
1286 10 my ($self) = @_;
1287 $self->{exception} =
1288 10 ▶ ( (ref($@) || (defined($@) && length($@) > 0)) ? $@ :
Branch: 2 branches
BranchTrueFalseTotal
ref $@ || defined $@ && length $@ > 0 ? : 10 0 10
defined $Error::THROWN ? : 0 0 0
Condition50%3/6
ref $@ or defined $@ and length $@ > 0
l!l&&r!l&&!r
280
defined $@ and length $@ > 0
!ll&&!rl&&r
008
MC/DC0%0/3
ref $@ or defined $@ and length $@ > 0
ref $@ defined $@ length $@ > 0
Truth table50%2/4
A or B and C
A= ref $@B= defined $@C= length $@ > 0
ABCresult
1XX1
0111
00X0
0100
1289 # Factor L<Error> in (TODO: add L<Exception::Class> as
1290 # well):
1291 defined($Error::THROWN) ? $Error::THROWN :
1292 undef );
1293 }
1294  
1295 =head3 _make_todo_string (@subtests)
1296  
1297 Pretty-prints an appropriate string to return as the second element in
1298 the returned list on behalf of L</as_Test_Builder_params>. @subtests
1299 are the TODO sub-tests that the caller wants to talk about (depending
1300 on the situation, that would be all the L</todo_subtests>, or only the
1301 L</unexpected_success_subtests>).
1302  
1303 =cut
1304  
1305 12 ▶sub _make_todo_string {
Subroutine _make_todo_string: called CC=2 SCAR=7.1
1306 12 my ($self, @subtests) = @_;
1307 12 ▶ return join(", ", map { $_->{todo} || "(no TODO explanation)" }
Condition50%1/2
$_->{'todo'} || '(no TODO explanation)'
l!l
150
MC/DC0%0/1
$_->{'todo'} || '(no TODO explanation)'
$_->{'todo'}
Truth table50%1/2
A
A= $_->{'todo'}
Aresult
11
00
1308 @subtests);
1309 }
1310  
1311 =head2 Test::Builder::_HijackedByTestGroup internal class
1312  
1313 This is an internal subclass of L<Test::Builder> used as an accomplice
1314 by L</_hijack> to hijack the method calls performed upon the
1315 Test::Builder singleton (see L<Test::Builder/new>) by the various
1316 testing modules from the CPAN, e.g. L<Test::More>, L<Test::Pod> and
1317 friends. It works almost the same as the real thing, except for the
1318 following method calls:
1319  
1320 =cut
1321  
1322 package Test::Builder::_HijackedByTestGroup;
1323 76 ▶use base "Test::Builder";
Subroutine BEGIN: called CC=1 SCAR=0.0
1324  
1325 =head3 ok ()
1326  
1327 =head3 skip ()
1328  
1329 =head3 diag ()
1330  
1331 These methods are delegated to the L</current> instance of
1332 I<Test::Group::_Runner>.
1333  
1334 =cut
1335  
1336 76 foreach my $delegated (qw(ok skip diag)) {
1337 76 ▶ no strict "refs";
Subroutine BEGIN: called CC=1 SCAR=0.0
1338 228 ▶ *{$delegated} = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1339 2213 my $self = shift;
1340 2213 unshift(@_, Test::Group::_Runner->current);
1341 2213 goto &{"Test::Group::_Runner::".$delegated};
1342 228 };
1343 }
1344  
1345 =end internals
1346  
1347 =head1 BUGS
1348  
1349 This class uses a somewhat unhealthy dose of black magic to take over
1350 control from L<Test::Builder> when running inside a L</test> group
1351 sub. While the temporary re-blessing trick used therein is thought to
1352 be very robust, it is not very elegant.
1353  
1354 The experimental use_subtest() feature allows you to avoid the black
1355 magic if your L<Test::Builder> is recent enough to support subtests.
1356  
1357 =head1 SEE ALSO
1358  
1359 L<Test::Simple>, L<Test::More>, L<Test::Builder>, and friends
1360  
1361 The C<perl-qa> project, L<http://qa.perl.org/>.
1362  
1363 =head2 Similar modules on CPAN
1364  
1365 L<Test::Class> can be used to turn a test suite into a full-fledged
1366 object class of its own, in xUnit style. It also happens to support a
1367 similar form of test grouping using the C<:Test(no_plan)> or C<:Tests>
1368 attributes. Switching over to I<Test::Class> will make a test suite
1369 more rugged and provide a number of advantages, but it will also
1370 dilute the "quick-and-dirty" aspect of .t files somewhat. This may or
1371 may not be what you want: for example, the author of this module
1372 enjoys programming most when writing tests, because the most infamous
1373 Perl hacks are par for the course then :-). Anyway TIMTOWTDI, and
1374 I<Test::Group> is a way to reap some of the benefits of I<Test::Class>
1375 (e.g. running only part of the test suite) without changing one's
1376 programming style too much.
1377  
1378 =head1 AUTHORS
1379  
1380 Nick Cleaton <ncleaton@cpan.org>
1381  
1382 Dominique Quatravaux <domq@cpan.org>
1383  
1384 Nicolas M. ThiE<eacute>ry <nthiery@users.sf.net>
1385  
1386 =head1 LICENSE
1387  
1388 Copyright (C) 2004 by IDEALX <http://www.idealx.com>
1389  
1390 Copyright (c) 2009 by Nick Cleaton and Dominique Quatravaux
1391  
1392 This library is free software; you can redistribute it and/or modify
1393 it under the same terms as Perl itself, either Perl version 5.8.1 or,
1394 at your option, any later version of Perl 5 you may have available.
1395  
1396 =cut
1397  
1398 76 1;
« blib/lib/Test/Group/Tester.pm ↑ Summary blib/lib/Test/Group/Plan.pm »