lib/Test/Consumer/Contract.pm

filter: Statementstmt 99.8% 798 / 799 Branchbran 91.0% 193 / 212 Conditioncond 74.1% 103 / 139 MC/DCmcdc 50.0% 40 / 80 Subroutinesub 100% 152 / 152 Podpod 100% 11 / 11 totaltotal 93.1% 1297 / 1393 CC 190 SCAR 15.6
CC
190
Cov
95%
_assert_shapes
17.1
new
12.1
_choose_form
9.2
CRAP 4.8
↑ Summary
1 package Test::Consumer::Contract;
2  
3 57 ▶use 5.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 57 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 57 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 # Sub::Private reads its mode as it wraps each :Private sub, at CHECK time, so
8 # enforce mode has to be chosen before the module is loaded. Enforce mode is
9 # the one that works with method calls ($self->_helper).
10 57 ▶BEGIN { $Sub::Private::config{'mode'} = 'enforce' }
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 57 ▶use autodie qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 57 ▶use Carp qw(croak confess);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 57 ▶use Cwd qw(abs_path getcwd);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 57 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
16 57 ▶use File::Basename qw(basename dirname);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 57 ▶use File::Find ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 57 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 57 ▶use List::Util qw(first);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 57 ▶use Module::Runtime qw(is_module_name module_notional_filename require_module);
Subroutine BEGIN: called CC=1 SCAR=0.0
21 57 ▶use Params::Get qw(get_params);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 57 ▶use Params::Validate::Strict qw(validate_strict);
Subroutine BEGIN: called CC=1 SCAR=0.0
23 57 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 57 ▶use Return::Set qw(set_return);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 57 ▶use Scalar::Util qw(blessed looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 57 ▶use Sub::Private;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 57 ▶use Sub::Protected;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 57 ▶use Test::More;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 57 ▶use Text::Balanced qw(extract_bracketed);
Subroutine BEGIN: called CC=1 SCAR=0.0
30 57 ▶use lib ();
Subroutine BEGIN: called CC=1 SCAR=0.0
31  
32 57 our @EXPORT_OK = qw(run_consumer_contract);
33  
34 57 our $VERSION = '0.04';
35  
36 =head1 NAME
37  
38 Test::Consumer::Contract - check that code reading a result only reads the fields that are always there
39  
40 =head1 VERSION
41  
42 Version 0.04
43  
44 =head1 SYNOPSIS
45  
46 =head2 1. The usual case: results are hashes, readers live in other distributions
47  
48 A geocoder hands back a hash. C<x> and C<y> are always in it; C<colour> is
49 only sometimes there. This test fails if any reader in the workspace reads
50 C<colour> without saying why that is safe.
51  
52 use Test::Most;
53 use Test::Consumer::Contract qw(run_consumer_contract);
54  
55 run_consumer_contract(
56 source => 'Widget::Maker', # readers mention this name
57 methods => [qw(geocode)], # the call that returns a result
58 guaranteed => [qw(x y)], # always set
59 conditional => { colour => 'only the painted path sets it' },
60 producers => { 'lib/Widget/Maker.pm' => [qw(x y colour)] },
61 consumers => { 'Widget-User/lib/Widget/User.pm' => {} },
62 require_workspace => ['Widget-User'],
63 );
64  
65 done_testing();
66  
67 =head2 2. Allowing one reader to read an optional field
68  
69 The reader in C<render()> reads C<colour> on purpose, and handles it being
70 missing. Say so, with the reason, under the name of the sub that reads it:
71  
72 consumers => {
73 'Widget-User/lib/Widget/User.pm' => {
74 may_rely_on => {
75 render => { colour => 'defaults to undef on purpose' },
76 },
77 },
78 },
79  
80 =head2 3. Results that are objects with accessor methods
81  
82 When a result is an object, readers call methods (C<< $entry->memo >>) instead
83 of reading hash keys. Name the methods a reader may call, and let the checker
84 compare that list with what the class documents:
85  
86 run_consumer_contract(
87 source => 'Ledger::Entry',
88 methods => ['Ledger::Entry->new', 'entry'], # 'Class->new': only this class
89 list_methods => ['results'], # returns a list of results
90 value_object => {
91 class => 'Ledger::Entry',
92 from => { amount => 7 }, # build one like this...
93 derives => { cents => 700 }, # ...and expect these values
94 },
95 guaranteed => [qw(amount memo cents)],
96 accessors => [qw(amount memo cents)],
97 not_accessors => { new => 'the constructor' },
98 inspection => [qw(can isa DOES)],
99 conditional => { note => 'only some entries carry a note' },
100 include => ['Ledger-Store/lib'],
101 own_consumers => 1, # this distribution reads them too
102 consumers => { 'Ledger-UI/lib/Ledger/UI.pm' => {} },
103 require_workspace => ['Ledger-UI'],
104 );
105  
106 =head2 4. A call that returns many results at once
107  
108 C<geocode_many()> returns one hash: the results under their names, plus counts.
109 The counts are not fields of a result, so name the call in C<batch_methods>:
110  
111 methods => [qw(geocode geocode_many)],
112 batch_methods => ['geocode_many'],
113  
114 =head2 5. Using the scanner yourself
115  
116 The object's methods can be used outside a test, for example to see what the
117 checker finds in one file:
118  
119 my $contract = Test::Consumer::Contract->new(
120 source => 'Widget::Maker', methods => ['geocode'], guaranteed => [],
121 );
122 my $code = $contract->strip($source_text); # drop POD and comments
123 foreach my $read (@{ $contract->reads_of_results($code) }) {
124 my ($key, $line, $kind, $sub) = @{$read};
125 print "line $line, in $sub: reads $key ($kind)\n";
126 }
127  
128 =head2 6. Changing the wording of the messages
129  
130 # For every contract built after this line:
131 $Test::Consumer::Contract::config{'messages'}{'skip.siblings'}
132 = 'Geschwister fehlen: {missing}';
133  
134 # For one contract only:
135 run_consumer_contract(%declaration, messages => {
136 'check.producers' => 'les producteurs posent toujours les cles promises',
137 });
138  
139 =head1 DESCRIPTION
140  
141 =head2 The problem
142  
143 One piece of code (the I<producer>) makes a I<result>: a hash or an object
144 with named fields. Other code (the I<consumers>, or readers) reads those
145 fields. Some fields are always set. Others are set only on some paths - for
146 example, only when a lookup found a postcode.
147  
148 A reader that reads an only-sometimes field works in testing and then fails
149 for the one input where the field is missing. This module finds those reads
150 before that happens, by reading the source code of every reader.
151  
152 =head2 Words used in this document
153  
154 producer code that makes a result (for example geocode())
155 result the hash or object the producer hands back
156 value object the class of a result, when the result is an object
157 key, field one named value in a result: $r->{'x'} or $r->x
158 guaranteed a key every result has
159 conditional a key only some results have
160 consumer a file that reads keys of a result
161 distribution one project folder, such as Widget-Maker/
162 workspace the folder that holds several distributions side by side
163 declaration the options you pass to new() or run_consumer_contract()
164  
165 A typical workspace:
166  
167 workspace/
168 Widget-Maker/ the producer and the value object
169 Widget-User/ a consumer
170 Widget-Contract/ holds t/contract.t, which declares the contract
171 (this is dist_root; it may also be Widget-Maker)
172  
173 =head2 The five checks
174  
175 C<run()> runs these checks. Each one is a subtest in the TAP output.
176  
177 =over 4
178  
179 =item 1. the producers still set the keys the contract claims
180  
181 Each file in C<producers> and C<workspace_producers> must still contain an
182 assignment to each key listed for it. POD and comments do not count: a key
183 shown in an example is not a key being set. A workspace producer whose sibling
184 distribution is not checked out is skipped, not failed; one whose sibling is
185 there but whose file is not still fails.
186  
187 =item 2. the value object still derives what it promises
188  
189 Only when C<value_object> has C<derives>. An object is built from C<from>, and
190 each method named in C<derives> must return the value given. If the class
191 cannot be found, this check is skipped. If the class is found but does not
192 compile, or its constructor dies, the check fails.
193  
194 =item 3. registered consumers read only what every producer sets
195  
196 Each file in C<consumers> is read. Every read of a result is listed with its
197 line and the sub it is in. Reading a guaranteed key is fine. Reading any
198 other key fails, unless the consumer lists that key in C<may_rely_on> under
199 the name of the sub that reads it. An entry in C<may_rely_on> that the code
200 no longer reads also fails, so the list stays true.
201  
202 =item 4. the accessor lists match the value object
203  
204 Only when C<value_object> is given and C<accessors> or C<not_accessors> is
205 not empty. Every name you list must exist in the class. And every name the
206 class documents (its C<=head2> headings and public subs) must appear in
207 C<accessors>, C<not_accessors> or C<conditional>. So when the class gains a
208 new field, this check fails until the contract says what the field is.
209  
210 =item 5. every discovered consumer is registered
211  
212 Every C<.pm>, C<.t>, C<.pl> file and every program (a file with no extension
213 that starts with C<#!>) in the other distributions of the workspace is read.
214 A file that mentions C<source> and reads a result must be listed in
215 C<consumers> or C<ignored>. So a new reader cannot be added without being
216 checked.
217  
218 =back
219  
220 Checks 3 and 5 need the other distributions. If one named in
221 C<require_workspace> is missing (for example when the module is installed from
222 CPAN), those checks are skipped with a message.
223  
224 The checker only reads source code. It never runs the producer or the
225 consumers. See L</LIMITATIONS> for what it cannot see.
226  
227 =head1 REQUIREMENTS
228  
229 Load a test module (L<Test::Most> or L<Test::More>) before calling, and call
230 C<done_testing()> after. This module adds subtests; it does not start or end
231 the test plan.
232  
233 Perl 5.14 or later.
234  
235 =head1 CONFIGURATION
236  
237 C<%Test::Consumer::Contract::config> holds settings shared by all contracts.
238 It has the shape L<Object::Configure> produces. Each contract copies it when
239 C<new()> is called, so a change made later does not affect a contract that
240 already exists.
241  
242 Key Meaning Default
243 ----------------- ------------------------------------------- ---------------------
244 sibling_dirs folders read in another distribution lib bin t
245 own_dirs folders read in dist_root (own_consumers) lib bin scripts
246 source_extensions file extensions that hold Perl code pm t pl PL pm6
247 skipped_dirs folder names never entered blib xt inc local
248 node_modules .git
249 .build
250 messages message key => text, replacing the built-in (empty)
251  
252 C<new()> does not call L<Object::Configure/configure> itself, because that
253 would let an environment variable change a contract that should be written in
254 code.
255  
256 =head1 COMMON PITFALLS
257  
258 =over 4
259  
260 =item * B<undef means "use the default".>
261  
262 Giving an optional option the value C<undef> is the same as not giving it.
263 For a required option (C<source>, C<guaranteed>, C<methods>), C<undef> is an
264 error. Inside lists and hashes, C<undef> is not cleaned up: an C<undef> in
265 C<guaranteed> is a key that no read can match.
266  
267 =item * B<Nothing is merged deeply.>
268  
269 An option you give replaces the default completely; it is not merged with it.
270 A message you give in C<messages> replaces the whole built-in message. If the
271 built-in message has several forms (C<one>, C<other>), your replacement must
272 give every form you need, or it is used for all counts.
273  
274 =item * B<The contract keeps your lists, it does not copy them.>
275  
276 The arrays and hashes you pass are used as they are. If you change them after
277 C<new()>, the contract changes too. Build the declaration first, then call
278 C<new()>.
279  
280 =item * B<C<%config> is copied only one level deep.>
281  
282 A new contract gets its own copy of each list and of the C<messages> hash.
283 But a message that is itself a hash of forms is shared. Replace such an entry;
284 do not change it in place.
285  
286 =item * B<Paths always use C</>.>
287  
288 Write C<'Widget-User/lib/Widget/User.pm'>, also on Windows. Consumer and
289 ignored paths are relative to the workspace. Producer paths are relative to
290 C<dist_root>, unless they are given in C<workspace_producers>.
291  
292 =item * B<An C<ignored> rule is a plain prefix.>
293  
294 C<'Widget-List'> also ignores C<Widget-Listing/>. End the prefix with C</>
295 to ignore exactly one folder.
296  
297 =item * B<A bare C<new> in C<methods> matches every constructor.>
298  
299 C<methods =E<gt> ['new']> makes C<< Any::Class->new(...) >> a result. Write
300 C<< 'Widget->new' >> so that only that class counts.
301  
302 =item * B<Reads outside any sub belong to C<(file scope)>.>
303  
304 A program's main code is not in a sub. To allow a read there, use the name
305 C<'(file scope)'> in C<may_rely_on>.
306  
307 =item * B<With an empty C<require_workspace>, check 5 may fail.>
308  
309 If no other distribution is present, check 5 finds no consumer at all, and
310 fails rather than pass on nothing. Name the distributions your consumers are
311 in.
312  
313 =item * B<Variable names count for the whole file.>
314  
315 If C<$point> holds a result in one sub, every C<$point> in the same file is
316 treated as a result. Use different names for different things.
317  
318 =item * B<List context or scalar context.>
319  
320 C<reads_of_results()> and C<documented_accessors()> return a list when called
321 in list context and an array reference in scalar context.
322 C<my $n = $contract-E<gt>reads_of_results($t)> is a reference, not a count.
323  
324 =item * B<C<include> changes C<@INC> for the whole program.>
325  
326 The last directory listed ends up first. The change stays after the contract
327 is gone.
328  
329 =item * B<Other tests may match the English text.>
330  
331 The test names and messages are part of the output. If you change their
332 wording with C<messages>, anything that searches the output for the English
333 text will stop matching.
334  
335 =back
336  
337 =head1 ENCODING
338  
339 =over 4
340  
341 =item * B<Source files are read as bytes.>
342  
343 Files are not decoded. Any bytes - UTF-8, Latin-1, emoji - may appear in
344 strings, comments and POD of the files that are read; they do no harm.
345  
346 =item * B<Keys and method names must be ASCII to be found.>
347  
348 A read is found only when the key or method name is made of C<A-Z>, C<a-z>,
349 C<0-9> and C<_>. A read of C<< $r->{'grosse'} >> is found; a read of a key
350 with a non-ASCII letter in it is B<not> found, so it can never fail check 3.
351 The same is true of producer keys passed to C<sets_key()> for check 1 when the
352 text is bytes and the key is a character string.
353  
354 =item * B<C<strip()>, C<reads_of_results()> and C<documented_accessors()>
355 accept bytes or characters.>
356  
357 If you pass them text you decoded yourself (for example with
358 C<< :encoding(UTF-8) >>), non-ASCII letters count as word characters, and
359 non-ASCII keys are found.
360  
361 =item * B<C<sets_key()> compares the key and the text exactly.>
362  
363 Give both as bytes, or both as decoded characters. Mixing them can make a key
364 that is in the text appear to be missing.
365  
366 =item * B<C<source> is compared with the file's bytes.>
367  
368 Keep it ASCII (a Perl package name always is).
369  
370 =item * B<Paths should be ASCII.>
371  
372 Paths are passed to the operating system as they are. On Unix a non-ASCII
373 path works when it is given as UTF-8 bytes. On Windows non-ASCII paths may not
374 be found.
375  
376 =item * B<Messages may use any Unicode text, including emoji.>
377  
378 Message templates, reasons in C<conditional>, C<may_rely_on> and C<ignored>,
379 and the arguments to C<i18n()> may be any character strings. When they
380 contain characters above 255, Test::Builder prints a C<Wide character>
381 warning unless its output handles have an encoding layer:
382  
383 binmode(Test::More->builder->$_, ':encoding(UTF-8)')
384 for qw(output failure_output todo_output);
385  
386 =back
387  
388 =cut
389  
390 # ---------------------------------------------------------------------------
391 # Constants and configuration
392 # ---------------------------------------------------------------------------
393  
394 # The options new() requires; the rest have defaults.
395 57 Readonly::Array my @REQUIRED => qw(source guaranteed methods);
396  
397 # How a read outside any named sub is reported, and how the contract spells
398 # the separator between directories whatever the platform uses.
399 57 Readonly::Scalar my $FILE_SCOPE => '(file scope)';
400 57 Readonly::Scalar my $SEPARATOR => '/';
401 57 Readonly::Scalar my $SHEBANG => '#!';
402  
403 # The two kinds of read a consumer can make of a result.
404 57 Readonly::Scalar my $KIND_KEY => 'key';
405 57 Readonly::Scalar my $KIND_ACCESSOR => 'accessor';
406  
407 # Diagnostics are indented one tab, one item per line.
408 57 Readonly::Scalar my $DIAG_INDENT => "\n\t";
409  
410 # The delimiters Text::Balanced balances a block by: braces, skipping any that
411 # sit inside a quoted string, such as the key in $_->{'}'}.
412 57 Readonly::Scalar my $BLOCK_DELIMITERS => q({}"');
413  
414 # Lexical building blocks shared by the scanner's passes, so that every pass
415 # agrees on what a variable, an assignment and a key read look like. The
416 # assignment refuses '==' and '=~': neither puts a value into the variable.
417 57 Readonly::Scalar my $VARIABLE => qr/\$[A-Za-z_]\w*/;
418 57 Readonly::Scalar my $DECLARATOR => qr/(?:my|our|local)?\s*/;
419 57 Readonly::Scalar my $ASSIGNMENT => qr/\s*=(?![=~])\s*/;
420 57 Readonly::Scalar my $KEY_READ => qr/\s*->\s*\{\s*['"]?(\w+)['"]?\s*\}/;
421 57 Readonly::Scalar my $NEVER => qr/(?!)/;
422  
423 # A producing call written with its class: Widget::Maker->fetch or
424 # Widget::Maker::fetch.
425 57 Readonly::Scalar my $QUALIFIED_NAME => qr/\A([\w:]+)\s*(?:->|::)\s*(\w+)\z/;
426  
427 # A message placeholder: {name}, or {name:%fmt} for a sprintf conversion. Only
428 # the conversions that format a value are allowed - never %n, which writes.
429 57 Readonly::Scalar my $PLACEHOLDER => qr/\{(\w+)(?::(%[-+ 0#]*\d*(?:\.\d+)?[sdfgeExXobu]))?\}/;
430  
431 # The tunables (see CONFIGURATION). A package hash rather than constants so a
432 # configuration layer can reach them.
433 57 our %config = (
434 sibling_dirs => [qw(lib bin t)],
435 own_dirs => [qw(lib bin scripts)],
436 source_extensions => [qw(pm t pl PL pm6)],
437 skipped_dirs => [qw(blib xt inc local node_modules .git .build)],
438 messages => {},
439 );
440  
441 # Every user-facing string, by key. A value is a template, or a hash of
442 # templates chosen by the 'context' argument (gender, say) or by 'count'
443 # (zero/one/other). See i18n().
444 57 Readonly::Hash my %MESSAGES => (
445 'i18n.unknown' => "no message called '{key}'",
446 'list.and' => '{head} and {last}',
447 'argument.invalid' => '{package}::{routine}(): {error}',
448 'argument.missing' => "{package}::{routine}() needs a '{argument}'",
449 'option.unknown' => '{package}::new() does not know the option(s): {options}',
450 'option.required' => "{package}::new() needs a '{option}'",
451 'option.invalid' => '{package}::new(): {error}',
452 'option.ignored' => "{package}::new(): each 'ignored' rule must be [prefix, reason], not {rule}",
453 'option.consumer' => "{package}::new(): consumer '{consumer}' must be { may_rely_on => { sub => { key => why } } }",
454 'option.class' => "{package}::new(): value_object needs a 'class' that is a module name, not '{class}'",
455 'option.directory' => "{package}::new(): {option} '{path}' is not a directory: {error}",
456 'check.producers' => 'the producers still set the keys the contract claims',
457 'check.derivation' => '{class} derives {keys}',
458 'check.consumers' => 'registered consumers read only what every producer sets',
459 'check.accessors' => 'the accessor list matches the value object',
460 'check.discovery' => 'every discovered consumer is registered',
461 'file.readable' => '{file} is readable',
462 'file.unreadable' => 'cannot read {file}: {error}',
463 'producer.sets' => "{file} sets '{key}'",
464 'class.unavailable' => '{class} is not available in this checkout',
465 'class.compiles' => '{class} compiles',
466 'derivation.made' => 'a {short} can still be made from {from}',
467 'derivation.key' => '{key} is derived',
468 'consumer.offender' => "{file} line {line} in {sub}() reads '{key}' ({kind}) - {why}",
469 'consumer.clean' => '{file} reads only keys every producer sets',
470 'consumer.stale' => "{sub}() reads '{key}' - {why}",
471 'consumer.not_stale' => '{file} still reads the keys it is allowed to rely on',
472 'consumer.stale_advice' => 'Remove the stale entry, so the registry keeps describing the code.',
473 'why.unpromised' => 'no producer in this workspace ever sets it',
474 'skip.siblings' => 'sibling checkouts are not present ({missing})',
475 'skip.producer' => '{file} is not checked: {sibling} is not in the workspace',
476 'accessor.documented' => '{accessor} is a documented accessor of {class}',
477 'accessor.accounted' => '{class} documents no accessor the contract accounts for nowhere',
478 'accessor.drift' => {
479 one => "{class} documents {names}, which this contract does not mention.\n"
480 . "The value object and the reader contract have drifted apart. For the\n"
481 . "name above: list it in 'accessors' if a consumer may read it off a\n"
482 . "result, in 'conditional' with the reason only some results carry it,\n"
483 . "or in 'not_accessors' with the reason it is not a slot of one result.",
484 other => "{class} documents {names}, which this contract does not mention.\n"
485 . "The value object and the reader contract have drifted apart. For each\n"
486 . "name above: list it in 'accessors' if a consumer may read it off a\n"
487 . "result, in 'conditional' with the reason only some results carry it,\n"
488 . "or in 'not_accessors' with the reason it is not a slot of one result.",
489 },
490 'discovery.checked' => 'found sources mentioning {source} ({count} checked)',
491 'discovery.registered' => 'the scanner found the registered consumer ({count} read a result)',
492 'discovery.clean' => 'no unregistered consumer reads a {source} result',
493 'discovery.header' => 'unregistered consumers of {source} results:',
494 'discovery.advice' => {
495 one => "Register it in 'consumers' (with its justification) or in 'ignored'\n"
496 . '(with the reason it cannot receive one).',
497 other => "Register each in 'consumers' (with its justification) or in 'ignored'\n"
498 . '(with the reason it cannot receive one).',
499 },
500 );
501  
502 # The schema new() validates a declaration against; its keys are also the
503 # list of options new() knows.
504 57 Readonly::Hash my %SCHEMA => (
505 dist_root => { type => 'string', optional => 1 },
506 workspace => { type => 'string', optional => 1 },
507 include => { type => 'arrayref', optional => 1 },
508 source => { type => 'string', min => 1 },
509 value_object => { type => 'hashref', optional => 1 },
510 guaranteed => { type => 'arrayref' },
511 conditional => { type => 'hashref', optional => 1 },
512 producers => { type => 'hashref', optional => 1 },
513 workspace_producers => { type => 'hashref', optional => 1 },
514 consumers => { type => 'hashref', optional => 1 },
515 ignored => { type => 'arrayref', optional => 1 },
516 accessors => { type => 'arrayref', optional => 1 },
517 not_accessors => { type => 'hashref', optional => 1 },
518 inspection => { type => 'arrayref', optional => 1 },
519 methods => { type => 'arrayref' },
520 batch_methods => { type => 'arrayref', optional => 1 },
521 list_methods => { type => 'arrayref', optional => 1 },
522 own_consumers => { type => 'boolean', optional => 1 },
523 require_workspace => { type => 'arrayref', optional => 1 },
524 messages => { type => 'hashref', optional => 1 },
525 );
526  
527 # What the scanner does beyond reading a file, one name per rule, with the sub
528 # each rule is exercised through. A mutation of that sub puts the rule back the
529 # way it was before it was written, and t/contract.t does that for every name in
530 # this list: each rule has a mutation subtest, and a rule with no mutation - or a
531 # mutation for a rule that is not here - fails the test.
532 #
533 # The list is part of the module because it has to move with it. Its seam is
534 # named rather than the whole of the rule's implementation, because that is the
535 # one place a mutation has to reach: everything else follows from it.
536 57 Readonly::Hash my %SCANNER_RULE_SEAM => (
537 shebang_programs => '_program',
538 batch_methods => '_batch_methods_re',
539 batch_selection => '_selection_re',
540 batch_value_sinks => '_batch_value_sinks',
541 list_methods => '_list_methods_re',
542 invocant_parameter => '_sub_ranges',
543 accessor_reads => '_accessor_read',
544 accessor_headings => 'documented_accessors',
545 qualified_calls => '_alternation',
546 code_not_prose => 'strip',
547 own_consumers => 'new',
548 );
549  
550 # ---------------------------------------------------------------------------
551 # Construction
552 # ---------------------------------------------------------------------------
553  
554 =head1 METHODS
555  
556 =head2 new
557  
558 my $contract = Test::Consumer::Contract->new(%declaration);
559  
560 =head3 Purpose
561  
562 Builds a contract from a declaration, validating it before any check runs.
563  
564 =head3 Arguments
565  
566 A list of pairs, or one hashref. C<source>, C<guaranteed> and C<methods> are
567 required; every other option has a default. An optional option given as
568 C<undef> takes its default, as if it had not been given.
569  
570 =over 4
571  
572 =item C<source> (string, required)
573  
574 The name that marks a file as one that may consume results: a file that does
575 not contain it is not scanned during discovery. Usually the producer's class.
576  
577 =item C<guaranteed> (arrayref, required)
578  
579 The keys every producer sets on every result. A read of one of these is
580 always safe.
581  
582 =item C<methods> (arrayref, required)
583  
584 The calls that hand a result to the caller, as your producer spells them:
585 C<[qw(geocode reverse_geocode)]> for a geocoder, C<[qw(fetch find)]> for a
586 store. There is no default: the checker cannot guess what your producer calls
587 its lookups, and a name it guessed would quietly find nothing. A name may be
588 written with its class, C<< 'Widget->new' >> or C<'Widget::new'>, and then only
589 that class's call matches. A variable bound from one of these is followed, as
590 is a variable passed to a sub that this file calls with it.
591  
592 =item C<batch_methods> (arrayref)
593  
594 The producing methods that return a batch of results rather than one result;
595 none by default. A batch's keys are the results, plus counts about the batch
596 itself, so a variable bound from a batch method is not treated as a result -
597 C<< $batch->{'lookups'} >> is not a read of one - while
598 C<< my $point = $batch->{$value} >> makes C<$point> a result.
599  
600 =item C<list_methods> (arrayref)
601  
602 The producing methods that hand back a list of results rather than one - a
603 report's C<results()>, the checks a runner ran; none by default. The variable
604 that takes a result out of the list is a result like any other: the loop
605 variable of C<< for my $entry (@{ $report->results() }) >>, of a list assigned
606 from that call first, and the topic of a C<map> or C<grep> block over it.
607  
608 =item C<value_object> (hashref)
609  
610 C<< { class => 'Widget', from => {...}, derives => {...} } >>. C<class> is
611 required when this is given and must be a module name. C<from> is what an
612 object is built from for check 2, C<derives> the accessor => value pairs it
613 must then return.
614  
615 =item C<conditional> (hashref)
616  
617 Key => why it is not guaranteed, used in the failure messages and accepted by
618 check 4 as accounting for a documented accessor.
619  
620 =item C<producers> (hashref)
621  
622 Path => arrayref of keys the file must still set. Paths are relative to
623 C<dist_root>, or absolute.
624  
625 =item C<workspace_producers> (hashref)
626  
627 Like C<producers>, but paths are relative to the workspace: producers in a
628 sibling distribution that this distribution's value object comes from. The
629 first component of the path names that sibling; when it is not in the
630 workspace, the file's checks are skipped (C<skip.producer>), so a declaration
631 that names one still passes on a CPAN install.
632  
633 =item C<consumers> (hashref)
634  
635 Workspace-relative (or, for C<own_consumers>, C<dist_root>-relative) path =>
636 C<< { may_rely_on => { sub_name => { key => why } } } >>. A read outside any
637 named sub is registered under the sub name C<(file scope)>.
638  
639 =item C<ignored> (arrayref)
640  
641 C<[prefix, reason]> pairs: a discovered file whose path starts with the prefix
642 is not a consumer. Each rule must be an arrayref whose first element is the
643 prefix.
644  
645 =item C<accessors> (arrayref)
646  
647 Documented accessors a consumer may call on a result.
648  
649 =item C<not_accessors> (hashref)
650  
651 Documented accessors of the value object that are not a slot of one result -
652 the constructor, a class constant - as name => why, so that the accessor check
653 can be satisfied by saying what a name is instead of listing it as something a
654 consumer may read. A name here that the value object does not document fails,
655 as an entry in C<accessors> would.
656  
657 =item C<inspection> (arrayref)
658  
659 Methods such as C<can>, C<isa> and C<DOES> that may be called on a result
660 without being a read of a field.
661  
662 =item C<own_consumers> (boolean)
663  
664 True when the distribution being checked is one of its own value object's
665 readers; false by default. Its C<lib>, C<bin> and C<scripts> are then scanned
666 for consumers and discovered like a sibling's, but not its C<t/> and C<xt/>: its
667 tests are the proof of the value object rather than readers of it. Its paths
668 are named relative to the distribution, the way a producer's are, so they still
669 point at the right file when the distribution is installed under a versioned
670 directory name.
671  
672 =item C<dist_root> (string)
673  
674 The distribution being checked. Defaults to the parent of the directory
675 holding the running test file, falling back to the current directory when that
676 is not a distribution root. When given, it must be an existing directory.
677  
678 =item C<workspace> (string)
679  
680 The directory holding the sibling distributions. Defaults to the parent of
681 C<dist_root>. When given, it must be an existing directory.
682  
683 =item C<include> (arrayref)
684  
685 Workspace-relative lib directories to put at the front of C<@INC>, so a value
686 object is read from the checkout in the workspace rather than from an
687 installed copy.
688  
689 =item C<require_workspace> (arrayref)
690  
691 Sibling distribution names that must exist for checks 3 and 5 to run. Pass the
692 ones your consumers live in, or those checks cannot tell a missing checkout
693 from a passing one.
694  
695 =item C<messages> (hashref)
696  
697 Message key => template, overriding the catalogue for this object only. See
698 L</i18n>.
699  
700 =back
701  
702 Every path in a declaration is written with C</> between the directories,
703 whatever separator the platform itself uses, and the checks name files the
704 same way, so a path can be copied from a failure message into the declaration.
705  
706 =head3 Returns
707  
708 The new object.
709  
710 =head3 Side Effects
711  
712 Each existing C<include> directory is moved to the front of C<@INC> (through
713 L<lib>, so it appears there once however many contracts name it); the last one
714 listed ends up first. C<@INC> is process-wide: the change outlives the
715 object.
716  
717 =head3 EXAMPLE
718  
719 my $contract = Test::Consumer::Contract->new({
720 source => 'Warehouse::Stock',
721 methods => [qw(fetch scan)],
722 guaranteed => [qw(grams name)],
723 conditional => { bin => 'only scan() knows the bin' },
724 });
725  
726 =head3 API SPECIFICATION
727  
728 =head4 Input
729  
730 {
731 source => { type => 'string', min => 1 },
732 guaranteed => { type => 'arrayref' },
733 methods => { type => 'arrayref' },
734 dist_root => { type => 'string', optional => 1 },
735 workspace => { type => 'string', optional => 1 },
736 include => { type => 'arrayref', optional => 1 },
737 value_object => { type => 'hashref', optional => 1 },
738 conditional => { type => 'hashref', optional => 1 },
739 producers => { type => 'hashref', optional => 1 },
740 workspace_producers => { type => 'hashref', optional => 1 },
741 consumers => { type => 'hashref', optional => 1 },
742 ignored => { type => 'arrayref', optional => 1 },
743 accessors => { type => 'arrayref', optional => 1 },
744 not_accessors => { type => 'hashref', optional => 1 },
745 inspection => { type => 'arrayref', optional => 1 },
746 batch_methods => { type => 'arrayref', optional => 1 },
747 list_methods => { type => 'arrayref', optional => 1 },
748 own_consumers => { type => 'boolean', optional => 1 },
749 require_workspace => { type => 'arrayref', optional => 1 },
750 messages => { type => 'hashref', optional => 1 },
751 }
752  
753 =head4 Output
754  
755 { type => 'object', isa => 'Test::Consumer::Contract' }
756  
757 =head3 MESSAGES
758  
759 Message Meaning / Resolution
760 ---------------------------------------------- ----------------------------------------
761 "...::new() does not know the option(s): X" An option is misspelt or unknown. Fix
762 the name; nothing is silently ignored.
763 "...::new() needs a 'X'" A required option is missing or undef.
764 "...::new(): <validator message>" An option has the wrong type, for
765 example a string where an arrayref is
766 expected.
767 "...::new(): each 'ignored' rule must be An 'ignored' entry is not an arrayref
768 [prefix, reason], not X" starting with a prefix. Write
769 ['Dist/', 'why'].
770 "...::new(): consumer 'X' must be {...}" A consumers entry is not a hashref, or
771 its may_rely_on is not sub => {key=>why}.
772 "...::new(): value_object needs a 'class' value_object without a valid module name
773 that is a module name, not 'X'" in 'class'.
774 "...::new(): dist_root 'X' is not a An explicit dist_root or workspace does
775 directory: <OS error>" not exist; the OS error says why.
776  
777 =head3 PSEUDOCODE
778  
779 normalise the arguments into one hash
780 croak on any option outside the schema
781 croak on any required option that is undef
782 validate the types; croak with the validator's reason on failure
783 croak on malformed ignored rules, consumer entries or value_object class
784 croak on an explicit dist_root or workspace that is not a directory
785 fill in defaults, take a copy of %config
786 put the include directories at the front of @INC
787 return the object
788  
789 =cut
790  
791 sub new
792 101 ▶{
Subroutine new: called CC=12 SCAR=24.9
Pod documented
793 101 my $class = shift;
794  
795 # Params::Get accepts a list of pairs or one hashref, so a declaration can
796 # be written either way. An odd-length list is its error to report.
797 101 ▶ my $spec = eval { get_params(undef, \@_) } // {};
Condition50%1/2
eval { do { get_params(undef, \@_) } } // {}
l!l
1010
MC/DC0%0/1
eval { do { get_params(undef, \@_) } } // {}
eval { do { get_params(undef, \@_) } }
Truth table50%1/2
A
A= eval { do { get_params(undef, \@_) } }
Aresult
11
00
798 101 ▶ $class->_croak('option.invalid', { error => _first_line($@) }) if($@);
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 101 101
799  
800 # A misspelt option fails before anything else: a declaration that quietly
801 # ignored 'ignores' would pass for the wrong reason.
802 101 my @unknown = grep { !exists($SCHEMA{$_}) } sort keys %{$spec};
803 101 ▶ $class->_croak('option.unknown', { options => join(' ', @unknown) }) if(@unknown);
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 100 101
804  
805 # Checked here rather than by the validator, which accepts an undef value
806 # for a required string and words the error its own way.
807 100 foreach my $required (@REQUIRED) {
808 297 ▶ $class->_croak('option.required', { option => $required }) unless(defined($spec->{$required}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec->{$required} 4 293 297
809 }
810  
811 96 my $valid = eval { validate_strict(schema => \%SCHEMA, input => $spec) };
812 96 ▶ $class->_croak('option.invalid', { error => _first_line($@) }) unless(defined($valid));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $valid 2 94 96
813  
814 94 $class->_assert_shapes($valid);
815  
816 # An explicit root that is not there is a mistake in the declaration; a
817 # defaulted one is wherever the test is running, which always exists.
818 89 foreach my $option (qw(dist_root workspace)) {
819 174 ▶ $class->_assert_directory($option, $valid->{$option}) if(defined($valid->{$option}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $valid->{$option} 19 155 174
820 }
821  
822 81 ▶ my $dist_root = $valid->{'dist_root'} // _default_dist_root();
Condition66%2/3
$valid->{"dist_root"} // _default_dist_root()
l!l&&r!l&&!r
3780
MC/DC0%0/2
$valid->{"dist_root"} // _default_dist_root()
$valid->{"dist_root"} _default_dist_root()
Truth table66%2/3
A // B
A= $valid->{"dist_root"}B= _default_dist_root()
ABresult
1X1
011
000
823  
824 # An optional option given as undef means "use the default", the same as
825 # leaving it out: stored as undef, it was dereferenced later and died in
826 # the middle of run().
827 81 my %given = map { $_ => $valid->{$_} } grep { defined($valid->{$_}) } keys %{$valid};
828  
829 my $self = bless {
830 81 ▶ %{_defaults()},
Branch: 1 branch
BranchTrueFalseTotal
$valid->{'own_consumers'} ? : 11 70 81
Condition66%2/3
$valid->{"workspace"} // dirname($dist_root)
l!l&&r!l&&!r
8730
MC/DC0%0/2
$valid->{"workspace"} // dirname($dist_root)
$valid->{"workspace"} dirname($dist_root)
Truth table66%2/3
A // B
A= $valid->{"workspace"}B= dirname($dist_root)
ABresult
1X1
011
000
831 %given,
832 dist_root => $dist_root,
833 dist_name => basename($dist_root),
834 workspace => $valid->{'workspace'} // dirname($dist_root),
835 81 own_consumers => $valid->{'own_consumers'} ? 1 : 0,
836 config => _config_snapshot(),
837 _cache => {},
838 }, $class;
839  
840 81 return set_return($self->_include_workspace_libs(), { type => 'object' });
841 }
842  
843 # _defaults
844 # Purpose : The value of every optional option that was not given.
845 # Entry : None.
846 # Exit status : A new hashref each call, so no two objects share a list.
847 # Side effects : None.
848 81 ▶sub _defaults :Private
Subroutine _defaults: called CC=1 SCAR=0.0
849 {
850 return {
851 81 include => [],
852 value_object => undef,
853 conditional => {},
854 producers => {},
855 workspace_producers => {},
856 consumers => {},
857 ignored => [],
858 accessors => [],
859 not_accessors => {},
860 inspection => [],
861 batch_methods => [],
862 list_methods => [],
863 require_workspace => [],
864 messages => {},
865 };
866 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
867  
868 # _config_snapshot
869 # Purpose : A copy of %config one level deep, taken when an object is built.
870 # Entry : None.
871 # Exit status : A new hashref of new arrayrefs/hashrefs.
872 # Side effects : None. A later change to %config does not reach the object.
873 81 ▶sub _config_snapshot :Private
Subroutine _config_snapshot: called CC=2 SCAR=6.9
874 {
875 return { map {
876 81 my $value = $config{$_};
877 405 ▶ $_ => (ref($value) eq 'HASH') ? { %{$value} } : [ @{$value} ];
Branch: 1 branch
BranchTrueFalseTotal
ref $value eq 'HASH' ? : 81 324 405
878 } keys %config };
879 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
880  
881 # _assert_shapes
882 # Purpose : The structural checks the type schema cannot express: the
883 # shape of each ignored rule, of each consumer entry, and the
884 # value object's class name.
885 # Entry : $spec -- the type-validated declaration.
886 # Exit status : Returns the class; croaks on the first malformed entry.
887 # Side effects : None.
888 94 ▶sub _assert_shapes :Private
Subroutine _assert_shapes: called CC=17 SCAR=28.4
889 {
890 94 my ($class, $spec) = @_;
891  
892 # An 'ignored' rule written as a bare string used to be skipped without a
893 # word, so the file it meant to ignore was reported as unregistered.
894 94 ▶ foreach my $rule (@{$spec->{'ignored'} || []}) {
Condition100%2/2
$spec->{'ignored'} || []
l!l
5539
MC/DC100%1/1
$spec->{'ignored'} || []
$spec->{'ignored'}
Truth table100%2/2
A
A= $spec->{'ignored'}
Aresult
11
00
895 5 ▶ $class->_croak('option.ignored', { rule => $rule // 'undef' })
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rule eq "ARRAY" and defined $rule->[0] and not ref $rule->[0] 1 4 5
Condition62%5/8
ref $rule eq "ARRAY" and defined $rule->[0] and not ref $rule->[0]
!ll&&!rl&&r
104
ref $rule eq "ARRAY" and defined $rule->[0]
!ll&&!rl&&r
104
$rule // "undef"
l!l
10
MC/DC33%1/3
ref $rule eq "ARRAY" and defined $rule->[0] and not ref $rule->[0]
ref $rule eq "ARRAY" defined $rule->[0] not ref $rule->[0]
MC/DC0%0/1
$rule // "undef"
$rule
Truth table50%2/4
A and B and not(C)
A= ref $rule eq "ARRAY"B= defined $rule->[0]C= not ref $rule->[0]
ABCresult
0XX0
10X0
1100
1111
Truth table50%1/2
A
A= $rule
Aresult
11
00
896 unless(ref($rule) eq 'ARRAY' && defined($rule->[0]) && !ref($rule->[0]));
897 }
898  
899 # A consumer entry is dereferenced two levels deep during check 3; a wrong
900 # shape there died with "Not a HASH reference" in the middle of a subtest.
901 93 ▶ my $consumers = $spec->{'consumers'} || {};
Condition100%2/2
$spec->{'consumers'} || {}
l!l
5538
MC/DC100%1/1
$spec->{'consumers'} || {}
$spec->{'consumers'}
Truth table100%2/2
A
A= $spec->{'consumers'}
Aresult
11
00
902 93 foreach my $consumer (sort keys %{$consumers}) {
903 65 my $entry = $consumers->{$consumer};
904 65 ▶ my $rely = (ref($entry) eq 'HASH') ? ($entry->{'may_rely_on'} // {}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $entry eq 'HASH' ? : 64 1 65
Condition100%2/2
$entry->{"may_rely_on"} // {}
l!l
631
MC/DC100%1/1
$entry->{"may_rely_on"} // {}
$entry->{"may_rely_on"}
Truth table100%2/2
A
A= $entry->{"may_rely_on"}
Aresult
11
00
905 65 ▶ my $ok = (ref($rely) eq 'HASH') && !grep { ref($_) ne 'HASH' } values %{$rely};
Condition100%3/3
ref $rely eq 'HASH' && !grep({ref $_ ne 'HASH';} values %{$rely;})
!ll&&!rl&&r
1163
MC/DC100%2/2
ref $rely eq 'HASH' && !grep({ref $_ ne 'HASH';} values %{$rely;})
ref $rely eq 'HASH' !grep({ref $_ ne 'HASH';} values %{$rely;})
Truth table100%3/3
A && not(B)
A= ref $rely eq 'HASH'B= !grep({ref $_ ne 'HASH';} values %{$rely;})
ABresult
0X0
100
111
906 65 ▶ $class->_croak('option.consumer', { consumer => $consumer }) unless($ok);
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 2 63 65
907 }
908  
909 # The class is loaded by name, so only a module name is allowed: a path
910 # fragment here would be handed to require.
911 91 ▶ if(my $value_object = $spec->{'value_object'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $value_object = $spec->{"value_object"}) 54 37 91
912 54 my $name = $value_object->{'class'};
913 54 ▶ $class->_croak('option.class', { class => $name // 'undef' })
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and &is_module_name($name) 2 52 54
Condition100%5/5
defined $name and &is_module_name($name)
!ll&&!rl&&r
1152
$name // "undef"
l!l
11
MC/DC100%2/2
defined $name and &is_module_name($name)
defined $name &is_module_name($name)
MC/DC100%1/1
$name // "undef"
$name
Truth table100%3/3
A and B
A= defined $nameB= &is_module_name($name)
ABresult
0X0
100
111
Truth table100%2/2
A
A= $name
Aresult
11
00
914 unless(defined($name) && is_module_name($name));
915 }
916  
917 89 return $class;
918 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
919  
920 # _assert_directory
921 # Purpose : Croak, with the OS's own reason, when an option names a path
922 # that cannot be opened as a directory.
923 # Entry : $option -- the option name; $path -- its value.
924 # Exit status : Returns the class when the directory opens; croaks otherwise.
925 # Side effects : Opens and closes the directory.
926 19 ▶sub _assert_directory :Private
Subroutine _assert_directory: called CC=2 SCAR=6.9
927 {
928 19 my ($class, $option, $path) = @_;
929  
930 # opendir under autodie throws an exception that carries errno, so the
931 # message says ENOENT or ENOTDIR (EINVAL on Windows) in the words of the
932 # platform.
933 19 my $opened = eval { opendir(my $dh, $path); closedir($dh); 1 };
934 19 ▶ $class->_croak('option.directory', { option => $option, path => $path, error => _os_error($@) })
Branch: 1 branch
BranchTrueFalseTotal
unless $opened 8 11 19
935 unless($opened);
936  
937 11 return $class;
938 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
939  
940 # _include_workspace_libs
941 # Purpose : Put each existing 'include' directory at the front of @INC so
942 # the value object is read from the workspace checkout.
943 # Entry : An object whose workspace and include are set.
944 # Exit status : Returns $self.
945 # Side effects : Changes @INC for the whole process.
946 81 ▶sub _include_workspace_libs :Private
Subroutine _include_workspace_libs: called CC=2 SCAR=6.9
947 {
948 81 my $self = shift;
949  
950 # lib->import removes a directory already in @INC before adding it again,
951 # so building many contracts does not grow @INC without bound. Reversed,
952 # so the last one listed is first, as it always has been.
953 55 my @dirs = grep { -d $_ }
954 81 map { File::Spec->catdir($self->{'workspace'}, split(m{/}, $_)) } @{$self->{'include'}};
955 81 ▶ lib->import(reverse @dirs) if(@dirs);
Branch: 1 branch
BranchTrueFalseTotal
if @dirs 55 26 81
956  
957 81 return $self;
958 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
959  
960 # _default_dist_root
961 # Purpose : Find the distribution that the running test belongs to.
962 # Entry : $0 is the running test, normally <dist>/t/<name>.t.
963 # Exit status : An absolute directory path; the current directory when the
964 # grandparent of $0 has no lib/.
965 # Side effects : None.
966 78 ▶sub _default_dist_root :Private
Subroutine _default_dist_root: called CC=4 SCAR=15.6
967 {
968 # abs_path() is undef for a $0 that is not a file, such as '-e'.
969 78 my $script = abs_path($0);
970 78 ▶ my $root = defined($script) ? dirname(dirname($script)) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $script ? : 78 0 78
971  
972 # Without a lib/ it is not a distribution, so fall back to where we are.
973 78 ▶ $root = getcwd() unless(defined($root) && -d File::Spec->catdir($root, 'lib'));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $root and -d "File::Spec"->catdir($root, "lib") 0 78 78
Condition33%1/3
defined $root and -d "File::Spec"->catdir($root, "lib")
!ll&&!rl&&r
0078
MC/DC0%0/2
defined $root and -d "File::Spec"->catdir($root, "lib")
defined $root -d "File::Spec"->catdir($root, "lib")
Truth table33%1/3
A and B
A= defined $rootB= -d "File::Spec"->catdir($root, "lib")
ABresult
0X0
100
111
974  
975 78 return $root;
976 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
977  
978 =head2 run
979  
980 $contract->run();
981  
982 =head3 Purpose
983  
984 Runs the five checks described in L</DESCRIPTION>, each as a subtest. Called
985 for you by C<run_consumer_contract()>.
986  
987 =head3 Arguments
988  
989 None.
990  
991 =head3 Returns
992  
993 The object, so calls can be chained.
994  
995 =head3 Side Effects
996  
997 Emits TAP through L<Test::Builder>. Loads the value object's class.
998  
999 =head3 EXAMPLE
1000  
1001 Test::Consumer::Contract->new(%declaration)->run();
1002 done_testing();
1003  
1004 =head3 API SPECIFICATION
1005  
1006 =head4 Input
1007  
1008 {}
1009  
1010 =head4 Output
1011  
1012 { type => 'object', isa => 'Test::Consumer::Contract' }
1013  
1014 =head3 MESSAGES
1015  
1016 None of its own: each check's messages are listed in L</DIAGNOSTICS>.
1017  
1018 =cut
1019  
1020 sub run
1021 52 ▶{
Subroutine run: called CC=1 SCAR=0.0
Pod documented
1022 52 my $self = shift;
1023  
1024 # Each check decides for itself whether it applies, so the order here is
1025 # the whole of what run() knows about them.
1026 52 return set_return($self->_check_producers()->_check_derivation()->_check_consumers()
1027 ->_check_accessors()->_check_discovery(), { type => 'object' });
1028 }
1029  
1030 =head2 run_consumer_contract
1031  
1032 my $contract = run_consumer_contract(%declaration);
1033  
1034 =head3 Purpose
1035  
1036 Builds the contract and runs it: C<< new(...)->run() >> as one exportable call.
1037  
1038 =head3 Arguments
1039  
1040 The declaration, as for L</new>.
1041  
1042 =head3 Returns
1043  
1044 The object.
1045  
1046 =head3 Side Effects
1047  
1048 Those of L</new> and L</run>.
1049  
1050 =head3 EXAMPLE
1051  
1052 use Test::Most;
1053 use Test::Consumer::Contract qw(run_consumer_contract);
1054  
1055 run_consumer_contract(source => 'S', methods => ['fetch'], guaranteed => ['id']);
1056 done_testing();
1057  
1058 =head3 API SPECIFICATION
1059  
1060 =head4 Input
1061  
1062 As for L</new>.
1063  
1064 =head4 Output
1065  
1066 { type => 'object', isa => 'Test::Consumer::Contract' }
1067  
1068 =head3 MESSAGES
1069  
1070 Those of L</new>.
1071  
1072 =cut
1073  
1074 sub run_consumer_contract
1075 51 ▶{
Subroutine run_consumer_contract: called CC=1 SCAR=0.0
Pod documented
1076 51 return set_return(__PACKAGE__->new(@_)->run(), { type => 'object' });
1077 }
1078  
1079 =head2 workspace_present
1080  
1081 if($contract->workspace_present()) { ... }
1082  
1083 =head3 Purpose
1084  
1085 Says whether every distribution named in C<require_workspace> is in the
1086 workspace, which is what checks 3 and 5 need to run.
1087  
1088 =head3 Arguments
1089  
1090 None.
1091  
1092 =head3 Returns
1093  
1094 1 when every one is there, otherwise 0.
1095  
1096 =head3 Side Effects
1097  
1098 Caches the answer in the object.
1099  
1100 =head3 EXAMPLE
1101  
1102 plan skip_all => 'no siblings' unless $contract->workspace_present();
1103  
1104 =head3 API SPECIFICATION
1105  
1106 =head4 Input
1107  
1108 {}
1109  
1110 =head4 Output
1111  
1112 { type => 'boolean' }
1113  
1114 =head3 MESSAGES
1115  
1116 None.
1117  
1118 =cut
1119  
1120 sub workspace_present
1121 2 ▶{
Subroutine workspace_present: called CC=2 SCAR=6.9
Pod documented
1122 2 my $self = shift;
1123  
1124 # Asked through the cache-filling method: the cache is only built when a
1125 # check first needs it, and reading the slot directly found nothing there.
1126 2 ▶ return set_return(@{$self->_missing_siblings()} ? 0 : 1, { type => 'boolean' });
Branch: 1 branch
BranchTrueFalseTotal
@{$self->_missing_siblings;} ? : 1 1 2
1127 }
1128  
1129 # _missing_siblings
1130 # Purpose : The require_workspace distributions not in the workspace.
1131 # Entry : A constructed object.
1132 # Exit status : An arrayref of names, possibly empty.
1133 # Side effects : Caches the arrayref in the object.
1134 105 ▶sub _missing_siblings :Private
Subroutine _missing_siblings: called CC=2 SCAR=6.9
1135 {
1136 105 my $self = shift;
1137  
1138 return $self->{'_cache'}{'missing_siblings'} //= [
1139 105 ▶ grep { !-d File::Spec->catdir($self->{'workspace'}, $_) } @{$self->{'require_workspace'}}
Condition100%2/2
$self->{"_cache"}{"missing_siblings"} //= [grep({not -d "File::Spec"->catdir($self->{"workspace"}, $_);} @{$$self{"require_workspace"};})]
l!l
5154
MC/DC100%1/1
$self->{"_cache"}{"missing_siblings"} //= [grep({not -d "File::Spec"->catdir($self->{"workspace"}, $_);} @{$$self{"require_workspace"};})]
$self->{"_cache"}{"missing_siblings"}
Truth table100%2/2
A
A= $self->{"_cache"}{"missing_siblings"}
Aresult
11
00
1140 ];
1141 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1142  
1143 =head2 i18n
1144  
1145 my $text = $contract->i18n('check.producers');
1146 my $text = Test::Consumer::Contract->i18n('skip.siblings', { missing => 'X' });
1147  
1148 =head3 Purpose
1149  
1150 Turns a message key and its arguments into the text the user sees. Every
1151 diagnostic, test name and error this module produces goes through here, so all
1152 of them can be reworded or translated.
1153  
1154 =head3 Arguments
1155  
1156 =over 4
1157  
1158 =item C<$key> (string, required)
1159  
1160 The message key, such as C<check.producers>.
1161  
1162 =item C<\%args> (hashref)
1163  
1164 The values for the template's placeholders. C<{name}> is replaced by the
1165 value; C<{name:%.2f}> formats it with that C<sprintf> conversion (only the
1166 conversions C<s d f g e E x X o b u>, with their flags, are honoured). An
1167 arrayref value is joined with C<, >. A placeholder with no value is left as
1168 written, so a missing argument shows rather than vanishes. C<package>
1169 defaults to this module's name.
1170  
1171 When the template is a hash of forms, C<context> picks one by name (a gender,
1172 say), and otherwise C<count> picks C<zero> (if present), C<one> or C<other>.
1173  
1174 =back
1175  
1176 The template is looked up in the object's C<messages> option, then in
1177 C<$config{messages}>, then in the built-in catalogue.
1178  
1179 =head3 Returns
1180  
1181 The message text.
1182  
1183 =head3 Side Effects
1184  
1185 None.
1186  
1187 =head3 EXAMPLE
1188  
1189 local $Test::Consumer::Contract::config{'messages'}{'check.producers'}
1190 = 'die Erzeuger setzen noch die zugesagten Schluessel';
1191  
1192 my $contract = Test::Consumer::Contract->new(%declaration, messages => {
1193 'skip.siblings' => { one => 'missing: {missing}', other => 'missing ({count}): {missing}' },
1194 });
1195  
1196 print $contract->i18n('skip.siblings', { missing => 'A, B', count => 2 });
1197 # missing (2): A, B
1198  
1199 =head3 API SPECIFICATION
1200  
1201 =head4 Input
1202  
1203 {
1204 key => { type => 'string', min => 1, position => 0 },
1205 args => { type => 'hashref', optional => 1, position => 1 },
1206 }
1207  
1208 =head4 Output
1209  
1210 { type => 'string' }
1211  
1212 =head3 MESSAGES
1213  
1214 Message Meaning / Resolution
1215 ------------------------------- ---------------------------------------------
1216 "no message called 'X'" The key is in no catalogue. This is a
1217 programming error and is raised with confess,
1218 so the stack trace shows the caller.
1219 "...::i18n() needs a 'key'" The key is missing or undef.
1220  
1221 =head3 PSEUDOCODE
1222  
1223 validate the key and the arguments
1224 add package => this module's name under the caller's arguments
1225 take the first template defined in: object messages, %config messages, built-in
1226 confess if there is none
1227 if the template is a hash of forms, choose one by context, else by count
1228 replace each {name} or {name:%fmt} that has a value; leave the rest
1229 return the text
1230  
1231 =cut
1232  
1233 sub i18n
1234 1687 ▶{
Subroutine i18n: called CC=5 SCAR=16.1
Pod documented
1235 1687 my $self = shift;
1236 1687 my $params = $self->_arguments('i18n', [qw(key args)],
1237 { key => { type => 'string', min => 1 }, args => { type => 'hashref', optional => 1 } }, @_);
1238  
1239 1685 my $key = $params->{'key'};
1240 1685 ▶ my %args = (package => __PACKAGE__, %{$params->{'args'} || {}});
Condition100%2/2
$params->{'args'} || {}
l!l
1408277
MC/DC100%1/1
$params->{'args'} || {}
$params->{'args'}
Truth table100%2/2
A
A= $params->{'args'}
Aresult
11
00
1241  
1242 # The object's own wording first, then the configured, then the built-in.
1243 5028 ▶ my $entry = first { defined($_) }
Subroutine __ANON__: called CC=1 SCAR=0.0
1244 1685 ▶ (ref($self) ? $self->{'messages'}{$key} : undef), $config{'messages'}{$key}, $MESSAGES{$key};
Branch: 1 branch
BranchTrueFalseTotal
ref $self ? : 1626 59 1685
1245  
1246 # Not through _croak: an unknown key here would recurse. confess, because
1247 # a missing key is the module's own bug and the stack is what finds it.
1248 1685 ▶ confess(_interpolate($MESSAGES{'i18n.unknown'}, { key => $key })) unless(defined($entry));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $entry 1 1684 1685
1249  
1250 1684 ▶ $entry = _choose_form($entry, \%args) if(ref($entry) eq 'HASH');
Branch: 1 branch
BranchTrueFalseTotal
if ref $entry eq "HASH" 106 1578 1684
1251  
1252 1684 return set_return(_interpolate($entry, \%args), { type => 'string' });
1253 }
1254  
1255 # _choose_form
1256 # Purpose : Pick one template out of a hash of forms.
1257 # Entry : $forms -- { context_or_plural_form => template };
1258 # $args -- the message arguments ('context', 'count').
1259 # Exit status : A template string ('' when the hash has no usable form).
1260 # Side effects : None.
1261 106 ▶sub _choose_form :Private
Subroutine _choose_form: called CC=9 SCAR=22.1
1262 {
1263 106 my ($forms, $args) = @_;
1264  
1265 106 my ($context, $count) = @{$args}{qw(context count)};
1266  
1267 # A named context (a gender, a register) wins over the count; the count
1268 # picks the plural form, with 'zero' optional and 'other' the fallback.
1269 my $form = (defined($context) && exists($forms->{$context})) ? $context
1270 : !looks_like_number($count) ? 'other'
1271 106 ▶ : ($count == 0 && exists($forms->{'zero'})) ? 'zero'
Branch: 4 branches
BranchTrueFalseTotal
defined $context && exists $forms->{$context} ? : 1 105 106
!&looks_like_number($count) ? : 2 103 105
$count == 0 && exists $forms->{'zero'} ? : 1 102 103
$count == 1 ? : 11 91 102
Condition100%6/6
defined $context and exists $forms->{$context}
!ll&&!rl&&r
10411
$count == 0 and exists $forms->{"zero"}
!ll&&!rl&&r
13891
MC/DC100%2/2
defined $context and exists $forms->{$context}
defined $context exists $forms->{$context}
MC/DC100%2/2
$count == 0 and exists $forms->{"zero"}
$count == 0 exists $forms->{"zero"}
Truth table100%3/3
A and B
A= defined $contextB= exists $forms->{$context}
ABresult
0X0
100
111
Truth table100%3/3
A and B
A= $count == 0B= exists $forms->{"zero"}
ABresult
0X0
100
111
1272 : ($count == 1) ? 'one'
1273 : 'other';
1274  
1275 106 ▶ return $forms->{$form} // $forms->{'other'} // '';
Condition40%2/5
($forms->{$form} // $forms->{"other"}) // ""
l!l
1060
$forms->{$form} // $forms->{"other"}
l!l&&r!l&&!r
10600
MC/DC0%0/2
($forms->{$form} // $forms->{"other"}) // ""
$forms->{$form} $forms->{"other"}
Truth table33%1/3
A // B
A= $forms->{$form}B= $forms->{"other"}
ABresult
1X1
011
000
1276 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1277  
1278 # _interpolate
1279 # Purpose : Replace each placeholder in a template with its argument.
1280 # Entry : $template -- a string; $args -- name => value.
1281 # Exit status : The text, with unknown placeholders left as written.
1282 # Side effects : None.
1283 1685 ▶sub _interpolate :Private
Subroutine _interpolate: called CC=2 SCAR=6.9
1284 {
1285 1685 my ($template, $args) = @_;
1286  
1287 # /p gives ${^MATCH}, which puts an unmatched placeholder back exactly as it
1288 # was written, without the global cost $& has on older perls.
1289 1685 (my $text = $template) =~ s{$PLACEHOLDER}{
1290 2063 ▶ exists($args->{$1}) ? _format_value($args->{$1}, $2) : ${^MATCH}
Branch: 1 branch
BranchTrueFalseTotal
exists $args->{$1} ? : 2061 2 2063
1291 }gep;
1292  
1293 1685 return $text;
1294 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1295  
1296 # _format_value
1297 # Purpose : Render one placeholder's value.
1298 # Entry : $value -- scalar, arrayref or undef; $format -- a sprintf
1299 # conversion, or undef.
1300 # Exit status : A string; undef renders as ''.
1301 # Side effects : None. 'numeric' warnings are off: a %d given text renders 0
1302 # rather than shouting in the middle of a diagnostic.
1303 2061 ▶sub _format_value :Private
Subroutine _format_value: called CC=4 SCAR=13.9
1304 {
1305 2061 my ($value, $format) = @_;
1306  
1307 57 ▶ no warnings 'numeric';
Subroutine BEGIN: called CC=1 SCAR=0.0
1308 my $text = !defined($value) ? ''
1309 2061 ▶ : (ref($value) eq 'ARRAY') ? join(', ', @{$value})
Branch: 3 branches
BranchTrueFalseTotal
!defined($value) ? : 1 2060 2061
ref $value eq 'ARRAY' ? : 1 2059 2060
defined $format ? : 2 2057 2059
1310 : defined($format) ? sprintf($format, $value)
1311 : $value;
1312  
1313 2061 return $text;
1314 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1315  
1316 # _croak
1317 # Purpose : Raise an error whose text comes from the catalogue.
1318 # Entry : $key -- message key; $args -- its arguments.
1319 # Exit status : Does not return.
1320 # Side effects : Croaks, from the perspective of the caller outside this module.
1321 26 ▶sub _croak :Private
Subroutine _croak: called CC=1 SCAR=0.0
1322 {
1323 26 my ($self, $key, $args) = @_;
1324  
1325 26 croak($self->i18n($key, $args));
1326 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1327  
1328 # _arguments
1329 # Purpose : Normalise a public method's arguments with Params::Get and
1330 # check them with Params::Validate::Strict, in one place.
1331 # Entry : $routine -- name for messages; $names -- positional names;
1332 # $schema -- the input schema; @args -- the caller's arguments.
1333 # Exit status : The validated hashref; croaks through the catalogue on failure.
1334 # Side effects : None.
1335 2668 ▶sub _arguments :Private
Subroutine _arguments: called CC=5 SCAR=16.1
1336 {
1337 2668 my ($self, $routine, $names, $schema, @args) = @_;
1338  
1339 2668 ▶ my $params = eval { get_params($names, @args) } // {};
Condition50%1/2
eval { do { get_params($names, @args) } } // {}
l!l
26680
MC/DC0%0/1
eval { do { get_params($names, @args) } } // {}
eval { do { get_params($names, @args) } }
Truth table50%1/2
A
A= eval { do { get_params($names, @args) } }
Aresult
11
00
1340  
1341 # A missing argument is named before the types are checked, in the
1342 # catalogue's words: the validator lets some undefs through and words the
1343 # others its own way.
1344 2668 foreach my $name (grep { !$schema->{$_}{'optional'} } sort keys %{$schema}) {
1345 $self->_croak('argument.missing', { routine => $routine, argument => $name })
1346 2876 ▶ unless(defined($params->{$name}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $params->{$name} 4 2872 2876
1347 }
1348  
1349 2664 my $valid = eval { validate_strict(schema => $schema, input => $params) };
1350 2664 ▶ $self->_croak('argument.invalid', { routine => $routine, error => _first_line($@) }) unless(defined($valid));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $valid 2 2662 2664
1351  
1352 2662 return $valid;
1353 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1354  
1355 # _first_line
1356 # Purpose : The first line of an error, without Perl's " at FILE line N."
1357 # Entry : $error -- an exception (string or object) or undef.
1358 # Exit status : A string, possibly empty.
1359 # Side effects : None.
1360 6 ▶sub _first_line :Private
Subroutine _first_line: called CC=3 SCAR=11.4
1361 {
1362 6 ▶ my ($line) = split(/\n/, defined($_[0]) ? "$_[0]" : '');
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 6 0 6
1363 6 ▶ $line //= '';
Condition50%1/2
$line //= ""
l!l
60
MC/DC0%0/1
$line //= ""
$line
Truth table50%1/2
A
A= $line
Aresult
11
00
1364 6 $line =~ s/ at \S+ line \d+\.?\z//;
1365  
1366 6 return $line;
1367 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1368  
1369 # _os_error
1370 # Purpose : The operating system's text for the error behind an exception.
1371 # Entry : $exception -- an autodie::exception, or any other error.
1372 # Exit status : The errno string as Perl renders "$!", else the first line.
1373 # Side effects : None.
1374 13 ▶sub _os_error :Private
Subroutine _os_error: called CC=3 SCAR=13.1
1375 {
1376 13 my $exception = shift;
1377  
1378 13 ▶ return (blessed($exception) && $exception->can('errno')) ? $exception->errno : _first_line($exception);
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($exception) && $exception->can('errno') ? : 13 0 13
Condition33%1/3
builtin::blessed($exception) and $exception->can("errno")
!ll&&!rl&&r
0013
MC/DC0%0/2
builtin::blessed($exception) and $exception->can("errno")
builtin::blessed($exception) $exception->can("errno")
Truth table33%1/3
A and B
A= builtin::blessed($exception)B= $exception->can("errno")
ABresult
0X0
100
111
1379 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1380  
1381 # ---------------------------------------------------------------------------
1382 # Reading source
1383 # ---------------------------------------------------------------------------
1384  
1385 # _read_source
1386 # Purpose : Read a whole file without dying.
1387 # Entry : $path -- a path.
1388 # Exit status : { text => content } on success, { error => OS error } otherwise.
1389 # Side effects : Opens and closes the file.
1390 381 ▶sub _read_source :Private
Subroutine _read_source: called CC=2 SCAR=6.9
1391 {
1392 381 my (undef, $path) = @_;
1393  
1394 381 my %result;
1395  
1396 # autodie's exception keeps errno apart from the sentence around it, which
1397 # the i18n message needs; File::Slurper would fold both into English.
1398 381 my $read = eval {
1399 381 open(my $fh, '<', $path);
1400 376 local $/;
1401 376 $result{'text'} = <$fh>;
1402 376 close($fh);
1403 376 1;
1404 };
1405 381 ▶ $result{'error'} = _os_error($@) unless($read);
Branch: 1 branch
BranchTrueFalseTotal
unless $read 5 376 381
1406  
1407 381 return \%result;
1408 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1409  
1410 # _readable
1411 # Purpose : Read a file the check depends on, asserting that it could be.
1412 # Entry : $path -- where it is; $label -- how the contract names it.
1413 # Exit status : The content, or undef when it could not be read.
1414 # Side effects : Emits one ok(), and a diag() with the OS error on failure.
1415 206 ▶sub _readable :Private
Subroutine _readable: called CC=2 SCAR=6.9
1416 {
1417 206 my ($self, $path, $label) = @_;
1418  
1419 206 my $source = $self->_read_source($path);
1420  
1421 ok(defined($source->{'text'}), $self->i18n('file.readable', { file => $label }))
1422 206 ▶ or diag($self->i18n('file.unreadable', { file => $label, error => $source->{'error'} }));
Branch: 1 branch
BranchTrueFalseTotal
&ok(defined $source->{"text"}, scalar $self->i18n("file.readable", {"file", $label})) or diag($self->i18n("file.unreadable", {"file", $label, "error", $source->{"error"}})) 204 2 206
1423  
1424 206 return $source->{'text'};
1425 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1426  
1427 =head2 sets_key
1428  
1429 $contract->sets_key($source_text, 'database')
1430  
1431 =head3 Purpose
1432  
1433 Says whether the text assigns the key, in any of the spellings a producer might
1434 use: C<< key => value >>, C<< 'key' => value >>, C<< $obj->{'key'} = value >>,
1435 C<< $obj->{'key'} ||= value >> and C<< $obj->{'key'} //= value >>.
1436  
1437 =head3 Arguments
1438  
1439 =over 4
1440  
1441 =item C<$text> (string, required) - source, normally passed through L</strip>.
1442  
1443 =item C<$key> (string, required) - the key.
1444  
1445 =back
1446  
1447 =head3 Returns
1448  
1449 1 or 0.
1450  
1451 =head3 Side Effects
1452  
1453 None.
1454  
1455 =head3 EXAMPLE
1456  
1457 my $text = $contract->strip($source);
1458 ok($contract->sets_key($text, 'colour'), 'the producer still sets colour');
1459  
1460 =head3 API SPECIFICATION
1461  
1462 =head4 Input
1463  
1464 {
1465 text => { type => 'string', position => 0 },
1466 key => { type => 'string', min => 1, position => 1 },
1467 }
1468  
1469 =head4 Output
1470  
1471 { type => 'boolean' }
1472  
1473 =head3 MESSAGES
1474  
1475 Message Meaning / Resolution
1476 ------------------------------------------- ----------------------------------
1477 "...::sets_key(): <validator message>" An argument has the wrong type.
1478 "...::sets_key() needs a 'X'" An argument is missing or undef.
1479  
1480 =cut
1481  
1482 sub sets_key
1483 209 ▶{
Subroutine sets_key: called CC=4 SCAR=13.9
Pod documented
1484 209 my $self = shift;
1485 209 my $params = $self->_arguments('sets_key', [qw(text key)],
1486 { text => { type => 'string' }, key => { type => 'string', min => 1 } }, @_);
1487  
1488 208 my ($text, $k) = ($params->{'text'}, quotemeta($params->{'key'}));
1489  
1490 # 'key' => value (the quotes must match) / key => value / ->{key} = value.
1491 # '==' and '=~' compare the key's value; neither sets it.
1492 208 ▶ my $sets = ($text =~ /(['"])$k\1\s*=>/)
Condition100%6/6
$text =~ /(['"])$k\1\s*=>/u || $text =~ /(?:^|[\s(,{])$k\s*=>/mu || $text =~ m[->\s*\{\s*(['"]?)$k\1\s*\}\s*(?:=(?![=~])|\|\|=|//=)]u
l!l&&r!l&&!r
19639
$text =~ /(['"])$k\1\s*=>/u or $text =~ /(?:^|[\s(,{])$k\s*=>/mu
l!l&&r!l&&!r
219412
MC/DC100%3/3
$text =~ /(['"])$k\1\s*=>/u || $text =~ /(?:^|[\s(,{])$k\s*=>/mu || $text =~ m[->\s*\{\s*(['"]?)$k\1\s*\}\s*(?:=(?![=~])|\|\|=|//=)]u
$text =~ /(['"])$k\1\s*=>/u $text =~ /(?:^|[\s(,{])$k\s*=>/mu $text =~ m[->\s*\{\s*(['"]?)$k\1\s*\}\s*(?:=(?![=~])|\|\|=|//=)]u
Truth table100%4/4
A or B || C
A= $text =~ /(['"])$k\1\s*=>/uB= $text =~ /(?:^|[\s(,{])$k\s*=>/muC= $text =~ m[->\s*\{\s*(['"]?)$k\1\s*\}\s*(?:=(?![=~])|\|\|=|//=)]u
ABCresult
1XX1
01X1
0011
0000
1493 || ($text =~ /(?:^|[\s(,{])$k\s*=>/m)
1494 || ($text =~ /->\s*\{\s*(['"]?)$k\1\s*\}\s*(?:=(?![=~])|\|\|=|\/\/=)/);
1495  
1496 208 ▶ return set_return($sets ? 1 : 0, { type => 'boolean' });
Branch: 1 branch
BranchTrueFalseTotal
$sets ? : 199 9 208
1497 }
1498  
1499 # _producer_evidence
1500 # Purpose : Every producer the declaration names, with its path resolved.
1501 # Entry : A constructed object.
1502 # Exit status : An arrayref of { path, label, keys }, sorted by path.
1503 # Side effects : None.
1504 53 ▶sub _producer_evidence :Private
Subroutine _producer_evidence: called CC=4 SCAR=13.9
1505 {
1506 53 my $self = shift;
1507  
1508 53 my @evidence;
1509  
1510 # Dist-relative (or absolute) producers, then workspace-relative ones. The
1511 # label is the path as the declaration spells it, for readable messages.
1512 53 foreach my $file (keys %{$self->{'producers'}}) {
1513 my $path = File::Spec->file_name_is_absolute($file)
1514 ? $file
1515 47 ▶ : File::Spec->catfile($self->{'dist_root'}, split(m{/}, $file));
Branch: 1 branch
BranchTrueFalseTotal
'File::Spec'->file_name_is_absolute($file) ? : 0 47 47
1516 47 push @evidence, { path => $path, label => $file, keys => $self->{'producers'}{$file} };
1517 }
1518 # A workspace producer also carries the sibling it lives in - the first
1519 # component of its path - so that a missing checkout can be told apart from
1520 # a missing file.
1521 53 foreach my $file (keys %{$self->{'workspace_producers'}}) {
1522 52 my @parts = split(m{/}, $file);
1523 push @evidence, {
1524 path => File::Spec->catfile($self->{'workspace'}, @parts),
1525 label => $file,
1526 52 keys => $self->{'workspace_producers'}{$file},
1527 sibling => $parts[0],
1528 };
1529 }
1530  
1531 53 return [ sort { $a->{'path'} cmp $b->{'path'} } @evidence ];
1532 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1533  
1534 # _check_producers
1535 # Purpose : Check 1: each producer still sets each key it is named for.
1536 # Entry : A constructed object.
1537 # Exit status : Returns $self.
1538 # Side effects : One subtest, unless no producer is declared.
1539 53 ▶sub _check_producers :Protected
Subroutine _check_producers: called CC=2 SCAR=6.9
1540 {
1541 53 my $self = shift;
1542  
1543 53 my $evidence = $self->_producer_evidence();
1544  
1545 53 ▶ if(@{$evidence}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$evidence;}) 51 2 53
1546 51 ▶ subtest $self->i18n('check.producers') => sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
1547 51 foreach my $producer (@{$evidence}) {
1548 # A producer in a sibling that is not checked out is skipped, as
1549 # the workspace checks are: outside a workspace (a CPAN install,
1550 # a single-repository CI job) there is nothing to read, and that
1551 # is not a broken contract. A sibling that is there but no longer
1552 # has the file still fails below, since the file has moved.
1553 99 ▶ if(defined(my $sibling = $producer->{'sibling'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $sibling = $producer->{"sibling"})) 52 47 99
1554 52 ▶ if(!-d File::Spec->catdir($self->{'workspace'}, $sibling)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d "File::Spec"->catdir($self->{"workspace"}, $sibling)) 1 51 52
1555 SKIP: {
1556 1 skip($self->i18n('skip.producer', { file => $producer->{'label'}, sibling => $sibling }),
1557 1 1 + scalar(@{$producer->{'keys'}}));
1558 }
1559 1 next;
1560 }
1561 }
1562  
1563 98 my $raw = $self->_readable($producer->{'path'}, $producer->{'label'});
1564 98 ▶ next unless(defined($raw));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 2 96 98
1565  
1566 # The evidence is the code: a key in a POD example or a comment
1567 # documents the promise, it does not keep it.
1568 96 my $text = $self->strip($raw);
1569  
1570 96 foreach my $key (@{$producer->{'keys'}}) {
1571 ok($self->sets_key($text, $key),
1572 196 $self->i18n('producer.sets', { file => $producer->{'label'}, key => $key }));
1573 }
1574 }
1575 51 };
1576 }
1577  
1578 53 return $self;
1579 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1580  
1581 # ---------------------------------------------------------------------------
1582 # The value object
1583 # ---------------------------------------------------------------------------
1584  
1585 # _load_class
1586 # Purpose : Load the value object's class, telling "not installed" apart
1587 # from "installed but broken".
1588 # Entry : $class -- a module name (validated by new()).
1589 # Exit status : {} when loaded; { missing => 1 } when its file is not in
1590 # @INC; { error => text } when it is there but fails to load.
1591 # Side effects : Loads the class; caches the answer in the object.
1592 102 ▶sub _load_class :Private
Subroutine _load_class: called CC=4 SCAR=13.9
1593 {
1594 102 my ($self, $class) = @_;
1595  
1596 102 ▶ return $self->{'_cache'}{'class'}{$class} //= do {
Condition66%2/3
$self->{"_cache"}{"class"}{$class} //= do { my $loaded = eval { do { &require_module($class); 1 } }; my $error = $@; my $file = &module_notional_filename($class); $loaded ? {} : ($error =~ /\ACan't locate \Q$file\E in \@INC/u ? {"missing", 1} : {"error", _first_line($error)}) }
l!l&&r!l&&!r
51510
MC/DC0%0/2
$self->{"_cache"}{"class"}{$class} //= do { my $loaded = eval { do { &require_module($class); 1 } }; my $error = $@; my $file = &module_notional_filename($class); $loaded ? {} : ($error =~ /\ACan't locate \Q$file\E in \@INC/u ? {"missing", 1} : {"error", _first_line($error)}) }
$self->{"_cache"}{"class"}{$class} do { my $loaded = eval { do { &require_module($class); 1 } }; my $error = $@; my $file = &module_notional_filename($class); $loaded ? {} : ($error =~ /\ACan't locate \Q$file\E in \@INC/u ? {"missing", 1} : {"error", _first_line($error)}) }
Truth table66%2/3
A //= B
A= $self->{"_cache"}{"class"}{$class}B= do { my $loaded = eval { do { &require_module($class); 1 } }; my $error = $@; my $file = &module_notional_filename($class); $loaded ? {} : ($error =~ /\ACan't locate \Q$file\E in \@INC/u ? {"missing", 1} : {"error", _first_line($error)}) }
ABresult
1X1
011
000
1597 51 my $loaded = eval { require_module($class); 1 };
1598 51 my $error = $@;
1599 51 my $file = module_notional_filename($class);
1600  
1601 # Only a failure to find the class's own file means it is absent; a
1602 # syntax error, or a dependency it cannot find, means it is broken.
1603 51 ▶ $loaded ? {}
Branch: 2 branches
BranchTrueFalseTotal
$loaded ? : 49 2 51
$error =~ /\ACan't locate \Q$file\E in \@INC/u ? : 1 1 2
1604 : ($error =~ /\ACan't locate \Q$file\E in \@INC/) ? { missing => 1 }
1605 : { error => _first_line($error) };
1606 };
1607 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1608  
1609 # _class_ready
1610 # Purpose : Start a value-object subtest: skip it when the class is not
1611 # in this checkout, fail it when the class is broken.
1612 # Entry : Called first inside a subtest, before any assertion.
1613 # Exit status : True when the class is loaded, false when the subtest should
1614 # stop.
1615 # Side effects : May plan skip_all (which leaves the subtest), or emit one
1616 # assertion (and a diag() when it fails).
1617 102 ▶sub _class_ready :Private
Subroutine _class_ready: called CC=3 SCAR=11.0
1618 {
1619 102 my ($self, $class) = @_;
1620  
1621 102 my $state = $self->_load_class($class);
1622  
1623 102 ▶ plan(skip_all => $self->i18n('class.unavailable', { class => $class })) if($state->{'missing'});
Branch: 1 branch
BranchTrueFalseTotal
if $state->{"missing"} 2 100 102
1624  
1625 # Skipping a class that does not compile used to hide the breakage: the
1626 # check passed precisely when the value object was most wrong.
1627 100 my $ready = ok(!defined($state->{'error'}), $self->i18n('class.compiles', { class => $class }));
1628 100 ▶ diag($state->{'error'}) unless($ready);
Branch: 1 branch
BranchTrueFalseTotal
unless $ready 2 98 100
1629  
1630 100 return $ready;
1631 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1632  
1633 # _check_derivation
1634 # Purpose : Check 2: the value object still derives what it promises.
1635 # Entry : A constructed object.
1636 # Exit status : Returns $self.
1637 # Side effects : One subtest when value_object has 'derives'; loads the class
1638 # and calls its constructor and accessors.
1639 52 ▶sub _check_derivation :Protected
Subroutine _check_derivation: called CC=5 SCAR=16.1
1640 {
1641 52 my $self = shift;
1642  
1643 52 ▶ my $spec = $self->{'value_object'} || {};
Condition100%2/2
$self->{'value_object'} || {}
l!l
511
MC/DC100%1/1
$self->{'value_object'} || {}
$self->{'value_object'}
Truth table100%2/2
A
A= $self->{'value_object'}
Aresult
11
00
1644 52 ▶ my $derives = $spec->{'derives'} || {};
Condition100%2/2
$spec->{'derives'} || {}
l!l
511
MC/DC100%1/1
$spec->{'derives'} || {}
$spec->{'derives'}
Truth table100%2/2
A
A= $spec->{'derives'}
Aresult
11
00
1645  
1646 52 ▶ return $self unless(%{$derives});
Branch: 1 branch
BranchTrueFalseTotal
unless %{$derives;} 1 51 52
1647  
1648 51 my $class = $spec->{'class'};
1649 51 ▶ my $from = $spec->{'from'} || {};
Condition50%1/2
$spec->{'from'} || {}
l!l
510
MC/DC0%0/1
$spec->{'from'} || {}
$spec->{'from'}
Truth table50%1/2
A
A= $spec->{'from'}
Aresult
11
00
1650 51 (my $short = lc($class)) =~ s/.*:://;
1651  
1652 51 ▶ subtest $self->i18n('check.derivation', { class => $class, keys => _list(sort keys %{$derives}) }) => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1653 51 ▶ $self->_class_ready($class) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_class_ready($class) or return 49 1 50
1654  
1655 # A constructor that dies used to end the whole test file. The error is
1656 # kept at once: i18n() validates its arguments in an eval of its own,
1657 # which resets $@ before the diagnostic could read it.
1658 49 my $object = eval { $class->new(%{$from}) };
1659 49 my $error = $@;
1660 49 ▶ ok($object, $self->i18n('derivation.made', { short => $short, from => join('/', sort keys %{$from}) }))
Branch: 1 branch
BranchTrueFalseTotal
&ok($object, scalar $self->i18n("derivation.made", {"short", $short, "from", join("/", sort(keys %{$from;}))})) or return diag(_first_line($error)) 48 1 49
1661 or return diag(_first_line($error));
1662  
1663 48 foreach my $key (sort keys %{$derives}) {
1664 82 is(scalar(eval { $object->$key() }), $derives->{$key}, $self->i18n('derivation.key', { key => $key }));
1665 }
1666 51 };
1667  
1668 51 return $self;
1669 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1670  
1671 # _list
1672 # Purpose : A list in prose: 'a', 'a and b', 'a, b and c'.
1673 # Entry : @items -- strings.
1674 # Exit status : A string; '' for no items.
1675 # Side effects : None. The conjunction comes from the 'list.and' message.
1676 100 ▶sub _list :Private
Subroutine _list: called CC=3 SCAR=11.0
1677 {
1678 100 my @items = @_;
1679  
1680 100 my $last = pop(@items);
1681  
1682 100 ▶ return !defined($last) ? ''
Branch: 2 branches
BranchTrueFalseTotal
!defined($last) ? : 46 54 100
!@items ? : 17 37 54
1683 : !@items ? $last
1684 : __PACKAGE__->i18n('list.and', { head => join(', ', @items), last => $last });
1685 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1686  
1687 # ---------------------------------------------------------------------------
1688 # Reading a consumer
1689 # ---------------------------------------------------------------------------
1690  
1691 =head2 strip
1692  
1693 my $code = $contract->strip($source);
1694  
1695 =head3 Purpose
1696  
1697 Removes what is not code, so that prose about a key is not mistaken for a use
1698 of it: POD (to its C<=cut>, or to the end of the file when it has none),
1699 whole-line comments, and everything after C<__END__> or C<__DATA__>.
1700  
1701 =head3 Arguments
1702  
1703 =over 4
1704  
1705 =item C<$text> (string, required) - Perl source.
1706  
1707 =back
1708  
1709 =head3 Returns
1710  
1711 The source with POD and comments blanked. The lines are kept, so a line
1712 number found in the result is the line number in the file.
1713  
1714 =head3 Side Effects
1715  
1716 None.
1717  
1718 =head3 EXAMPLE
1719  
1720 my $code = $contract->strip("=head1 X\n\n\$w->{'pod'}\n\n=cut\nmy \$x = 1;\n");
1721 # "\n\n\n\n\nmy \$x = 1;\n"
1722  
1723 =head3 API SPECIFICATION
1724  
1725 =head4 Input
1726  
1727 { text => { type => 'string', position => 0 } }
1728  
1729 =head4 Output
1730  
1731 { type => 'string' }
1732  
1733 =head3 MESSAGES
1734  
1735 Message Meaning / Resolution
1736 ------------------------------------------- ----------------------------------
1737 "...::strip() needs a 'text'" The text is missing or undef.
1738  
1739 =cut
1740  
1741 sub strip
1742 280 ▶{
Subroutine strip: called CC=1 SCAR=0.0
Pod documented
1743 280 my $self = shift;
1744 280 my $text = $self->_arguments('strip', ['text'], { text => { type => 'string' } }, @_)->{'text'};
1745  
1746 # POD runs from a command paragraph to =cut, or to the end of the file when
1747 # it is never closed - common after __END__. Only its newlines are kept.
1748 279 $text =~ s{(^=[a-zA-Z].*?(?:^=cut\b[^\n]*|\z))}{ (my $pod = $1) =~ tr/\n//cd; $pod }gems;
1749  
1750 # After __END__ or __DATA__ nothing is code. Truncating there does not
1751 # move any line before it.
1752 279 $text =~ s{^__(?:END|DATA)__\b.*\z}{}ms;
1753  
1754 # Whole-line comments only: a '#' later in a line may be in a string, a
1755 # regex or $#array, which a lexical scanner cannot tell apart.
1756 279 $text =~ s{^[ \t]*\#[^\n]*}{}gm;
1757  
1758 279 return set_return($text, { type => 'string' });
1759 }
1760  
1761 # _line_number
1762 # Purpose : The 1-based line that a position in the text is on.
1763 # Entry : $text -- the text; $pos -- an offset into it.
1764 # Exit status : A line number.
1765 # Side effects : None. Counts on a copy: a /g match here would move the
1766 # caller's pos().
1767 272 ▶sub _line_number :Private
Subroutine _line_number: called CC=1 SCAR=0.0
1768 {
1769 272 my ($text, $pos) = @_;
1770  
1771 272 my $prefix = substr($text, 0, $pos);
1772  
1773 272 return 1 + ($prefix =~ tr/\n//);
1774 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1775  
1776 # ---------------------------------------------------------------------------
1777 # The rules the scanner applies to source
1778 # ---------------------------------------------------------------------------
1779  
1780 =head2 scanner_capabilities
1781  
1782 my $seam = Test::Consumer::Contract->scanner_capabilities();
1783 my @rules = sort keys %{$seam};
1784  
1785 =head3 Purpose
1786  
1787 Every rule the scanner applies to source beyond reading the file, as rule name
1788 => the name of the sub the rule is exercised through. C<shebang_programs> is
1789 an extensionless program being a consumer; C<accessor_headings> is where a
1790 value object documents an accessor; C<code_not_prose> is producer evidence
1791 having to be code. The list is here so that the tests and the code cannot
1792 drift apart: C<t/contract.t> mutates each named sub back to its behaviour
1793 before the rule existed, and fails when a rule here has no mutation subtest,
1794 when a mutation names a rule that is not here, and when a row names a sub this
1795 module does not define. A rule therefore cannot be added without the test
1796 that shows what it catches.
1797  
1798 =head3 Arguments
1799  
1800 None. May be called on the class or an object.
1801  
1802 =head3 Returns
1803  
1804 A new hashref, in any context: a list of names where a hash of names to seams
1805 was asked for would leave every seam undef. The caller may change it freely.
1806  
1807 =head3 Side Effects
1808  
1809 None.
1810  
1811 =head3 EXAMPLE
1812  
1813 my $seam = Test::Consumer::Contract->scanner_capabilities();
1814 print "$_ -> $seam->{$_}\n" for sort keys %{$seam};
1815  
1816 =head3 API SPECIFICATION
1817  
1818 =head4 Input
1819  
1820 {}
1821  
1822 =head4 Output
1823  
1824 { type => 'hashref' }
1825  
1826 =head3 MESSAGES
1827  
1828 None.
1829  
1830 =cut
1831  
1832 sub scanner_capabilities
1833 15 ▶{
Subroutine scanner_capabilities: called CC=1 SCAR=0.0
Pod documented
1834 15 return set_return({ %SCANNER_RULE_SEAM }, { type => 'hashref' });
1835 }
1836  
1837 # _alternation
1838 # Purpose : One regex matching any of a list of producing calls.
1839 # Entry : $cache_key -- where to keep it; $names -- the calls, bare
1840 # ('fetch') or qualified ('Widget::Maker->fetch').
1841 # Exit status : A qr//. With no names it is a pattern that never matches: an
1842 # empty alternation would match everywhere and make every '(' a
1843 # producing call.
1844 # Side effects : Caches the regex in the object.
1845 # Notes : Bare names go longest first, so 'geocode' is not matched as
1846 # the prefix of 'geocode_many'. A qualified name matches only
1847 # that class's call, written with '->' or '::'. Both parts are
1848 # quotemeta'd here: a \Q that arrives by interpolation is not
1849 # honoured, so writing one would leave the class name unquoted.
1850 600 ▶sub _alternation :Private
Subroutine _alternation: called CC=3 SCAR=11.0
1851 {
1852 600 my ($self, $cache_key, $names) = @_;
1853  
1854 600 ▶ return $self->{'_cache'}{$cache_key} //= do {
Condition66%2/3
$self->{"_cache"}{$cache_key} //= do { my(@bare) = (sort {length $b <=> length $a;} grep({not /$QUALIFIED_NAME/u;} @{$names;})); my(@qualified) = map({[/$QUALIFIED_NAME/u];} grep({/$QUALIFIED_NAME/u;} @{$names;})); my(@calls) = (map({'->\\s*' . quotemeta($_);} @bare), map({'(?<![\\w:])' . quotemeta($_->[0]) . '\\s*(?:->|::)\\s*' . quotemeta($_->[1]);} @qualified)); @calls ? qr/(?:@{[join("|", @calls)];})/u : $NEVER }
l!l&&r!l&&!r
4431570
MC/DC0%0/2
$self->{"_cache"}{$cache_key} //= do { my(@bare) = (sort {length $b <=> length $a;} grep({not /$QUALIFIED_NAME/u;} @{$names;})); my(@qualified) = map({[/$QUALIFIED_NAME/u];} grep({/$QUALIFIED_NAME/u;} @{$names;})); my(@calls) = (map({'->\\s*' . quotemeta($_);} @bare), map({'(?<![\\w:])' . quotemeta($_->[0]) . '\\s*(?:->|::)\\s*' . quotemeta($_->[1]);} @qualified)); @calls ? qr/(?:@{[join("|", @calls)];})/u : $NEVER }
$self->{"_cache"}{$cache_key} do { my(@bare) = (sort {length $b <=> length $a;} grep({not /$QUALIFIED_NAME/u;} @{$names;})); my(@qualified) = map({[/$QUALIFIED_NAME/u];} grep({/$QUALIFIED_NAME/u;} @{$names;})); my(@calls) = (map({'->\\s*' . quotemeta($_);} @bare), map({'(?<![\\w:])' . quotemeta($_->[0]) . '\\s*(?:->|::)\\s*' . quotemeta($_->[1]);} @qualified)); @calls ? qr/(?:@{[join("|", @calls)];})/u : $NEVER }
Truth table66%2/3
A //= B
A= $self->{"_cache"}{$cache_key}B= do { my(@bare) = (sort {length $b <=> length $a;} grep({not /$QUALIFIED_NAME/u;} @{$names;})); my(@qualified) = map({[/$QUALIFIED_NAME/u];} grep({/$QUALIFIED_NAME/u;} @{$names;})); my(@calls) = (map({'->\\s*' . quotemeta($_);} @bare), map({'(?<![\\w:])' . quotemeta($_->[0]) . '\\s*(?:->|::)\\s*' . quotemeta($_->[1]);} @qualified)); @calls ? qr/(?:@{[join("|", @calls)];})/u : $NEVER }
ABresult
1X1
011
000
1855 157 my @bare = sort { length($b) <=> length($a) } grep { !/$QUALIFIED_NAME/ } @{$names};
1856 157 my @qualified = map { [ /$QUALIFIED_NAME/ ] } grep { /$QUALIFIED_NAME/ } @{$names};
1857  
1858 my @calls = (
1859 135 (map { '->\s*' . quotemeta($_) } @bare),
1860 157 (map { '(?<![\w:])' . quotemeta($_->[0]) . '\s*(?:->|::)\s*' . quotemeta($_->[1]) } @qualified),
1861 );
1862  
1863 157 ▶ @calls ? qr/(?:@{[ join('|', @calls) ]})/ : $NEVER;
Branch: 1 branch
BranchTrueFalseTotal
@calls ? : 95 62 157
1864 };
1865 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1866  
1867 # _methods_re
1868 # Purpose : The calls that hand one result to a variable.
1869 # Entry/Exit : A constructed object / a qr//.
1870 # Side effects : Caches through _alternation.
1871 207 ▶sub _methods_re :Private
Subroutine _methods_re: called CC=1 SCAR=0.0
1872 {
1873 207 my $self = shift;
1874  
1875 207 return $self->_alternation('methods_re', $self->{'methods'});
1876 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1877  
1878 # _batch_methods_re
1879 # Purpose : The calls that hand a batch of results to a variable.
1880 # Entry/Exit : A constructed object / a qr//.
1881 # Side effects : Caches through _alternation.
1882 202 ▶sub _batch_methods_re :Private
Subroutine _batch_methods_re: called CC=1 SCAR=0.0
1883 {
1884 202 my $self = shift;
1885  
1886 202 return $self->_alternation('batch_methods_re', $self->{'batch_methods'});
1887 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1888  
1889 # _list_methods_re
1890 # Purpose : The calls that hand back a list of results. The name alone
1891 # does not say which variable holds one: the shape of the read
1892 # does, and _bind_list_results() works that out.
1893 # Entry/Exit : A constructed object / a qr//.
1894 # Side effects : Caches through _alternation.
1895 203 ▶sub _list_methods_re :Private
Subroutine _list_methods_re: called CC=1 SCAR=0.0
1896 {
1897 203 my $self = shift;
1898  
1899 203 return $self->_alternation('list_methods_re', $self->{'list_methods'});
1900 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1901  
1902 # _selection_re
1903 # Purpose : A value selected out of a batch: ->{$value}, ->{'London'}.
1904 # The selector is a word, or a variable holding one - $_
1905 # included, which is how a map over the batch is written.
1906 # Entry/Exit : None / a qr// with no capturing group.
1907 # Side effects : None.
1908 399 ▶sub _selection_re :Private
Subroutine _selection_re: called CC=1 SCAR=0.0
1909 {
1910 399 return qr/->\s*\{\s*(?:['"]?\w+['"]?|\$[A-Za-z_]\w*)\s*\}/;
1911 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1912  
1913 # _accessor_read
1914 # Purpose : A read through an accessor: ->name, with or without its
1915 # parentheses. $result->score and $result->score() are the
1916 # same read; insisting on the parentheses found nothing in a
1917 # reader written the first way.
1918 # Entry/Exit : None / a qr// capturing the accessor name in $1.
1919 # Side effects : None.
1920 202 ▶sub _accessor_read :Private
Subroutine _accessor_read: called CC=1 SCAR=0.0
1921 {
1922 202 return qr/\s*->\s*(\w+)\s*(?:\(|\b)/;
1923 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1924  
1925 # _block_end
1926 # Purpose : Where the block opened at $open closes, counting the braces of
1927 # anything nested inside it.
1928 # Entry : $text; $open -- the offset of a '{'.
1929 # Exit status : The offset of the matching '}', or undef if it never closes.
1930 # Side effects : None (works on a copy, so the caller's pos() is untouched).
1931 # Notes : Text::Balanced also skips braces inside quoted strings, which
1932 # a bare depth count took for real ones.
1933 9 ▶sub _block_end :Private
Subroutine _block_end: called CC=3 SCAR=12.0
1934 {
1935 9 my ($text, $open) = @_;
1936  
1937 9 pos($text) = $open;
1938 9 my ($block) = extract_bracketed($text, $BLOCK_DELIMITERS);
1939  
1940 9 ▶ return (defined($block) && length($block)) ? $open + length($block) - 1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $block && length $block ? : 9 0 9
Condition33%1/3
defined $block and length $block
!ll&&!rl&&r
009
MC/DC0%0/2
defined $block and length $block
defined $block length $block
Truth table33%1/3
A and B
A= defined $blockB= length $block
ABresult
0X0
100
111
1941 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1942  
1943 # _sub_ranges
1944 # Purpose : Where each named sub starts and ends, and what it declares.
1945 # Entry : $text -- stripped source.
1946 # Exit status : An arrayref of { name, start, end, params }, in file order.
1947 # params lists the parameters in order, the invocant first when
1948 # it is declared 'my $self = shift'.
1949 # Side effects : None.
1950 # Notes : A sub starts with 'sub NAME' in column 0. One whose braces
1951 # close on the same line ends there; any other ends at the next
1952 # '}' in column 0. Without the one-line case 'sub x { ... }'
1953 # ran on to the next sub's closing brace, and that sub was then
1954 # reported under the wrong name. A forward declaration
1955 # ('sub x;') has no body and no range.
1956 207 ▶sub _sub_ranges :Private
Subroutine _sub_ranges: called CC=7 SCAR=19.6
1957 {
1958 207 my (undef, $text) = @_;
1959  
1960 207 my @ranges;
1961 207 ▶ while($text =~ /^sub\s+(\w+)\b([^\n]*)/mg) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /^sub\s+(\w+)\b([^\n]*)/gmu) 340 207 547
1962 340 my ($name, $rest, $start) = ($1, $2, $-[0]);
1963 340 ▶ next if($rest =~ /\A\s*;/);
Branch: 1 branch
BranchTrueFalseTotal
if $rest =~ /\A\s*;/u 1 339 340
1964  
1965 # Balanced, non-zero braces on the 'sub' line are a one-line body.
1966 # Otherwise carry on from here to the closing brace in column 0.
1967 339 my $opens = ($rest =~ tr/{//);
1968 339 ▶ my $end = ($opens && $opens == ($rest =~ tr/}//)) ? $+[0]
Branch: 2 branches
BranchTrueFalseTotal
$opens && $opens == $rest =~ tr/}// ? : 72 267 339
$text =~ /\G.*?^\}/cgmsu ? : 267 0 267
Condition66%2/3
$opens and $opens == $rest =~ tr/}//
!ll&&!rl&&r
267072
MC/DC50%1/2
$opens and $opens == $rest =~ tr/}//
$opens $opens == $rest =~ tr/}//
Truth table66%2/3
A and B
A= $opensB= $opens == $rest =~ tr/}//
ABresult
0X0
100
111
1969 : ($text =~ /\G.*?^\}/msgc) ? $+[0]
1970 : undef;
1971 339 ▶ next unless(defined($end));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $end 0 339 339
1972  
1973 339 push @ranges, {
1974 name => $name,
1975 start => $start,
1976 end => $end,
1977 params => _declared_params(substr($text, $start, $end - $start)),
1978 };
1979 }
1980  
1981 207 return \@ranges;
1982 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
1983  
1984 # _declared_params
1985 # Purpose : The parameters a sub body declares, in order, so a caller's
1986 # argument can be matched to the parameter that receives it.
1987 # Entry : $body -- the text of one sub.
1988 # Exit status : An arrayref of variable names ('$self', '$result', ...).
1989 # Side effects : None.
1990 339 ▶sub _declared_params :Private
Subroutine _declared_params: called CC=6 SCAR=17.9
1991 {
1992 339 my $body = shift;
1993  
1994 # my ($self, $result) = @_; - every list taken from @_, in order.
1995 339 my @params;
1996 339 ▶ while($body =~ /^\s*my\s*\(([^)]*)\)\s*=\s*\@_/mg) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body =~ /^\s*my\s*\(([^)]*)\)\s*=\s*\@_/gmu) 264 339 603
1997 264 push @params, ($1 =~ /(\$[A-Za-z_]\w*)/g);
1998 }
1999  
2000 # my $self = shift; - the invocant, declared without a list. Any other
2001 # first 'my' is taken as the single parameter of a function.
2002 339 ▶ if($body =~ /^\s*my\s+(\$[A-Za-z_]\w*)\s*=\s*shift\b/m) {
Branch: 2 branches
BranchTrueFalseTotal
if ($body =~ /^\s*my\s+(\$[A-Za-z_]\w*)\s*=\s*shift\b/mu) { } 2 337 339
elsif (not @params and $body =~ /^\s*my\s+(\$[A-Za-z_]\w*)/mu) { } 1 600 601
2003 2 ▶ unshift @params, $1 if($1 eq '$self');
Branch: 1 branch
BranchTrueFalseTotal
if $1 eq "\$self" 0 2 2
2004 ▶ } elsif(!@params && $body =~ /^\s*my\s+(\$[A-Za-z_]\w*)/m) {
Condition100%3/3
not @params and $body =~ /^\s*my\s+(\$[A-Za-z_]\w*)/mu
!ll&&!rl&&r
264721
MC/DC100%2/2
not @params and $body =~ /^\s*my\s+(\$[A-Za-z_]\w*)/mu
not @params $body =~ /^\s*my\s+(\$[A-Za-z_]\w*)/mu
Truth table100%3/3
not(A) and B
A= not @paramsB= $body =~ /^\s*my\s+(\$[A-Za-z_]\w*)/mu
ABresult
0X0
100
111
2005 1 @params = ($1);
2006 }
2007  
2008 339 return \@params;
2009 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2010  
2011 # _enclosing_sub
2012 # Purpose : The name of the sub a position falls in.
2013 # Entry : $ranges -- from _sub_ranges(); $pos -- an offset.
2014 # Exit status : The sub's name, or '(file scope)'.
2015 # Side effects : None.
2016 272 ▶sub _enclosing_sub :Private
Subroutine _enclosing_sub: called CC=2 SCAR=7.0
2017 {
2018 272 my ($ranges, $pos) = @_;
2019  
2020 272 ▶ my $range = first { $pos >= $_->{'start'} && $pos < $_->{'end'} } @{$ranges};
Subroutine __ANON__: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
$pos >= $_->{"start"} and $pos < $_->{"end"} 312 0 312
2021  
2022 272 ▶ return $range ? $range->{'name'} : $FILE_SCOPE;
Branch: 1 branch
BranchTrueFalseTotal
$range ? : 249 23 272
2023 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2024  
2025 # _assigned_from
2026 # Purpose : The variables a statement assigns from an expression that
2027 # reaches $source_re: my $x = ... $maker->geocode(...
2028 # Entry : $text -- stripped source; $source_re -- what the right-hand
2029 # side must reach before the statement ends.
2030 # Exit status : An arrayref of variable names, in file order.
2031 # Side effects : None.
2032 434 ▶sub _assigned_from :Private
Subroutine _assigned_from: called CC=2 SCAR=6.9
2033 {
2034 434 my ($text, $source_re) = @_;
2035  
2036 # The right-hand side stops at ';', '{' or '}', so a value in a later
2037 # statement or a block is never taken for this one's.
2038 434 my @names;
2039 434 ▶ push @names, $1 while($text =~ /$DECLARATOR($VARIABLE)$ASSIGNMENT[^;{}]*?$source_re/g);
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /$DECLARATOR($VARIABLE)${ASSIGNMENT}[^;{}]*?$source_re/gu and do { push @names, $1 } 176 434 610
2040  
2041 434 return \@names;
2042 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2043  
2044 # _collect_reads
2045 # Purpose : Record each read of a result that a prefix leads to: the
2046 # ->{key} after it, and the ->accessor after it.
2047 # Entry : $text -- stripped source; $prefix -- a qr// for what holds a
2048 # result (it must not capture); $ranges -- from _sub_ranges();
2049 # $reads -- the arrayref to add to.
2050 # Exit status : Returns $reads.
2051 # Side effects : Pushes [key, line, kind, sub] onto $reads.
2052 206 ▶sub _collect_reads :Private
Subroutine _collect_reads: called CC=3 SCAR=11.0
2053 {
2054 206 my ($text, $prefix, $ranges, $reads) = @_;
2055  
2056 # Every pass reports reads the same way, so one routine does it for all of
2057 # them. _accessor_read() is asked each time because it is a seam.
2058 206 my %kinds = ($KIND_KEY => qr/$prefix$KEY_READ/, $KIND_ACCESSOR => qr/$prefix${\ _accessor_read()}/);
2059  
2060 206 foreach my $kind ($KIND_KEY, $KIND_ACCESSOR) {
2061 412 ▶ while($text =~ /$kinds{$kind}/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /$kinds{$kind}/gu) 272 412 684
2062 272 my $at = pos($text);
2063 272 push @{$reads}, [$1, _line_number($text, $at), $kind, _enclosing_sub($ranges, $at)];
2064 }
2065 }
2066  
2067 206 return $reads;
2068 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2069  
2070 =head2 reads_of_results
2071  
2072 my @reads = $contract->reads_of_results($stripped_text);
2073 my $reads = $contract->reads_of_results($stripped_text);
2074  
2075 =head3 Purpose
2076  
2077 Finds every place in the text that reads a field of a result: a hash key,
2078 C<< $r->{'key'} >>, or a method call, C<< $r->key >> or C<< $r->key() >>.
2079  
2080 First it works out which variables hold a result. A variable holds a result
2081 when:
2082  
2083 =over 4
2084  
2085 =item * it is set from a call named in C<methods>:
2086 C<< my $r = $maker->geocode(...) >>;
2087  
2088 =item * it takes one result at a time from a call named in C<list_methods>:
2089 C<< for my $r (@{ $report->results }) >>, or C<$_> in a C<map> or C<grep>
2090 over that call;
2091  
2092 =item * it is set from one entry of a batch (a call named in
2093 C<batch_methods>): C<< my $r = $batch->{$name} >>. A batch entry also counts
2094 when it is put into a hash, or returned from a sub - the callers of that sub
2095 then get results too;
2096  
2097 =item * it is the parameter of a sub that this file calls with a result. For
2098 a method call (C<< $self->show($r) >>) that is the parameter after C<$self>.
2099  
2100 =back
2101  
2102 Then it lists every read of those variables.
2103  
2104 =head3 Arguments
2105  
2106 =over 4
2107  
2108 =item C<$text> (string, required) - source, normally passed through L</strip>.
2109  
2110 =back
2111  
2112 =head3 Returns
2113  
2114 In list context, the reads; in scalar context, an arrayref of them. Each read
2115 is C<[key, line, kind, sub]>: C<kind> is C<key> or C<accessor>, C<sub> is the
2116 enclosing sub or C<(file scope)>. They are in line order.
2117  
2118 =head3 Side Effects
2119  
2120 None.
2121  
2122 =head3 EXAMPLE
2123  
2124 my $reads = $contract->reads_of_results($contract->strip(<<'CODE'));
2125 my $w = $maker->make(size => 2);
2126 return $w->{'colour'};
2127 CODE
2128 # [ ['colour', 2, 'key', '(file scope)'] ]
2129  
2130 =head3 API SPECIFICATION
2131  
2132 =head4 Input
2133  
2134 { text => { type => 'string', position => 0 } }
2135  
2136 =head4 Output
2137  
2138 {
2139 type => 'arrayref',
2140 element => { type => 'arrayref' }, # [key, line, kind, sub]
2141 }
2142  
2143 =head3 MESSAGES
2144  
2145 Message Meaning / Resolution
2146 ------------------------------------------- ----------------------------------
2147 "...::reads_of_results() needs a 'text'" The text is missing or undef.
2148  
2149 =head3 PSEUDOCODE
2150  
2151 batches := variables assigned from a batch method call
2152 bound := variables assigned from a producing call, minus batches
2153 add the loop variables and topics over a list method's results
2154 add the variables assigned a value selected out of a batch
2155 sinks := hashes holding batch values; subs returning one
2156 for each sub returning a batch value:
2157 add the variables assigned from a call to it
2158 record reads written straight off a call to it
2159 repeat until nothing new: add the parameter that receives a bound variable
2160 record reads off every bound variable
2161 record reads straight off a batch selection
2162 record reads through an element of a hash that holds results
2163 sort the reads by line
2164  
2165 =cut
2166  
2167 sub reads_of_results
2168 208 ▶{
Subroutine reads_of_results: called CC=9 SCAR=22.0
Pod documented
2169 208 my $self = shift;
2170 208 my $text = $self->_arguments('reads_of_results', ['text'], { text => { type => 'string' } }, @_)->{'text'};
2171  
2172 207 my $ranges = $self->_sub_ranges($text);
2173 207 my $selection = _selection_re();
2174  
2175 # A batch - geocode_many() - is a hash of results with counts about the
2176 # batch beside them, so the variable is noted apart from the results.
2177 207 my %is_batch = map { $_ => 1 } @{_assigned_from($text, qr/${\ $self->_batch_methods_re()}\s*\(/)};
2178  
2179 118 my %bound = map { $_ => 1 } grep { !$is_batch{$_} }
2180 207 @{_assigned_from($text, qr/${\ $self->_methods_re()}\s*\(/)};
2181  
2182 207 $self->_bind_list_results($text, \%bound);
2183  
2184 # Into a variable: my $point = $batch->{$value};
2185 207 foreach my $batch_var (sort keys %is_batch) {
2186 15 $bound{$_} = 1 for grep { !$is_batch{$_} }
2187 15 @{_assigned_from($text, qr/\Q$batch_var\E\s*$selection/)};
2188 }
2189  
2190 # A value taken out of a batch can also go straight into a hash, or
2191 # straight back out of a sub. Both are found in one place.
2192 207 my $sinks = $self->_batch_value_sinks($text, $ranges, \%is_batch);
2193  
2194 207 my @reads;
2195  
2196 # A sub that hands a result back is a source of them: a variable bound from
2197 # a call to it holds one - $self->pick(...) or pick(...) - and a read
2198 # written straight off the call is a read of one.
2199 207 foreach my $name (sort keys %{$sinks->{'hands_back'}}) {
2200 5 my $call = qr/(?<![\w:])\Q$name\E\s*\(/;
2201 0 $bound{$_} = 1 for grep { !$is_batch{$_} } @{_assigned_from($text, $call)};
2202 5 _collect_reads($text, qr/(?<![\w:])(?:->\s*)?\Q$name\E\s*\([^()]*\)/, $ranges, \@reads);
2203 }
2204  
2205 207 $self->_follow_helpers($text, $ranges, \%bound);
2206  
2207 207 foreach my $var (grep { !$is_batch{$_} } sort keys %bound) {
2208 174 _collect_reads($text, qr/\Q$var\E/, $ranges, \@reads);
2209 }
2210  
2211 # A value taken out of a batch and read there and then, with no variable
2212 # in between: in a hash literal, an argument or a returned expression.
2213 207 foreach my $batch_var (sort keys %is_batch) {
2214 15 _collect_reads($text, qr/\Q$batch_var\E\s*$selection/, $ranges, \@reads);
2215 }
2216  
2217 # Through an element of a hash that holds results. A hash is declared with
2218 # its own sigil and read through a scalar's - my %points is read
2219 # $points{$key} - so the element is spelled with '$' however it was named.
2220 207 foreach my $var (sort keys %{$sinks->{'holds'}}) {
2221 12 my $name = substr($var, 1);
2222 12 _collect_reads($text,
2223 qr/\$\Q$name\E\s*(?:->)?\s*\{\s*(?:['"]?\w+['"]?|\$[A-Za-z_]\w*)\s*\}/, $ranges, \@reads);
2224 }
2225  
2226 # The passes run one shape at a time, so the reads are put back in the
2227 # order a person reads the file. Perl's sort is stable, so ties keep the
2228 # order the passes found them in.
2229 207 @reads = sort { $a->[1] <=> $b->[1] } @reads;
2230  
2231 207 ▶ return wantarray ? @reads : set_return(\@reads, { type => 'arrayref' });
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 22 185 207
2232 }
2233  
2234 # _bind_list_results
2235 # Purpose : Mark the variables that take one result out of a list method:
2236 # the loop variable of a loop over the call, or over a list
2237 # assigned from it; the topic of a map or grep over it; and a
2238 # scalar assigned out of such a list.
2239 # Entry : $text -- stripped source; $bound -- the set to add to.
2240 # Exit status : Returns $self.
2241 # Side effects : Adds names to %$bound.
2242 207 ▶sub _bind_list_results :Private
Subroutine _bind_list_results: called CC=9 SCAR=22.1
2243 {
2244 207 my ($self, $text, $bound) = @_;
2245  
2246 207 my $list = $self->_list_methods_re();
2247 207 my $list_call = qr/\@\{\s*[^;{}]*?$list\s*\(?\s*\}/;
2248  
2249 207 my @lists;
2250 207 ▶ push @lists, quotemeta($1) while($text =~ /(?<![\w:])(?:my|our|local)\s*\@([A-Za-z_]\w*)\s*=\s*$list_call/g);
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /(?<![\w:])(?:my|our|local)\s*\@([A-Za-z_]\w*)\s*=\s*$list_call/gu and do { push @lists, quotemeta $1 } 1 207 208
2251  
2252 207 ▶ $bound->{$1} = 1 while($text =~ /for\s+my\s+($VARIABLE)\s*\([^;]*?$list_call/g);
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /for\s+my\s+($VARIABLE)\s*\([^;]*?$list_call/gu and do { $bound->{$1} = 1 } 20 207 227
2253  
2254 # The block is found by balancing its braces rather than by matching to
2255 # the first '}': a map over results reads a key, and a key read has braces
2256 # of its own, so the first '}' can be the one inside $_->{'cents'}.
2257 207 ▶ while($text =~ /(?:map|grep)\s*\{/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /(?:map|grep)\s*\{/gu) 9 205 214
2258 9 my $close = _block_end($text, pos($text) - 1);
2259 9 ▶ next unless(defined($close) && substr($text, $close + 1) =~ /\A\s*$list_call/);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $close and substr($text, $close + 1) =~ /\A\s*$list_call/u 7 2 9
Condition66%2/3
defined $close and substr($text, $close + 1) =~ /\A\s*$list_call/u
!ll&&!rl&&r
072
MC/DC50%1/2
defined $close and substr($text, $close + 1) =~ /\A\s*$list_call/u
defined $close substr($text, $close + 1) =~ /\A\s*$list_call/u
Truth table66%2/3
A and B
A= defined $closeB= substr($text, $close + 1) =~ /\A\s*$list_call/u
ABresult
0X0
100
111
2260 2 $bound->{'$_'} = 1;
2261 2 last;
2262 }
2263  
2264 207 foreach my $name (@lists) {
2265 1 ▶ $bound->{$1} = 1 while($text =~ /for\s+my\s+($VARIABLE)\s*\(\s*\@$name\s*\)/g);
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /for\s+my\s+($VARIABLE)\s*\(\s*\@$name\s*\)/gu and do { $bound->{$1} = 1 } 0 1 1
2266 1 ▶ $bound->{$1} = 1 while($text =~ /(?<![\w:])$DECLARATOR\(?\s*($VARIABLE)\s*\)?$ASSIGNMENT\@$name\b/g);
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /(?<![\w:])$DECLARATOR\(?\s*($VARIABLE)\s*\)?$ASSIGNMENT\@$name\b/gu and do { $bound->{$1} = 1 } 0 1 1
2267 }
2268  
2269 207 return $self;
2270 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2271  
2272 # _follow_helpers
2273 # Purpose : Follow a result into the subs it is passed to, until nothing
2274 # new is found.
2275 # Entry : $text -- stripped source; $ranges -- from _sub_ranges();
2276 # $bound -- the variables known to hold a result.
2277 # Exit status : Returns $self.
2278 # Side effects : Adds the receiving parameters to %$bound.
2279 # Notes : The receiving parameter is the first for a plain call and the
2280 # one after the invocant for a method whose first parameter is
2281 # $self: reading that as the first made $self a result, and
2282 # every $self->{...} in the file a read of one.
2283 207 ▶sub _follow_helpers :Private
Subroutine _follow_helpers: called CC=7 SCAR=19.5
2284 {
2285 207 my ($self, $text, $ranges, $bound) = @_;
2286  
2287 207 my %declares = map { $_->{'name'} => $_->{'params'} } @{$ranges};
2288  
2289 # A fixed point: a parameter bound in one round may be passed on in the next.
2290 207 my $found = 1;
2291 207 ▶ while($found) {
Branch: 1 branch
BranchTrueFalseTotal
if ($found) 227 207 434
2292 227 $found = 0;
2293 227 foreach my $name (grep { @{$declares{$_}} } sort keys %declares) {
2294 328 my @declare = @{$declares{$name}};
2295 328 foreach my $caller_var (sort keys %{$bound}) {
2296 344 my $index = _argument_index($text, $name, $caller_var, $declare[0]);
2297 344 ▶ next unless(defined($index) && defined($declare[$index]) && !$bound->{$declare[$index]});
Branch: 1 branch
BranchTrueFalseTotal
unless defined $index and defined $declare[$index] and not $$bound{$declare[$index]} 324 20 344
Condition83%5/6
defined $index and defined $declare[$index] and not $$bound{$declare[$index]}
!ll&&!rl&&r
3022220
defined $index and defined $declare[$index]
!ll&&!rl&&r
302042
MC/DC66%2/3
defined $index and defined $declare[$index] and not $$bound{$declare[$index]}
defined $index defined $declare[$index] not $$bound{$declare[$index]}
Truth table75%3/4
A and B and not(C)
A= defined $indexB= defined $declare[$index]C= not $$bound{$declare[$index]}
ABCresult
0XX0
10X0
1100
1111
2298 20 $bound->{$declare[$index]} = 1;
2299 20 $found = 1;
2300 }
2301 }
2302 }
2303  
2304 207 return $self;
2305 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2306  
2307 # _argument_index
2308 # Purpose : Which of a sub's parameters receives a variable, if this file
2309 # passes the variable to it at all.
2310 # Entry : $text; $name -- the sub; $var -- the variable; $first -- the
2311 # sub's first declared parameter.
2312 # Exit status : 1 for $obj->name($var) when $first is $self, 0 for any other
2313 # call that passes $var first, undef when there is none.
2314 # Side effects : None.
2315 344 ▶sub _argument_index :Private
Subroutine _argument_index: called CC=5 SCAR=16.4
2316 {
2317 344 my ($text, $name, $var, $first) = @_;
2318  
2319 344 my ($n, $v) = (quotemeta($name), quotemeta($var));
2320  
2321 344 ▶ return ($text =~ /->\s*$n\s*\(\s*$v\b/) ? ((($first // '') eq '$self') ? 1 : 0)
Branch: 3 branches
BranchTrueFalseTotal
$text =~ /->\s*$n\s*\(\s*$v\b/u ? : 40 304 344
($first // '') eq '$self' ? : 40 0 40
$text =~ /(?<![\w:>-])$n\s*\(\s*(?:\{\s*\w+\s*=>\s*)?$v\b/u ? : 2 302 304
Condition50%1/2
$first // ""
l!l
400
MC/DC0%0/1
$first // ""
$first
Truth table50%1/2
A
A= $first
Aresult
11
00
2322 : ($text =~ /(?<![\w:>-])$n\s*\(\s*(?:\{\s*\w+\s*=>\s*)?$v\b/) ? 0
2323 : undef;
2324 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2325  
2326 # _batch_value_sinks
2327 # Purpose : Where a value taken out of a batch goes when it does not go
2328 # into a variable of its own: into a hash, or back out of a sub.
2329 # Entry : $text; $ranges -- from _sub_ranges(); $is_batch -- the batch
2330 # variables.
2331 # Exit status : { holds => { '%name' or '$name' => 1 },
2332 # hands_back => { sub_name => 1 } }.
2333 # Side effects : None.
2334 202 ▶sub _batch_value_sinks :Private
Subroutine _batch_value_sinks: called CC=6 SCAR=17.9
2335 {
2336 202 my ($self, $text, $ranges, $is_batch) = @_;
2337  
2338 202 my $selection = _selection_re();
2339 202 my (%holds, %hands_back);
2340  
2341 202 foreach my $batch_var (sort keys %{$is_batch}) {
2342 13 my $from_batch = qr/\Q$batch_var\E\s*$selection/;
2343  
2344 # Into an element: $points{$value} = $batch->{$value}. The lookbehind
2345 # keeps $self->{'points'}{$value} - a hash held in a field - from
2346 # naming $self as the hash, which would make every read of $self one.
2347 13 ▶ $holds{$1} = 1 while($text =~ /(?<![\w\$>\]])([%\$][A-Za-z_]\w*)\s*(?:->\s*)?\{[^{}]*\}\s*=[^;]*?$from_batch/g);
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /(?<![\w\$>\]])([%\$][A-Za-z_]\w*)\s*(?:->\s*)?\{[^{}]*\}\s*=[^;]*?$from_batch/gu and do { $holds{$1} = 1 } 0 13 13
2348  
2349 # Into a whole hash built around the batch: a map over its values, a
2350 # list of pairs, a hashref literal. The statement ends at ';', so the
2351 # braces of those forms are crossed and nothing else is.
2352 13 ▶ $holds{$1} = 1 while($text =~ /$DECLARATOR([%\$][A-Za-z_]\w*)$ASSIGNMENT[^;]*?$from_batch/g);
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /$DECLARATOR([%\$][A-Za-z_]\w*)${ASSIGNMENT}[^;]*?$from_batch/gu and do { $holds{$1} = 1 } 12 13 25
2353  
2354 # Out of a sub: only a return that is nothing but the value counts -
2355 # 'return $batch->{$v} if $want' has another way out, and this scanner
2356 # does not follow a branch.
2357 13 foreach my $range (@{$ranges}) {
2358 23 my $body = substr($text, $range->{'start'}, $range->{'end'} - $range->{'start'});
2359 23 ▶ $hands_back{$range->{'name'}} = 1 if($body =~ /\breturn\s+$from_batch\s*;/);
Branch: 1 branch
BranchTrueFalseTotal
if $body =~ /\breturn\s+$from_batch\s*;/u 5 18 23
2360 }
2361 }
2362  
2363 202 return { holds => \%holds, hands_back => \%hands_back };
2364 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2365  
2366 # _why
2367 # Purpose : Why a key is not safe to read: its 'conditional' reason, or
2368 # the fact that no producer sets it.
2369 # Entry/Exit : $key / a string.
2370 # Side effects : None.
2371 12 ▶sub _why :Private
Subroutine _why: called CC=2 SCAR=6.9
2372 {
2373 12 my ($self, $key) = @_;
2374  
2375 12 ▶ return exists($self->{'conditional'}{$key}) ? $self->{'conditional'}{$key} : $self->i18n('why.unpromised');
Branch: 1 branch
BranchTrueFalseTotal
exists $self->{'conditional'}{$key} ? : 7 5 12
2376 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2377  
2378 # ---------------------------------------------------------------------------
2379 # CHECK 3 - registered consumers read only guaranteed keys
2380 # ---------------------------------------------------------------------------
2381  
2382 # _skip_without_siblings
2383 # Purpose : Skip a workspace subtest when a required sibling is absent.
2384 # Entry : Called first inside a subtest.
2385 # Exit status : Returns $self when every sibling is there.
2386 # Side effects : plan skip_all, which leaves the subtest, when one is missing.
2387 103 ▶sub _skip_without_siblings :Private
Subroutine _skip_without_siblings: called CC=2 SCAR=6.9
2388 {
2389 103 my $self = shift;
2390  
2391 103 my @missing = sort @{$self->_missing_siblings()};
2392 103 ▶ plan(skip_all => $self->i18n('skip.siblings', { missing => join(', ', @missing), count => scalar(@missing) }))
Branch: 1 branch
BranchTrueFalseTotal
if @missing 5 98 103
2393 if(@missing);
2394  
2395 98 return $self;
2396 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2397  
2398 =head2 consumer_path
2399  
2400 my $path = $contract->consumer_path($relative);
2401  
2402 =head3 Purpose
2403  
2404 Where a registered consumer is, as a path on this platform. A consumer in a
2405 sibling distribution is named relative to C<workspace>; one in the
2406 distribution being checked is named the way a producer is, relative to
2407 C<dist_root>, because the directory a distribution is installed under is not
2408 the name the contract spells.
2409  
2410 =head3 Arguments
2411  
2412 =over 4
2413  
2414 =item C<$relative> (string, required) - the path as the contract spells it.
2415  
2416 =back
2417  
2418 =head3 Returns
2419  
2420 The workspace path when a file is there, otherwise the C<dist_root> path
2421 (whether or not that exists).
2422  
2423 =head3 Side Effects
2424  
2425 None.
2426  
2427 =head3 EXAMPLE
2428  
2429 my $path = $contract->consumer_path('Widget-User/lib/Widget/User.pm');
2430  
2431 =head3 API SPECIFICATION
2432  
2433 =head4 Input
2434  
2435 { relative => { type => 'string', min => 1, position => 0 } }
2436  
2437 =head4 Output
2438  
2439 { type => 'string' }
2440  
2441 =head3 MESSAGES
2442  
2443 Message Meaning / Resolution
2444 ---------------------------------------------- ----------------------------------
2445 "...::consumer_path() needs a 'relative'" The path is missing or undef.
2446  
2447 =cut
2448  
2449 sub consumer_path
2450 234 ▶{
Subroutine consumer_path: called CC=2 SCAR=6.9
Pod documented
2451 234 my $self = shift;
2452 my $rel = $self->_arguments('consumer_path', ['relative'],
2453 234 { relative => { type => 'string', min => 1 } }, @_)->{'relative'};
2454  
2455 233 my $path = File::Spec->catfile($self->{'workspace'}, split(m{/}, $rel));
2456 233 ▶ $path = File::Spec->catfile($self->{'dist_root'}, split(m{/}, $rel)) unless(-f $path);
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path 31 202 233
2457  
2458 233 return set_return($path, { type => 'string' });
2459 }
2460  
2461 # _expect_none
2462 # Purpose : One assertion that a list is empty, with a readable
2463 # diagnostic when it is not.
2464 # Entry : $found -- arrayref; $name -- the test name; $lines -- the
2465 # diagnostic lines (default: the found items).
2466 # Exit status : The assertion's result.
2467 # Side effects : One is_deeply(); a diag() on failure.
2468 216 ▶sub _expect_none :Private
Subroutine _expect_none: called CC=3 SCAR=11.0
2469 {
2470 216 my ($self, $found, $name, $lines) = @_;
2471  
2472 216 my $ok = is_deeply($found, [], $name);
2473 216 ▶ diag($DIAG_INDENT . join($DIAG_INDENT, @{$lines // $found}) . "\n") unless($ok);
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 19 197 216
Condition66%2/3
$lines // $found
l!l&&r!l&&!r
1090
MC/DC0%0/2
$lines // $found
$lines $found
Truth table66%2/3
A // B
A= $linesB= $found
ABresult
1X1
011
000
2474  
2475 216 return $ok;
2476 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2477  
2478 # _check_consumers
2479 # Purpose : Check 3: every registered consumer reads only guaranteed
2480 # keys, and still reads every key it registered.
2481 # Entry : A constructed object.
2482 # Exit status : Returns $self.
2483 # Side effects : One subtest when consumers are declared.
2484 52 ▶sub _check_consumers :Protected
Subroutine _check_consumers: called CC=2 SCAR=7.0
2485 {
2486 52 my $self = shift;
2487  
2488 52 my $consumers = $self->{'consumers'};
2489  
2490 52 ▶ if(%{$consumers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (%{$consumers;}) 51 1 52
2491 51 ▶ subtest $self->i18n('check.consumers') => sub {
Subroutine __ANON__: called CC=4 SCAR=14.2
2492 51 $self->_skip_without_siblings();
2493  
2494 49 foreach my $rel (sort keys %{$consumers}) {
2495 59 my $raw = $self->_readable($self->consumer_path($rel), $rel);
2496 59 ▶ next unless(defined($raw));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw 0 59 59
2497  
2498 59 ▶ $self->_check_one_consumer($rel, $consumers->{$rel}{'may_rely_on'} || {},
Condition50%1/2
$consumers->{$rel}{'may_rely_on'} || {}
l!l
590
MC/DC0%0/1
$consumers->{$rel}{'may_rely_on'} || {}
$consumers->{$rel}{'may_rely_on'}
Truth table50%1/2
A
A= $consumers->{$rel}{'may_rely_on'}
Aresult
11
00
2499 scalar($self->reads_of_results($self->strip($raw))));
2500 }
2501 51 };
2502 }
2503  
2504 52 return $self;
2505 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2506  
2507 # _check_one_consumer
2508 # Purpose : The two assertions check 3 makes about one consumer.
2509 # Entry : $rel -- the consumer as named; $may_rely_on -- its registry
2510 # entry; $reads -- from reads_of_results().
2511 # Exit status : Returns $self.
2512 # Side effects : Two assertions.
2513 59 ▶sub _check_one_consumer :Private
Subroutine _check_one_consumer: called CC=8 SCAR=20.8
2514 {
2515 59 my ($self, $rel, $may_rely_on, $reads) = @_;
2516  
2517 # Built once: a grep over the lists for every read was quadratic.
2518 59 my %guaranteed = map { $_ => 1 } @{$self->{'guaranteed'}};
2519 59 my %callable = map { $_ => 1 } (@{$self->{'accessors'}}, @{$self->{'inspection'}});
2520  
2521 59 my (@offenders, %used);
2522 59 foreach my $read (@{$reads}) {
2523 117 my ($key, $line, $kind, $sub) = @{$read};
2524 117 $used{"$sub|$key"} = 1;
2525  
2526 117 ▶ next if($guaranteed{$key});
Branch: 1 branch
BranchTrueFalseTotal
if $guaranteed{$key} 95 22 117
2527 22 ▶ next if($may_rely_on->{$sub} && exists($may_rely_on->{$sub}{$key}));
Branch: 1 branch
BranchTrueFalseTotal
if $may_rely_on->{$sub} and exists $may_rely_on->{$sub}{$key} 1 21 22
Condition66%2/3
$may_rely_on->{$sub} and exists $may_rely_on->{$sub}{$key}
!ll&&!rl&&r
2101
MC/DC50%1/2
$may_rely_on->{$sub} and exists $may_rely_on->{$sub}{$key}
$may_rely_on->{$sub} exists $may_rely_on->{$sub}{$key}
Truth table66%2/3
A and B
A= $may_rely_on->{$sub}B= exists $may_rely_on->{$sub}{$key}
ABresult
0X0
100
111
2528 21 ▶ next if($kind eq $KIND_ACCESSOR && $callable{$key});
Branch: 1 branch
BranchTrueFalseTotal
if $kind eq $KIND_ACCESSOR and $callable{$key} 9 12 21
Condition100%3/3
$kind eq $KIND_ACCESSOR and $callable{$key}
!ll&&!rl&&r
939
MC/DC100%2/2
$kind eq $KIND_ACCESSOR and $callable{$key}
$kind eq $KIND_ACCESSOR $callable{$key}
Truth table100%3/3
A and B
A= $kind eq $KIND_ACCESSORB= $callable{$key}
ABresult
0X0
100
111
2529  
2530 12 push @offenders, $self->i18n('consumer.offender',
2531 { file => $rel, line => $line, sub => $sub, key => $key, kind => $kind, why => $self->_why($key) });
2532 }
2533 59 $self->_expect_none(\@offenders, $self->i18n('consumer.clean', { file => $rel }));
2534  
2535 # A registry entry nothing reads any more no longer describes the code.
2536 59 my @stale;
2537 59 foreach my $sub (sort keys %{$may_rely_on}) {
2538 1 push @stale, map { $self->i18n('consumer.stale', { sub => $sub, key => $_, why => $may_rely_on->{$sub}{$_} }) }
2539 2 grep { !$used{"$sub|$_"} } sort keys %{$may_rely_on->{$sub}};
2540 }
2541 59 $self->_expect_none(\@stale, $self->i18n('consumer.not_stale', { file => $rel }),
2542 [ @stale, $self->i18n('consumer.stale_advice') ]);
2543  
2544 59 return $self;
2545 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2546  
2547 # ---------------------------------------------------------------------------
2548 # CHECK 5 - no unregistered consumer
2549 # ---------------------------------------------------------------------------
2550  
2551 # _children
2552 # Purpose : The visible entries of a directory.
2553 # Entry : $dir -- a directory path.
2554 # Exit status : An arrayref of names (no '.', '..' or dot-files); empty when
2555 # the directory cannot be opened.
2556 # Side effects : Opens and closes the directory.
2557 151 ▶sub _children :Private
Subroutine _children: called CC=1 SCAR=0.0
2558 {
2559 151 my $dir = shift;
2560  
2561 151 my @entries;
2562 151 eval {
2563 151 opendir(my $dh, $dir);
2564 151 @entries = grep { !/\A\./ } readdir($dh);
2565 151 closedir($dh);
2566 };
2567  
2568 151 return \@entries;
2569 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2570  
2571 # _workspace_sources
2572 # Purpose : Every source file that might consume a result: those of the
2573 # sibling distributions and, with own_consumers, this one's.
2574 # Entry : A constructed object.
2575 # Exit status : An arrayref of paths, spelled as the contract spells them.
2576 # Side effects : Walks the file system.
2577 # Notes : Sibling paths are workspace-relative. The checked
2578 # distribution's are dist-relative, like its producers, so they
2579 # still point at the right file when it is installed under a
2580 # versioned directory name. Its t/ is not scanned: its tests
2581 # prove the value object rather than consume it.
2582 51 ▶sub _workspace_sources :Private
Subroutine _workspace_sources: called CC=5 SCAR=16.1
2583 {
2584 51 my $self = shift;
2585  
2586 51 my @files;
2587 51 foreach my $dist (sort @{_children($self->{'workspace'})}) {
2588 141 ▶ next if($dist eq $self->{'dist_name'});
Branch: 1 branch
BranchTrueFalseTotal
if $dist eq $self->{"dist_name"} 51 90 141
2589  
2590 90 my $dir = File::Spec->catdir($self->{'workspace'}, $dist);
2591 90 ▶ next unless(-d $dir);
Branch: 1 branch
BranchTrueFalseTotal
unless -d $dir 0 90 90
2592  
2593 90 push @files, @{$self->_sources_below($dir, $self->{'workspace'}, $self->{'config'}{'sibling_dirs'})};
2594 }
2595  
2596 10 push @files, @{$self->_sources_below($self->{'dist_root'}, $self->{'dist_root'}, $self->{'config'}{'own_dirs'})}
2597 51 ▶ if($self->{'own_consumers'});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"own_consumers"} 10 41 51
2598  
2599 51 return \@files;
2600 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2601  
2602 # _sources_below
2603 # Purpose : The source files of one distribution.
2604 # Entry : $dir -- the distribution; $base -- what the names are
2605 # relative to; $subdirs -- the directories to walk.
2606 # Exit status : An arrayref of relative paths, '/'-separated.
2607 # Side effects : Walks the file system.
2608 100 ▶sub _sources_below :Private
Subroutine _sources_below: called CC=3 SCAR=11.0
2609 {
2610 100 my ($self, $dir, $base, $subdirs) = @_;
2611  
2612 100 my $extension = $self->_extension_re();
2613 100 my @files;
2614  
2615 100 foreach my $root (grep { -d $_ } map { File::Spec->catdir($dir, $_) } @{$subdirs}) {
2616 File::Find::find({
2617 no_chdir => 1,
2618 381 ▶ wanted => sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
2619 381 my $path = $File::Find::name;
2620 381 ▶ $File::Find::prune = 1 if(-d $path && $self->_skipped_dir($path));
Branch: 1 branch
BranchTrueFalseTotal
if -d $path and $self->_skipped_dir($path) 0 381 381
Condition66%2/3
-d $path and $self->_skipped_dir($path)
!ll&&!rl&&r
1772040
MC/DC0%0/2
-d $path and $self->_skipped_dir($path)
-d $path $self->_skipped_dir($path)
Truth table66%2/3
A and B
A= -d $pathB= $self->_skipped_dir($path)
ABresult
0X0
100
111
2621 381 ▶ return unless(-f $path && ($path =~ $extension || $self->_program($path)));
Branch: 1 branch
BranchTrueFalseTotal
unless -f $path and $path =~ /$extension/u || $self->_program($path) 205 176 381
Condition100%6/6
-f $path and $path =~ /$extension/u || $self->_program($path)
!ll&&!rl&&r
2041176
$path =~ /$extension/u or $self->_program($path)
l!l&&r!l&&!r
17331
MC/DC100%3/3
-f $path and $path =~ /$extension/u || $self->_program($path)
-f $path $path =~ /$extension/u $self->_program($path)
Truth table100%4/4
A and B or C
A= -f $pathB= $path =~ /$extension/uC= $self->_program($path)
ABCresult
0XX0
1000
11X1
1011
2622 176 push @files, $self->_ported(File::Spec->abs2rel($path, $base));
2623 },
2624 104 }, $root);
2625 }
2626  
2627 # Programs at the distribution root: a program needs neither an extension
2628 # nor a bin/ to be one - ged2map is at the root of HTML-Genealogy-Map - and
2629 # its loop is often a copy of a module's.
2630 1 push @files, map { $self->_ported(File::Spec->abs2rel($_, $base)) }
2631 115 ▶ grep { -f $_ && $self->_program($_) }
Condition66%2/3
-f $_ && $self->_program($_)
!ll&&!rl&&r
11401
MC/DC50%1/2
-f $_ && $self->_program($_)
-f $_ $self->_program($_)
Truth table66%2/3
A && B
A= -f $_B= $self->_program($_)
ABresult
0X0
100
111
2632 100 map { File::Spec->catfile($dir, $_) } @{_children($dir)};
2633  
2634 100 return \@files;
2635 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2636  
2637 # _extension_re
2638 # Purpose : The file names that hold Perl source, from the configuration.
2639 # Entry/Exit : A constructed object / a qr// anchored at the end.
2640 # Side effects : Caches the regex in the object.
2641 100 ▶sub _extension_re :Private
Subroutine _extension_re: called CC=2 SCAR=6.9
2642 {
2643 100 my $self = shift;
2644  
2645 100 ▶ return $self->{'_cache'}{'extension_re'} //=
Condition100%2/2
$self->{"_cache"}{"extension_re"} //= qr/\.(?:@{[join("|", map({quotemeta $_;} @{$$self{"config"}{"source_extensions"};}))];})\z/u
l!l
4951
MC/DC100%1/1
$self->{"_cache"}{"extension_re"} //= qr/\.(?:@{[join("|", map({quotemeta $_;} @{$$self{"config"}{"source_extensions"};}))];})\z/u
$self->{"_cache"}{"extension_re"}
Truth table100%2/2
A
A= $self->{"_cache"}{"extension_re"}
Aresult
11
00
2646 51 qr/\.(?:@{[ join('|', map { quotemeta } @{$self->{'config'}{'source_extensions'}}) ]})\z/;
2647 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2648  
2649 # _program
2650 # Purpose : Whether an extensionless file is a program.
2651 # Entry : $path -- a file.
2652 # Exit status : 1 when its name has no '.' and it starts with '#!', else 0.
2653 # Side effects : Reads two bytes of the file.
2654 # Notes : The executable bit is advisory, and on Windows true for most
2655 # files, so the file is asked what it is. README, Changes and
2656 # LICENSE have no extension either, and none starts with '#!'.
2657 7 ▶sub _program :Private
Subroutine _program: called CC=3 SCAR=11.0
2658 {
2659 7 my (undef, $path) = @_;
2660  
2661 # Two bytes, not a line: a line of a binary file can be all of it.
2662 7 my $magic = '';
2663 7 ▶ if(basename($path) !~ /\./) {
Branch: 1 branch
BranchTrueFalseTotal
unless (basename($path) =~ /\./u) 6 1 7
2664 6 eval { open(my $fh, '<:raw', $path); read($fh, $magic, length($SHEBANG)); close($fh) };
2665 }
2666  
2667 7 ▶ return ($magic eq $SHEBANG) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$magic eq $SHEBANG ? : 5 2 7
2668 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2669  
2670 # _ported
2671 # Purpose : A path spelled the way the contract spells paths, with '/'
2672 # between directories whatever the platform uses.
2673 # Entry/Exit : $path / the path with every '\' turned into '/'.
2674 # Side effects : None. File::Spec->abs2rel() answers with '\' on Windows,
2675 # which matched no registry key and made every consumer
2676 # unregistered there.
2677 179 ▶sub _ported :Private
Subroutine _ported: called CC=1 SCAR=0.0
2678 {
2679 179 my (undef, $path) = @_;
2680  
2681 179 (my $ported = $path) =~ s{\\}{$SEPARATOR}g;
2682  
2683 179 return $ported;
2684 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2685  
2686 # _skipped_dir
2687 # Purpose : Whether a directory holds something other than this
2688 # checkout's source: a build product, a bundled dependency,
2689 # another version control tree.
2690 # Entry/Exit : $path / 1 or 0.
2691 # Side effects : Caches the regex in the object.
2692 # Notes : The name is matched after a separator of either spelling,
2693 # because File::Find names files the platform's way: matched
2694 # after '/' only, this pruned nothing on Windows.
2695 208 ▶sub _skipped_dir :Private
Subroutine _skipped_dir: called CC=3 SCAR=11.0
2696 {
2697 208 my ($self, $path) = @_;
2698  
2699 208 ▶ my $skipped = $self->{'_cache'}{'skipped_re'} //=
Condition100%2/2
$self->{"_cache"}{"skipped_re"} //= qr#[/\\](?:@{[join("|", map({quotemeta $_;} @{$$self{"config"}{"skipped_dirs"};}))];})\z#u
l!l
15652
MC/DC100%1/1
$self->{"_cache"}{"skipped_re"} //= qr#[/\\](?:@{[join("|", map({quotemeta $_;} @{$$self{"config"}{"skipped_dirs"};}))];})\z#u
$self->{"_cache"}{"skipped_re"}
Truth table100%2/2
A
A= $self->{"_cache"}{"skipped_re"}
Aresult
11
00
2700 52 qr{[/\\](?:@{[ join('|', map { quotemeta } @{$self->{'config'}{'skipped_dirs'}}) ]})\z};
2701  
2702 208 ▶ return ($path =~ $skipped) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$path =~ /$skipped/u ? : 3 205 208
2703 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2704  
2705 # _ignored
2706 # Purpose : The reason a file is ignored, if an 'ignored' rule covers it.
2707 # Entry/Exit : $rel -- a contract-spelled path / the reason (1 when the
2708 # rule gives none), or undef.
2709 # Side effects : None.
2710 8 ▶sub _ignored :Private
Subroutine _ignored: called CC=3 SCAR=11.0
2711 {
2712 8 my ($self, $rel) = @_;
2713  
2714 8 ▶ my $rule = first { index($rel, $_->[0]) == 0 } @{$self->{'ignored'}};
Subroutine __ANON__: called CC=1 SCAR=0.0
2715  
2716 8 ▶ return $rule ? ($rule->[1] // 1) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$rule ? : 2 6 8
Condition50%1/2
$rule->[1] // 1
l!l
20
MC/DC0%0/1
$rule->[1] // 1
$rule->[1]
Truth table50%1/2
A
A= $rule->[1]
Aresult
11
00
2717 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2718  
2719 =head2 documented_accessors
2720  
2721 my @names = $contract->documented_accessors($source);
2722 my $names = $contract->documented_accessors($source);
2723  
2724 =head3 Purpose
2725  
2726 Every name the value object's source documents as part of its interface: its
2727 C<=head2> headings and the public subs it defines. C<=head1> headings are left
2728 out (NAME, VERSION and the rest of the boilerplate), as are deeper headings,
2729 which are sections about the accessor above them rather than accessors, and
2730 private subs. A method implemented through C<AUTOLOAD> is found by its
2731 heading, which is what makes this the list of what is documented rather than
2732 of what is compiled.
2733  
2734 =head3 Arguments
2735  
2736 =over 4
2737  
2738 =item C<$text> (string, required) - the value object's source, POD included.
2739  
2740 =back
2741  
2742 =head3 Returns
2743  
2744 The names, sorted and unique: a list in list context, an arrayref in scalar
2745 context.
2746  
2747 =head3 Side Effects
2748  
2749 None.
2750  
2751 =head3 EXAMPLE
2752  
2753 my $names = $contract->documented_accessors("=head2 x\n\n=head3 PURPOSE\n\n=cut\n\nsub y {}\n");
2754 # ['x', 'y']
2755  
2756 =head3 API SPECIFICATION
2757  
2758 =head4 Input
2759  
2760 { text => { type => 'string', position => 0 } }
2761  
2762 =head4 Output
2763  
2764 { type => 'arrayref', element => { type => 'string' } }
2765  
2766 =head3 MESSAGES
2767  
2768 Message Meaning / Resolution
2769 ----------------------------------------------- ----------------------------------
2770 "...::documented_accessors() needs a 'text'" The text is missing or undef.
2771  
2772 =cut
2773  
2774 sub documented_accessors
2775 50 ▶{
Subroutine documented_accessors: called CC=4 SCAR=13.9
Pod documented
2776 50 my $self = shift;
2777 50 my $text = $self->_arguments('documented_accessors', ['text'], { text => { type => 'string' } }, @_)->{'text'};
2778  
2779 50 my %found;
2780  
2781 # =head2 only. A deeper heading is a section about the one above it: a
2782 # value object documenting each accessor with '=head2 score' and then
2783 # '=head3 PURPOSE' has one accessor there, not two.
2784 50 ▶ $found{$1} = 1 while($text =~ /^=head2\s+(?:B<)?(\w+)/gm);
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /^=head2\s+(?:B<)?(\w+)/gmu and do { $found{$1} = 1 } 33 50 83
2785 50 ▶ $found{$1} = 1 while($text =~ /^sub\s+([A-Za-z]\w*)/gm);
Branch: 1 branch
BranchTrueFalseTotal
$text =~ /^sub\s+([A-Za-z]\w*)/gmu and do { $found{$1} = 1 } 198 50 248
2786  
2787 50 my @names = sort keys %found;
2788  
2789 50 ▶ return wantarray ? @names : set_return(\@names, { type => 'arrayref' });
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 1 49 50
2790 }
2791  
2792 # _check_accessors
2793 # Purpose : Check 4: the accessor lists match the value object, both ways.
2794 # Entry : A constructed object.
2795 # Exit status : Returns $self.
2796 # Side effects : One subtest when value_object and an accessor list are
2797 # declared; loads the class and reads its file.
2798 52 ▶sub _check_accessors :Protected
Subroutine _check_accessors: called CC=4 SCAR=14.0
2799 {
2800 52 my $self = shift;
2801  
2802 52 my @accessors = @{$self->{'accessors'}};
2803 52 my @not_accessors = sort keys %{$self->{'not_accessors'}};
2804  
2805 52 ▶ return $self unless($self->{'value_object'} && (@accessors || @not_accessors));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"value_object"} and @accessors || @not_accessors 1 51 52
Condition50%3/6
$self->{"value_object"} and @accessors || @not_accessors
!ll&&!rl&&r
1051
@accessors or @not_accessors
l!l&&r!l&&!r
5100
MC/DC33%1/3
$self->{"value_object"} and @accessors || @not_accessors
$self->{"value_object"} @accessors @not_accessors
Truth table50%2/4
A and B or C
A= $self->{"value_object"}B= @accessorsC= @not_accessors
ABCresult
0XX0
1000
11X1
1011
2806  
2807 51 my $class = $self->{'value_object'}{'class'};
2808  
2809 51 ▶ subtest $self->i18n('check.accessors') => sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
2810 51 ▶ $self->_class_ready($class) or return;
Branch: 1 branch
BranchTrueFalseTotal
$self->_class_ready($class) or return 49 1 50
2811  
2812 49 ▶ my $text = $self->_readable($INC{module_notional_filename($class)} // '', $class);
Condition50%1/2
$INC{&module_notional_filename($class)} // ""
l!l
490
MC/DC0%0/1
$INC{&module_notional_filename($class)} // ""
$INC{&module_notional_filename($class)}
Truth table50%1/2
A
A= $INC{&module_notional_filename($class)}
Aresult
11
00
2813 49 ▶ return unless(defined($text));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 0 49 49
2814  
2815 # One idea of "documented" for both directions; the first used to accept
2816 # a 'sub name' anywhere in the file, the second only at column 0.
2817 49 my %documented = map { $_ => 1 } @{scalar($self->documented_accessors($text))};
2818  
2819 # What the declaration names is what the value object has: an accessor
2820 # that has gone, or has been renamed, fails rather than being described.
2821 49 foreach my $accessor (@accessors, @not_accessors) {
2822 163 ▶ ok($class->can($accessor) || $documented{$accessor},
Condition66%2/3
$class->can($accessor) || $documented{$accessor}
l!l&&r!l&&!r
16201
MC/DC50%1/2
$class->can($accessor) || $documented{$accessor}
$class->can($accessor) $documented{$accessor}
Truth table66%2/3
A || B
A= $class->can($accessor)B= $documented{$accessor}
ABresult
1X1
011
000
2823 $self->i18n('accessor.documented', { accessor => $accessor, class => $class }));
2824 }
2825  
2826 # And what the value object documents is what the declaration names:
2827 # without this a value object that gains an accessor leaves the
2828 # declaration behind, and the next reader of it is never checked.
2829 49 my %accounted = map { $_ => 1 } (@accessors, @not_accessors, keys %{$self->{'conditional'}});
2830 49 my @unlisted = grep { !$accounted{$_} } sort keys %documented;
2831  
2832 $self->_expect_none(\@unlisted, $self->i18n('accessor.accounted', { class => $class }), [
2833 split(/\n/, $self->i18n('accessor.drift',
2834 49 { class => $class, names => _list(map { "'$_'" } @unlisted), count => scalar(@unlisted) })),
2835 ]);
2836 51 };
2837  
2838 51 return $self;
2839 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2840  
2841 # _check_discovery
2842 # Purpose : Check 5: every file that reads a result is registered.
2843 # Entry : A constructed object.
2844 # Exit status : Returns $self.
2845 # Side effects : One subtest; walks and reads the workspace.
2846 52 ▶sub _check_discovery :Protected
Subroutine _check_discovery: called CC=1 SCAR=0.0
2847 {
2848 52 my $self = shift;
2849  
2850 52 my $source = $self->{'source'};
2851 52 my $consumers = $self->{'consumers'};
2852  
2853 52 ▶ subtest $self->i18n('check.discovery') => sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
2854 52 $self->_skip_without_siblings();
2855  
2856 49 my (@unregistered, @discovered);
2857 49 my $checked = 0;
2858 49 foreach my $rel (@{$self->_workspace_sources()}) {
2859 172 my $raw = $self->_read_source($self->consumer_path($rel))->{'text'};
2860 172 ▶ next unless(defined($raw) && index($raw, $source) >= 0);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw and index($raw, $source) != -1 47 125 172
Condition66%2/3
defined $raw and index($raw, $source) != -1
!ll&&!rl&&r
047125
MC/DC50%1/2
defined $raw and index($raw, $source) != -1
defined $raw index($raw, $source) != -1
Truth table66%2/3
A and B
A= defined $rawB= index($raw, $source) != -1
ABresult
0X0
100
111
2861  
2862 125 $checked++;
2863 125 ▶ next unless(@{$self->reads_of_results($self->strip($raw))});
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->reads_of_results($self->strip($raw));} 62 63 125
2864  
2865 63 push @discovered, $rel;
2866 63 ▶ push @unregistered, $rel unless(exists($consumers->{$rel}) || defined($self->_ignored($rel)));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $consumers->{$rel} or defined $self->_ignored($rel) 6 57 63
Condition100%3/3
exists $consumers->{$rel} or defined $self->_ignored($rel)
l!l&&r!l&&!r
5526
MC/DC100%2/2
exists $consumers->{$rel} or defined $self->_ignored($rel)
exists $consumers->{$rel} defined $self->_ignored($rel)
Truth table100%3/3
A or B
A= exists $consumers->{$rel}B= defined $self->_ignored($rel)
ABresult
1X1
011
000
2867 }
2868  
2869 49 cmp_ok($checked, '>', 0, $self->i18n('discovery.checked', { source => $source, count => $checked }));
2870  
2871 # Without this the whole subtest could pass by finding nothing at all.
2872 49 ok(scalar(grep { exists($consumers->{$_}) } @discovered),
2873 $self->i18n('discovery.registered', { count => scalar(@discovered) }));
2874  
2875 49 $self->_expect_none(\@unregistered, $self->i18n('discovery.clean', { source => $source }), [
2876 $self->i18n('discovery.header', { source => $source }),
2877 @unregistered,
2878 split(/\n/, $self->i18n('discovery.advice', { count => scalar(@unregistered) })),
2879 ]);
2880 52 };
2881  
2882 52 return $self;
2883 57 ▶}
Subroutine BEGIN: called CC=1 SCAR=0.0
2884  
2885 57 1;
2886  
2887 __END__
↑ Summary