lib/Template/Test.pm

filter: Statementstmt 81.8% 126 / 154 Branchbran 67.1% 43 / 64 Conditioncond 64.2% 9 / 14 MC/DCmcdc 50.0% 4 / 8 Subroutinesub 94.1% 16 / 17 Podpod 50.0% 5 / 10 totaltotal 76.0% 203 / 267 CC 42 SCAR 31.4
CC
42
Cov
77%
test_expect
41.2
assert
12.0
match
6.5
CRAP 23.1
« lib/Template/Stash.pm ↑ Summary lib/Template/View.pm »
1 #============================================================= -*-Perl-*-
2 #
3 # Template::Test
4 #
5 # DESCRIPTION
6 # Module defining a test harness which processes template input and
7 # then compares the output against pre-define expected output.
8 # Uses Test::Builder for TAP output, compatible with Test::Harness
9 # and subtests. This was originally the t/texpect.pl script.
10 #
11 # AUTHOR
12 # Andy Wardley <abw@wardley.org>
13 #
14 # COPYRIGHT
15 # Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved.
16 #
17 # This module is free software; you can redistribute it and/or
18 # modify it under the same terms as Perl itself.
19 #
20 #============================================================================
21  
22 package Template::Test;
23  
24 94 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 94 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 94 ▶use Template;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 94 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 94 ▶use Test::Builder;
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 94 ▶use constant MSWin32 => $^O eq 'MSWin32';
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 94 our $VERSION = '3.106';
33 94 our $DEBUG = 0;
34 94 our @ISA = qw( Exporter );
35 94 our @EXPORT = qw( ntests ok is match flush skip_all test_expect callsign banner );
36 94 our @EXPORT_OK = ( 'assert' );
37 94 our %EXPORT_TAGS = ( all => [ @EXPORT_OK, @EXPORT ] );
38 94 $| = 1;
39  
40 94 our $REASON = 'not applicable on this platform';
41 94 our $NO_FLUSH = 0;
42 94 our $EXTRA = 0; # any extra tests to come after test_expect()
43 94 ▶our $PRESERVE = 0 # don't mangle newlines in output/expect
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Template::Test::PRESERVE 94 0 94
44 unless defined $PRESERVE;
45  
46 94 our ($loaded, %callsign);
47  
48 # always set binmode on Win32 machines so that any output generated
49 # is true to what we expect
50 94 $Template::BINMODE = (MSWin32) ? 1 : 0;
51  
52 94 my $TB = Test::Builder->new;
53 94 my @results = ();
54 94 my $plan_declared = 0;
55 94 *is = \&match;
56  
57 94 ▶END {
Subroutine END: called CC=1 SCAR=0.0
58 # ensure flush() is called to print any cached results
59 94 flush();
60 }
61  
62  
63 #------------------------------------------------------------------------
64 # ntests($n)
65 #
66 # Declare how many (more) tests are expected to come. If ok() is called
67 # before ntests() then the results are cached instead of being printed
68 # to STDOUT. When ntests() is called, the total number of tests
69 # (including any cached) is known and the "1..$ntests" line can be
70 # printed along with the cached results. After that, calls to ok()
71 # generated printed output immediately.
72 #------------------------------------------------------------------------
73  
74 89 ▶sub ntests {
Subroutine ntests: called CC=3 SCAR=11.2
Pod documented
75 89 my $n = shift;
76 # add any pre-declared extra tests, or pre-stored test @results, to
77 # the grand total of tests
78 89 $n += $EXTRA + scalar @results;
79  
80 89 ▶ if ($n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n) { } 89 0 89
81 89 $TB->plan(tests => $n);
82 }
83 else {
84 0 $TB->skip_all($REASON);
85 }
86 89 $plan_declared = 1;
87  
88 # flush cached results
89 89 foreach my $pre_test (@results) {
90 241 ok(@$pre_test);
91 }
92 89 @results = ();
93 }
94  
95  
96 #------------------------------------------------------------------------
97 # ok($truth, $msg)
98 #
99 # Tests the value passed for truth and generates an "ok $n" or "not ok $n"
100 # line accordingly. If ntests() hasn't been called then we cached
101 # results for later, instead.
102 #------------------------------------------------------------------------
103  
104 3263 ▶sub ok {
Subroutine ok: called CC=2 SCAR=6.9
Pod documented
105 3263 my ($ok, $msg) = @_;
106  
107 # cache results if ntests() not yet called
108 3263 ▶ unless ($plan_declared) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($plan_declared) 241 3022 3263
109 241 push(@results, [ $ok, $msg ]);
110 241 return $ok;
111 }
112  
113 3022 $TB->ok($ok, $msg);
114 3022 return $ok;
115 }
116  
117  
118  
119 #------------------------------------------------------------------------
120 # assert($truth, $error)
121 #
122 # Test value for truth, die if false.
123 #------------------------------------------------------------------------
124  
125 0 ▶sub assert {
Subroutine assert: not called CC=3 SCAR=24.8
Pod undocumented
126 0 my ($ok, $err) = @_;
127 0 ▶ return ok(1) if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
128  
129 # failed
130 0 my ($pkg, $file, $line) = caller();
131 0 ▶ $err ||= "assert failed";
Condition0%0/2
$err ||= "assert failed"
l!l
00
MC/DC0%0/1
$err ||= "assert failed"
$err
Truth table0%0/2
A
A= $err
Aresult
11
00
132 0 $err .= " at $file line $line\n";
133 0 ok(0);
134 0 die $err;
135 }
136  
137 #------------------------------------------------------------------------
138 # match( $result, $expect )
139 #------------------------------------------------------------------------
140  
141 90 ▶sub match {
Subroutine match: called CC=4 SCAR=18.7
Pod undocumented
142 90 my ($result, $expect, $msg) = @_;
143  
144 # force stringification of $result to avoid 'no eq method' overload errors
145 90 ▶ $result = "$result" if ref $result;
Branch: 1 branch
BranchTrueFalseTotal
if ref $result 0 90 90
146  
147 90 ▶ if ($result eq $expect) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result eq $expect) { } 90 0 90
148 90 return ok(1, $msg);
149 }
150 else {
151 0 ▶ my $count = $plan_declared ? $TB->current_test + 1 : scalar @results + 1;
Branch: 1 branch
BranchTrueFalseTotal
$plan_declared ? : 0 0 0
152 0 $TB->diag("FAILED $count:\n expect: [$expect]\n result: [$result]");
153 0 return ok(0, $msg);
154 }
155 }
156  
157  
158 #------------------------------------------------------------------------
159 # flush()
160 #
161 # Flush any tests results.
162 #------------------------------------------------------------------------
163  
164 94 ▶sub flush {
Subroutine flush: called CC=3 SCAR=11.0
Pod undocumented
165 94 ▶ ntests(0)
Branch: 1 branch
BranchTrueFalseTotal
unless $plan_declared or $Template::Test::NO_FLUSH 8 86 94
Condition100%3/3
$plan_declared or $Template::Test::NO_FLUSH
l!l&&r!l&&!r
8158
MC/DC100%2/2
$plan_declared or $Template::Test::NO_FLUSH
$plan_declared $Template::Test::NO_FLUSH
Truth table100%3/3
A or B
A= $plan_declaredB= $Template::Test::NO_FLUSH
ABresult
1X1
011
000
166 unless $plan_declared || $NO_FLUSH;
167 }
168  
169  
170 #------------------------------------------------------------------------
171 # skip_all($reason)
172 #
173 # Skip all tests, setting $REASON to contain any message passed. Calls
174 # exit(0) which triggers flush() which generates a "1..0 # $REASON"
175 # string to keep to test harness happy.
176 #------------------------------------------------------------------------
177  
178 5 ▶sub skip_all {
Subroutine skip_all: called CC=1 SCAR=0.0
Pod undocumented
179 5 $REASON = join('', @_);
180 5 $NO_FLUSH = 1;
181 5 $TB->skip_all($REASON);
182 }
183  
184  
185 #------------------------------------------------------------------------
186 # test_expect($input, $template, \%replace)
187 #
188 # This is the main testing sub-routine. The $input parameter should be a
189 # text string or a filehandle reference (e.g. GLOB or IO::Handle) from
190 # which the input text can be read. The input should contain a number
191 # of tests which are split up and processed individually, comparing the
192 # generated output against the expected output. Tests should be defined
193 # as follows:
194 #
195 # -- test --
196 # test input
197 # -- expect --
198 # expected output
199 #
200 # -- test --
201 # etc...
202 #
203 # The number of tests is determined and ntests() is called to generate
204 # the "0..$n" line compatible with Test::Harness. Each test input is
205 # then processed by the Template object passed as the second parameter,
206 # $template. This may also be a hash reference containing configuration
207 # which are used to instantiate a Template object, or may be left
208 # undefined in which case a default Template object will be instantiated.
209 # The third parameter, also optional, may be a reference to a hash array
210 # defining template variables. This is passed to the template process()
211 # method.
212 #------------------------------------------------------------------------
213  
214 77 ▶sub test_expect {
Subroutine test_expect: called CC=30 SCAR=37.2
Pod documented
215 77 my ($src, $tproc, $params) = @_;
216 77 my ($input, @tests);
217 77 my ($output, $expect, $match);
218 77 my $count = 0;
219 77 my $ttprocs;
220  
221 # read input text
222 77 eval {
223 77 local $/ = undef;
224 77 ▶ $input = ref $src ? <$src> : $src;
Branch: 1 branch
BranchTrueFalseTotal
ref $src ? : 77 0 77
225 };
226 77 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 77 77
227 0 ntests(1); ok(0);
228 0 warn "Cannot read input text from $src\n";
229 0 return undef;
230 }
231  
232 # remove any comment lines
233 77 $input =~ s/^#.*?\n//gm;
234  
235 # remove anything before '-- start --' and/or after '-- stop --'
236 77 ▶ $input = $' if $input =~ /\s*--\s*start\s*--\s*/;
Branch: 1 branch
BranchTrueFalseTotal
if $input =~ /\s*--\s*start\s*--\s*/ 0 77 77
237 77 ▶ $input = $` if $input =~ /\s*--\s*stop\s*--\s*/;
Branch: 1 branch
BranchTrueFalseTotal
if $input =~ /\s*--\s*stop\s*--\s*/ 7 70 77
238  
239 77 @tests = split(/^\s*--\s*test\s*--\s*\n/im, $input);
240  
241 # if the first line of the file was '--test--' (optional) then the
242 # first test will be empty and can be discarded
243 77 ▶ shift(@tests) if $tests[0] =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $tests[0] =~ /^\s*$/ 70 7 77
244  
245 77 ntests(3 + scalar(@tests) * 2);
246  
247 # first test is that Template loaded OK, which it did
248 77 ok(1, 'running test_expect()');
249  
250 # optional second param may contain a Template reference or a HASH ref
251 # of constructor options, or may be undefined
252 77 ▶ if (ref($tproc) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $tproc eq 'HASH') { } 31 46 77
elsif (ref $tproc eq 'ARRAY') { } 26 20 46
elsif (not ref $tproc) { } 17 3 20
253 # create Template object using hash of config items
254 31 ▶ $tproc = Template->new($tproc)
Condition50%1/2
'Template'->new($tproc) || die('Template'->error, "\n")
l!l
310
MC/DC0%0/1
'Template'->new($tproc) || die('Template'->error, "\n")
'Template'->new($tproc)
Truth table50%1/2
A
A= 'Template'->new($tproc)
Aresult
11
00
255 || die Template->error(), "\n";
256 }
257 elsif (ref($tproc) eq 'ARRAY') {
258 # list of [ name => $tproc, name => $tproc ], use first $tproc
259 26 $ttprocs = { @$tproc };
260 26 $tproc = $tproc->[1];
261 }
262 elsif (! ref $tproc) {
263 17 ▶ $tproc = Template->new()
Condition50%1/2
'Template'->new || die('Template'->error, "\n")
l!l
170
MC/DC0%0/1
'Template'->new || die('Template'->error, "\n")
'Template'->new
Truth table50%1/2
A
A= 'Template'->new
Aresult
11
00
264 || die Template->error(), "\n";
265 }
266 # otherwise, we assume it's a Template reference
267  
268 # test: template processor created OK
269 77 ok($tproc, 'template processor is engaged');
270  
271 # third test is that the input read ok, which it did
272 77 ok(1, 'input read and split into ' . scalar @tests . ' tests');
273  
274 # the remaining tests are defined in @tests...
275 77 foreach $input (@tests) {
276 1205 $count++;
277 1205 my $name = '';
278  
279 1205 ▶ if ($input =~ s/^\s*-- name:? (.*?) --\s*\n//im) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input =~ s/^\s*-- name:? (.*?) --\s*\n//im) { } 151 1054 1205
280 151 $name = $1;
281 }
282 else {
283 1054 $name = "template text $count";
284 }
285  
286 # Configure a test as TODO
287 1205 my $todo = '';
288 1205 ▶ if ($input =~ s/^\s*-- todo:? (.*?) --\s*\n//im) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input =~ s/^\s*-- todo:? (.*?) --\s*\n//im) 0 1205 1205
289 0 ▶ $todo = ( $1 eq '' ) ? 'No reason given' : $1;
Branch: 1 branch
BranchTrueFalseTotal
$1 eq '' ? : 0 0 0
290 }
291  
292 # split input by a line like "-- expect --"
293 1205 ($input, $expect) =
294 split(/^\s*--\s*expect\s*--\s*\n/im, $input);
295 1205 ▶ $expect //= '';
Condition100%2/2
$expect //= ""
l!l
11987
MC/DC100%1/1
$expect //= ""
$expect
Truth table100%2/2
A
A= $expect
Aresult
11
00
296  
297 1205 $output = '';
298  
299 # input text may be prefixed with "-- use name --" to indicate a
300 # Template object in the $ttproc hash which we should use
301 1205 ▶ if ($input =~ s/^\s*--\s*use\s+(\S+)\s*--\s*\n//im) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input =~ s/^\s*--\s*use\s+(\S+)\s*--\s*\n//im) 77 1128 1205
302 77 my $ttname = $1;
303 77 my $ttlookup;
304 77 ▶ if ($ttlookup = $ttprocs->{ $ttname }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ttlookup = $ttprocs->{$ttname}) { } 77 0 77
305 77 $tproc = $ttlookup;
306 }
307 else {
308 0 warn "no such template object to use: $ttname\n";
309 }
310 }
311  
312 # process input text
313 1205 ▶ $tproc->process(\$input, $params, \$output) || do {
Branch: 1 branch
BranchTrueFalseTotal
$tproc->process(\$input, $params, \$output) or do { warn "Template process failed: ", $tproc->error, "\n"; ok(0, "$name process FAILED: " . subtext($input)); ok(0, "(obviously did not match expected)"); next } 1205 0 1205
314 0 warn "Template process failed: ", $tproc->error(), "\n";
315 # report failure and automatically fail the expect match
316 0 ok(0, "$name process FAILED: " . subtext($input));
317 0 ok(0, '(obviously did not match expected)');
318 0 next;
319 };
320  
321 # processed OK
322 1205 ok(1, "$name processed OK: " . subtext($input));
323  
324 # another hack: if the '-- expect --' section starts with
325 # '-- process --' then we process the expected output
326 # before comparing it with the generated output. This is
327 # slightly twisted but it makes it possible to run tests
328 # where the expected output isn't static. See t/date.t for
329 # an example.
330  
331 1205 ▶ if ($expect =~ s/^\s*--+\s*process\s*--+\s*\n//im) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expect =~ s/^\s*--+\s*process\s*--+\s*\n//im) 33 1172 1205
332 33 my $out;
333 33 ▶ $tproc->process(\$expect, $params, \$out) || do {
Branch: 1 branch
BranchTrueFalseTotal
$tproc->process(\$expect, $params, \$out) or do { warn "Template process failed (expect): ", $tproc->error, "\n"; ok(0, 'failed to process expected output [' . subtext($expect) . ']'); next } 33 0 33
334 0 warn(
335 "Template process failed (expect): ",
336 $tproc->error(), "\n"
337 );
338 # report failure and automatically fail the expect match
339 0 ok(
340 0,
341 "failed to process expected output [" . subtext($expect) . ']'
342 );
343 0 next;
344 };
345 33 $expect = $out;
346 };
347  
348 # strip any trailing blank lines from expected and real output
349 1205 foreach ($expect, $output) {
350 2410 s/[\n\r]*\Z//mg;
351 }
352  
353 1205 ▶ $match = ($expect eq $output) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$expect eq $output ? : 1202 3 1205
354 1205 ▶ if (! $match || $DEBUG) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $match or $Template::Test::DEBUG) 3 1202 1205
Condition66%2/3
not $match or $Template::Test::DEBUG
l!l&&r!l&&!r
301202
MC/DC50%1/2
not $match or $Template::Test::DEBUG
not $match $Template::Test::DEBUG
Truth table66%2/3
not(A) or B
A= not $matchB= $Template::Test::DEBUG
ABresult
1X1
011
000
355 3 ▶ $TB->diag("MATCH FAILED")
Branch: 1 branch
BranchTrueFalseTotal
unless $match 3 0 3
356 unless $match;
357  
358 3 my ($copyi, $copye, $copyo) = ($input, $expect, $output);
359 3 ▶ unless ($PRESERVE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Template::Test::PRESERVE) 3 0 3
360 3 foreach ($copyi, $copye, $copyo) {
361 9 s/\n/\\n/g;
362 }
363 }
364 3 $TB->diag(sprintf(
365 " input: [%s]\nexpect: [%s]\noutput: [%s]",
366 $copyi, $copye, $copyo
367 ));
368 }
369  
370 1205 my $testprefix = $name;
371 1205 ▶ if ( $todo ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($todo) 0 1205 1205
372 0 $testprefix = "# TODO $todo - $name";
373 }
374  
375 1205 ▶ ok($match, $match ? "$testprefix matched expected" : "$testprefix did not match expected");
Branch: 1 branch
BranchTrueFalseTotal
$match ? : 1202 3 1205
376 };
377 }
378  
379 #------------------------------------------------------------------------
380 # callsign()
381 #
382 # Returns a hash array mapping lower a..z to their phonetic alphabet
383 # equivalent.
384 #------------------------------------------------------------------------
385  
386 20 ▶sub callsign {
Subroutine callsign: called CC=1 SCAR=0.0
Pod documented
387 20 my %callsign;
388 20 @callsign{ 'a'..'z' } = qw(
389 alpha bravo charlie delta echo foxtrot golf hotel india
390 juliet kilo lima mike november oscar papa quebec romeo
391 sierra tango umbrella victor whisky x-ray yankee zulu );
392 20 return \%callsign;
393 }
394  
395  
396 #------------------------------------------------------------------------
397 # banner($text)
398 #
399 # Prints a banner with the specified text if $DEBUG is set.
400 #------------------------------------------------------------------------
401  
402 5 ▶sub banner {
Subroutine banner: called CC=2 SCAR=11.6
Pod documented
403 5 ▶ return unless $DEBUG;
Branch: 1 branch
BranchTrueFalseTotal
unless $Template::Test::DEBUG 5 0 5
404 0 my $text = join('', @_);
405 0 my $count = $TB->current_test;
406 0 $TB->note("-" x 72 . "\n$text ($count tests completed)\n" . "-" x 72);
407 }
408  
409  
410 1205 ▶sub subtext {
Subroutine subtext: called CC=2 SCAR=6.9
Pod undocumented
411 1205 my $text = shift;
412 1205 $text =~ s/\s*$//sg;
413 1205 ▶ $text = substr($text, 0, 32) . '...' if length $text > 32;
Branch: 1 branch
BranchTrueFalseTotal
if length $text > 32 974 231 1205
414 1205 $text =~ s/\n/\\n/g;
415 1205 return $text;
416 }
417  
418  
419 94 1;
420  
421 __END__
« lib/Template/Stash.pm ↑ Summary lib/Template/View.pm »