lib/Template/Test.pm

filter: Statementstmt 81.8% 126 / 154 Branchbran 68.1% 45 / 66 Conditioncond 58.3% 7 / 12 MC/DCmcdc 42.8% 3 / 7 Subroutinesub 94.1% 16 / 17 Podpod 40.0% 4 / 10 totaltotal 75.5% 201 / 266 CC 42 SCAR 31.4
CC
42
Cov
77%
test_expect
41.2
assert
12.0
match
6.5
CRAP 23.1
« blib/lib/Template/Constants.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 93 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 93 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 93 ▶use Template;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 93 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 93 ▶use Test::Builder;
Subroutine BEGIN: called CC=1 SCAR=0.0
29  
30 93 ▶use constant MSWin32 => $^O eq 'MSWin32';
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 93 our $VERSION = '3.100';
33 93 our $DEBUG = 0;
34 93 our @ISA = qw( Exporter );
35 93 our @EXPORT = qw( ntests ok is match flush skip_all test_expect callsign banner );
36 93 our @EXPORT_OK = ( 'assert' );
37 93 our %EXPORT_TAGS = ( all => [ @EXPORT_OK, @EXPORT ] );
38 93 $| = 1;
39  
40 93 our $REASON = 'not applicable on this platform';
41 93 our $NO_FLUSH = 0;
42 93 our $EXTRA = 0; # any extra tests to come after test_expect()
43 93 ▶our $PRESERVE = 0 # don't mangle newlines in output/expect
Branch: 1 branch
BranchTrueFalseTotal
unless defined $Template::Test::PRESERVE 93 0 93
44 unless defined $PRESERVE;
45  
46 93 our ($loaded, %callsign);
47  
48 # always set binmode on Win32 machines so that any output generated
49 # is true to what we expect
50 93 $Template::BINMODE = (MSWin32) ? 1 : 0;
51  
52 93 my $TB = Test::Builder->new;
53 93 my @results = ();
54 93 my $plan_declared = 0;
55 93 *is = \&match;
56  
57 END {
58 # ensure flush() is called to print any cached results
59 93 ▶ flush();
Subroutine END: called CC=1 SCAR=0.0
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 sub ntests {
75 88 ▶ my $n = shift;
Subroutine ntests: called CC=3 SCAR=11.2
Pod documented
76 # add any pre-declared extra tests, or pre-stored test @results, to
77 # the grand total of tests
78 88 $n += $EXTRA + scalar @results;
79  
80 88 ▶ if ($n) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n) { } 88 0 88
81 88 $TB->plan(tests => $n);
82 }
83 else {
84 0 $TB->skip_all($REASON);
85 }
86 88 $plan_declared = 1;
87  
88 # flush cached results
89 88 foreach my $pre_test (@results) {
90 241 ok(@$pre_test);
91 }
92 88 @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 sub ok {
105 3176 ▶ my ($ok, $msg) = @_;
Subroutine ok: called CC=2 SCAR=6.9
Pod documented
106  
107 # cache results if ntests() not yet called
108 3176 ▶ unless ($plan_declared) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($plan_declared) 241 2935 3176
109 241 push(@results, [ $ok, $msg ]);
110 241 return $ok;
111 }
112  
113 2935 $TB->ok($ok, $msg);
114 2935 return $ok;
115 }
116  
117  
118  
119 #------------------------------------------------------------------------
120 # assert($truth, $error)
121 #
122 # Test value for truth, die if false.
123 #------------------------------------------------------------------------
124  
125 sub assert {
126 0 ▶ my ($ok, $err) = @_;
Subroutine assert: not called CC=3 SCAR=24.8
Pod undocumented
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 sub match {
142 90 ▶ my ($result, $expect, $msg) = @_;
Subroutine match: called CC=4 SCAR=18.7
Pod undocumented
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 sub flush {
165 93 ▶ ntests(0)
Subroutine flush: called CC=3 SCAR=11.0
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
unless $plan_declared or $Template::Test::NO_FLUSH 8 85 93
Condition100%3/3
$plan_declared or $Template::Test::NO_FLUSH
l!l&&r!l&&!r
8058
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 sub skip_all {
179 5 ▶ $REASON = join('', @_);
Subroutine skip_all: called CC=1 SCAR=0.0
Pod undocumented
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 sub test_expect {
215 76 ▶ my ($src, $tproc, $params) = @_;
Subroutine test_expect: called CC=30 SCAR=37.2
Pod undocumented
216 76 my ($input, @tests);
217 76 my ($output, $expect, $match);
218 76 my $count = 0;
219 76 my $ttprocs;
220  
221 # read input text
222 76 eval {
223 76 local $/ = undef;
224 76 ▶ $input = ref $src ? <$src> : $src;
Branch: 1 branch
BranchTrueFalseTotal
ref $src ? : 76 0 76
225 };
226 76 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 76 76
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 76 $input =~ s/^#.*?\n//gm;
234  
235 # remove anything before '-- start --' and/or after '-- stop --'
236 76 ▶ $input = $' if $input =~ /\s*--\s*start\s*--\s*/;
Branch: 1 branch
BranchTrueFalseTotal
if $input =~ /\s*--\s*start\s*--\s*/ 0 76 76
237 76 ▶ $input = $` if $input =~ /\s*--\s*stop\s*--\s*/;
Branch: 1 branch
BranchTrueFalseTotal
if $input =~ /\s*--\s*stop\s*--\s*/ 7 69 76
238  
239 76 @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 76 ▶ shift(@tests) if $tests[0] =~ /^\s*$/;
Branch: 1 branch
BranchTrueFalseTotal
if $tests[0] =~ /^\s*$/ 69 7 76
244  
245 76 ntests(3 + scalar(@tests) * 2);
246  
247 # first test is that Template loaded OK, which it did
248 76 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 76 ▶ if (ref($tproc) eq 'HASH') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $tproc eq 'HASH') { } 31 45 76
elsif (ref $tproc eq 'ARRAY') { } 26 19 45
elsif (not ref $tproc) { } 16 3 19
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 16 ▶ $tproc = Template->new()
Condition50%1/2
'Template'->new || die('Template'->error, "\n")
l!l
160
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 76 ok($tproc, 'template processor is engaged');
270  
271 # third test is that the input read ok, which it did
272 76 ok(1, 'input read and split into ' . scalar @tests . ' tests');
273  
274 # the remaining tests are defined in @tests...
275 76 foreach $input (@tests) {
276 1163 $count++;
277 1163 my $name = '';
278  
279 1163 ▶ if ($input =~ s/^\s*-- name:? (.*?) --\s*\n//im) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input =~ s/^\s*-- name:? (.*?) --\s*\n//im) { } 128 1035 1163
280 128 $name = $1;
281 }
282 else {
283 1035 $name = "template text $count";
284 }
285  
286 # Configure a test as TODO
287 1163 my $todo = '';
288 1163 ▶ if ($input =~ s/^\s*-- todo:? (.*?) --\s*\n//im) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input =~ s/^\s*-- todo:? (.*?) --\s*\n//im) 0 1163 1163
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 1163 ($input, $expect) =
294 split(/^\s*--\s*expect\s*--\s*\n/im, $input);
295 1163 ▶ $expect = ''
Branch: 1 branch
BranchTrueFalseTotal
unless defined $expect 7 1156 1163
296 unless defined $expect;
297  
298 1163 $output = '';
299  
300 # input text may be prefixed with "-- use name --" to indicate a
301 # Template object in the $ttproc hash which we should use
302 1163 ▶ 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 1086 1163
303 77 my $ttname = $1;
304 77 my $ttlookup;
305 77 ▶ if ($ttlookup = $ttprocs->{ $ttname }) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ttlookup = $ttprocs->{$ttname}) { } 77 0 77
306 77 $tproc = $ttlookup;
307 }
308 else {
309 0 warn "no such template object to use: $ttname\n";
310 }
311 }
312  
313 # process input text
314 1163 ▶ $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 } 0 1163 1163
315 0 warn "Template process failed: ", $tproc->error(), "\n";
316 # report failure and automatically fail the expect match
317 0 ok(0, "$name process FAILED: " . subtext($input));
318 0 ok(0, '(obviously did not match expected)');
319 0 next;
320 };
321  
322 # processed OK
323 1163 ok(1, "$name processed OK: " . subtext($input));
324  
325 # another hack: if the '-- expect --' section starts with
326 # '-- process --' then we process the expected output
327 # before comparing it with the generated output. This is
328 # slightly twisted but it makes it possible to run tests
329 # where the expected output isn't static. See t/date.t for
330 # an example.
331  
332 1163 ▶ 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 1130 1163
333 33 my $out;
334 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 } 0 33 33
335 0 warn(
336 "Template process failed (expect): ",
337 $tproc->error(), "\n"
338 );
339 # report failure and automatically fail the expect match
340 0 ok(
341 0,
342 "failed to process expected output [" . subtext($expect) . ']'
343 );
344 0 next;
345 };
346 33 $expect = $out;
347 };
348  
349 # strip any trailing blank lines from expected and real output
350 1163 foreach ($expect, $output) {
351 2326 s/[\n\r]*\Z//mg;
352 }
353  
354 1163 ▶ $match = ($expect eq $output) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$expect eq $output ? : 1162 1 1163
355 1163 ▶ if (! $match || $DEBUG) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $match or $Template::Test::DEBUG) 1 1162 1163
Condition66%2/3
not $match or $Template::Test::DEBUG
l!l&&r!l&&!r
101162
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
356 1 ▶ $TB->diag("MATCH FAILED")
Branch: 1 branch
BranchTrueFalseTotal
unless $match 1 0 1
357 unless $match;
358  
359 1 my ($copyi, $copye, $copyo) = ($input, $expect, $output);
360 1 ▶ unless ($PRESERVE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Template::Test::PRESERVE) 1 0 1
361 1 foreach ($copyi, $copye, $copyo) {
362 3 s/\n/\\n/g;
363 }
364 }
365 1 $TB->diag(sprintf(
366 " input: [%s]\nexpect: [%s]\noutput: [%s]",
367 $copyi, $copye, $copyo
368 ));
369 }
370  
371 1163 my $testprefix = $name;
372 1163 ▶ if ( $todo ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($todo) 0 1163 1163
373 0 $testprefix = "# TODO $todo - $name";
374 }
375  
376 1163 ▶ ok($match, $match ? "$testprefix matched expected" : "$testprefix did not match expected");
Branch: 1 branch
BranchTrueFalseTotal
$match ? : 1162 1 1163
377 };
378 }
379  
380 #------------------------------------------------------------------------
381 # callsign()
382 #
383 # Returns a hash array mapping lower a..z to their phonetic alphabet
384 # equivalent.
385 #------------------------------------------------------------------------
386  
387 sub callsign {
388 20 ▶ my %callsign;
Subroutine callsign: called CC=1 SCAR=0.0
Pod documented
389 20 @callsign{ 'a'..'z' } = qw(
390 alpha bravo charlie delta echo foxtrot golf hotel india
391 juliet kilo lima mike november oscar papa quebec romeo
392 sierra tango umbrella victor whisky x-ray yankee zulu );
393 20 return \%callsign;
394 }
395  
396  
397 #------------------------------------------------------------------------
398 # banner($text)
399 #
400 # Prints a banner with the specified text if $DEBUG is set.
401 #------------------------------------------------------------------------
402  
403 sub banner {
404 5 ▶ return unless $DEBUG;
Subroutine banner: called CC=2 SCAR=11.6
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
unless $Template::Test::DEBUG 5 0 5
405 0 my $text = join('', @_);
406 0 my $count = $TB->current_test;
407 0 $TB->note("-" x 72 . "\n$text ($count tests completed)\n" . "-" x 72);
408 }
409  
410  
411 sub subtext {
412 1163 ▶ my $text = shift;
Subroutine subtext: called CC=2 SCAR=6.9
Pod undocumented
413 1163 $text =~ s/\s*$//sg;
414 1163 ▶ $text = substr($text, 0, 32) . '...' if length $text > 32;
Branch: 1 branch
BranchTrueFalseTotal
if length $text > 32 935 228 1163
415 1163 $text =~ s/\n/\\n/g;
416 1163 return $text;
417 }
418  
419  
420 93 1;
421  
422 __END__
« blib/lib/Template/Constants.pm ↑ Summary lib/Template/View.pm »