blib/lib/Test/Class/Tiny.pm

filter: Statementstmt 90.1% 110 / 122 Branchbran 68.7% 33 / 48 Conditioncond 83.3% 5 / 6 MC/DCmcdc 50.0% 2 / 4 Subroutinesub 100% 13 / 13 Podpod 25.0% 1 / 4 totaltotal 83.2% 164 / 197 CC 31 SCAR 22.5
CC
31
Cov
84%
runtests
18.5
_analyze
8.0
__ANON__
4.0
CRAP 9.5
↑ Summary
1 package Test::Class::Tiny;
2  
3 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 5 our $VERSION;
7 5 $VERSION = '0.03';
8  
9 =encoding utf-8
10  
11 =head1 NAME
12  
13 Test::Class::Tiny - xUnit in Perl, simplified
14  
15 =head1 SYNOPSIS
16  
17 package t::mytest;
18  
19 use parent qw( Test::Class::Tiny );
20  
21 __PACKAGE__->runtests() if !caller;
22  
23 sub T_startup_something {
24 # Runs at the start of the test run.
25 }
26  
27 sub something_T_setup {
28 # Runs before each normal test function
29 }
30  
31 # Expects 2 assertions:
32 sub T2_normal {
33 ok(1, 'yes');
34 ok( !0, 'no');
35 }
36  
37 # Ignores assertion count:
38 sub T0_whatever {
39 ok(1, 'yes');
40 }
41  
42 sub T_teardown_something {
43 # Runs after each normal test function
44 }
45  
46 sub T_shutdown_something {
47 # Runs at the end of the test run.
48 }
49  
50 =head1 STATUS
51  
52 This module is B<EXPERIMENTAL>. If you use it, you MUST check the changelog
53 before upgrading to a new version. Any CPAN distributions that use this module
54 could break whenever this module is updated.
55  
56 =head1 DESCRIPTION
57  
58 L<Test::Class> has served Perl’s xUnit needs for a long time
59 but is incompatible with the L<Test2> framework. This module allows for
60 a similar workflow but in a way that works with both L<Test2> and the older,
61 L<Test::Builder>-based modules.
62  
63 =head1 HOW (AND WHY) TO USE THIS MODULE
64  
65 xUnit encourages well-designed tests by encouraging organization of test
66 logic into independent chunks of test logic rather than a single monolithic
67 block of code.
68  
69 xUnit provides standard hooks for:
70  
71 =over
72  
73 =item * startup: The start of all tests
74  
75 =item * setup: The start of an individual test group (i.e., Perl function)
76  
77 =item * teardown: The end of an individual test group
78  
79 =item * shutdown: The end of all tests
80  
81 =back
82  
83 To write functions that execute at these points in the workflow,
84 name those functions with the prefixes C<T_startup_>, C<T_setup_>,
85 C<T_teardown_>, or C<T_shutdown_>. B<Alternatively>, name such functions
86 with the I<suffixes> C<_T_startup>, C<_T_setup>, C<_T_teardown>, or
87 C<_T_shutdown>.
88  
89 To write a test function—i.e., a function that actually runs some
90 assertions—prefix the function name with C<T>, the number of test assertions
91 in the function, then an underscore. For example, a function that contains
92 9 assertions might be named C<T9_check_validation()>. If that function
93 doesn’t run exactly 9 assertions, a test failure is produced.
94  
95 To forgo counting test assertions, use 0 as the test count, e.g.,
96 C<T0_check_validation()>.
97  
98 You may alternatively use suffix-style naming for test functions well,
99 e.g., C<check_validation_T9()>, C<check_validation_T0()>.
100  
101 The above convention is a significant departure from L<Test::Class>,
102 which uses Perl subroutine attributes to indicate this information.
103 Using method names is dramatically simpler to implement and also easier
104 to type.
105  
106 In most other respects this module attempts to imitate L<Test::Class>.
107  
108 =head2 PLANS
109  
110 The concept of a global “plan” (i.e., an expected number of assertions)
111 isn’t all that sensible with xUnit because each test function has its
112 own plan. So, ideally the total number of expected assertions for a given
113 test module is just the sum of all test functions’ expected assertions.
114  
115 Thus, currently, C<runtests()> sets the L<Test2::Hub> object’s plan to
116 C<no_plan> if the plan is undefined.
117  
118 =head1 TEST INHERITANCE
119  
120 Like L<Test::Class>, this module seamlessly integrates inherited methods.
121 To have one test module inherit another module’s tests, just make that
122 first module a subclass of the latter.
123  
124 B<CAVEAT EMPTOR:> Inheritance in tests, while occasionally useful, can also
125 make for difficult maintenance over time if overused. Where I’ve found it
126 most useful is cases like L<Promise::ES6>, where each test needs to run with
127 each backend implementation.
128  
129 =head1 RUNNING YOUR TEST
130  
131 To use this module to write normal Perl test scripts, just define
132 the script’s package (ideally not C<main>, but it’ll work) as a subclass of
133 this module. Then put the following somewhere in the script:
134  
135 __PACKAGE__->runtests() if !caller;
136  
137 Your test will thus execute as a “modulino”.
138  
139 =head1 SPECIAL FEATURES
140  
141 =over
142  
143 =item * As in L<Test::Class>, a C<SKIP_CLASS()> method may be defined. If this
144 method returns truthy, then the class’s tests are skipped, and that truthy
145 return is given as the reason for the skip.
146  
147 =item * The C<TEST_METHOD> environment variable is honored as in L<Test::Class>.
148  
149 =item * L<Test::Class>’s C<fail_if_returned_early()> method is NOT recognized
150 here because an early return will already trigger a failure.
151  
152 =item * Within a test method, C<num_tests()> may be called to retrieve the
153 number of expected test assertions.
154  
155 =item * To define a test function whose test count isn’t known until runtime,
156 name it B<without> the usual C<T$num> prefix, then at runtime do:
157  
158 $test_obj->num_method_tests( $name, $count )
159  
160 See F<t/> in the distribution for an example of this.
161  
162 =back
163  
164 =head1 COMMON PITFALLS
165  
166 Avoid the following:
167  
168 =over
169  
170 =item * Writing startup logic outside of the module class, e.g.:
171  
172 if (!caller) {
173 my $mock = Test::MockModule->new('Some::Module');
174 $mock->redefine('somefunc', sub { .. } );
175  
176 __PACKAGE__->runtests();
177 }
178  
179 The above works I<only> if the test module runs in its own process; if you try
180 to run this module with anything else it’ll fail because C<caller()> will be
181 truthy, which will prevent the mocking from being set up, which your test
182 probably depends on.
183  
184 Instead of the above, write a wrapper around C<runtests()>, thus:
185  
186 sub runtests {
187 my $self = shift;
188  
189 my $mock = Test::MockModule->new('Some::Module');
190 $mock->redefine('somefunc', sub { .. } );
191  
192 $self->SUPER::runtests();
193 }
194  
195 This ensures your test module will always run with the intended mocking.
196  
197 =item * REDUX: Writing startup logic outside of the module class, e.g.:
198  
199 my $mock = Test::MockModule->new('Some::Module');
200 $mock->redefine('somefunc', sub { .. } );
201  
202 __PACKAGE__->runtests() if !caller;
203  
204 This is even worse than before because the mock will be global, which
205 will quietly apply it where we don’t intend. This produces
206 action-at-a-distance bugs, which can be notoriously hard to find.
207  
208 =back
209  
210 =head1 SEE ALSO
211  
212 Besides L<Test::Class>, you might also look at the following:
213  
214 =over
215  
216 =item * L<Test2::Tools::xUnit> also implements xUnit for L<Test2> but doesn’t
217 allow inheritance.
218  
219 =item * L<Test::Class::Moose> works with L<Test2>, but the L<Moose> requirement
220 makes use in CPAN modules problematic.
221  
222 =back
223  
224 =head1 AUTHOR
225  
226 Copyright 2019 L<Gasper Software Consulting|http://gaspersoftware.com> (FELIPE)
227  
228 =head1 LICENSE
229  
230 This code is licensed under the same license as Perl itself.
231  
232 =cut
233  
234 #----------------------------------------------------------------------
235  
236 5 ▶use mro ();
Subroutine BEGIN: called CC=1 SCAR=0.0
237  
238 5 ▶use Test2::API ();
Subroutine BEGIN: called CC=1 SCAR=0.0
239  
240 5 our ($a, $b);
241  
242 #----------------------------------------------------------------------
243  
244 5 ▶use constant SKIP_CLASS => ();
Subroutine BEGIN: called CC=1 SCAR=0.0
245  
246 5 ▶sub new { bless {}, shift }
Subroutine new: called CC=1 SCAR=0.0
Pod undocumented
247  
248 2 ▶sub num_tests {
Subroutine num_tests: called CC=2 SCAR=7.6
Pod documented
249 2 my ($self) = @_;
250  
251 2 ▶ if (!$self->{'_running'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_running"}) 0 2 2
252 0 die "num_tests() called outside of running test!";
253 }
254  
255 2 return $self->{'_num_tests'};
256 }
257  
258 1 ▶sub num_method_tests {
Subroutine num_method_tests: called CC=3 SCAR=11.6
Pod undocumented
259 1 my ($self, $name, $count) = @_;
260  
261 1 ▶ die 'need name!' if !$name;
Branch: 1 branch
BranchTrueFalseTotal
unless $name 0 1 1
262  
263 1 ▶ if (@_ == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2) 0 1 1
264 0 return $self->{'test'}{$name};
265 }
266  
267 1 $self->{'test'}{$name}{'count'} = $count;
268 1 $self->{'test'}{$name}{'simple_name'} = $name;
269  
270 1 return $self;
271 }
272  
273 5 ▶sub runtests {
Subroutine runtests: called CC=16 SCAR=29.2
Pod undocumented
274 5 my ($self) = @_;
275  
276 5 ▶ if (!ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 4 1 5
277 4 $self = $self->new();
278 }
279  
280 5 local $self->{'_running'} = 1;
281  
282 # Allow calls as either instance or object method.
283 5 ▶ if (!ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self) 0 5 5
284 0 my $obj = $self->new();
285 0 $self = $obj;
286 }
287  
288 5 my $big_ctx = Test2::API::context();
289 5 my $ctx = $big_ctx->snapshot();
290 5 $big_ctx->release();
291  
292 5 ▶ if (my $reason = $self->SKIP_CLASS()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $reason = $self->SKIP_CLASS) { } 0 5 5
293 0 $ctx->plan(1);
294 0 $ctx->skip( ref($self), $reason );
295 }
296 else {
297 5 $self->_analyze();
298  
299 5 ▶ if ( my $startup_hr = $self->{'startup'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $startup_hr = $self->{"startup"}) 1 4 5
300 1 $self->_run_funcs($startup_hr);
301 }
302  
303 5 ▶ if ( my $tests_hr = $self->{'test'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $tests_hr = $self->{"test"}) 5 0 5
304 5 my $setup_hr = $self->{'setup'};
305 5 my $teardown_hr = $self->{'teardown'};
306  
307 5 my $filter_fn;
308 my $got_count;
309  
310 5 my $hub = $ctx->hub();
311  
312 5 ▶ $hub->plan('NO PLAN') if !defined $hub->plan();
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hub->plan 5 0 5
313  
314 26 ▶ my $filter_cr = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
315 26 my ($hub, $event) = @_;
316  
317 26 ▶ $got_count++ if $event->increments_count();
Branch: 1 branch
BranchTrueFalseTotal
if $event->increments_count 24 2 26
318  
319 26 ▶ if ($event->can('name') && !defined $event->name()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($event->can("name") and not defined $event->name) 10 16 26
Condition100%3/3
$event->can("name") and not defined $event->name
!ll&&!rl&&r
21410
MC/DC100%2/2
$event->can("name") and not defined $event->name
$event->can("name") not defined $event->name
Truth table100%3/3
A and not(B)
A= $event->can("name")B= not defined $event->name
ABresult
0X0
100
111
320 10 my $name = $tests_hr->{$filter_fn}{'simple_name'};
321 10 $name =~ tr<_>< >;
322 10 $event->set_name($name);
323 }
324  
325 26 return $event;
326 5 };
327  
328 5 $hub->filter($filter_cr);
329  
330 my @sorted_fns = sort {
331 5 ▶ ( $tests_hr->{$a}{'simple_name'} cmp $tests_hr->{$b}{'simple_name'} )
Condition66%2/3
$tests_hr->{$a}{'simple_name'} cmp $tests_hr->{$b}{'simple_name'} || $a cmp $b
l!l&&r!l&&!r
1710
MC/DC0%0/2
$tests_hr->{$a}{'simple_name'} cmp $tests_hr->{$b}{'simple_name'} || $a cmp $b
$tests_hr->{$a}{'simple_name'} cmp $tests_hr->{$b}{'simple_name'} $a cmp $b
Truth table66%2/3
A || B
A= $tests_hr->{$a}{'simple_name'} cmp $tests_hr->{$b}{'simple_name'}B= $a cmp $b
ABresult
1X1
011
000
332 || ( $a cmp $b )
333 } keys %$tests_hr;
334  
335 5 for my $fn (@sorted_fns) {
336 17 $filter_fn = $fn;
337  
338 17 ▶ if (my $ptn = $ENV{'TEST_METHOD'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ptn = $ENV{"TEST_METHOD"}) 0 17 17
339 0 ▶ next if $fn !~ m<$ptn>;
Branch: 1 branch
BranchTrueFalseTotal
unless $fn =~ /$ptn/ 0 0 0
340 }
341  
342 17 ▶ if ($ENV{'TEST_VERBOSE'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"TEST_VERBOSE"}) 0 17 17
343 0 $ctx->diag( $/ . ref($self) . "->$fn()" );
344 }
345  
346 17 $self->_run_funcs($setup_hr);
347  
348 17 $got_count = 0;
349  
350 17 my $want_count = $tests_hr->{$fn}{'count'};
351  
352 17 local $self->{'_num_tests'} = $want_count;
353  
354 17 local $@;
355 17 ▶ eval { $self->$fn(); 1 } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $self->$fn; 1 } } or do { my $err = $@; $ctx->fail("$fn()", "Caught exception: $err") } 17 0 17
356 0 my $err = $@;
357 0 $ctx->fail("$fn()", "Caught exception: $err");
358 };
359  
360 17 ▶ if ($want_count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want_count) 15 2 17
361 15 ▶ if ($want_count != $got_count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($want_count != $got_count) 0 15 15
362 0 $ctx->fail("Test count mismatch: got $got_count, expected $want_count");
363 }
364 }
365  
366 17 $self->_run_funcs($teardown_hr);
367 }
368  
369 5 $hub->unfilter($filter_cr);
370 }
371  
372 5 ▶ if ( my $shutdown_hr = $self->{'shutdown'} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $shutdown_hr = $self->{"shutdown"}) 1 4 5
373 1 $self->_run_funcs($shutdown_hr);
374 }
375 }
376  
377 5 return;
378 }
379  
380 5 ▶sub _analyze {
Subroutine _analyze: called CC=8 SCAR=20.8
381 5 my ($self) = @_;
382  
383 5 ▶ if (!$self->{'_analyzed'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_analyzed"}) 5 0 5
384 5 my @isa = @{ mro::get_linear_isa(ref $self) };
385  
386 5 my $t_regexp = q<T(_setup|_teardown|_startup|_shutdown|[0-9]+)>;
387 5 my $prefix_regexp = qr<\A${t_regexp}_(.+)>;
388 5 my $suffix_regexp = qr<(.+)_$t_regexp\z>;
389  
390 5 for my $ns (@isa) {
391 12 my $ptbl_hr = do {
392 5 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
393 12 \%{"${ns}::"};
394 };
395  
396 12 for my $name (keys %$ptbl_hr) {
397 770 ▶ next if !$self->can($name);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->can($name) 37 733 770
398  
399 733 my ($whatsit, $simple_name);
400  
401 733 ▶ if ($name =~ $prefix_regexp) {
Branch: 2 branches
BranchTrueFalseTotal
if ($name =~ /$prefix_regexp/) { } 11 722 733
elsif ($name =~ /$suffix_regexp/) { } 9 713 722
402 11 $whatsit = $1;
403 11 $simple_name = $2;
404 }
405 elsif ($name =~ $suffix_regexp) {
406 9 $simple_name = $1;
407 9 $whatsit = $2;
408 }
409 else {
410 713 next;
411 }
412  
413 20 ▶ if ( $whatsit =~ s<_><> ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($whatsit =~ s/_//) { } 4 16 20
414 4 $self->{$whatsit}{$name} = undef;
415 }
416 else {
417 16 $self->{'test'}{$name} = {
418 count => $whatsit,
419 simple_name => $simple_name,
420 };
421 }
422 }
423 }
424  
425 5 $self->{'_analyzed'} = 1;
426 }
427  
428 5 return;
429 }
430  
431 36 ▶sub _run_funcs {
Subroutine _run_funcs: called CC=3 SCAR=11.4
432 36 my ($self, $funcs_hr) = @_;
433  
434 36 for my $fn (sort keys %$funcs_hr) {
435 12 ▶ if ( $funcs_hr->{$fn} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($funcs_hr->{$fn}) { } 0 12 12
436 0 $funcs_hr->{$fn}->($self);
437 }
438 else {
439 12 $self->$fn();
440 }
441 }
442  
443 36 return;
444 }
445  
446 5 1;
↑ Summary