blib/lib/Test/Log/Abstraction.pm

filter: Statementstmt 100% 492 / 492 Branchbran 100% 228 / 228 Conditioncond 100% 130 / 130 MC/DCmcdc 100% 73 / 73 Subroutinesub 100% 84 / 84 Podpod 100% 14 / 14 totaltotal 100% 1021 / 1021 CC 165 SCAR 18.7
CC
165
Cov
100%
_format
16.0
_entry
15.0
_resolve_lang
14.0
CRAP 6.5
↑ Summary
1 package Test::Log::Abstraction;
2  
3 =head1 NAME
4  
5 Test::Log::Abstraction - Capture log output in tests and assert on it
6  
7 =head1 VERSION
8  
9 0.002.2
10  
11 =cut
12  
13 # Post-release roadmap (from the 0.002.0 gap analysis)
14 #
15 # Technical debt:
16 # TODO: Split this file: move the message catalogues into
17 # Test::Log::Abstraction::I18N and most of the POD into a .pod file, so
18 # translations are easier to contribute and diffs easier to review.
19 # TODO: Emit through Test2::API::context() instead of Test::Builder, which
20 # removes the $Test::Builder::Level bookkeeping and the TODO-handle
21 # special cases in _emit().
22 # TODO: Add a CI check against the real Log::Abstraction that fails when
23 # it gains a public method this module lacks, or changes behaviour (as
24 # with level methods called with no arguments); t/integration.t checks
25 # only some of this, and only when Log::Abstraction is installed.
26 #
27 # Features:
28 # TODO: Strict mode: at done_testing, fail if error or more serious
29 # messages were logged but no assertion looked at them, as
30 # Test::Warnings's had_no_warnings does for warnings.
31 # TODO: Test::Log::Abstraction->install, hooking Log::Abstraction->new so
32 # that code which builds its own logger is still captured.
33 # TODO: Richer assertions: fields_like($level, \%fields),
34 # logged_in_order([qr/a/, qr/b/]), count_like(qr//, $n), and
35 # messages_are([...]) with a readable diff on failure.
36 # TODO: An optional normalise_levels => 1, so that count('warn') includes
37 # warning() (removes the "different names for one level" pitfall).
38 # TODO: Record the file and line each message was logged from, so a test
39 # can check where a message came from.
40 # TODO: Adapters for Log::Any, Log::Log4perl and Log::Dispatch, reusing
41 # the same assertion API.
42  
43 =head1 SYNOPSIS
44  
45 =head2 Check what your code logged
46  
47 use Test::Most;
48 use Test::Log::Abstraction;
49  
50 # Give the test logger to the code that you are testing
51 my $logger = Test::Log::Abstraction->new();
52 my $obj = Some::Class->new(logger => $logger);
53  
54 $obj->do_something();
55  
56 # Each of these is one TAP test
57 $logger->like(qr/updated/, 'do_something() logs that it updated');
58 $logger->has_level('error', 'an error was logged');
59 $logger->unlike(qr/fatal/, 'nothing fatal was logged');
60 is($logger->count(), 3, 'three messages were logged');
61  
62 done_testing();
63  
64 =head2 Check that nothing was logged
65  
66 my $logger = Test::Log::Abstraction->new();
67 Some::Class->new(logger => $logger)->run();
68 $logger->empty('a normal run logs nothing');
69  
70 =head2 Test several steps with one logger
71  
72 my $logger = Test::Log::Abstraction->new();
73 my $obj = Some::Class->new(logger => $logger);
74  
75 $obj->load('good.csv');
76 $logger->empty('good file: no messages');
77  
78 $logger->clear(); # forget the messages from the first step
79 $obj->load('bad.csv');
80 $logger->has_level('warn', 'bad file: a warning');
81  
82 =head2 Look at the messages yourself
83  
84 foreach my $entry (@{ $logger->messages() }) {
85 print "$entry->{level}: $entry->{message}\n";
86 }
87  
88 # Structured fields, from a call such as
89 # $logger->info('user logged in', { user => 'alice' })
90 is($logger->messages()->[0]->{fields}->{user}, 'alice', 'user field');
91  
92 =head2 Control what is printed while the test runs
93  
94 # Print nothing (the messages are still captured)
95 my $quiet = Test::Log::Abstraction->new(diag => 'none');
96  
97 # Print everything
98 my $loud = Test::Log::Abstraction->new(verbose => 1);
99  
100 # Print only errors and more serious messages
101 my $errors = Test::Log::Abstraction->new(diag => 'error');
102  
103 =head2 Test code that checks the log level
104  
105 # The code under test does: if($logger->is_debug()) { ... }
106 my $logger = Test::Log::Abstraction->new(level => 'warning');
107 ok(!$logger->is_debug(), 'debug output is turned off');
108  
109 =head2 Get this module's own messages in another language
110  
111 my $logger = Test::Log::Abstraction->new(lang => 'de'); # German
112 my $french = Test::Log::Abstraction->new(country => 'FR'); # French
113  
114 =head1 DESCRIPTION
115  
116 =head2 What this module is
117  
118 Some code writes log messages through a logger object. In production that
119 object is usually a L<Log::Abstraction> logger. In a test, you give the code
120 a C<Test::Log::Abstraction> object instead.
121  
122 This object does not write the messages to a file. It keeps them in a list
123 in memory. After the code has run, your test can check the list: was a
124 message logged, at which level, and what did it say?
125  
126 It never writes to disk, and it does not load any logging backend.
127  
128 =head2 Which methods it has
129  
130 =over 4
131  
132 =item * B<Log levels.> The level methods of L<Log::Abstraction>:
133 C<trace>, C<debug>, C<info>, C<notice>, C<warn>, C<error>, C<fatal>,
134 C<critical>, C<alert> and C<emergency>. It also accepts the syslog names
135 C<warning>, C<err>, C<crit>, C<emerg>, C<panic> and C<informational>.
136  
137 =item * B<Other logger methods.> C<level()>, C<is_debug()> and the other
138 C<is_E<lt>levelE<gt>()> methods, C<messages()>, C<flush()> and
139 C<reopen()>. Code under test may call these, so they work as they do in
140 L<Log::Abstraction>.
141  
142 =item * B<Test methods.> C<like>, C<unlike>, C<has_level> and C<empty>.
143 Each one reports one test result, like C<ok()> in L<Test::More>.
144  
145 =item * B<Helper methods.> C<count>, C<clear>, C<verbose> and C<lang>.
146  
147 =back
148  
149 =head2 Which messages are printed
150  
151 Every message is always stored. This section is only about which messages
152 are also printed in the test output, as TAP comments (lines that start with
153 C<#>).
154  
155 By default, C<warning> and more serious levels are printed. So if a test
156 causes a warning by accident, you see it. C<trace>, C<debug>, C<info> and
157 C<notice> messages are not printed.
158  
159 Verbose mode prints every message. Verbose mode is on when you pass
160 C<< verbose => 1 >> to C<new()>. If you do not pass C<verbose>, it is on
161 when the environment variable C<TEST_VERBOSE> is true (C<prove -v> sets
162 it), or when C<VERBOSE> is true.
163  
164 To choose the levels, use the C<diag> option of C<new()>:
165  
166 =over 4
167  
168 =item * C<'all'> - print every message.
169  
170 =item * C<'none'> - print nothing (verbose mode still prints everything).
171  
172 =item * A level name, such as C<'error'> - print that level and every more
173 serious level.
174  
175 =item * A list, such as C<['info', 'error']> - print only these levels.
176  
177 =back
178  
179 Put exactly: a message is printed when B<any one> of these is true, and
180 not otherwise:
181  
182 =over 4
183  
184 =item 1. Verbose mode is on.
185  
186 =item 2. C<diag> is C<'all'>.
187  
188 =item 3. C<diag> is a list, and the message's level name is in it.
189  
190 =item 4. C<diag> is a level name, the message's level is a known level, and
191 its number is the same as, or lower than, that level's number.
192  
193 =back
194  
195 So a misspelt level (caught by L</AUTOLOAD>) is printed only by rules 1 to
196 3; and C<'none'> or an empty list means only rule 1 can apply.
197  
198 When a test method fails, the messages that explain the failure are printed
199 under it. So you can see why it failed without running the test again.
200  
201 A printed message may hold text that your test did not write, such as data
202 from a fixture. So when a message is printed, its control characters are
203 shown as C<\xNN>, except tab and newline, which lay it out. The escape
204 character that starts a terminal control sequence, for example, is shown
205 as C<\x1B>. A message's level is shown the same way. The stored message
206 is not changed: C<like>, C<unlike> and C<messages()> see it exactly as it
207 was logged.
208  
209 =head2 Global variables are left alone
210  
211 No method changes C<$@>, C<$!> or C<$_>, and none of them touches an
212 C<alarm()> timer. So you can log, or test the log, inside an error
213 handler, and C<$@> still holds the error afterwards. (A method that stops
214 with an error does set C<$@>, as every Perl error does.)
215  
216 =head2 Levels and how serious they are
217  
218 Each level has a number. A lower number means a more serious message.
219 These are the syslog numbers. The names and numbers come from
220 L<Readonly::Values::Syslog>, so they are the same as in other modules that
221 use it.
222  
223 0 emergency, emerg, panic
224 1 alert
225 2 critical, crit, fatal
226 3 error, err
227 4 warning, warn
228 5 notice
229 6 info, informational
230 7 debug, trace
231  
232 =head2 Language of this module's messages
233  
234 This module has its own messages: error messages, warnings, and the text
235 that explains a failed test. They can be in English (C<en>), German
236 (C<de>), French (C<fr>) or Simplified Chinese (C<zh>).
237  
238 The language is chosen like this. The first rule that gives an answer is
239 used:
240  
241 =over 4
242  
243 =item 1. The C<lang> option, for example C<< lang => 'de' >>.
244  
245 =item 2. The C<country> option, a two-letter country code such as C<'FR'>.
246  
247 =item 3. Only when C<< lang => 'auto' >>: the environment variables
248 C<LC_ALL>, C<LC_MESSAGES> and C<LANG>, in that order.
249  
250 =item 4. C<$Test::Log::Abstraction::config{lang}>, which is C<'en'>.
251  
252 =back
253  
254 The default is English, not the language of your computer. This is on
255 purpose: the test output is then the same on every computer.
256  
257 If a message has no translation, the English message is used. You can add
258 or change messages with the C<i18n> option of C<new()>.
259  
260 This only changes this module's own messages. The messages that your code
261 logs are never changed.
262  
263 =head2 Default settings
264  
265 The defaults for C<new()> are in the hash
266 C<%Test::Log::Abstraction::config>. It has the same keys as the options of
267 C<new()>. You can change it in a test, or fill it with
268 L<Object::Configure>:
269  
270 $Test::Log::Abstraction::config{'diag'} = 'none';
271  
272 A change only affects loggers that are created after it.
273  
274 You can also pass the result of L<Object::Configure> straight to C<new()>.
275 Settings in environment variables named C<Test__Log__Abstraction__KEY>
276 then override the arguments; the extra keys that L<Object::Configure>
277 adds (such as its own C<logger>) are ignored:
278  
279 # In the shell: export Test__Log__Abstraction__diag=none
280 my $params = Object::Configure::configure('Test::Log::Abstraction', { level => 'error' });
281 my $logger = Test::Log::Abstraction->new($params);
282  
283 =head1 COMMON PITFALLS
284  
285 =over 4
286  
287 =item * B<The test methods are tests.> C<like>, C<unlike>, C<has_level>
288 and C<empty> each add one test to the TAP output. If you give a test
289 plan (C<< tests => 5 >>), count them. Or use C<done_testing()>.
290  
291 =item * B<Messages from earlier steps are still there.> A logger keeps
292 every message until you call C<clear()>. If one logger is used for
293 several steps, C<like> may match a message from an earlier step.
294  
295 =item * B<A string pattern is a regular expression.> C<like('a.c')>
296 matches C<'abc'>, because C<.> means "any character". To match the text
297 exactly, use C<qr/\Qa.c\E/>.
298  
299 =item * B<Different names for one level are counted apart.> C<warn> and
300 C<warning> have the same number, but C<count('warn')> and
301 C<has_level('warn')> do not see messages logged with C<warning()>. Check
302 the name that the code under test uses. C<fatal> is stored as C<fatal>,
303 but L<Log::Abstraction> stores it as C<error>.
304  
305 =item * B<C<undef> is not the same as "no value".>
306  
307 =over 4
308  
309 =item * An C<undef> argument to a level method becomes the text
310 C<undef> in the message. (L<Log::Abstraction> drops it.)
311  
312 =item * C<< verbose => undef >> turns verbose mode B<off>. To use the
313 environment variables instead, do not pass C<verbose> at all.
314  
315 =item * C<< diag => undef >> and C<< level => undef >> use the default
316 from C<%config>.
317  
318 =item * C<count(undef)> counts all messages. C<level(undef)> returns the
319 level number and changes nothing.
320  
321 =item * C<like(undef)>, C<unlike(undef)> and C<has_level(undef)> stop the
322 test with an error.
323  
324 =back
325  
326 =item * B<One hash reference, or a hash reference at the end.>
327 C<< $logger->info({ a => 1 }) >> logs the text C<{a =E<gt> 1}>. But
328 C<< $logger->info('text', { a => 1 }) >> logs the text C<text> and stores
329 C<< { a => 1 } >> in C<fields>. An empty hash at the end is dropped.
330  
331 =item * B<Copies are shallow (only one level deep).>
332  
333 =over 4
334  
335 =item * When a message has C<fields>, the fields hash is copied. But a
336 hash or array B<inside> the fields is not copied. If your code changes it
337 later, the stored message changes too. And if the fields contain the
338 logger itself, the logger is never freed (a reference cycle) until you
339 call C<clear()>.
340  
341 =item * C<messages()> returns a new list, but the entries in it are the
342 stored entries. Do not change them, unless you want to change what was
343 captured.
344  
345 =item * C<new()> keeps its own copy of the C<diag> list and the C<i18n>
346 tables. Changing your array or hash afterwards does not change the
347 logger. (A part of an C<i18n> table that contains itself is left out of
348 the copy; it would only ever render as an empty string.)
349  
350 =item * When you clone a logger with C<< $logger->new(%options) >>, each
351 option replaces the old option completely. For example,
352 C<< $logger->new(i18n => { de => {...} }) >> replaces the whole C<i18n>
353 hash. The translations in the old hash are not kept.
354  
355 =back
356  
357 =item * B<The C<i18n> option is merged message by message.> You only
358 need to give the messages that you want to change. For each message,
359 this module looks in your C<i18n> hash first, and then in its own list.
360 So any message that you do not give keeps its normal text.
361  
362 =item * B<A misspelt method name does not stop the test.>
363 C<< $logger->wran('x') >> stores the message under the name C<wran> and
364 prints a notice. The test still passes, unless you check the messages.
365 A misspelt level name given to C<count()> is not caught either: see
366 L</LIMITATIONS>.
367  
368 =item * B<C<prove -v> prints everything.> C<prove -v> sets
369 C<TEST_VERBOSE>, which turns verbose mode on. If a test checks what is
370 printed, set C<< verbose => 0 >> or C<$ENV{TEST_VERBOSE} = 0>.
371  
372 =item * B<C<level()> does not hide messages.> It only changes the answers
373 of the C<is_*> methods. Every message is still stored.
374  
375 =item * B<Printed messages are escaped.> When a message is printed, its
376 control characters (except tab and newline) are shown as C<\xNN>, so text
377 from a fixture cannot control your terminal. L<Log::Abstraction> prints
378 them as they are. The stored message is not changed, so this matters only
379 if your test checks what is printed.
380  
381 =item * B<A very big number is not always written the same way.> In a
382 message template, a number too big for an integer format (such as
383 C<%{count}d> of C<1e30>) is shown as Perl writes it. Most Perls write
384 C<1e30> as C<1e+30>. A Perl built with C<-Duselongdouble> may write all
385 31 digits, C<1000000000000000000000000000000>. So in a test, do not type
386 the expected text. Let Perl make it:
387  
388 my $written = '' . 1e30; # '1e+30' or all 31 digits
389 is($self->i18n('n', { count => 1e30 }), "$written items");
390  
391 A string, such as C<'1e30'> in quotes, is always shown exactly as you
392 typed it.
393  
394 =back
395  
396 =head1 ENCODING
397  
398 This module never changes the text that your code logs. It stores each
399 message exactly as it was given.
400  
401 =over 4
402  
403 =item * B<Log messages and fields: any text.> ASCII, other languages and
404 emoji are all stored safely. It does not matter if the text is a Perl
405 character string (decoded, for example with C<use utf8> or
406 L<Encode/decode>) or a byte string (for example, UTF-8 bytes read from a
407 file).
408  
409 =item * B<Matching with C<like> and C<unlike>.> The pattern is matched
410 against the stored text as it is. So the pattern and the message must be
411 the same kind of string. A pattern with a character, such as
412 C<qr/\x{1F600}/>, does not match the same emoji stored as UTF-8 bytes.
413  
414 =item * B<Printed messages.> Control characters, except tab and
415 newline, are printed as C<\xNN> (see L</Which messages are printed>). A
416 Perl character string that has any character above ASCII is printed as
417 UTF-8. A character string whose bytes are not valid UTF-8 is printed
418 with U+FFFD in place of each bad part. A byte string is printed
419 unchanged. Perl cannot always see the difference: a string that was not
420 decoded, and has no character above 255 (such as C<"caf\x{e9}">), is
421 treated as bytes. If the output already has an encoding layer (for example, set
422 by L<Test2::Plugin::UTF8>), the text is not encoded again.
423  
424 =item * B<This module's own messages.> German, French and Chinese messages
425 are character strings, and they are printed as UTF-8. There is one
426 problem case: a translated message that includes a logged message that is
427 a non-ASCII byte string. That part of the text is printed wrongly (it is
428 encoded twice). English messages do not have this problem.
429  
430 =item * B<Options.> C<lang> and C<country> must be ASCII, in the formats
431 given under L</new>. Level names are ASCII. Templates in the C<i18n>
432 option may contain any characters, but placeholder names must be ASCII
433 letters, digits or C<_>.
434  
435 =item * B<Test names.> Test names are passed to L<Test::Builder>
436 unchanged.
437  
438 =back
439  
440 =cut
441  
442 34 ▶use 5.026;
Subroutine BEGIN: called CC=1 SCAR=0.0
443 34 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
444 34 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
445  
446 # Nothing is imported as a function: anything defined in this package is a
447 # method on every logger, and would answer a call that should reach
448 # AUTOLOAD ($logger->croak('x') would croak, $logger->carp('x') warn)
449 34 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
450 34 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
451 34 ▶use Hash::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
452 34 ▶use List::Util 1.33 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
453 34 ▶use overload ();
Subroutine BEGIN: called CC=1 SCAR=0.0
454 34 ▶use Params::Get ();
Subroutine BEGIN: called CC=1 SCAR=0.0
455 32 ▶use Params::Validate::Strict ();
Subroutine BEGIN: called CC=1 SCAR=0.0
456 31 ▶use Readonly ();
Subroutine BEGIN: called CC=1 SCAR=0.0
457 31 ▶use Readonly::Values::Syslog 0.04 qw(%SYSLOG_LEVELS);
Subroutine BEGIN: called CC=1 SCAR=0.0
458 30 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
459 30 ▶use Test::Builder ();
Subroutine BEGIN: called CC=1 SCAR=0.0
460  
461 30 ▶use version (); our $VERSION = version->declare('0.002.2');
Subroutine BEGIN: called CC=1 SCAR=0.0
462 30 our $AUTOLOAD;
463  
464 # Routines whose names start with '_' are internal. They are not checked
465 # at run time: the modules that did that (Sub::Private, Sub::Protected)
466 # brought in compiled dependencies that crash on Windows with Perl 5.42,
467 # cost about 40% of every log call, and were switched off under prove
468 # anyway. The leading underscore, and the POD, are the contract.
469  
470 # Defaults for new(); a flat hash so Object::Configure, or a test, can
471 # override any of them before loggers are created
472 30 our %config = (
473 diag => 'warning', # print this level and more severe by default
474 lang => 'en', # deterministic output unless asked otherwise
475 level => 'trace', # threshold reported by level() and is_*()
476 );
477  
478 # Level -> severity, lower is more severe, following POSIX syslog priorities.
479 # trace and debug share a severity, as they do in Log::Abstraction
480 # The names and numbers come from Readonly::Values::Syslog, so they are not
481 # kept in two places. This table is read on every log call, and that one
482 # is a Readonly hash, which is tied, so each lookup would be a method call;
483 # a plain copy locked with Hash::Util's lock_hash() is just as read-only
484 # with no tie. (A locked hash croaks on a lookup of a missing key, so every
485 # lookup is guarded by exists(), as it already had to be for Readonly.)
486 30 my %SEVERITY = %SYSLOG_LEVELS;
487 30 Hash::Util::lock_hash(%SEVERITY);
488  
489 # Log::Abstraction ignores a call with no arguments at this severity or more
490 # serious (warn() to emergency()), but stores an empty message for the less
491 # serious levels; a drop-in replacement must count the same
492 30 Readonly::Scalar my $NEEDS_ARGUMENTS => $SEVERITY{'warn'};
493  
494 # The levels that Log::Abstraction has is_<level>() predicates for
495 30 Readonly::Array my @PREDICATES => qw(trace debug info notice warn error critical alert emergency);
496  
497 # diag option values that are not level names
498 30 Readonly::Scalar my $DIAG_ALL => 'all';
499 30 Readonly::Scalar my $DIAG_NONE => 'none';
500  
501 # lang option value that means "read the POSIX locale variables"
502 30 Readonly::Scalar my $LANG_AUTO => 'auto';
503  
504 # Catalogue used when a key has no translation in the chosen language
505 30 Readonly::Scalar my $FALLBACK_LANG => 'en';
506  
507 # Locale environment variables, most specific first, as POSIX defines them
508 30 Readonly::Array my @LOCALE_VARS => qw(LC_ALL LC_MESSAGES LANG);
509  
510 # Longest explanation kept from another module's error, which may repeat
511 # a hostile value of any size
512 30 Readonly::Scalar my $MAX_REASON => 200;
513  
514 # How many captured messages a failing assertion lists before summarising
515 30 Readonly::Scalar my $MAX_EXPLAIN => 20;
516  
517 # Shown in place of a reference that contains itself, so rendering a
518 # self-referential structure cannot recurse forever
519 30 Readonly::Scalar my $CYCLE => '(cycle)';
520  
521 # ISO 3166 country code -> catalogue language
522 30 Readonly::Hash my %COUNTRY_LANG => (
523 AT => 'de', AU => 'en', BE => 'fr', CA => 'en', CH => 'de',
524 CN => 'zh', DE => 'de', FR => 'fr', GB => 'en', HK => 'zh',
525 IE => 'en', LU => 'fr', NZ => 'en', SG => 'zh', TW => 'zh',
526 UK => 'en', US => 'en',
527 );
528  
529 # CLDR plural categories per language; 'zero' is not a CLDR category for
530 # these languages, so templates may add it as an explicit "=0" case
531 Readonly::Hash my %PLURAL => (
532 135 ▶ en => sub { ($_[0] == 1) ? 'one' : 'other' },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] == 1 ? : 72 63 135
533 14 ▶ de => sub { ($_[0] == 1) ? 'one' : 'other' },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
$_[0] == 1 ? : 5 9 14
534 21 ▶ fr => sub { (abs($_[0]) < 2) ? 'one' : 'other' }, # French counts 0 as singular
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
abs $_[0] < 2 ? : 11 10 21
535 9 ▶ zh => sub { 'other' }, # Chinese has no grammatical plural
Subroutine __ANON__: called CC=1 SCAR=0.0
536 30 );
537  
538 # Message catalogues. Templates use %{name}s-style placeholders (any sprintf
539 # conversion may follow the name), and may be a hash keyed by gender or by
540 # plural category instead of a string; see i18n(). Non-English text is
541 # written with \x{} escapes to keep this source file ASCII.
542 # It is Readonly on purpose, as well as locked with Hash::Util below: a bug
543 # that writes to it is caught at once. The tie makes every read a method
544 # call, so i18n() runs about a quarter slower than with a plain hash; that
545 # is accepted. Do not make it plain to gain speed. Every lookup in it is
546 # guarded with exists(), as a locked hash croaks on a missing key.
547 30 Readonly::Hash my %MESSAGES => (
548 en => {
549 class_invocant => '%{class}s: %{method}s() must be called on an object, not on the class',
550 invalid_argument => '%{class}s: invalid argument: %{reason}s',
551 invalid_diag_level => q{%{class}s: invalid diag level '%{level}s'},
552 invalid_diag_type => '%{class}s: diag must be a level name, "all", "none" or an array reference of level names',
553 invalid_level => q{%{class}s: invalid syslog level '%{level}s'},
554 needs_level => '%{class}s: %{method}s() needs a level name',
555 needs_pattern => '%{class}s: %{method}s() needs a pattern',
556 no_method => q{%{class}s: no method '%{method}s'},
557 captured => {
558 zero => '%{class}s: no messages were captured',
559 one => '%{class}s: %{count}d message was captured:',
560 other => '%{class}s: %{count}d messages were captured:',
561 },
562 matched => {
563 one => '%{class}s: %{count}d message matched:',
564 other => '%{class}s: %{count}d messages matched:',
565 },
566 entry => ' [%{level}s] %{message}s',
567 truncated => ' ... and %{count}d more',
568 }, de => {
569 class_invocant => '%{class}s: %{method}s() muss an einem Objekt aufgerufen werden, nicht an der Klasse',
570 invalid_argument => "%{class}s: ung\x{fc}ltiges Argument: %{reason}s",
571 invalid_diag_level => "%{class}s: ung\x{fc}ltige diag-Stufe '%{level}s'",
572 invalid_diag_type => '%{class}s: diag muss ein Stufenname, "all", "none" oder eine Array-Referenz von Stufennamen sein',
573 invalid_level => "%{class}s: ung\x{fc}ltige Syslog-Stufe '%{level}s'",
574 needs_level => "%{class}s: %{method}s() ben\x{f6}tigt einen Stufennamen",
575 needs_pattern => "%{class}s: %{method}s() ben\x{f6}tigt ein Muster",
576 no_method => q{%{class}s: keine Methode '%{method}s'},
577 captured => {
578 zero => '%{class}s: es wurden keine Meldungen erfasst',
579 one => '%{class}s: %{count}d Meldung wurde erfasst:',
580 other => '%{class}s: %{count}d Meldungen wurden erfasst:',
581 },
582 matched => {
583 one => '%{class}s: %{count}d Meldung passte:',
584 other => '%{class}s: %{count}d Meldungen passten:',
585 },
586 truncated => ' ... und %{count}d weitere',
587 }, fr => {
588 class_invocant => "%{class}s : %{method}s() doit \x{ea}tre appel\x{e9}e sur un objet, pas sur la classe",
589 invalid_argument => '%{class}s : argument invalide : %{reason}s',
590 invalid_diag_level => q{%{class}s : niveau diag invalide '%{level}s'},
591 invalid_diag_type => "%{class}s : diag doit \x{ea}tre un nom de niveau, \"all\", \"none\" ou une r\x{e9}f\x{e9}rence de tableau de noms de niveaux",
592 invalid_level => q{%{class}s : niveau syslog invalide '%{level}s'},
593 needs_level => "%{class}s : %{method}s() n\x{e9}cessite un nom de niveau",
594 needs_pattern => "%{class}s : %{method}s() n\x{e9}cessite un motif",
595 no_method => "%{class}s : aucune m\x{e9}thode '%{method}s'",
596 captured => {
597 zero => "%{class}s : aucun message n'a \x{e9}t\x{e9} captur\x{e9}",
598 one => "%{class}s : %{count}d message a \x{e9}t\x{e9} captur\x{e9} :",
599 other => "%{class}s : %{count}d messages ont \x{e9}t\x{e9} captur\x{e9}s :",
600 },
601 matched => {
602 one => '%{class}s : %{count}d message correspond :',
603 other => '%{class}s : %{count}d messages correspondent :',
604 },
605 truncated => ' ... et %{count}d de plus',
606 },
607 zh => {
608 # "must be called on an object, not on the class"
609 class_invocant => "%{class}s\x{ff1a}%{method}s() \x{5fc5}\x{987b}\x{5728}\x{5bf9}\x{8c61}\x{4e0a}\x{8c03}\x{7528}\x{ff0c}\x{800c}\x{4e0d}\x{662f}\x{5728}\x{7c7b}\x{4e0a}\x{8c03}\x{7528}",
610 # "invalid argument"
611 invalid_argument => "%{class}s\x{ff1a}\x{65e0}\x{6548}\x{7684}\x{53c2}\x{6570}\x{ff1a}%{reason}s",
612 # "invalid diag level"
613 invalid_diag_level => "%{class}s\x{ff1a}\x{65e0}\x{6548}\x{7684} diag \x{7ea7}\x{522b} '%{level}s'",
614 # "diag must be a level name, all, none or an array reference of level names"
615 invalid_diag_type => "%{class}s\x{ff1a}diag \x{5fc5}\x{987b}\x{662f}\x{7ea7}\x{522b}\x{540d}\x{79f0}\x{3001}\"all\"\x{3001}\"none\" \x{6216}\x{7ea7}\x{522b}\x{540d}\x{79f0}\x{7684}\x{6570}\x{7ec4}\x{5f15}\x{7528}",
616 # "invalid syslog level"
617 invalid_level => "%{class}s\x{ff1a}\x{65e0}\x{6548}\x{7684} syslog \x{7ea7}\x{522b} '%{level}s'",
618 # "needs a level name"
619 needs_level => "%{class}s\x{ff1a}%{method}s() \x{9700}\x{8981}\x{4e00}\x{4e2a}\x{7ea7}\x{522b}\x{540d}\x{79f0}",
620 # "needs a pattern"
621 needs_pattern => "%{class}s\x{ff1a}%{method}s() \x{9700}\x{8981}\x{4e00}\x{4e2a}\x{6a21}\x{5f0f}",
622 # "no method"
623 no_method => "%{class}s\x{ff1a}\x{6ca1}\x{6709}\x{65b9}\x{6cd5} '%{method}s'",
624 captured => {
625 # "no messages were captured"
626 zero => "%{class}s\x{ff1a}\x{6ca1}\x{6709}\x{6355}\x{83b7}\x{5230}\x{4efb}\x{4f55}\x{6d88}\x{606f}",
627 # "captured N messages"
628 other => "%{class}s\x{ff1a}\x{6355}\x{83b7}\x{4e86} %{count}d \x{6761}\x{6d88}\x{606f}\x{ff1a}",
629 },
630 # "N messages matched"
631 matched => {
632 other => "%{class}s\x{ff1a}%{count}d \x{6761}\x{6d88}\x{606f}\x{5339}\x{914d}\x{ff1a}",
633 },
634 # "... N more"
635 truncated => " \x{2026}\x{2026}\x{8fd8}\x{6709} %{count}d \x{6761}",
636 },
637 );
638 30 Hash::Util::lock_hash_recurse(%MESSAGES);
639  
640 # What the lang option may look like. It is written on one line because
641 # Params::Validate::Strict quotes it in its error message. In parts:
642 # \A (?: (?i:auto) read the locale from the environment
643 # | [A-Za-z]{2,3} or a language code: 'de', 'eng'
644 # (?: [_.\@-] [\w.\@-]*+ )? then optionally a separator and a
645 # territory, codeset or modifier
646 # ) \z
647 # The tail is possessive (*+): nothing after it can use characters it gave
648 # back, so a long invalid value fails in one pass instead of being retried
649 # at every length.
650 30 Readonly::Scalar my $LANG_FORMAT => qr/\A(?:(?i:auto)|[A-Za-z]{2,3}(?:[_.\@-][\w.\@-]*+)?)\z/;
651  
652 # The schemas below are Readonly on purpose: a bug that writes to one is
653 # caught at once. Params::Validate::Strict reads every schema many times
654 # per call, and through Readonly's tie new() is about three times slower,
655 # and like() and has_level() about a third slower, than with plain hashes;
656 # that is accepted. Do not make them plain to gain speed. They are not
657 # locked with Hash::Util: Params::Validate::Strict reads keys a schema does
658 # not have (such as 'members'), which a locked hash refuses.
659  
660 # Schema for new()'s options. diag is not listed: _diag_rule() validates it,
661 # because its messages say what a valid diag is, which a type error cannot
662 30 Readonly::Hash my %NEW_SCHEMA => (
663 verbose => { type => 'scalar', optional => 1 },
664 level => { type => 'string', optional => 1 },
665 lang => { type => 'string', optional => 1, matches => $LANG_FORMAT },
666 country => { type => 'string', optional => 1, matches => qr/\A[A-Za-z]{2}\z/ },
667 i18n => { type => 'hashref', optional => 1 },
668 );
669  
670 # Schema shared by like() and unlike()
671 30 Readonly::Hash my %PATTERN_SCHEMA => (
672 pattern => { type => ['regex', 'string'] },
673 name => { type => 'string', optional => 1 },
674 );
675  
676 # Schema for count()
677 30 Readonly::Hash my %COUNT_SCHEMA => (
678 level => { type => 'string', optional => 1 },
679 );
680  
681 # Schema for empty(): only a test name
682 30 Readonly::Hash my %NAME_SCHEMA => (
683 name => { type => 'string', optional => 1 },
684 );
685  
686 # Schema for has_level()
687 30 Readonly::Hash my %LEVEL_SCHEMA => (
688 level => { type => 'string' },
689 name => { type => 'string', optional => 1 },
690 );
691  
692 =head1 METHODS
693  
694 =head2 new
695  
696 Create a new test logger.
697  
698 =head3 Purpose
699  
700 Make a logger that stores every message it is given, so that your test can
701 check the messages later.
702  
703 =head3 Args
704  
705 All options are optional. Give them as a list (C<< key => value >>) or as
706 one hash reference.
707  
708 =over 4
709  
710 =item * C<verbose> - true: print every message. False: use the C<diag>
711 rule. If you do not give it, the value of C<$ENV{TEST_VERBOSE}> or
712 C<$ENV{VERBOSE}> is used.
713  
714 =item * C<diag> - which messages to print. C<'all'>, C<'none'>, a level
715 name (print that level and every more serious level), or an array
716 reference of level names. Upper or lower case does not matter. The
717 default is C<'warning'>.
718  
719 =item * C<level> - the level that C<level()> and the C<is_*> methods
720 report. The default is C<'trace'>, so every C<is_*> method returns 1, and
721 the code under test runs all its debug code. This option does not stop
722 any message from being stored.
723  
724 =item * C<lang> - the language of this module's own messages: C<'en'>,
725 C<'de'>, C<'fr'>, C<'zh'>, a locale name such as C<'de_DE.UTF-8'>, or
726 C<'auto'> (read the environment). Must be 2 or 3 ASCII letters, then
727 optionally C<_>, C<.>, C<@> or C<-> and more text.
728  
729 =item * C<country> - a two-letter country code such as C<'GB'> or
730 C<'fr'> (upper or lower case). Used to choose the language when C<lang>
731 is not given.
732  
733 =item * C<i18n> - your own message texts, as
734 C<< { language => { message_key => template } } >>. See L</i18n>.
735  
736 =back
737  
738 Other options are allowed and ignored. (A L<Log::Abstraction>
739 configuration hash can be passed unchanged.) If you pass an odd number of
740 arguments, they are all ignored.
741  
742 =head3 Three ways to call it
743  
744 =over 4
745  
746 =item * C<< Test::Log::Abstraction->new(%options) >> - the usual way.
747  
748 =item * C<< $logger->new(%options) >> - make a B<clone>: a new logger with
749 the same options, the same C<verbose> and C<level> settings, and a copy of
750 the stored messages. The options that you pass replace the old ones.
751  
752 =item * C<Test::Log::Abstraction::new(%options)> - called as a function.
753 This works too.
754  
755 =back
756  
757 =head3 Returns
758  
759 The new logger object.
760  
761 =head3 Side Effects
762  
763 Reads C<%ENV> to decide on verbose mode, and, with C<< lang => 'auto' >>,
764 to choose the language. Nothing else changes. A clone does not change the
765 original logger.
766  
767 =head3 EXAMPLE
768  
769 # The usual way
770 my $logger = Test::Log::Abstraction->new();
771  
772 # Store everything, print nothing
773 my $quiet = Test::Log::Abstraction->new(diag => 'none');
774  
775 # A hash reference works too; messages in German
776 my $german = Test::Log::Abstraction->new({ country => 'DE' });
777  
778 # A clone that prints everything; $logger is not changed
779 my $loud = $logger->new(diag => 'all');
780  
781 =head3 API SPECIFICATION
782  
783 =head4 Input
784  
785 {
786 verbose => { type => 'scalar', optional => 1 },
787 diag => { type => ['string', 'arrayref'], optional => 1 },
788 level => { type => 'string', optional => 1 },
789 lang => { type => 'string', optional => 1, matches => qr/\A(?:(?i:auto)|[A-Za-z]{2,3}(?:[_.\@-][\w.\@-]*+)?)\z/ },
790 country => { type => 'string', optional => 1, matches => qr/\A[A-Za-z]{2}\z/ },
791 i18n => { type => 'hashref', optional => 1 },
792 }
793  
794 Domains (valid / invalid / boundaries):
795  
796 verbose valid: any plain value, Perl truth decides ('0', '' and undef
797 are off; '00', '0.0' and ' ' are on); absent: from
798 TEST_VERBOSE or VERBOSE. Invalid: any reference.
799 diag valid: 'all' or 'none' (any case); a level name (any case),
800 which prints severity 0 (emergency) up to that level's
801 number, 7 (trace) being every level; an array reference of
802 level names, [] printing nothing and duplicates counting
803 once; absent or undef: $config{diag}. Invalid: any other
804 string, including '' and numbers such as '4'; a list
805 element that is not a level name (or is 'all'); a hash,
806 code or scalar reference; any object, including one that
807 only claims to be an array, such as bless({}, 'ARRAY').
808 (An array blessed into the class ARRAY is still an array
809 of names, and valid.)
810 level valid: the 16 level names, any case, setting 0 (emergency)
811 to 7 (trace); absent or undef: $config{level}. Invalid:
812 '', numbers (even 0 to 7), any other name. The error shows
813 the name as it was given ('LOUD', not 'loud'). Level names are
814 ASCII: a non-ASCII letter ('\x{130}NFO', a dotted
815 capital I) makes another name, even after lower-casing.
816 lang valid: 'auto' (any case); 2 or 3 ASCII letters, then
817 optionally one of _ . @ - and anything else ('de',
818 'eng', 'de_DE.UTF-8', 'zh-Hant'). A code with no catalogue
819 ('ja', 'eng') gives 'en'. Invalid: 1 letter, 4 or more
820 letters, '', digits, a non-ASCII letter in the code, any
821 whitespace or newline.
822 country valid: exactly 2 ASCII letters, any case; one with no
823 mapping ('JP') gives 'en'. Invalid: 1 or 3 letters, '',
824 digits, non-ASCII letters.
825 i18n valid: a hash reference (even empty). Invalid: any other
826 type. A reference that only claims to be a hash, such
827 as bless([], 'HASH'), passes the type check and is then
828 ignored, as is a language table or a form that is not
829 really a hash. Tables may be nested to any depth; a part
830 of a table that contains itself is left out of the copy.
831  
832 An "invalid argument" explanation, and a level or diag name repeated in an
833 error, is at most 200 characters; one longer is cut to 200 and ends with
834 "...". Control characters in it are shown as C<\xNN>. A level or diag name that is a
835 character string but not valid UTF-8 is never a level name, and is shown
836 with U+FFFD in place of each bad part.
837  
838 =head4 Output
839  
840 { type => 'object', isa => 'Test::Log::Abstraction' }
841  
842 =head3 MESSAGES
843  
844 All of these stop the program (C<croak>).
845  
846 Message Meaning What to do
847 ------------------------------ ---------------------------- ------------------------------
848 invalid diag level 'X' X is not a level name Use a name from the level table
849 diag must be a level name ... diag is a hash or code ref Give a string or an array ref
850 invalid syslog level 'X' the level option is unknown Use a name from the level table
851 invalid argument: ... an option has the wrong type Fix the option that is named
852 or format
853  
854 =head3 PSEUDOCODE
855  
856 if new() was called on a logger object:
857 options = the object's options, replaced by the new options
858 build a logger from the options, with a copy of the messages
859 copy verbose and level from the object, unless new values were given
860 else:
861 if new() was called as a function, the first argument is an option
862 turn the arguments into a hash (ignore an odd-length list)
863 check the options
864 choose the language, then the diag rule, then the level
865 return the logger
866  
867 =cut
868  
869 5177 ▶sub new {
Subroutine new: called CC=4 SCAR=13.9
Pod documented
870 5177 my ($class, @args) = @_;
871  
872 # Clone form: $logger->new(%overrides), as in Log::Abstraction
873 5177 ▶ return $class->_clone(_args(\@args)) if(Scalar::Util::blessed($class));
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($class) 2057 3120 5177
874  
875 # Function-call form, Test::Log::Abstraction::new(...): whatever was
876 # passed first is an option, not a class name.
877 # Premise 1: UNIVERSAL::isa() is false, without a warning, for undef,
878 # '', any unblessed reference and any unrelated name.
879 # Premise 2: objects were dealt with above.
880 # So: one isa() test separates "a class name" from "an option".
881 3120 ▶ if(!UNIVERSAL::isa($class, __PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (UNIVERSAL::isa($class, __PACKAGE__)) 12 3108 3120
882 12 ▶ unshift @args, $class if(defined($class));
Branch: 1 branch
BranchTrueFalseTotal
if defined $class 8 4 12
883 12 $class = __PACKAGE__;
884 }
885  
886 3120 return $class->_build(_args(\@args), []);
887 }
888  
889 # _args - normalise constructor arguments to a hash reference
890 #
891 # Purpose: Accept every argument shape used across the tests that this
892 # module replaces MyLogger in.
893 # Entry: $args - array reference of what the caller passed after the
894 # class or invocant.
895 # Exit: Returns a new hash reference; empty for no arguments or for
896 # an odd-length list that is not a single hash reference.
897 # Side effects: None. The caller's hash is copied, never kept.
898 5208 ▶sub _args {
Subroutine _args: called CC=7 SCAR=19.5
899 5208 my $args = shift;
900  
901 # Params::Get croaks on an odd list, and warns on an undefined key; a
902 # stray argument must not break a test run, so only hand it the two
903 # shapes it accepts. The key check is the costly test, so it runs last,
904 # only for a non-empty, even-length list.
905 5208 my $count = scalar(@{$args});
906 my $usable = (($count == 1) && (ref($args->[0]) eq 'HASH'))
907 5208 ▶ || ($count && !($count % 2) && !grep { !defined($args->[$_]) } grep { !($_ % 2) } 0 .. $count - 1);
Condition100%12/12
$count == 1 && ref $args->[0] eq 'HASH' || $count && !($count % 2) && !grep({not defined $args->[$_];} grep({not $_ % 2;} 0 .. $count - 1))
l!l&&r!l&&!r
931052094
$count == 1 and ref $args->[0] eq "HASH"
!ll&&!rl&&r
5187129
$count and not $count % 2 and not grep({not defined $args->[$_];} grep({not $_ % 2;} 0 .. $count - 1))
!ll&&!rl&&r
208863105
$count and not $count % 2
!ll&&!rl&&r
2074143111
MC/DC100%5/5
$count == 1 && ref $args->[0] eq 'HASH' || $count && !($count % 2) && !grep({not defined $args->[$_];} grep({not $_ % 2;} 0 .. $count - 1))
$count == 1 ref $args->[0] eq "HASH" $count not $count % 2 not grep({not defined $args->[$_];} grep({not $_ % 2;} 0 .. $count - 1))
Truth table66%6/9
A and B || C and not(D) and not(E)
A= $count == 1B= ref $args->[0] eq "HASH"C= $countD= not $count % 2E= not grep({not defined $args->[$_];} grep({not $_ % 2;} 0 .. $count - 1))
ABCDEresult
11XXX1
0X1111
101111
0X0XX0
0X10X0
0X1100
100XX0
1010X0
101100
908 5208 ▶ my $params = $usable ? Params::Get::get_params(undef, $args) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$usable ? : 3114 2094 5208
909  
910 5207 ▶ return { %{$params || {}} };
Condition100%2/2
$params || {}
l!l
31082099
MC/DC100%1/1
$params || {}
$params
Truth table100%2/2
A
A= $params
Aresult
11
00
911 }
912  
913 # _build - construct a logger from validated options
914 #
915 # Purpose: The one place a logger's state is set up, shared by new()
916 # and _clone() so the two cannot drift apart.
917 # Entry: $class - package to bless into.
918 # $options - hash reference from _args().
919 # $messages - array reference of entries to start with.
920 # Exit: Returns the blessed logger.
921 # Side effects: Reads %ENV. Croaks, in the logger's language, on an
922 # invalid option.
923 5205 ▶sub _build {
Subroutine _build: called CC=11 SCAR=24.0
924 5205 my ($class, $options, $messages) = @_;
925  
926 # Keep diag aside: _diag_rule() gives it a better message than a schema
927 5205 my $valid = $class->_validate(\%NEW_SCHEMA, $options);
928 5073 ▶ $valid->{'diag'} = $options->{'diag'} if(exists($options->{'diag'}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $options->{"diag"} 4915 158 5073
929  
930 # The diag list and the i18n tables are the caller's structures; copy
931 # them, or changing them later would change this logger (and its
932 # clones). A diag list holds names, so one level is enough, and keeps
933 # a bad element as it was for _diag_rule() to report.
934 5073 ▶ $valid->{'diag'} = [ @{$valid->{'diag'}} ] if(_is_a($valid->{'diag'}, 'ARRAY'));
Branch: 1 branch
BranchTrueFalseTotal
if _is_a($valid->{"diag"}, "ARRAY") 40 5032 5072
935 5072 ▶ $valid->{'i18n'} = _copy_tree($valid->{'i18n'}, {}) if(exists($valid->{'i18n'}));
Branch: 1 branch
BranchTrueFalseTotal
if exists $valid->{"i18n"} 97 4975 5072
936  
937 # Internal state is kept apart from options, so no option name can
938 # overwrite it (an option called 'messages' once replaced the capture)
939 my $self = bless {
940 messages => $messages,
941 options => $valid,
942 5071 ▶ verbose => exists($valid->{'verbose'}) ? ($valid->{'verbose'} ? 1 : 0) : (($ENV{'TEST_VERBOSE'} || $ENV{'VERBOSE'}) ? 1 : 0),
Branch: 3 branches
BranchTrueFalseTotal
exists $valid->{'verbose'} ? : 4756 315 5071
$valid->{'verbose'} ? : 39 4717 4756
$ENV{'TEST_VERBOSE'} || $ENV{'VERBOSE'} ? : 11 304 315
Condition100%3/3
$ENV{"TEST_VERBOSE"} or $ENV{"VERBOSE"}
l!l&&r!l&&!r
74304
MC/DC100%2/2
$ENV{"TEST_VERBOSE"} or $ENV{"VERBOSE"}
$ENV{"TEST_VERBOSE"} $ENV{"VERBOSE"}
Truth table100%3/3
A or B
A= $ENV{"TEST_VERBOSE"}B= $ENV{"VERBOSE"}
ABresult
1X1
011
000
943 }, $class;
944  
945 # The language first, so that the checks below report in it
946 5071 $self->{'lang'} = _resolve_lang($valid);
947 # Absent and undef both mean "the default", and _diag_rule() turns undef
948 # into $config{diag}; so the value is passed as it is
949 5067 $self->{'diag_rule'} = $self->_diag_rule($valid->{'diag'});
950  
951 # An unknown level at construction is a programming error, so fatal;
952 # level() only carps, as Log::Abstraction's does
953 # The name is looked up in lower case, but reported as it was given, as
954 # level() and every other error do
955 5005 ▶ my $given = defined($valid->{'level'}) ? $valid->{'level'} : $config{'level'};
Branch: 1 branch
BranchTrueFalseTotal
defined $valid->{'level'} ? : 108 4897 5005
956 5005 ▶ my $level = defined($given) ? _lc($given) : 'undef';
Branch: 1 branch
BranchTrueFalseTotal
defined $given ? : 5003 2 5005
957 5005 ▶ $self->_croak('invalid_level', { level => _shown($given) }) if(!exists($SEVERITY{$level}));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $SEVERITY{$level} 51 4954 5005
958 4954 $self->{'level'} = $SEVERITY{$level};
959  
960 4954 return $self;
961 }
962  
963 # _copy_tree - deep copy of plain hashes and arrays, without cycles
964 #
965 # Purpose: Give a logger its own copy of option structures.
966 # Entry: $value - any value.
967 # $path - hash reference of the addresses of the structures
968 # being copied further up this call chain.
969 # Exit: Returns the copy; anything other than a plain hash or array
970 # (strings, code, objects) is returned as it is. A reference
971 # back to a structure on the current path becomes undef, so
972 # the copy has no cycles and is freed with the logger. (A
973 # cyclic template renders as '' either way; see _variant.)
974 # Side effects: None on $value. $path is restored on return.
975 205674 ▶sub _copy_tree {
Subroutine _copy_tree: called CC=5 SCAR=16.1
976 205674 my ($value, $path) = @_;
977  
978 # Nested option tables are legitimate; Perl's warning at depth 100 is noise
979 30 ▶ no warnings 'recursion'; ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
980  
981 # Through _is_a(): bless([], 'HASH') says 'HASH' but cannot be walked
982 # as one, and would kill new() with Perl's "Not a HASH reference"
983 205674 my $hash = _is_a($value, 'HASH');
984 205674 ▶ return $value if(!$hash && !_is_a($value, 'ARRAY'));
Branch: 1 branch
BranchTrueFalseTotal
unless $hash or _is_a($value, "ARRAY") 146 205528 205674
Condition100%3/3
$hash or _is_a($value, "ARRAY")
l!l&&r!l&&!r
2055217146
MC/DC100%2/2
$hash or _is_a($value, "ARRAY")
$hash _is_a($value, "ARRAY")
Truth table100%3/3
A or B
A= $hashB= _is_a($value, "ARRAY")
ABresult
1X1
011
000
985  
986 205528 my $address = Scalar::Util::refaddr($value);
987 205528 ▶ return if($path->{$address});
Branch: 1 branch
BranchTrueFalseTotal
if $path->{$address} 8 205520 205528
988 205520 local $path->{$address} = 1;
989  
990 205520 ▶ return { map { $_ => scalar(_copy_tree($value->{$_}, $path)) } keys %{$value} } if($hash);
Branch: 1 branch
BranchTrueFalseTotal
if $hash 205514 6 205520
991  
992 6 return [ map { scalar(_copy_tree($_, $path)) } @{$value} ];
993 }
994  
995 # _clone - copy a logger, as Log::Abstraction->new does on an object
996 #
997 # Purpose: Clone with overrides, re-validating everything so that, for
998 # example, a new diag option really changes the diag rule.
999 # Entry: $self - logger to copy.
1000 # $overrides - hash reference of options to change.
1001 # Exit: Returns the clone.
1002 # Side effects: None on $self; entries are copied so that neither logger can
1003 # alter the other's history.
1004 2068 ▶sub _clone {
Subroutine _clone: called CC=4 SCAR=13.9
1005 2068 my ($self, $overrides) = @_;
1006  
1007 2068 ▶ my $copy = [ map { +{ %{$_}, ($_->{'fields'} ? (fields => { %{$_->{'fields'}} }) : ()) } } @{$self->{'messages'}} ];
Branch: 1 branch
BranchTrueFalseTotal
$_->{'fields'} ? : 2088 2128 4216
1008 2068 my $clone = ref($self)->_build({ %{$self->{'options'}}, %{$overrides} }, $copy);
1009  
1010 # Runtime changes made with verbose() and level() carry over, unless the
1011 # caller asked for something else
1012 2058 ▶ $clone->{'verbose'} = $self->{'verbose'} if(!exists($overrides->{'verbose'}));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $overrides->{"verbose"} 2049 9 2058
1013 2058 ▶ $clone->{'level'} = $self->{'level'} if(!exists($overrides->{'level'}));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $overrides->{"level"} 2050 8 2058
1014  
1015 2058 return $clone;
1016 }
1017  
1018 # _validate - check arguments against a Params::Validate::Strict schema
1019 #
1020 # Purpose: Run validate_strict, reporting failures through i18n so the
1021 # message is in the logger's language and blames the caller.
1022 # Entry: $self - logger or class name.
1023 # $schema - schema hash reference.
1024 # $input - hash reference of arguments.
1025 # Exit: Returns the validated hash reference; unknown keys dropped.
1026 # Side effects: Croaks with 'invalid_argument' on failure. Leaves $@ alone
1027 # on success.
1028 5823 ▶sub _validate {
Subroutine _validate: called CC=3 SCAR=11.0
1029 5823 my ($self, $schema, $input) = @_;
1030  
1031 # The caller's $@ must survive a successful check
1032 5823 local $@;
1033 5823 my $valid;
1034 5823 ▶ if(!eval { $valid = Params::Validate::Strict::validate_strict(schema => $schema, input => $input, unknown_parameter_handler => 'ignore'); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $valid = Params::Validate::Strict::validate_strict("schema", $schema, "input", $input, "unknown_parameter_handler", "ignore"); 1 } }) 189 5634 5823
1035 # Keep the validator's explanation, but not its file and line,
1036 # which point inside Params::Validate::Strict, not at the caller
1037 # The validator may nest its own messages; keep only the innermost.
1038 # Its prefix is matched whole: matching 'validate_strict:' alone
1039 # would also stop inside the caller's value, which the message
1040 # quotes, so lang => 'x validate_strict: y' lost the parameter's
1041 # name and most of the value. Linear: the start is anchored, and
1042 # the digits are possessive
1043 189 (my $reason = $@) =~ s{
1044 \A .* # everything up to the last prefix (greedy: the innermost message)
1045 Params::Validate::Strict\ line\ \d++:\ validate_strict:
1046 \s*+ # and the space after it
1047 }{}sx;
1048 189 $self->_croak('invalid_argument', { reason => _reason($reason) });
1049 }
1050  
1051 5634 ▶ return $valid || {};
Condition100%2/2
$valid || {}
l!l
56295
MC/DC100%1/1
$valid || {}
$valid
Truth table100%2/2
A
A= $valid
Aresult
11
00
1052 }
1053  
1054 # _reason - strip the location from an error message
1055 #
1056 # Purpose: An error raised inside another module names that module's
1057 # file and line; the caller only needs the explanation.
1058 # Entry: $error - error text, such as $@.
1059 # Exit: Returns the text without a trailing ' at FILE line N.', or
1060 # any ' at THIS-FILE line N.' anywhere in it, made safe to
1061 # show by _shown().
1062 251 ▶sub _reason {
Subroutine _reason: called CC=2 SCAR=6.9
1063 251 my $error = shift;
1064  
1065 # (?<!\s) lets a match start only where a run of whitespace starts, and
1066 # the possessive quantifiers never give characters back; so even a huge
1067 # run of spaces is scanned once, not once per space
1068 251 ▶ (my $reason = defined($error) ? "$error" : '') =~ s/(?<!\s)\s++at\ \S++\ line\ \d++\.?\s*+\z//sx;
Branch: 1 branch
BranchTrueFalseTotal
defined $error ? : 249 2 251
1069  
1070 # Another module reports where this file called it, which means nothing
1071 # to our caller, and may do so in the middle of its text
1072 251 $reason =~ s/(?<!\s)\s++at\ \Q${\ __FILE__}\E\ line\ \d++\.?//gx;
1073  
1074 251 return _shown($reason);
1075 }
1076  
1077 # _string - a value as text, without letting overloading die
1078 #
1079 # Purpose: Turn a caller's value into text for a lookup or a message.
1080 # An object's overloaded "" may die or return undef; neither
1081 # may turn a log call, a warning or a translated error into a
1082 # crash, so the form that ignores overloading is used instead.
1083 # Entry: $value - a defined value: a string, number or reference.
1084 # Exit: Returns its text: Perl's normal stringification (objects
1085 # honour overloading), or Class=HASH(0x...) when that dies.
1086 # Side effects: None. Never dies or warns, and leaves $@ alone.
1087 125483 ▶sub _string {
Subroutine _string: called CC=3 SCAR=11.0
1088 125483 my $value = shift;
1089  
1090 # Plain values have no overloading and cannot die when turned into text
1091 125483 ▶ return "$value" if(!ref($value));
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value 125343 140 125483
1092  
1093 140 local $@; # the caught error must not reach the caller
1094 30 ▶ my $text = eval { no warnings 'uninitialized'; my $string = "$value"; $string }; ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
1095  
1096 140 ▶ return defined($text) ? $text : overload::StrVal($value);
Branch: 1 branch
BranchTrueFalseTotal
defined $text ? : 80 60 140
1097 }
1098  
1099 # _repaired - a character string made valid, so that Perl can read it
1100 #
1101 # Purpose: A character string whose bytes are not valid UTF-8 kills a
1102 # regex that reads it as characters ("Malformed UTF-8
1103 # character (fatal)"); lc() dies on it too, and length() and
1104 # substr() warn. A caller can pass one (Encode::_utf8_on() on
1105 # bytes makes one), and no method may die or warn with Perl's
1106 # message because of it.
1107 # Entry: $text - a defined, non-reference value.
1108 # Exit: Returns the text unchanged if it is a byte string or a valid
1109 # character string. Otherwise returns a copy whose bytes have
1110 # been decoded again, leniently: each bad sequence becomes
1111 # U+FFFD, and the result is a valid character string.
1112 # Side effects: None; only the copy changes, never the caller's value or
1113 # what was stored.
1114 244627 ▶sub _repaired {
Subroutine _repaired: called CC=3 SCAR=11.0
1115 244627 my $text = shift;
1116  
1117 # Cheap tests first: a byte string, or valid text, is returned as it is
1118 244627 ▶ return $text if(!utf8::is_utf8($text) || utf8::valid($text));
Branch: 1 branch
BranchTrueFalseTotal
if not utf8::is_utf8($text) or utf8::valid($text) 244565 62 244627
Condition100%3/3
not utf8::is_utf8($text) or utf8::valid($text)
l!l&&r!l&&!r
24431325262
MC/DC100%2/2
not utf8::is_utf8($text) or utf8::valid($text)
not utf8::is_utf8($text) utf8::valid($text)
Truth table100%3/3
not(A) or B
A= not utf8::is_utf8($text)B= utf8::valid($text)
ABresult
1X1
011
000
1119  
1120 62 Encode::_utf8_off($text);
1121 62 return Encode::decode('UTF-8', $text);
1122 }
1123  
1124 # _lc - a caller's name in lower case, for a lookup
1125 #
1126 # Purpose: Level and diag names are matched without regard to case. A
1127 # name may be any string the caller passed: lc() dies on one
1128 # that is not valid UTF-8, and warns on a UTF-16 surrogate.
1129 # Entry: $text - a defined, non-reference value.
1130 # Exit: Returns the text in lower case, repaired by _repaired()
1131 # first if it had to be. A repaired name is never a level
1132 # name, so it fails the lookup, as it should.
1133 # Side effects: None. Never dies or warns.
1134 236101 ▶sub _lc {
Subroutine _lc: called CC=1 SCAR=0.0
1135 236101 my $text = _repaired(shift);
1136  
1137 # 'utf8' covers the surrogate warning; the name is only a lookup key
1138 30 ▶ no warnings 'utf8'; ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
1139 236101 return lc($text);
1140 }
1141  
1142 # _is_a - is a value really the plain reference type it claims to be?
1143 #
1144 # Purpose: ref() reports the class of an object, so bless({}, 'ARRAY')
1145 # says 'ARRAY' while it is a hash, and dereferencing it as an
1146 # array dies with Perl's "Not an ARRAY reference". Every
1147 # option or template that is walked as a hash or an array is
1148 # tested with this first.
1149 # Entry: $value - any value, or undef.
1150 # $type - 'HASH' or 'ARRAY'.
1151 # Exit: Returns true if ref($value) and its underlying type are both
1152 # $type; false otherwise, including for undef.
1153 # Side effects: None.
1154 675839 ▶sub _is_a {
Subroutine _is_a: called CC=2 SCAR=6.9
1155 675839 my ($value, $type) = @_;
1156  
1157 # reftype() is only reached for a reference, so it is never undef here
1158 675839 ▶ return (ref($value) eq $type) && (Scalar::Util::reftype($value) eq $type);
Condition100%3/3
ref $value eq $type && builtin::reftype($value) eq $type
!ll&&!rl&&r
15306057522722
MC/DC100%2/2
ref $value eq $type && builtin::reftype($value) eq $type
ref $value eq $type builtin::reftype($value) eq $type
Truth table100%3/3
A && B
A= ref $value eq $typeB= builtin::reftype($value) eq $type
ABresult
0X0
100
111
1159 }
1160  
1161 # Characters that are written as escapes in printed text. A terminal acts
1162 # on them instead of showing them: ESC (\x1B) starts a control sequence that
1163 # can clear the screen, hide lines or, on some terminals, set the clipboard;
1164 # a newline can start a forged TAP line; and the bidi controls reorder what
1165 # is shown, so the text on screen is not the text that was printed.
1166 30 Readonly::Scalar my $CONTROL => qr/[\x00-\x1F\x7F]/;
1167 # The same, without tab (\x09) and newline (\x0A), for a logged message:
1168 # they lay it out, and Test::Builder starts every line with '#'
1169 30 Readonly::Scalar my $CONTROL_NOT_LAYOUT => qr/[\x00-\x08\x0B-\x1F\x7F]/;
1170 # The C1 controls. U+009B is a one-character CSI that some terminals obey
1171 30 Readonly::Scalar my $C1 => qr/[\x{80}-\x{9F}]/;
1172 # Bidi marks, embeddings, overrides and isolates
1173 30 Readonly::Scalar my $BIDI => qr/[\x{200E}\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}]/;
1174  
1175 # _escape - write control characters as escapes
1176 #
1177 # Purpose: The one place that decides how a control character is shown,
1178 # for _shown() and _printable().
1179 # Entry: $text - a defined string.
1180 # $controls - qr// matching the C0 controls to escape.
1181 # Exit: Returns the text with those controls written as \xHH, and in
1182 # a character string the C1 controls too. In a byte string
1183 # the bytes 0x80 to 0x9F are kept: they are usually part of
1184 # UTF-8 text, which escaping them would mangle. A character
1185 # string that is not valid UTF-8 is returned valid, with
1186 # U+FFFD for each bad sequence.
1187 # Side effects: None.
1188 6336 ▶sub _escape {
Subroutine _escape: called CC=2 SCAR=6.9
1189 6336 my ($text, $controls) = @_;
1190  
1191 6336 $text = _repaired($text);
1192 6336 $text =~ s/($controls)/sprintf('\\x%02X', ord($1))/ge;
1193 6336 ▶ $text =~ s/($C1)/sprintf('\\x%02X', ord($1))/ge if(utf8::is_utf8($text));
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($text) 166 6170 6336
1194  
1195 6336 return $text;
1196 }
1197  
1198 # _printable - make captured text safe to print
1199 #
1200 # Purpose: A logged message, or a level name (AUTOLOAD stores any method
1201 # name), may hold text the test did not write, such as data
1202 # from a fixture. Printed raw, its control characters would
1203 # reach the terminal.
1204 # Entry: $text - the text, or undef.
1205 # Exit: Returns the text with control characters other than tab and
1206 # newline written as \xHH (see _escape()); undef is returned
1207 # as undef. The stored entry is not changed.
1208 # Side effects: None.
1209 3172 ▶sub _printable {
Subroutine _printable: called CC=2 SCAR=6.9
1210 3172 my $text = shift;
1211  
1212 3172 ▶ return defined($text) ? _escape($text, $CONTROL_NOT_LAYOUT) : $text;
Branch: 1 branch
BranchTrueFalseTotal
defined $text ? : 3166 6 3172
1213 }
1214  
1215 # _shown - make a caller's value safe to repeat in an error message
1216 #
1217 # Purpose: An error that repeats what the caller passed must not let
1218 # that value add lines to the output (a newline followed by
1219 # 'ok 5' is a forged TAP result when STDERR is merged into the
1220 # TAP stream), send terminal escape sequences, or make the
1221 # error enormous.
1222 # Entry: $value - the value to show; a string, a reference, or undef.
1223 # Exit: Returns the value with control characters written as \xHH
1224 # (C1 controls too, in a character string; see _escape()) and
1225 # bidi controls as \x{HHHH}, cut to $MAX_REASON characters
1226 # followed by '...' if longer; undef is shown as 'undef'. An
1227 # object whose overloaded "" dies is shown in plain form, as
1228 # Class=HASH(0x...).
1229 # Side effects: None. Never dies.
1230 3099 ▶sub _shown {
Subroutine _shown: called CC=3 SCAR=11.0
1231 3099 my $value = shift;
1232  
1233 3099 ▶ my $text = _escape(defined($value) ? _string($value) : 'undef', $CONTROL);
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 3084 15 3099
1234 # A bidi override would make the error read differently on screen from
1235 # what it says. Unlike the C1 controls, these are above U+00FF, so
1236 # they can only be in a character string, never in UTF-8 bytes.
1237 # _escape() has made any character string valid, so this cannot die
1238 3099 $text =~ s/($BIDI)/sprintf('\\x{%X}', ord($1))/ge;
1239  
1240 3099 ▶ return (length($text) > $MAX_REASON) ? substr($text, 0, $MAX_REASON) . '...' : $text;
Branch: 1 branch
BranchTrueFalseTotal
length $text > $MAX_REASON ? : 42 3057 3099
1241 }
1242  
1243 # _resolve_lang - choose the catalogue for a logger's own messages
1244 #
1245 # Purpose: Apply the documented precedence: lang, country, the POSIX
1246 # locale variables (only for lang => 'auto'), then %config.
1247 # Entry: $options - validated options hash reference.
1248 # Exit: Returns a language tag that has a catalogue (built in, or
1249 # supplied with the i18n option); otherwise $FALLBACK_LANG.
1250 # Side effects: Reads %ENV when the language is 'auto'.
1251 5611 ▶sub _resolve_lang {
Subroutine _resolve_lang: called CC=14 SCAR=26.4
1252 5611 my $options = shift;
1253  
1254 5611 my $tag;
1255 5611 ▶ if(defined($options->{'lang'}) && (lc($options->{'lang'}) ne $LANG_AUTO)) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $options->{'lang'} and lc $options->{'lang'} ne $LANG_AUTO) { } 4178 1433 5611
elsif (defined $options->{'country'}) { } 56 1377 1433
Condition100%3/3
defined $options->{"lang"} and lc $options->{"lang"} ne $LANG_AUTO
!ll&&!rl&&r
1396374178
MC/DC100%2/2
defined $options->{"lang"} and lc $options->{"lang"} ne $LANG_AUTO
defined $options->{"lang"} lc $options->{"lang"} ne $LANG_AUTO
Truth table100%3/3
A and B
A= defined $options->{"lang"}B= lc $options->{"lang"} ne $LANG_AUTO
ABresult
0X0
100
111
1256 4178 $tag = $options->{'lang'};
1257 } elsif(defined($options->{'country'})) {
1258 # exists() first: a Readonly hash croaks on autovivification
1259 56 my $country = uc($options->{'country'});
1260 56 ▶ $tag = exists($COUNTRY_LANG{$country}) ? $COUNTRY_LANG{$country} : $FALLBACK_LANG;
Branch: 1 branch
BranchTrueFalseTotal
exists $COUNTRY_LANG{$country} ? : 51 5 56
1261 } else {
1262 # lang => 'auto' given, or the configured default
1263 1377 ▶ my $wanted = defined($options->{'lang'}) ? $options->{'lang'} : $config{'lang'};
Branch: 1 branch
BranchTrueFalseTotal
defined $options->{'lang'} ? : 31 1346 1377
1264 1377 ▶ my $auto = defined($wanted) && (_lc($wanted) eq $LANG_AUTO);
Condition100%3/3
defined $wanted && _lc($wanted) eq $LANG_AUTO
!ll&&!rl&&r
3134034
MC/DC100%2/2
defined $wanted && _lc($wanted) eq $LANG_AUTO
defined $wanted _lc($wanted) eq $LANG_AUTO
Truth table100%3/3
A && B
A= defined $wantedB= _lc($wanted) eq $LANG_AUTO
ABresult
0X0
100
111
1265  
1266 # The first set variable wins, as in POSIX setlocale()
1267 1376 ▶ ($tag) = $auto ? (grep { defined($_) && length($_) } map { $ENV{$_} } @LOCALE_VARS) : ($wanted);
Branch: 1 branch
BranchTrueFalseTotal
$auto ? : 34 1342 1376
Condition100%3/3
defined $_ && length $_
!ll&&!rl&&r
71229
MC/DC100%2/2
defined $_ && length $_
defined $_ length $_
Truth table100%3/3
A && B
A= defined $_B= length $_
ABresult
0X0
100
111
1268 }
1269  
1270 # 'de_DE.UTF-8' -> 'de'; the C and POSIX locales are English
1271 5610 ▶ my ($lang) = (_lc(defined($tag) ? $tag : '') =~ /\A([a-z]{2,3})(?![a-z])/);
Branch: 1 branch
BranchTrueFalseTotal
defined $tag ? : 5599 11 5610
1272 5609 ▶ my $known = defined($lang) && (exists($MESSAGES{$lang}) || (_is_a($options->{'i18n'}, 'HASH') && $options->{'i18n'}->{$lang}));
Condition100%9/9
defined $lang && (exists $MESSAGES{$lang} || _is_a($options->{'i18n'}, 'HASH') && $options->{'i18n'}{$lang})
!ll&&!rl&&r
22165571
exists $MESSAGES{$lang} or _is_a($options->{"i18n"}, "HASH") and $options->{"i18n"}{$lang}
l!l&&r!l&&!r
5564716
_is_a($options->{"i18n"}, "HASH") and $options->{"i18n"}{$lang}
!ll&&!rl&&r
1337
MC/DC100%4/4
defined $lang && (exists $MESSAGES{$lang} || _is_a($options->{'i18n'}, 'HASH') && $options->{'i18n'}{$lang})
defined $lang exists $MESSAGES{$lang} _is_a($options->{"i18n"}, "HASH") $options->{"i18n"}{$lang}
Truth table100%5/5
A && B or C and D
A= defined $langB= exists $MESSAGES{$lang}C= _is_a($options->{"i18n"}, "HASH")D= $options->{"i18n"}{$lang}
ABCDresult
0XXX0
100X0
10100
11XX1
10111
1273  
1274 5609 ▶ return $known ? $lang : $FALLBACK_LANG;
Branch: 1 branch
BranchTrueFalseTotal
$known ? : 5571 38 5609
1275 }
1276  
1277 # _diag_rule - normalise the diag option into an internal rule
1278 #
1279 # Purpose: Validate the diag option once, at construction time.
1280 # Entry: $self - the logger being built (for its language).
1281 # $spec - 'all', 'none', a level name, or an array reference
1282 # of level names.
1283 # Exit: Returns { all => 1 }, { levels => {...} },
1284 # { threshold => $severity }, or {} for 'none'.
1285 # Side effects: Croaks on anything unrecognised: a silent typo in a test's
1286 # diag option would otherwise hide log output forever.
1287 5109 ▶sub _diag_rule {
Subroutine _diag_rule: called CC=7 SCAR=19.5
1288 5109 my ($self, $spec) = @_;
1289  
1290 5109 ▶ $spec = $config{'diag'} if(!defined($spec));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec 165 4944 5109
1291  
1292 5109 ▶ return { levels => { map { $self->_diag_level($_) => 1 } @{$spec} } } if(_is_a($spec, 'ARRAY'));
Branch: 1 branch
BranchTrueFalseTotal
if _is_a($spec, "ARRAY") 52 5057 5109
1293  
1294 5057 ▶ $self->_croak('invalid_diag_type') if(ref($spec));
Branch: 1 branch
BranchTrueFalseTotal
if ref $spec 22 5035 5057
1295  
1296 # 'all' and 'none' are matched without regard to case, as level names
1297 # are. An undefined default must reach _diag_level(), which reports it:
1298 # Premise 1: '' is neither 'all' nor 'none'.
1299 # Premise 2: undef is compared as '', so it is neither either.
1300 # So: one comparison each, with no defined() test before it.
1301 5035 ▶ my $name = defined($spec) ? _lc($spec) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $spec ? : 5030 5 5035
1302 5035 ▶ return {} if($name eq $DIAG_NONE);
Branch: 1 branch
BranchTrueFalseTotal
if $name eq $DIAG_NONE 2772 2263 5035
1303 2263 ▶ return { all => 1 } if($name eq $DIAG_ALL);
Branch: 1 branch
BranchTrueFalseTotal
if $name eq $DIAG_ALL 2059 204 2263
1304  
1305 204 return { threshold => $SEVERITY{$self->_diag_level($spec)} };
1306 }
1307  
1308 # _diag_level - check one level name given to the diag option
1309 #
1310 # Purpose: Shared by the list and single-name forms of the diag option,
1311 # so both reject a bad name with the same message.
1312 # Entry: $self - the logger being built (for its language).
1313 # $level - the name as given, or undef.
1314 # Exit: Returns the name in lower case.
1315 # Side effects: Croaks with 'invalid_diag_level' if it is not a level name.
1316 # 'undef' is not one, so an undefined name fails the same test
1317 # as any other bad name, and is reported as 'undef'.
1318 100325 ▶sub _diag_level {
Subroutine _diag_level: called CC=3 SCAR=11.0
1319 100325 my ($self, $level) = @_;
1320  
1321 # Through _string(), so that an object whose overloading dies is
1322 # reported, not allowed to crash the constructor with its own error
1323 100325 ▶ my $name = defined($level) ? _lc(_string($level)) : 'undef';
Branch: 1 branch
BranchTrueFalseTotal
defined $level ? : 100314 11 100325
1324 100325 ▶ $self->_croak('invalid_diag_level', { level => _shown($level) }) if(!exists($SEVERITY{$name}));
Branch: 1 branch
BranchTrueFalseTotal
unless exists $SEVERITY{$name} 75 100250 100325
1325  
1326 100250 return $name;
1327 }
1328  
1329 =head2 trace, debug, info, notice, warn, error, fatal, critical, alert, emergency
1330  
1331 Store a message at this level.
1332  
1333 =head3 Purpose
1334  
1335 These are the methods that the code under test calls to log something.
1336 There is one method for each L<Log::Abstraction> level, and one for each
1337 syslog name: C<warning>, C<err>, C<crit>, C<emerg>, C<panic> and
1338 C<informational>. Each method stores the message under the name that was
1339 called, and may print it (see L</Which messages are printed>).
1340  
1341 By default:
1342  
1343 =over 4
1344  
1345 =item * C<trace>, C<debug>, C<info>, C<informational>, C<notice> - stored,
1346 not printed.
1347  
1348 =item * C<warn>, C<warning>, C<error>, C<err>, C<critical>, C<crit>,
1349 C<fatal>, C<alert>, C<emergency>, C<emerg>, C<panic> - stored and printed.
1350  
1351 =back
1352  
1353 =head3 Args
1354  
1355 Any list of values. They are turned into one message like this:
1356  
1357 =over 4
1358  
1359 =item * With no values at all, C<warn> and the more serious levels
1360 (C<warning>, C<error>, C<err>, C<critical>, C<crit>, C<fatal>, C<alert>,
1361 C<emergency>, C<emerg>, C<panic>) store nothing, as in L<Log::Abstraction>.
1362 The less serious levels (C<trace>, C<debug>, C<info>, C<informational>,
1363 C<notice>) store an empty message, as L<Log::Abstraction> does.
1364  
1365 =item * All the values are joined together, with nothing between them.
1366  
1367 =item * One newline at the end is removed.
1368  
1369 =item * If the only value is an array reference, its items are the parts
1370 of the message.
1371  
1372 =item * If there are two or more values and the last one is a hash
1373 reference, that hash is not part of the message. A copy of it is stored as
1374 C<fields>. An empty hash is dropped. A tied hash that dies when it is
1375 read cannot be copied, so it stays in the message, written in Perl's
1376 plain form (C<HASH(0x...)>), and the log call still works.
1377  
1378 =item * A hash reference in the message is written as
1379 C<{key =E<gt> value, ...}>, with the keys sorted. An array reference is
1380 written as C<[a, b]>. So you can match their contents.
1381  
1382 =item * C<undef> is written as the text C<undef>. There is no warning.
1383  
1384 =item * An object is written as Perl normally writes it. If the object
1385 has its own text form (overloaded C<"">), that form is used. If that text
1386 form dies, the object is written in Perl's plain form, such as
1387 C<My::Class=HASH(0x55d0c8a1e2f8)>, and the log call still works.
1388  
1389 =item * A structure that contains itself is written as C<(cycle)> at the
1390 point where it repeats.
1391  
1392 =back
1393  
1394 =head3 Returns
1395  
1396 The logger, as in L<Log::Abstraction>. So you can chain calls:
1397 C<< $logger->info('a')->info('b') >>.
1398  
1399 =head3 Side Effects
1400  
1401 Adds one entry to the stored messages (none for a call with no values at
1402 C<warn> or above; see L</Args>). May print the message. The
1403 variables C<$@> and C<$!> are not changed. So you can log inside an error
1404 handler without losing the error.
1405  
1406 =head3 EXAMPLE
1407  
1408 $logger->warn('something looks wrong');
1409 $logger->warn('file ', $name, ' is empty'); # joined: one message
1410 $logger->info('started', { pid => $$ }); # message + fields
1411 $logger->error({ error => 'cannot open file' }); # hash as the message
1412 $logger->debug(['part 1, ', 'part 2']); # array of parts
1413  
1414 =head3 API SPECIFICATION
1415  
1416 =head4 Input
1417  
1418 {
1419 messages => { type => 'arrayref', position => 0, slurp => 1 },
1420 }
1421  
1422 Domains: any number of arguments (0 gives an empty message) of any
1423 kind and length. Exactly one trailing newline is removed (so "m\n\n"
1424 keeps one). A trailing hash after one or more values is fields; an empty
1425 one is dropped; a blessed hash is part of the message. Text may be ASCII,
1426 decoded text in any script (accents, CJK, emoji and emoji sequences,
1427 combining marks, right-to-left text, zero-width characters) or bytes; it
1428 is stored with its length unchanged. See L</ENCODING> for how it is
1429 printed. Hashes and arrays are rendered to any depth, in time linear in
1430 their size. A part that cannot be read (a tied value whose FETCH dies) is
1431 shown as its tie object's plain form; an element of a tied array or hash
1432 has no tie object of its own, so it is shown as the plain form of a
1433 reference to it, such as SCALAR(0x...). An argument such as
1434 substr($s, 10) that is out of range is undef, with no warning. A
1435 reference that is not really the type it claims, such as
1436 bless({}, 'ARRAY'), is shown in Perl's plain form.
1437  
1438 =head4 Output
1439  
1440 { type => 'object', isa => 'Test::Log::Abstraction' }
1441  
1442 =head3 MESSAGES
1443  
1444 Message Meaning What to do
1445 ------------------------------ ---------------------------- ------------------------------
1446 X() must be called on an not called on a logger Call it on a logger object
1447 object, not on the class (croak)
1448  
1449 =cut
1450  
1451 # Generate the level methods. Each is a thin wrapper over _record, and they
1452 # exist as real methods so that AUTOLOAD only sees genuinely unknown names
1453 30 foreach my $level (keys %SEVERITY) {
1454 480 my $ignore_empty = ($SEVERITY{$level} <= $NEEDS_ARGUMENTS);
1455 30 ▶ no strict 'refs'; ## no critic (ProhibitNoStrict)
Subroutine BEGIN: called CC=1 SCAR=0.0
1456 480 ▶ *{$level} = sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1457 116284 my $self = _object(shift, $level);
1458 116185 ▶ return ($ignore_empty && !@_) ? $self : $self->_record($level, \@_);
Branch: 1 branch
BranchTrueFalseTotal
$ignore_empty && !@_ ? : 30 116155 116185
Condition100%3/3
$ignore_empty and not @_
!ll&&!rl&&r
113622253330
MC/DC100%2/2
$ignore_empty and not @_
$ignore_empty not @_
Truth table100%3/3
A and not(B)
A= $ignore_emptyB= not @_
ABresult
0X0
100
111
1459 480 };
1460 }
1461  
1462 =head2 is_trace, is_debug, is_info, is_notice, is_warn, is_error, is_critical, is_alert, is_emergency
1463  
1464 Ask if a level is turned on.
1465  
1466 =head3 Purpose
1467  
1468 Some code only builds a log message if the level is turned on, for
1469 example C<< if($logger->is_debug()) { ... } >>. These methods answer that
1470 question, as L<Log::Abstraction> does.
1471  
1472 =head3 Args
1473  
1474 None.
1475  
1476 =head3 Returns
1477  
1478 1 if the level is turned on, otherwise 0. A level is turned on when its
1479 number is the same as, or lower than, the logger's level (see L</level>).
1480 The default level is C<trace>, so all these methods return 1.
1481  
1482 =head3 Side Effects
1483  
1484 None.
1485  
1486 =head3 EXAMPLE
1487  
1488 $logger->level('warning');
1489 $logger->is_warn(); # 1
1490 $logger->is_error(); # 1 (more serious than warning)
1491 $logger->is_info(); # 0 (less serious than warning)
1492  
1493 =head3 API SPECIFICATION
1494  
1495 =head4 Input
1496  
1497 {}
1498  
1499 Domains: no arguments. Each predicate is 1 exactly when its level's
1500 number is at or below the logger's level: at level 0 (emergency) only
1501 is_emergency is 1; at level 7 (trace) all are 1.
1502  
1503 =head4 Output
1504  
1505 { type => 'boolean' }
1506  
1507 =head3 MESSAGES
1508  
1509 Message Meaning What to do
1510 ------------------------------ ---------------------------- ------------------------------
1511 is_X() must be called on an not called on a logger Call it on a logger object
1512 object, not on the class (croak)
1513  
1514 =cut
1515  
1516 30 foreach my $level (@PREDICATES) {
1517 270 my $method = "is_$level";
1518 30 ▶ no strict 'refs'; ## no critic (ProhibitNoStrict)
Subroutine BEGIN: called CC=1 SCAR=0.0
1519 270 ▶ *{$method} = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1520 322 my $self = shift;
1521 322 ▶ return (_object($self, $method)->{'level'} >= $SEVERITY{$level}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
_object($self, $method)->{'level'} >= $SEVERITY{$level} ? : 182 107 289
1522 270 };
1523 }
1524  
1525 # _object - insist on an object invocant
1526 #
1527 # Purpose: Turn a class-method call such as
1528 # Test::Log::Abstraction->warn() into a clear error, rather
1529 # than Perl's "Can't use string as a HASH ref".
1530 # Entry: $self - the invocant.
1531 # $method - the public method's name, for the message.
1532 # Exit: Returns $self, for chaining.
1533 # Side effects: Croaks with 'class_invocant' unless $self is an object of
1534 # this class or a subclass.
1535 126890 ▶sub _object { ## no critic (RequireFinalReturn): ends in _croak(), which never returns
Subroutine _object: called CC=4 SCAR=13.9
1536 126890 my ($self, $method) = @_;
1537  
1538 # Called as a function, because the invocant may be undef, an unblessed
1539 # reference or another class's object, none of which can call methods
1540 126890 ▶ return $self if(Scalar::Util::blessed($self) && $self->isa(__PACKAGE__));
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($self) and $self->isa(__PACKAGE__) 126550 340 126890
Condition100%3/3
builtin::blessed($self) and $self->isa(__PACKAGE__)
!ll&&!rl&&r
27961126550
MC/DC100%2/2
builtin::blessed($self) and $self->isa(__PACKAGE__)
builtin::blessed($self) $self->isa(__PACKAGE__)
Truth table100%3/3
A and B
A= builtin::blessed($self)B= $self->isa(__PACKAGE__)
ABresult
0X0
100
111
1541  
1542 # Only on failure: which class to name in the message. A subclass's
1543 # name is named; anything else gives this class.
1544 # Premise 1: an object of this class (or a subclass) returned above.
1545 # Premise 2: UNIVERSAL::isa() is false, without a warning, for undef,
1546 # an unblessed reference and another class's object.
1547 # So: isa() alone is true only for a class name, and needs no
1548 # defined() or ref() test in front of it.
1549 340 ▶ my $class = UNIVERSAL::isa($self, __PACKAGE__) ? $self : __PACKAGE__;
Branch: 1 branch
BranchTrueFalseTotal
UNIVERSAL::isa($self, __PACKAGE__) ? : 134 206 340
1550 340 _croak($class, 'class_invocant', { method => _shown($method) });
1551 }
1552  
1553 # _record - capture one logged message
1554 #
1555 # Purpose: The single place every level method ends up.
1556 # Entry: $self - this logger.
1557 # $level - level name as called by the code under test.
1558 # $args - array reference of the log call's arguments.
1559 # Exit: Returns $self, for chaining.
1560 # Side effects: Pushes an entry onto the capture and prints it when the
1561 # diag rule allows. Localises $@ and $! so that the caller's
1562 # error state survives, as Log::Abstraction does.
1563 118316 ▶sub _record {
Subroutine _record: called CC=2 SCAR=6.9
1564 118316 my ($self, $level, $args) = @_;
1565  
1566 118316 local ($@, $!);
1567 118316 my $entry = _entry(_lc($level), $args);
1568 118313 push @{$self->{'messages'}}, $entry;
1569 # Printed through _printable(): the message may hold text the test did
1570 # not write. The stored entry keeps it as it was
1571 118313 ▶ $self->_emit(_printable($entry->{'message'})) if($self->_diags($entry->{'level'}));
Branch: 1 branch
BranchTrueFalseTotal
if $self->_diags($entry->{"level"}) 2457 115856 118313
1572  
1573 118303 return $self;
1574 }
1575  
1576 # _entry - turn a log call's arguments into a captured entry
1577 #
1578 # Purpose: Mirror Log::Abstraction's argument handling, but render
1579 # references readably instead of as HASH(0x...).
1580 # Entry: $level - lower-cased level name.
1581 # $args - array reference of the arguments.
1582 # Exit: Returns { level, message } plus 'fields' when a non-empty
1583 # hash reference followed one or more other arguments.
1584 # Side effects: None; the caller's arrays and hashes are not modified, and
1585 # the fields hash is copied so that later changes to it by the
1586 # caller cannot rewrite the captured history. Never dies, and
1587 # leaves $@ alone.
1588 118369 ▶sub _entry {
Subroutine _entry: called CC=15 SCAR=27.1
1589 118369 my ($level, $args) = @_;
1590  
1591 118369 my $entry = { level => $level };
1592 118369 local $@; # reading and rendering below may fail, inside eval; the caller's $@ stays
1593  
1594 # Copying the arguments reads them, and a tied scalar whose FETCH dies
1595 # would kill the log call. Each argument must also be read exactly
1596 # once: a tied one may give a new value on every read, and the entry
1597 # must hold the value at the moment it was logged. So the copy goes
1598 # one argument at a time, inside one eval for the usual case; push()
1599 # appends nothing when the read dies, so after a failure @args holds
1600 # exactly the arguments already read, and the copy resumes after the
1601 # one that died, which is shown as its tie object's plain form. An
1602 # element of a tied array or hash has no tie object of its own, so it
1603 # is shown as the plain form of a reference to it: undef would warn in
1604 # overload::StrVal(), and the part would vanish from the message
1605 # An argument such as substr($s, 10) is only evaluated when it is read,
1606 # here, and warns "substr outside of string" at this line; the mistake
1607 # is the caller's, and logging must not warn, so the read is silent and
1608 # the part is undef, shown as 'undef'. Nothing after this in the
1609 # routine uses substr()
1610 30 ▶ no warnings 'substr'; ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
1611 118369 my @args;
1612 118369 ▶ while(@args < @{$args}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args < @{$args;}) 118358 44 118402
1613 118358 ▶ last if(eval { push @args, $args->[$_] foreach scalar(@args) .. $#{$args}; 1 });
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { push @args, $args->[$_] foreach (scalar @args .. $#{$args;}); 1 } } 118325 33 118358
1614 33 my $tie = tied($args->[scalar(@args)]);
1615 33 ▶ push @args, overload::StrVal(defined($tie) ? $tie : \$args->[scalar(@args)]);
Branch: 1 branch
BranchTrueFalseTotal
defined $tie ? : 31 2 33
1616 }
1617  
1618 # A trailing plain hash after the message is structured fields. A tied
1619 # hash can die when it is read, and logging must not; one that cannot
1620 # be copied is put back as a message part, which is then shown in
1621 # Perl's plain form like any other part that cannot be rendered
1622 118369 ▶ if((@args >= 2) && (ref($args[-1]) eq 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args >= 2 and ref $args[-1] eq "HASH") 2149 116220 118369
Condition100%3/3
@args >= 2 and ref $args[-1] eq "HASH"
!ll&&!rl&&r
1160931272149
MC/DC100%2/2
@args >= 2 and ref $args[-1] eq "HASH"
@args >= 2 ref $args[-1] eq "HASH"
Truth table100%3/3
A and B
A= @args >= 2B= ref $args[-1] eq "HASH"
ABresult
0X0
100
111
1623 2149 my $fields = pop @args;
1624 2149 my $copy = eval { +{ %{$fields} } };
1625 2149 ▶ if(!$copy) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $copy) { } 5 2144 2149
elsif (%{$copy;}) { } 2138 6 2144
1626 5 push @args, $fields;
1627 2144 } elsif(%{$copy}) {
1628 2138 $entry->{'fields'} = $copy;
1629 }
1630 }
1631  
1632 # A lone array reference is a list of message parts. Reading it may
1633 # die: a tied array whose FETCHSIZE dies, or bless({}, 'ARRAY'), which
1634 # says it is an array but is not. Then it stays one part, which is
1635 # shown in Perl's plain form below
1636 118369 ▶ if((@args == 1) && (ref($args[0]) eq 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
if (@args == 1 and ref $args[0] eq "ARRAY") 18 118351 118369
Condition100%3/3
@args == 1 and ref $args[0] eq "ARRAY"
!ll&&!rl&&r
16411818718
MC/DC100%2/2
@args == 1 and ref $args[0] eq "ARRAY"
@args == 1 ref $args[0] eq "ARRAY"
Truth table100%3/3
A and B
A= @args == 1B= ref $args[0] eq "ARRAY"
ABresult
0X0
100
111
1637 18 my @parts;
1638 18 ▶ @args = @parts if(eval { @parts = @{$args[0]}; 1 });
Branch: 1 branch
BranchTrueFalseTotal
if eval { do { @parts = @{$args[0];}; 1 } } 10 8 18
1639 }
1640  
1641 # A part that cannot be rendered at all (a tied hash whose FETCH dies,
1642 # say) is shown in Perl's plain form, so that logging never dies
1643 # Only a reference can fail to render (overloading, a tied container);
1644 # a plain value is already a copy, read once, so it needs no eval
1645 my $message = join('', map {
1646 118369 my $part = $_;
1647 !ref($part) ? (defined($part) ? $part : 'undef')
1648 228540 ▶ : do { my $text = eval { _stringify($part, {}) }; defined($text) ? $text : overload::StrVal($part) }
Branch: 3 branches
BranchTrueFalseTotal
!ref($part) ? : 228443 97 228540
defined $part ? : 228430 13 228443
defined $text ? : 86 11 97
1649 } @args);
1650  
1651 # Remove one trailing newline. chomp() obeys $/, which the code under
1652 # test may have changed, so it is fixed here; and unlike s/// or
1653 # substr(), chomp() does not warn on a malformed UTF-8 string in Perl
1654 # 5.36 and earlier. $/ stays fixed until the routine returns, with no
1655 # block around it: nothing after the chomp() reads $/, and local()
1656 # restores the caller's value on return
1657 118369 local $/ = "\n";
1658 118369 chomp($message);
1659 118369 $entry->{'message'} = $message;
1660  
1661 118369 return $entry;
1662 }
1663  
1664 # _stringify - render any value as a readable string
1665 #
1666 # Purpose: Stringify log arguments without warnings or fatals.
1667 # Entry: $value - scalar, undef, or any reference.
1668 # $seen - hash reference of reference addresses being
1669 # rendered further up this call chain.
1670 # Exit: Returns a string: 'undef' for undef, '{k => v}' for a plain
1671 # hash, '[a, b]' for a plain array, $CYCLE for a reference
1672 # that contains itself, and Perl's normal stringification
1673 # otherwise (objects honour overloading).
1674 # Side effects: None. $seen is restored on return. Never warns, and an
1675 # object whose overloaded "" dies is shown as Class=HASH(...).
1676 # A tied container whose FETCH dies does die; the caller
1677 # catches that and shows the whole part in plain form.
1678 131 ▶sub _stringify {
Subroutine _stringify: called CC=1 SCAR=0.0
1679 131 my ($value, $seen) = @_;
1680  
1681 # One buffer for the whole rendering. Built by returning strings, each
1682 # level copied everything below it into a new string: quadratic in the
1683 # depth, 11 seconds for a hash nested 80,000 deep
1684 131 my $text = '';
1685 131 _render($value, $seen, \$text);
1686  
1687 120 return $text;
1688 }
1689  
1690 # _render - append the rendering of one value to a buffer
1691 #
1692 # Purpose: The recursive part of _stringify(), linear in the size of
1693 # what it renders.
1694 # Entry: $value - scalar, undef, or any reference.
1695 # $seen - as for _stringify().
1696 # $out - scalar reference to the buffer to append to.
1697 # Exit: Returns nothing useful.
1698 # Side effects: Appends to ${$out}. $seen is restored on return.
1699 315833 ▶sub _render {
Subroutine _render: called CC=8 SCAR=20.8
1700 315833 my ($value, $seen, $out) = @_;
1701  
1702 # Deeply nested data is legitimate; Perl's warning at depth 100 is noise
1703 30 ▶ no warnings 'recursion'; ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
1704  
1705 # Plain values, objects and other references: Perl's own form, through
1706 # _string() so that an overloaded "" that dies cannot break a log call.
1707 # Only plain hashes and arrays are written out as data; through _is_a(),
1708 # as bless({}, 'ARRAY') says 'ARRAY' but cannot be walked as one
1709 315831 my $hash = _is_a($value, 'HASH');
1710 315831 ▶ if(!$hash && !_is_a($value, 'ARRAY')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hash or _is_a($value, "ARRAY")) 10127 305704 315831
Condition100%3/3
$hash or _is_a($value, "ARRAY")
l!l&&r!l&&!r
20034710535710127
MC/DC100%2/2
$hash or _is_a($value, "ARRAY")
$hash _is_a($value, "ARRAY")
Truth table100%3/3
A or B
A= $hashB= _is_a($value, "ARRAY")
ABresult
1X1
011
000
1711 10127 ▶ ${$out} .= defined($value) ? _string($value) : 'undef';
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 10120 7 10127
1712 10127 return;
1713 }
1714  
1715 # A structure that contains itself would otherwise recurse forever
1716 305704 my $address = Scalar::Util::refaddr($value);
1717 305704 ▶ if($seen->{$address}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen->{$address}) 14 305690 305704
1718 14 ${$out} .= $CYCLE;
1719 14 return;
1720 }
1721 305690 local $seen->{$address} = 1;
1722  
1723 305690 my $separator = '';
1724 305690 ▶ if($hash) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hash) { } 200341 105349 305690
1725 200341 ${$out} .= '{';
1726 200341 foreach my $key (sort keys %{$value}) {
1727 200334 ${$out} .= "$separator$key => ";
1728 200334 _render($value->{$key}, $seen, $out);
1729 200333 $separator = ', ';
1730 }
1731 200334 ${$out} .= '}';
1732 } else {
1733 105349 ${$out} .= '[';
1734 105349 foreach my $item (@{$value}) {
1735 115360 ${$out} .= $separator;
1736 115360 _render($item, $seen, $out);
1737 115358 $separator = ', ';
1738 }
1739 105344 ${$out} .= ']';
1740 }
1741  
1742 305678 return;
1743 }
1744  
1745 # _diags - should this level be printed?
1746 #
1747 # Purpose: One decision per message, from the diag rule and verbosity.
1748 # Entry: $self - this logger.
1749 # $level - the lower-cased level name.
1750 # Exit: Returns 1 if the message should go to TAP diagnostics, else 0.
1751 # Side effects: None. An unknown level has no severity, so a threshold rule
1752 # never prints it; AUTOLOAD prints its own notice for those.
1753 118384 ▶sub _diags {
Subroutine _diags: called CC=8 SCAR=20.8
1754 118384 my ($self, $level) = @_;
1755  
1756 118384 my $rule = $self->{'diag_rule'};
1757  
1758 # Any one of four reasons is enough to print, so they are joined with
1759 # || and stop at the first that holds: verbose or 'all' print everything;
1760 # a list prints just its levels; a threshold prints known levels at least
1761 # that severe. This runs for every message, so the cheap tests go first.
1762 return ($self->{'verbose'}
1763 || $rule->{'all'}
1764 || ($rule->{'levels'} && $rule->{'levels'}->{$level})
1765 118384 ▶ || (defined($rule->{'threshold'}) && exists($SEVERITY{$level}) && ($SEVERITY{$level} <= $rule->{'threshold'}))) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'verbose'} || $rule->{'all'} || $rule->{'levels'} && $rule->{'levels'}{$level} || defined $rule->{'threshold'} && exists $SEVERITY{$level} && $SEVERITY{$level} <= $rule->{'threshold'} ? : 2515 115869 118384
Condition100%18/18
$self->{"verbose"} or $rule->{"all"} or $rule->{"levels"} and $rule->{"levels"}{$level} or defined $rule->{"threshold"} and exists $SEVERITY{$level} and $SEVERITY{$level} <= $rule->{"threshold"}
l!l&&r!l&&!r
2410105115869
$self->{"verbose"} or $rule->{"all"} or $rule->{"levels"} and $rule->{"levels"}{$level}
l!l&&r!l&&!r
237733115974
$self->{"verbose"} or $rule->{"all"}
l!l&&r!l&&!r
2172160116007
$rule->{"levels"} and $rule->{"levels"}{$level}
!ll&&!rl&&r
1158878733
defined $rule->{"threshold"} and exists $SEVERITY{$level} and $SEVERITY{$level} <= $rule->{"threshold"}
!ll&&!rl&&r
11580366105
defined $rule->{"threshold"} and exists $SEVERITY{$level}
!ll&&!rl&&r
1157994171
MC/DC100%7/7
$self->{"verbose"} or $rule->{"all"} or $rule->{"levels"} and $rule->{"levels"}{$level} or defined $rule->{"threshold"} and exists $SEVERITY{$level} and $SEVERITY{$level} <= $rule->{"threshold"}
$self->{"verbose"} $rule->{"all"} $rule->{"levels"} $rule->{"levels"}{$level} defined $rule->{"threshold"} exists $SEVERITY{$level} $SEVERITY{$level} <= $rule->{"threshold"}
Truth table72%8/11
A or B or C and D or E and F and G
A= $self->{"verbose"}B= $rule->{"all"}C= $rule->{"levels"}D= $rule->{"levels"}{$level}E= defined $rule->{"threshold"}F= exists $SEVERITY{$level}G= $SEVERITY{$level} <= $rule->{"threshold"}
ABCDEFGresult
1XXXXXX1
01XXXXX1
0011XXX1
000X1111
00101111
000X0XX0
000X10X0
000X1100
00100XX0
001010X0
00101100
1766 }
1767  
1768 =head2 AUTOLOAD
1769  
1770 Handle a call to a method that does not exist.
1771  
1772 =head3 Purpose
1773  
1774 Perl calls this when the code under test calls a method that this class
1775 does not have - usually a misspelt level, such as C<wran>. Any name
1776 works, even an empty one (C<< $logger->$name() >> with C<$name = ''>). Instead of
1777 stopping the test, the message is stored under the name that was called,
1778 and a notice is printed. The notice is always printed, whatever the
1779 C<diag> setting, so the mistake is not hidden.
1780  
1781 =head3 Args
1782  
1783 The same as a level method.
1784  
1785 =head3 Returns
1786  
1787 The logger.
1788  
1789 =head3 Side Effects
1790  
1791 Adds one entry, with the called name as its level. Prints
1792 C<no method 'name'>.
1793  
1794 =head3 EXAMPLE
1795  
1796 $logger->wran('oops'); # stored at level 'wran'; a notice is printed
1797 is($logger->count('wran'), 1, 'the misspelt call was stored');
1798  
1799 =head3 API SPECIFICATION
1800  
1801 =head4 Input
1802  
1803 {
1804 messages => { type => 'arrayref', position => 0, slurp => 1 },
1805 }
1806  
1807 Domains: any method name, including '', non-ASCII names and very long
1808 names. The message is stored under the name in lower case, in full. The
1809 notice shows the name escaped and cut: up to 200 characters it is shown
1810 whole, and from 201 on it is cut to 200 followed by '...' (see
1811 L</DIAGNOSTICS>). The length is counted in characters, not bytes. A
1812 name that is a character string but not valid UTF-8 is stored with U+FFFD
1813 in place of each bad part, and is found again by count() and has_level()
1814 under the same name.
1815  
1816 =head4 Output
1817  
1818 { type => 'object', isa => 'Test::Log::Abstraction' }
1819  
1820 =head3 MESSAGES
1821  
1822 Message Meaning What to do
1823 ------------------------------ ---------------------------- ------------------------------
1824 no method 'X' X is not a method or a level Fix the method name
1825 (notice; the test goes on)
1826 (X is shown escaped and cut;
1827 see DIAGNOSTICS)
1828 X() must be called on an an unknown method was called Call it on a logger object
1829 object, not on the class on the class name (croak)
1830  
1831 =cut
1832  
1833 2184 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=1 SCAR=0.0
1834 # Only the invocant is taken off. Copying the rest into a lexical
1835 # would read each one here, outside the eval that _entry() reads them
1836 # in, so a tied argument whose FETCH dies would kill the call; and it
1837 # would read a tied argument twice
1838 2184 my $self = shift;
1839  
1840 # A method name can be anything, even empty: $logger->$name() with ''.
1841 # Premise 1: Perl always sets $AUTOLOAD to "Package::name".
1842 # Premise 2: ([^:]*) matches any name after the last '::', even ''.
1843 # So: $name is always defined, and needs no fallback.
1844 # A name that is not valid UTF-8 panics the match ("pp_match start/end
1845 # pointers"), so it is repaired first; its bad bytes become U+FFFD
1846 2184 my ($name) = (_repaired($AUTOLOAD) =~ /::([^:]*)\z/);
1847 2183 _object($self, $name)->_record($name, \@_);
1848  
1849 # The name is the caller's, so it may hold control characters or be
1850 # huge; the notice repeats it escaped and cut, as every error does
1851 2168 return $self->_emit($self->i18n('no_method', { method => _shown($name) }));
1852 }
1853  
1854 # Defined so that object destruction never reaches AUTOLOAD
1855 5 ▶sub DESTROY { }
Subroutine DESTROY: called CC=1 SCAR=0.0
1856  
1857 =head2 messages
1858  
1859 Get the stored messages.
1860  
1861 =head3 Purpose
1862  
1863 Let your test look at everything that was logged.
1864  
1865 =head3 Args
1866  
1867 None.
1868  
1869 =head3 Returns
1870  
1871 A reference to a new array. It has one hash reference for each message,
1872 oldest first. Each hash has these keys:
1873  
1874 =over 4
1875  
1876 =item * C<level> - the level name, in lower case, as it was called.
1877  
1878 =item * C<message> - the message text.
1879  
1880 =item * C<fields> - only when fields were given: a hash reference.
1881  
1882 =back
1883  
1884 The array is a copy, as in L<Log::Abstraction>. Adding or removing items
1885 in it does not change the stored messages. But the hashes in it are the
1886 stored hashes (see L</COMMON PITFALLS>).
1887  
1888 =head3 Side Effects
1889  
1890 None.
1891  
1892 =head3 EXAMPLE
1893  
1894 foreach my $entry (@{ $logger->messages() }) {
1895 diag("$entry->{level}: $entry->{message}");
1896 }
1897  
1898 my $first = $logger->messages()->[0];
1899 is($first->{level}, 'warn', 'the first message is a warning');
1900  
1901 =head3 API SPECIFICATION
1902  
1903 =head4 Input
1904  
1905 {}
1906  
1907 Domains: no arguments; any that are given are ignored.
1908  
1909 =head4 Output
1910  
1911 { type => 'arrayref' }
1912  
1913 =head3 MESSAGES
1914  
1915 Message Meaning What to do
1916 ------------------------------ ---------------------------- ------------------------------
1917 messages() must be called on not called on a logger Call it on a logger object
1918 an object, not on the class (croak)
1919  
1920 =cut
1921  
1922 1043 ▶sub messages {
Subroutine messages: called CC=1 SCAR=0.0
Pod documented
1923 1043 my $self = shift;
1924  
1925 1043 return [ @{_object($self, 'messages')->{'messages'}} ];
1926 }
1927  
1928 =head2 clear
1929  
1930 Delete all stored messages.
1931  
1932 =head3 Purpose
1933  
1934 Start again with an empty list, for example between two steps of a test.
1935  
1936 =head3 Args
1937  
1938 None.
1939  
1940 =head3 Returns
1941  
1942 The logger, so you can chain calls.
1943  
1944 =head3 Side Effects
1945  
1946 All stored messages are deleted. The settings (C<verbose>, C<level>,
1947 C<diag>, language) do not change. On a logger with no messages, it does
1948 nothing, so it is safe to call before every step.
1949  
1950 =head3 EXAMPLE
1951  
1952 $logger->clear();
1953 $logger->clear()->empty('nothing logged yet');
1954  
1955 =head3 API SPECIFICATION
1956  
1957 =head4 Input
1958  
1959 {}
1960  
1961 Domains: no arguments; any that are given are ignored.
1962  
1963 =head4 Output
1964  
1965 { type => 'object', isa => 'Test::Log::Abstraction' }
1966  
1967 =head3 MESSAGES
1968  
1969 Message Meaning What to do
1970 ------------------------------ ---------------------------- ------------------------------
1971 clear() must be called on an not called on a logger Call it on a logger object
1972 object, not on the class (croak)
1973  
1974 =cut
1975  
1976 2193 ▶sub clear {
Subroutine clear: called CC=1 SCAR=0.0
Pod documented
1977 2193 my $self = shift;
1978  
1979 2193 @{_object($self, 'clear')->{'messages'}} = ();
1980  
1981 2179 return $self;
1982 }
1983  
1984 =head2 count
1985  
1986 Count the stored messages.
1987  
1988 =head3 Purpose
1989  
1990 Check how much was logged, in total or at one level.
1991  
1992 =head3 Args
1993  
1994 =over 4
1995  
1996 =item * C<$level> - optional. Count only messages at this level. Upper or
1997 lower case does not matter. Different names for the same level are counted
1998 apart: C<count('warn')> does not count C<warning()> calls.
1999  
2000 =back
2001  
2002 =head3 Returns
2003  
2004 The number of messages: 0 or more.
2005  
2006 =head3 Side Effects
2007  
2008 None.
2009  
2010 =head3 EXAMPLE
2011  
2012 is($logger->count(), 3, 'three messages in total');
2013 is($logger->count('error'), 1, 'one of them is an error');
2014  
2015 =head3 API SPECIFICATION
2016  
2017 =head4 Input
2018  
2019 {
2020 level => { type => 'string', optional => 1, position => 0 },
2021 }
2022  
2023 Domains: undef counts every message; a string counts messages at that
2024 level, any case ('', '0' and unknown names give 0; aliases are separate
2025 names). Invalid: any reference. A name may be any string, including non-ASCII text and a
2026 character string that is not valid UTF-8, which is matched as the same
2027 repaired name AUTOLOAD stores.
2028  
2029 =head4 Output
2030  
2031 { type => 'integer', min => 0 }
2032  
2033 =head3 MESSAGES
2034  
2035 Message Meaning What to do
2036 ------------------------------ ---------------------------- ------------------------------
2037 count() must be called on an not called on a logger Call it on a logger object
2038 object, not on the class (croak)
2039 invalid argument: ... the level is not a string Give a level name
2040 (croak)
2041  
2042 =cut
2043  
2044 823 ▶sub count {
Subroutine count: called CC=2 SCAR=6.9
Pod documented
2045 823 my ($self, $level) = @_;
2046  
2047 823 _object($self, 'count');
2048  
2049 # Without a level every message counts; with one, it is checked once and
2050 # then trusted (the schema has proved it is a string)
2051 804 ▶ my $messages = defined($level) ? $self->_at_level($self->_validate(\%COUNT_SCHEMA, { level => $level })->{'level'}) : $self->{'messages'};
Branch: 1 branch
BranchTrueFalseTotal
defined $level ? : 236 568 804
2052  
2053 784 return scalar(@{$messages});
2054 }
2055  
2056 =head2 like
2057  
2058 Test that a stored message matches a pattern.
2059  
2060 =head3 Purpose
2061  
2062 The test passes if at least one stored message matches the pattern.
2063  
2064 =head3 Args
2065  
2066 =over 4
2067  
2068 =item * C<$pattern> - required. A C<qr//> regular expression, or a string.
2069 A string is also used as a regular expression.
2070  
2071 =item * C<$name> - optional. The name of the test.
2072  
2073 =back
2074  
2075 =head3 Returns
2076  
2077 True if the test passed, false if it failed.
2078  
2079 =head3 Side Effects
2080  
2081 Adds one test result to the TAP output. If the test fails, all stored
2082 messages are printed under it (at most 20, then a count of the others).
2083  
2084 =head3 EXAMPLE
2085  
2086 $logger->like(qr/updated/, 'the update was logged');
2087 $logger->like(qr/^Cannot open/i, 'the open error was logged');
2088  
2089 =head3 API SPECIFICATION
2090  
2091 =head4 Input
2092  
2093 {
2094 pattern => { type => ['regex', 'string'], position => 0 },
2095 name => { type => 'string', optional => 1, position => 1 },
2096 }
2097  
2098 Domains: pattern - a qr// or a string, which is compiled as a regular
2099 expression ('' matches every message). Invalid: undef, any other
2100 reference, a string that does not compile or can never match, and a
2101 character string that is not valid UTF-8. A character pattern (such as
2102 qr/\x{1F600}/) matches text logged as characters, and not the same text
2103 logged as UTF-8 bytes; a byte pattern matches bytes only. name -
2104 undef, or any string (including '' and non-ASCII text). Invalid: a
2105 reference.
2106  
2107 =head4 Output
2108  
2109 { type => 'boolean' }
2110  
2111 =head3 MESSAGES
2112  
2113 Message Meaning What to do
2114 ------------------------------ ---------------------------- ------------------------------
2115 like() needs a pattern no pattern was given (croak) Give a qr// or a string
2116 invalid argument: ... the pattern is not a qr// or Give a qr// or a string
2117 a string, does not compile, that is a valid regex
2118 or can never match (croak)
2119 N messages were captured: the test failed; the stored Compare them with the pattern
2120 messages follow (output)
2121 like() must be called on not called on a logger Call it on a logger object
2122 an object, not on the class (croak)
2123  
2124 =cut
2125  
2126 2281 ▶sub like {
Subroutine like: called CC=2 SCAR=6.9
Pod documented
2127 2281 my ($self, $pattern, $name) = @_;
2128  
2129 2281 my $regex = _checked($self, 'like', 'needs_pattern', \%PATTERN_SCHEMA, pattern => $pattern, $name)->_regex($pattern);
2130  
2131 # Only whether one message matches matters, so stop at the first
2132 205 ▶ return $self->_assert((List::Util::any { $_->{'message'} =~ $regex } @{$self->{'messages'}}) ? 1 : 0, $name, 'captured', $self->{'messages'});
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
&List::Util::any(sub { $_->{'message'} =~ /$regex/u; } , @{$$self{'messages'};}) ? : 165 40 205
2133 }
2134  
2135 =head2 unlike
2136  
2137 Test that no stored message matches a pattern.
2138  
2139 =head3 Purpose
2140  
2141 The test passes if no stored message matches the pattern. It also passes
2142 when there are no messages.
2143  
2144 =head3 Args
2145  
2146 =over 4
2147  
2148 =item * C<$pattern> - required. A C<qr//> regular expression, or a string.
2149 A string is also used as a regular expression.
2150  
2151 =item * C<$name> - optional. The name of the test.
2152  
2153 =back
2154  
2155 =head3 Returns
2156  
2157 True if the test passed, false if it failed.
2158  
2159 =head3 Side Effects
2160  
2161 Adds one test result to the TAP output. If the test fails, the messages
2162 that matched are printed under it.
2163  
2164 =head3 EXAMPLE
2165  
2166 $logger->unlike(qr/fatal/i, 'nothing fatal was logged');
2167  
2168 =head3 API SPECIFICATION
2169  
2170 =head4 Input
2171  
2172 {
2173 pattern => { type => ['regex', 'string'], position => 0 },
2174 name => { type => 'string', optional => 1, position => 1 },
2175 }
2176  
2177 Domains: as for L</like>. Note that '' matches every message, so
2178 unlike('') fails whenever anything was logged.
2179  
2180 =head4 Output
2181  
2182 { type => 'boolean' }
2183  
2184 =head3 MESSAGES
2185  
2186 Message Meaning What to do
2187 ------------------------------ ---------------------------- ------------------------------
2188 unlike() needs a pattern no pattern was given (croak) Give a qr// or a string
2189 invalid argument: ... the pattern is not a qr// or Give a qr// or a string
2190 a string, does not compile, that is a valid regex
2191 or can never match (croak)
2192 N messages matched: the test failed; the Look at the listed messages
2193 matching messages follow
2194 unlike() must be called on not called on a logger Call it on a logger object
2195 an object, not on the class (croak)
2196  
2197 =cut
2198  
2199 75 ▶sub unlike {
Subroutine unlike: called CC=2 SCAR=6.9
Pod documented
2200 75 my ($self, $pattern, $name) = @_;
2201  
2202 75 my $regex = _checked($self, 'unlike', 'needs_pattern', \%PATTERN_SCHEMA, pattern => $pattern, $name)->_regex($pattern);
2203  
2204 # Stop at the first match; the full list is wanted only to explain a
2205 # failure, so it is gathered only then
2206 40 ▶ my $matched = List::Util::any { $_->{'message'} =~ $regex } @{$self->{'messages'}};
Subroutine __ANON__: called CC=1 SCAR=0.0
2207  
2208 40 ▶ return $self->_assert(!$matched, $name, 'matched', $matched ? $self->_matching($regex) : []);
Branch: 1 branch
BranchTrueFalseTotal
$matched ? : 18 22 40
2209 }
2210  
2211 =head2 has_level
2212  
2213 Test that something was logged at a level.
2214  
2215 =head3 Purpose
2216  
2217 The test passes if at least one message was stored at this level.
2218  
2219 =head3 Args
2220  
2221 =over 4
2222  
2223 =item * C<$level> - required. The level name. Upper or lower case does
2224 not matter. Different names for the same level are different:
2225 C<has_level('warn')> does not see C<warning()> calls.
2226  
2227 =item * C<$name> - optional. The name of the test.
2228  
2229 =back
2230  
2231 =head3 Returns
2232  
2233 True if the test passed, false if it failed.
2234  
2235 =head3 Side Effects
2236  
2237 Adds one test result to the TAP output. If the test fails, all stored
2238 messages are printed under it, so you can see which levels were used.
2239  
2240 =head3 EXAMPLE
2241  
2242 $logger->has_level('error', 'the failure was logged');
2243  
2244 =head3 API SPECIFICATION
2245  
2246 =head4 Input
2247  
2248 {
2249 level => { type => 'string', position => 0 },
2250 name => { type => 'string', optional => 1, position => 1 },
2251 }
2252  
2253 Domains: level - a string, any case ('' and unknown names match
2254 nothing; aliases are separate names). Invalid: undef, any reference.
2255 Any string is valid, as for L</count>.
2256 name - as for L</like>.
2257  
2258 =head4 Output
2259  
2260 { type => 'boolean' }
2261  
2262 =head3 MESSAGES
2263  
2264 Message Meaning What to do
2265 ------------------------------ ---------------------------- ------------------------------
2266 has_level() needs a level name no level was given (croak) Give a level name
2267 invalid argument: ... the level is not a string Give a level name
2268 (croak)
2269 N messages were captured: the test failed; the stored Look at the listed levels
2270 messages follow (output)
2271 has_level() must be called on not called on a logger Call it on a logger object
2272 an object, not on the class (croak)
2273  
2274 =cut
2275  
2276 78 ▶sub has_level {
Subroutine has_level: called CC=2 SCAR=6.9
Pod documented
2277 78 my ($self, $level, $name) = @_;
2278  
2279 78 _checked($self, 'has_level', 'needs_level', \%LEVEL_SCHEMA, level => $level, $name);
2280 47 my $wanted = _lc($level);
2281  
2282 # Only whether one message is at that level matters, so stop at the first
2283 47 ▶ return $self->_assert((List::Util::any { $_->{'level'} eq $wanted } @{$self->{'messages'}}) ? 1 : 0, $name, 'captured', $self->{'messages'});
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
&List::Util::any(sub { $_->{'level'} eq $wanted; } , @{$$self{'messages'};}) ? : 28 19 47
2284 }
2285  
2286 =head2 empty
2287  
2288 Test that nothing was logged.
2289  
2290 =head3 Purpose
2291  
2292 The test passes if there are no stored messages. Use it to check that a
2293 normal run logs nothing.
2294  
2295 =head3 Args
2296  
2297 =over 4
2298  
2299 =item * C<$name> - optional. The name of the test.
2300  
2301 =back
2302  
2303 =head3 Returns
2304  
2305 True if the test passed, false if it failed.
2306  
2307 =head3 Side Effects
2308  
2309 Adds one test result to the TAP output. If the test fails, the stored
2310 messages are printed under it.
2311  
2312 =head3 EXAMPLE
2313  
2314 $logger->empty('a normal run logs nothing');
2315  
2316 =head3 API SPECIFICATION
2317  
2318 =head4 Input
2319  
2320 {
2321 name => { type => 'string', optional => 1, position => 0 },
2322 }
2323  
2324 Domains: name - undef, or any string. Invalid: a reference.
2325  
2326 =head4 Output
2327  
2328 { type => 'boolean' }
2329  
2330 =head3 MESSAGES
2331  
2332 Message Meaning What to do
2333 ------------------------------ ---------------------------- ------------------------------
2334 N messages were captured: the test failed; the stored Look at the listed messages
2335 messages follow (output)
2336 empty() must be called on not called on a logger Call it on a logger object
2337 an object, not on the class (croak)
2338  
2339 =cut
2340  
2341 54 ▶sub empty {
Subroutine empty: called CC=2 SCAR=6.9
Pod documented
2342 54 my ($self, $name) = @_;
2343  
2344 54 my $messages = _object($self, 'empty')->{'messages'};
2345 43 ▶ $self->_validate(\%NAME_SCHEMA, { name => $name }) if(defined($name));
Branch: 1 branch
BranchTrueFalseTotal
if defined $name 21 22 43
2346  
2347 38 return $self->_assert(!@{$messages}, $name, 'captured', $messages);
2348 }
2349  
2350 # _matching - captured entries whose message matches a pattern
2351 #
2352 # Purpose: List what made unlike() fail.
2353 # Entry: $self - this logger.
2354 # $pattern - qr// or string. unlike() passes the pattern it
2355 # has already compiled, which Perl does not compile again.
2356 # Exit: Returns an array reference of matching entries, in order.
2357 # Side effects: Croaks with 'invalid_argument' if the pattern does not
2358 # compile.
2359 30 ▶sub _matching {
Subroutine _matching: called CC=1 SCAR=0.0
2360 30 my ($self, $pattern) = @_;
2361  
2362 30 my $regex = $self->_regex($pattern);
2363  
2364 23 return [ grep { $_->{'message'} =~ $regex } @{$self->{'messages'}} ];
2365 }
2366  
2367 # _checked - the checks every assertion with a required argument starts with
2368 #
2369 # Purpose: Shared by like(), unlike() and has_level(), so that they
2370 # reject a bad call in the same order and with the same words.
2371 # Entry: $self - the invocant, which may not be an object yet.
2372 # $method - the public method's name, for the messages.
2373 # $needs - message key for a missing required argument.
2374 # $schema - Params::Validate::Strict schema for the arguments.
2375 # $field - the required argument's name in the schema.
2376 # $value - the required argument.
2377 # $name - the test name, or undef.
2378 # Exit: Returns $self, for chaining.
2379 # Side effects: Croaks with 'class_invocant', $needs or 'invalid_argument'.
2380 2445 ▶sub _checked {
Subroutine _checked: called CC=3 SCAR=11.0
2381 2445 my ($self, $method, $needs, $schema, $field, $value, $name) = @_;
2382  
2383 # Called as a function: until _object() has passed, $self may be a
2384 # class name or an unblessed reference, which cannot call methods
2385 2445 _object($self, $method);
2386 2404 ▶ $self->_croak($needs, { method => $method }) if(!defined($value));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 2049 355 2404
2387 355 ▶ $self->_validate($schema, { $field => $value, (defined($name) ? (name => $name) : ()) });
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 230 125 355
2388  
2389 324 return $self;
2390 }
2391  
2392 # _regex - compile a pattern once
2393 #
2394 # Purpose: Turn a qr// or a string into a compiled regular expression,
2395 # so a search runs it without compiling it again.
2396 # Entry: $self - this logger (for the error's language).
2397 # $pattern - qr// or string.
2398 # Exit: Returns the compiled regular expression.
2399 # Side effects: Croaks with 'invalid_argument' if the pattern does not
2400 # compile, contains code, can never match, or is a character
2401 # string that is not valid UTF-8. Never warns: a warning
2402 # while compiling is the error. Leaves $@ and
2403 # $SIG{__WARN__} alone otherwise.
2404 311 ▶sub _regex {
Subroutine _regex: called CC=2 SCAR=6.9
2405 311 my ($self, $pattern) = @_;
2406  
2407 # A string is compiled here, so that a malformed one, one with code in
2408 # it (not allowed at run time), or one Perl warns can never match, is
2409 # the caller's error and not a crash or a stray warning. 'utf8' makes a
2410 # character string that is not valid UTF-8 the caller's error too, rather
2411 # than a stream of warnings and a pattern with unknown meaning; valid
2412 # text, even a surrogate or a non-character, compiles without a warning.
2413 # Perl 5.42 reports malformed UTF-8 as plain warnings before the fatal
2414 # one, whatever the lexical FATAL says; so any warning during the
2415 # compile becomes the error too, and the first, most detailed, is the
2416 # reason on every version
2417 311 local $@; # the caller's $@ must survive a good pattern
2418 311 my $regex = eval {
2419 30 ▶ use warnings FATAL => qw(regexp utf8);
Subroutine BEGIN: called CC=1 SCAR=0.0
2420 311 local $SIG{__WARN__} = \&CORE::die;
2421 311 qr/$pattern/;
2422 };
2423 311 ▶ $self->_croak('invalid_argument', { reason => _reason($@) }) if(!defined($regex));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $regex 38 273 311
2424  
2425 273 return $regex;
2426 }
2427  
2428 # _at_level - captured entries at one level
2429 #
2430 # Purpose: Shared by count() and has_level().
2431 # Entry: $self - this logger.
2432 # $level - level name, any case.
2433 # Exit: Returns an array reference of entries at that level.
2434 # Side effects: None.
2435 219 ▶sub _at_level {
Subroutine _at_level: called CC=1 SCAR=0.0
2436 219 my ($self, $level) = @_;
2437  
2438 219 my $wanted = _lc($level);
2439  
2440 219 return [ grep { $_->{'level'} eq $wanted } @{$self->{'messages'}} ];
2441 }
2442  
2443 # _assert - report an assertion as a TAP test
2444 #
2445 # Purpose: Shared by every assertion, so they report identically.
2446 # Entry: $self - this logger.
2447 # $ok - truth of the assertion.
2448 # $name - test name, or undef.
2449 # $key - i18n key heading the failure diagnostic.
2450 # $entries - array reference of entries to list on failure.
2451 # Exit: Returns Test::Builder's result.
2452 # Side effects: Emits one TAP test; on failure, diagnostics. The failure is
2453 # reported at the line that called the public assertion.
2454 324 ▶sub _assert {
Subroutine _assert: called CC=2 SCAR=6.9
2455 324 my ($self, $ok, $name, $key, $entries) = @_;
2456  
2457 # Report at the line that called the public assertion. $Level counts
2458 # from a call through Test::More::ok(), which is itself one frame; this
2459 # calls Test::Builder's ok() directly, so that frame is not there, and
2460 # skipping the public assertion's frame is enough. (+2 skipped one too
2461 # many: at the top level of a test file there is nothing above, so it
2462 # looked right, but inside a subtest it pointed into Test::Builder.)
2463 # Keep the caller's $@ and $!, which reporting may change
2464 324 local $Test::Builder::Level = $Test::Builder::Level + 1;
2465 324 local ($@, $!);
2466 324 my $result = Test::Builder->new()->ok($ok, $name);
2467 324 ▶ $self->_explain($key, $entries) if(!$ok);
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 89 235 324
2468  
2469 323 return $result;
2470 }
2471  
2472 # _explain - list the entries that explain a failed assertion
2473 #
2474 # Purpose: Make a failure self-explanatory in the TAP output.
2475 # Entry: $self - this logger.
2476 # $key - i18n key for the heading ('captured' or 'matched').
2477 # $entries - array reference of entries.
2478 # Exit: Returns $self.
2479 # Side effects: Prints at most $MAX_EXPLAIN entries plus a summary line.
2480 100 ▶sub _explain {
Subroutine _explain: called CC=4 SCAR=13.9
2481 100 my ($self, $key, $entries) = @_;
2482  
2483 100 my $total = scalar(@{$entries});
2484 100 $self->_emit($self->i18n($key, { count => $total }));
2485  
2486 100 ▶ my $last = ($total > $MAX_EXPLAIN) ? $MAX_EXPLAIN : $total;
Branch: 1 branch
BranchTrueFalseTotal
$total > $MAX_EXPLAIN ? : 8 92 100
2487 100 foreach my $entry (@{$entries}[0 .. $last - 1]) {
2488 # Both may hold text the test did not write: see _printable()
2489 355 $self->_emit($self->i18n('entry', { level => _printable($entry->{'level'}), message => _printable($entry->{'message'}) }));
2490 }
2491 100 ▶ $self->_emit($self->i18n('truncated', { count => $total - $last })) if($total > $last);
Branch: 1 branch
BranchTrueFalseTotal
if $total > $last 8 92 100
2492  
2493 100 return $self;
2494 }
2495  
2496 =head2 verbose
2497  
2498 Get or change verbose mode.
2499  
2500 =head3 Purpose
2501  
2502 In verbose mode, every message is printed, whatever the C<diag> rule says.
2503 This helps when you are finding out why a test fails.
2504  
2505 =head3 Args
2506  
2507 =over 4
2508  
2509 =item * C<$value> - optional. True turns verbose mode on, false turns it
2510 off. Without an argument, nothing changes.
2511  
2512 =back
2513  
2514 =head3 Returns
2515  
2516 The setting after the call: 1 (on) or 0 (off).
2517  
2518 =head3 Side Effects
2519  
2520 Changes the setting, when you give an argument.
2521  
2522 =head3 EXAMPLE
2523  
2524 $logger->verbose(1); # print everything from now on
2525 my $on = $logger->verbose(); # 1
2526  
2527 =head3 API SPECIFICATION
2528  
2529 =head4 Input
2530  
2531 {
2532 value => { type => 'scalar', optional => 1, position => 0 },
2533 }
2534  
2535 Domains: absent - get only; otherwise Perl truth decides ('0', '' and
2536 undef are off; '0.0' is on).
2537  
2538 =head4 Output
2539  
2540 { type => 'integer', min => 0, max => 1 }
2541  
2542 =head3 MESSAGES
2543  
2544 Message Meaning What to do
2545 ------------------------------ ---------------------------- ------------------------------
2546 verbose() must be called on an not called on a logger Call it on a logger object
2547 object, not on the class (croak)
2548  
2549 =cut
2550  
2551 429 ▶sub verbose {
Subroutine verbose: called CC=3 SCAR=11.0
Pod documented
2552 429 my ($self, @value) = @_;
2553  
2554 429 _object($self, 'verbose');
2555 415 ▶ $self->{'verbose'} = ($value[0] ? 1 : 0) if(@value);
Branch: 2 branches
BranchTrueFalseTotal
if @value 47 368 415
$value[0] ? : 31 16 47
2556  
2557 415 return $self->{'verbose'};
2558 }
2559  
2560 =head2 level
2561  
2562 Get or change the logger's level.
2563  
2564 =head3 Purpose
2565  
2566 Code under test may read or change the level, as it can with
2567 L<Log::Abstraction/level>. The level only changes the answers of the
2568 C<is_*> methods. Every message is still stored.
2569  
2570 =head3 Args
2571  
2572 =over 4
2573  
2574 =item * C<$name> - optional. A level name. Upper or lower case does not
2575 matter.
2576  
2577 =back
2578  
2579 =head3 Returns
2580  
2581 =over 4
2582  
2583 =item * No argument: the level's number, from 0 to 7.
2584  
2585 =item * A known level name: the logger, so you can chain calls.
2586  
2587 =item * An unknown level name: C<undef>, as in L<Log::Abstraction>.
2588  
2589 =back
2590  
2591 =head3 Side Effects
2592  
2593 With a known name, the level changes. With an unknown name, nothing
2594 changes and a warning is printed.
2595  
2596 =head3 EXAMPLE
2597  
2598 $logger->level('error');
2599 print $logger->level(), "\n"; # 3
2600  
2601 =head3 API SPECIFICATION
2602  
2603 =head4 Input
2604  
2605 {
2606 name => { type => 'string', optional => 1, position => 0 },
2607 }
2608  
2609 Domains: absent or undef - get only; one of the 16 level names, any
2610 case - set (0 for emergency to 7 for trace). Anything else - '', numbers
2611 such as '0' or '8', unknown names - warns and returns undef. A reference
2612 is treated as its text form: a plain reference such as ARRAY(0x...) is
2613 never a level name, so it warns; an object whose overloaded text form is
2614 a level name sets that level; an object whose text form dies is shown in
2615 plain form in the warning. A character string that is not valid
2616 UTF-8, or holds a surrogate, is never a level name: it warns, with no
2617 other warning.
2618  
2619 =head4 Output
2620  
2621 { type => ['integer', 'object'], optional => 1 }
2622  
2623 =head3 MESSAGES
2624  
2625 Message Meaning What to do
2626 ------------------------------ ---------------------------- ------------------------------
2627 invalid syslog level 'X' X is not a level name Use a name from the level table
2628 (warning; returns undef)
2629 level() must be called on not called on a logger Call it on a logger object
2630 an object, not on the class (croak)
2631  
2632 =cut
2633  
2634 619 ▶sub level {
Subroutine level: called CC=4 SCAR=13.9
Pod documented
2635 619 my ($self, $name) = @_;
2636  
2637 619 _object($self, 'level');
2638  
2639 # Exactly one of three cases holds: no name (get), a level name (set),
2640 # or anything else (warn, and return undef, as Log::Abstraction does).
2641 # Premise 1: _string() returns a defined string for any defined value.
2642 # Premise 2: so the lookup key is undefined exactly when $name is.
2643 # Conclusion: the get case is decided by $name alone, before any key
2644 # is made.
2645 599 ▶ return $self->{'level'} if(!defined($name));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name 416 183 599
2646  
2647 # The name as a lookup key. Through _string(): an object whose
2648 # overloading dies is not a level name, so it is warned about below
2649 # instead of crashing the call
2650 183 my $key = _lc(_string($name));
2651 183 my $known = exists($SEVERITY{$key});
2652 183 ▶ if($known) {
Branch: 1 branch
BranchTrueFalseTotal
if ($known) { } 48 135 183
2653 48 $self->{'level'} = $SEVERITY{$key};
2654 } else {
2655 # As in _croak(): Carp must not format the caller's arguments
2656 135 local $Carp::MaxArgNums = -1;
2657 135 Carp::carp($self->i18n('invalid_level', { level => _shown($name) }));
2658 }
2659  
2660 # undef as a value, not an empty list, so it is undef in list context
2661 # too
2662 180 ▶ return $known ? $self : undef;
Branch: 1 branch
BranchTrueFalseTotal
$known ? : 48 132 180
2663 }
2664  
2665 =head2 flush
2666  
2667 Do nothing.
2668  
2669 =head3 Purpose
2670  
2671 In L<Log::Abstraction>, C<flush()> sends e-mail messages that are waiting.
2672 The test logger never sends e-mail, but the code under test may still call
2673 C<flush()>, so it exists.
2674  
2675 =head3 Args
2676  
2677 None.
2678  
2679 =head3 Returns
2680  
2681 The logger, so you can chain calls.
2682  
2683 =head3 Side Effects
2684  
2685 None.
2686  
2687 =head3 EXAMPLE
2688  
2689 $logger->flush();
2690  
2691 =head3 API SPECIFICATION
2692  
2693 =head4 Input
2694  
2695 {}
2696  
2697 Domains: no arguments; any that are given are ignored.
2698  
2699 =head4 Output
2700  
2701 { type => 'object', isa => 'Test::Log::Abstraction' }
2702  
2703 =head3 MESSAGES
2704  
2705 Message Meaning What to do
2706 ------------------------------ ---------------------------- ------------------------------
2707 flush() must be called on an not called on a logger Call it on a logger object
2708 object, not on the class (croak)
2709  
2710 =cut
2711  
2712 37 ▶sub flush {
Subroutine flush: called CC=1 SCAR=0.0
Pod documented
2713 37 my $self = shift;
2714  
2715 37 return _object($self, 'flush');
2716 }
2717  
2718 =head2 reopen
2719  
2720 Do nothing.
2721  
2722 =head3 Purpose
2723  
2724 In L<Log::Abstraction> 0.41 and later, C<reopen()> closes the log files, so
2725 that the next message opens them again. A program calls it after another
2726 program has moved or renamed its log files (log rotation), often from a
2727 C<$SIG{HUP}> handler. The test logger has no files, but the code under
2728 test may still call C<reopen()>, so it exists. Without it, the call would
2729 be stored as a message at level C<reopen>, and a "no method" notice would
2730 be printed.
2731  
2732 =head3 Args
2733  
2734 None.
2735  
2736 =head3 Returns
2737  
2738 The logger, so you can chain calls.
2739  
2740 =head3 Side Effects
2741  
2742 None. No message is stored or printed, and C<$@> and C<$!> do not change.
2743  
2744 =head3 EXAMPLE
2745  
2746 # The code under test reopens its logs when it gets SIGHUP
2747 local $SIG{HUP} = sub { $logger->reopen() };
2748 kill('HUP', $$);
2749 $logger->empty('reopening the logs logged nothing');
2750  
2751 =head3 API SPECIFICATION
2752  
2753 =head4 Input
2754  
2755 {}
2756  
2757 Domains: no arguments; any that are given are ignored.
2758  
2759 =head4 Output
2760  
2761 { type => 'object', isa => 'Test::Log::Abstraction' }
2762  
2763 =head3 MESSAGES
2764  
2765 Message Meaning What to do
2766 ------------------------------ ---------------------------- ------------------------------
2767 reopen() must be called on an not called on a logger Call it on a logger object
2768 object, not on the class (croak)
2769  
2770 =cut
2771  
2772 38 ▶sub reopen {
Subroutine reopen: called CC=1 SCAR=0.0
Pod documented
2773 38 my $self = shift;
2774  
2775 38 return _object($self, 'reopen');
2776 }
2777  
2778 =head2 lang
2779  
2780 Get the language of this module's messages.
2781  
2782 =head3 Purpose
2783  
2784 Let a test check which language was chosen from the C<lang> and C<country>
2785 options or the environment.
2786  
2787 =head3 Args
2788  
2789 None.
2790  
2791 =head3 Returns
2792  
2793 A language code: C<en>, C<de>, C<fr>, C<zh>, or a code that you gave in the
2794 C<i18n> option.
2795  
2796 =head3 Side Effects
2797  
2798 None.
2799  
2800 =head3 EXAMPLE
2801  
2802 my $lang = Test::Log::Abstraction->new(country => 'FR')->lang(); # 'fr'
2803  
2804 =head3 API SPECIFICATION
2805  
2806 =head4 Input
2807  
2808 {}
2809  
2810 Domains: no arguments; any that are given are ignored.
2811  
2812 =head4 Output
2813  
2814 { type => 'string', matches => qr/\A[a-z]{2,3}\z/ }
2815  
2816 =head3 MESSAGES
2817  
2818 Message Meaning What to do
2819 ------------------------------ ---------------------------- ------------------------------
2820 lang() must be called on an not called on a logger Call it on a logger object
2821 object, not on the class (croak)
2822  
2823 =cut
2824  
2825 394 ▶sub lang {
Subroutine lang: called CC=1 SCAR=0.0
Pod documented
2826 394 my $self = shift;
2827  
2828 394 return _object($self, 'lang')->{'lang'};
2829 }
2830  
2831 =head1 METHODS FOR SUBCLASSES
2832  
2833 These methods are for this class, and classes that inherit from it. A
2834 subclass may call them, or replace them. Nothing stops other code calling
2835 them, but they are not part of the public interface, and may change.
2836  
2837 =head2 _emit
2838  
2839 Print one line of test output.
2840  
2841 =head3 Purpose
2842  
2843 Every line that this module prints goes through this method. A subclass
2844 can replace it to send the lines somewhere else.
2845  
2846 =head3 Args
2847  
2848 =over 4
2849  
2850 =item * C<$text> - the line to print.
2851  
2852 =back
2853  
2854 =head3 Returns
2855  
2856 The logger.
2857  
2858 =head3 Side Effects
2859  
2860 Prints the line as a TAP comment, with L<Test::Builder/diag>. This works
2861 even if the test did not load L<Test::More>. Text that came from a logged
2862 message has its control characters escaped before it is passed here (see
2863 L</Which messages are printed>), so a replacement C<_emit> gets safe text
2864 too. A Perl character string is
2865 encoded as UTF-8 first, unless the output already has an encoding layer
2866 (see L</ENCODING>).
2867  
2868 A level method stores its message before it calls C<_emit>. So if a
2869 replacement C<_emit> dies, the message is still captured, and the error
2870 reaches the code that logged.
2871  
2872 =head3 EXAMPLE
2873  
2874 package My::Logger;
2875 use parent -norequire, 'Test::Log::Abstraction';
2876  
2877 # Send the lines to STDERR instead of the TAP output
2878 sub _emit {
2879 my ($self, $text) = @_;
2880 print STDERR "$text\n";
2881 return $self;
2882 }
2883  
2884 =head3 API SPECIFICATION
2885  
2886 =head4 Input
2887  
2888 {
2889 text => { type => 'string', position => 0 },
2890 }
2891  
2892 =head4 Output
2893  
2894 { type => 'object', isa => 'Test::Log::Abstraction' }
2895  
2896 =head3 MESSAGES
2897  
2898 None. It never fails.
2899  
2900 =cut
2901  
2902 4971 ▶sub _emit {
Subroutine _emit: called CC=6 SCAR=17.9
2903 4971 my ($self, $text) = @_;
2904  
2905 # Output can fail (a full disk sets $! to ENOSPC); that must not leak
2906 # into the caller, which the POD promises
2907 4971 local ($@, $!);
2908 4971 my $tb = Test::Builder->new();
2909 4971 ▶ my $handle = $tb->in_todo() ? $tb->todo_output() : $tb->failure_output();
Branch: 1 branch
BranchTrueFalseTotal
$tb->in_todo ? : 313 4658 4971
2910 # Test::Builder may have no handle at all; then nothing encodes for us
2911 4971 ▶ my $layered = defined($handle) && grep { defined($_) && /\A(?:utf8|encoding)/ } PerlIO::get_layers($handle);
Condition100%6/6
defined $handle && grep({defined $_ and /\A(?:utf8|encoding)/u;} &PerlIO::get_layers($handle))
!ll&&!rl&&r
249636
defined $_ && /\A(?:utf8|encoding)/u
!ll&&!rl&&r
355777
MC/DC100%2/2
defined $handle && grep({defined $_ and /\A(?:utf8|encoding)/u;} &PerlIO::get_layers($handle))
defined $handle grep({defined $_ and /\A(?:utf8|encoding)/u;} &PerlIO::get_layers($handle))
MC/DC100%2/2
defined $_ && /\A(?:utf8|encoding)/u
defined $_ /\A(?:utf8|encoding)/u
Truth table100%3/3
A && B
A= defined $handleB= grep({defined $_ and /\A(?:utf8|encoding)/u;} &PerlIO::get_layers($handle))
ABresult
0X0
100
111
Truth table100%3/3
A && B
A= defined $_B= /\A(?:utf8|encoding)/u
ABresult
0X0
100
111
2912 # A flagged string is characters, which a raw handle needs as UTF-8;
2913 # an unflagged string is already bytes and is printed untouched
2914 4971 ▶ $text = Encode::encode('UTF-8', $text) if(!$layered && utf8::is_utf8($text));
Branch: 1 branch
BranchTrueFalseTotal
if not $layered and utf8::is_utf8($text) 2110 2861 4971
Condition100%3/3
not $layered and utf8::is_utf8($text)
!ll&&!rl&&r
628552110
MC/DC100%2/2
not $layered and utf8::is_utf8($text)
not $layered utf8::is_utf8($text)
Truth table100%3/3
not(A) and B
A= not $layeredB= utf8::is_utf8($text)
ABresult
0X0
100
111
2915 4970 $tb->diag($text);
2916  
2917 4968 return $self;
2918 }
2919  
2920 =head2 i18n
2921  
2922 Make one of this module's messages, in the logger's language.
2923  
2924 =head3 Purpose
2925  
2926 All the text that this module shows to people comes from here. So the
2927 text can be translated, or changed, without changing the code.
2928  
2929 =head3 Args
2930  
2931 =over 4
2932  
2933 =item * C<$key> - the name of the message, such as C<needs_pattern>.
2934  
2935 =item * C<\%args> - optional. Values for the placeholders in the message.
2936 C<class> is filled in for you (the logger's class). C<count> chooses the
2937 singular or plural form. C<gender> chooses a gender form.
2938  
2939 =back
2940  
2941 =head3 How a message template works
2942  
2943 A template is a string. C<%{name}s> is replaced by the value called
2944 C<name>. After the name you can use any C<sprintf> format letter, for
2945 example C<%{count}d> or C<%{ratio}.2f>. C<%%> gives one C<%>. A value
2946 that is missing becomes the text C<undef>, with no warning. A value that
2947 the format cannot show is written as it was given: text, infinity and NaN
2948 for any number format, and a number too big for an integer format such as
2949 C<%d> or C<%x>, which C<sprintf> would turn into C<-1>.
2950  
2951 A template can also be a hash. The keys are gender names (such as
2952 C<male>, C<female>) or plural forms (C<zero>, C<one>, C<two>, C<few>,
2953 C<many>, C<other>). The values are templates, so they can be hashes too.
2954 C<other> is used when nothing else fits. C<zero> is used for a count of
2955 0, if it is there.
2956  
2957 {
2958 zero => 'no messages',
2959 one => '%{count}d message',
2960 other => '%{count}d messages',
2961 }
2962  
2963 =head3 Where the template is found
2964  
2965 The first one found is used:
2966  
2967 =over 4
2968  
2969 =item 1. Your C<i18n> option, in the logger's language.
2970  
2971 =item 2. This module's messages, in the logger's language.
2972  
2973 =item 3. Your C<i18n> option, in English.
2974  
2975 =item 4. This module's messages, in English.
2976  
2977 =back
2978  
2979 If the key is not found anywhere, the key itself is returned.
2980  
2981 =head3 Returns
2982  
2983 The finished message, as a Perl character string.
2984  
2985 =head3 Side Effects
2986  
2987 None.
2988  
2989 =head3 EXAMPLE
2990  
2991 # Inside a subclass
2992 my $text = $self->i18n('needs_pattern', { method => 'like' });
2993 # "Test::Log::Abstraction: like() needs a pattern"
2994  
2995 # Your own message, with gender and plural forms. i18n() is
2996 # meant for subclasses, so call it from a method of your subclass.
2997 my $logger = My::Logger->new(i18n => {
2998 en => {
2999 logged => {
3000 male => { one => 'He logged %{count}d line', other => 'He logged %{count}d lines' },
3001 other => 'They logged %{count}d lines',
3002 },
3003 },
3004 });
3005 # In a method of My::Logger:
3006 $self->i18n('logged', { gender => 'male', count => 2 }); # 'He logged 2 lines'
3007  
3008 =head3 API SPECIFICATION
3009  
3010 =head4 Input
3011  
3012 {
3013 key => { type => 'string', position => 0 },
3014 args => { type => 'hashref', optional => 1, position => 1 },
3015 }
3016  
3017 Domains: key - any string; undef renders as '', a reference as its
3018 string form, and an unknown key is returned as it is. args - a hash
3019 reference; anything else is ignored. count - a number selects a plural
3020 form; anything else (text, '', undef, a reference) uses 'other'. A
3021 count equal to 0 (0, '0.0', '-0') uses 'zero' when the template has
3022 it. Otherwise: in English and German 'one' is exactly 1 (0.999, 1.001,
3023 -1 and 0 are 'other'); in French 'one' is any count above -2 and below 2
3024 (-2 and 2 are 'other', -1.999 and 1.999 are 'one'); in Chinese it is
3025 always 'other'. A form the template lacks becomes 'other'. gender - a
3026 value naming a form of the template selects it; any other value,
3027 including undef and '' when there is no such form, falls through to the
3028 plural forms. A gender that is an object is matched by its text form. A
3029 template or form that is not a string or a hash is shown as its text form.
3030 Placeholder values: any value. With an integer format, C<%d> and C<%i>
3031 show -2**63 to 2**63-1, and C<%u>, C<%o>, C<%x>, C<%X>, C<%b> and C<%c>
3032 show 0 to 2**64-1 (a negative number down to -2**63 in two's
3033 complement). Leading zeros and a leading C<+> are allowed, and '-0' is 0.
3034 A value outside these ranges, text, infinity and NaN are shown as written.
3035 (These limits are for a Perl with 64-bit integers.) "As written" means
3036 the text that Perl makes when it prints the value, C<"$value">. For a
3037 number (not a string) this text depends on how Perl was built: see
3038 L</COMMON PITFALLS>.
3039  
3040 =head4 Output
3041  
3042 { type => 'string' }
3043  
3044 =head3 MESSAGES
3045  
3046 None. It never fails, for any key or arguments.
3047  
3048 =head3 PSEUDOCODE
3049  
3050 language = the logger's language (for a class name: the configured one)
3051 template = the first one found in the four places listed above
3052 if no template was found, return the key
3053 while the template is a hash:
3054 choose by gender, else by plural form, else 'other'
3055 replace each %{name}format with sprintf(format, the value of name)
3056 return the text
3057  
3058 =cut
3059  
3060 5809 ▶sub i18n {
Subroutine i18n: called CC=6 SCAR=17.9
Pod documented
3061 5809 my ($self, $key, $args) = @_;
3062  
3063 # Documented always to return a string: an undefined key renders as '',
3064 # a reference key as its string form, and arguments that are not a hash
3065 # are ignored
3066 5809 ▶ $key = defined($key) ? _string($key) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $key ? : 5805 4 5809
3067 5809 ▶ my $class = ref($self) || $self;
Condition100%3/3
ref $self || $self
l!l&&r!l&&!r
53254813
MC/DC100%2/2
ref $self || $self
ref $self $self
Truth table100%3/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
3068 5809 ▶ my %args = (class => $class, ((ref($args) eq 'HASH') ? %{$args} : ()));
Branch: 1 branch
BranchTrueFalseTotal
ref $args eq 'HASH' ? : 5731 78 5809
3069 5809 ▶ my $lang = ref($self) ? $self->{'lang'} : _resolve_lang({});
Branch: 1 branch
BranchTrueFalseTotal
ref $self ? : 5325 484 5809
3070 5809 my $template = _template($self, $lang, $key);
3071  
3072 5809 ▶ return defined($template) ? _interpolate(_variant($template, \%args, $lang), \%args) : $key;
Branch: 1 branch
BranchTrueFalseTotal
defined $template ? : 5786 23 5809
3073 }
3074  
3075 # _template - find a message template
3076 #
3077 # Purpose: Look a key up in the logger's overrides and the built-in
3078 # catalogue, in the requested language and then English.
3079 # Entry: $self - logger or class name.
3080 # $lang - language tag.
3081 # $key - message key.
3082 # Exit: Returns the template (string or hash reference), or undef.
3083 # Side effects: None. exists() guards every level, as the locked catalogue
3084 # croaks if a lookup tries to autovivify into it.
3085 5854 ▶sub _template {
Subroutine _template: called CC=9 SCAR=22.0
3086 5854 my ($self, $lang, $key) = @_;
3087  
3088 # Through _is_a(): new() keeps an i18n option that only says it is a
3089 # hash, such as bless([], 'HASH'), and it is ignored here
3090 5854 ▶ my $i18n = ref($self) ? $self->{'options'}->{'i18n'} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $self ? : 5369 485 5854
3091 5854 ▶ my $overrides = _is_a($i18n, 'HASH') ? $i18n : {};
Branch: 1 branch
BranchTrueFalseTotal
_is_a($i18n, 'HASH') ? : 237 5617 5854
3092  
3093 # Overrides before built-ins, the logger's language before English
3094 5854 my $found;
3095 # Searching English twice can find nothing new, so an English logger
3096 # searches once
3097 5854 ▶ SEARCH: foreach my $tag (($lang eq $FALLBACK_LANG) ? ($lang) : ($lang, $FALLBACK_LANG)) {
Branch: 1 branch
BranchTrueFalseTotal
$lang eq $FALLBACK_LANG ? : 1583 4271 5854
3098 5883 foreach my $source ($overrides, \%MESSAGES) {
3099 11570 ▶ my $table = exists($source->{$tag}) ? $source->{$tag} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $source->{$tag} ? : 5920 5650 11570
3100 11570 ▶ next if(!_is_a($table, 'HASH') || !exists($table->{$key}));
Branch: 1 branch
BranchTrueFalseTotal
unless _is_a($table, "HASH") and exists $table->{$key} 5743 5827 11570
Condition100%3/3
_is_a($table, "HASH") and exists $table->{$key}
!ll&&!rl&&r
5660835827
MC/DC100%2/2
_is_a($table, "HASH") and exists $table->{$key}
_is_a($table, "HASH") exists $table->{$key}
Truth table100%3/3
A and B
A= _is_a($table, "HASH")B= exists $table->{$key}
ABresult
0X0
100
111
3101 5827 $found = $table->{$key};
3102 5827 last SEARCH;
3103 }
3104 }
3105  
3106 5854 return $found;
3107 }
3108  
3109 # _variant - pick a gender or plural form of a template
3110 #
3111 # Purpose: Resolve a hash-shaped template to a string.
3112 # Entry: $template - string or (nested) hash reference.
3113 # $args - placeholder values; 'gender' and 'count' are
3114 # consulted.
3115 # $lang - language, for its plural rules.
3116 # Exit: Returns a string; '' if no form applies. A form that is
3117 # not a string is shown as Perl's text for it.
3118 # Side effects: None. Each step descends one level, and a hash already
3119 # visited ends the walk, so even a cyclic template terminates.
3120 5816 ▶sub _variant {
Subroutine _variant: called CC=8 SCAR=20.8
3121 5816 my ($template, $args, $lang) = @_;
3122  
3123 5816 my %visited;
3124 5816 ▶ while(_is_a($template, 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_a($template, "HASH")) 5238 5813 11051
3125 # A template from the i18n option may contain itself
3126 5238 ▶ return '' if($visited{Scalar::Util::refaddr($template)}++);
Branch: 1 branch
BranchTrueFalseTotal
if $visited{builtin::refaddr($template)}++ 3 5235 5238
3127 # The gender is the caller's value, used as a key: through _string(),
3128 # so an object whose overloaded "" dies cannot kill i18n()
3129 5235 ▶ my $gender = defined($args->{'gender'}) ? _string($args->{'gender'}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{'gender'} ? : 30 5205 5235
3130 5235 ▶ my $form = (defined($gender) && exists($template->{$gender})) ? $gender : _plural($template, $args->{'count'}, $lang);
Branch: 1 branch
BranchTrueFalseTotal
defined $gender && exists $template->{$gender} ? : 15 5220 5235
Condition100%3/3
defined $gender and exists $template->{$gender}
!ll&&!rl&&r
52051515
MC/DC100%2/2
defined $gender and exists $template->{$gender}
defined $gender exists $template->{$gender}
Truth table100%3/3
A and B
A= defined $genderB= exists $template->{$gender}
ABresult
0X0
100
111
3131 5235 ▶ $template = exists($template->{$form}) ? $template->{$form} : '';
Branch: 1 branch
BranchTrueFalseTotal
exists $template->{$form} ? : 5227 8 5235
3132 }
3133  
3134 # A form given as undef in the i18n option renders as nothing. Any
3135 # other form is made text here, through _string(): an object whose
3136 # overloaded "" dies would otherwise kill _interpolate()
3137 5813 ▶ return defined($template) ? _string($template) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $template ? : 5809 4 5813
3138 }
3139  
3140 # _plural - choose a plural category for a count
3141 #
3142 # Purpose: Apply the explicit 'zero' case, then the language's rule.
3143 # Entry: $template - hash reference of forms.
3144 # $count - the count, or undef.
3145 # $lang - language tag.
3146 # Exit: Returns the key to use: 'zero', a CLDR category present in
3147 # $template, or 'other'.
3148 # Side effects: None.
3149 5282 ▶sub _plural {
Subroutine _plural: called CC=9 SCAR=22.0
3150 5282 my ($template, $count, $lang) = @_;
3151  
3152 # Without a numeric count there is nothing to pluralise on. 'other'
3153 # is the answer whether or not the template has it, so it is returned
3154 # without looking
3155 5282 ▶ return 'other' if(!(defined($count) && !ref($count) && Scalar::Util::looks_like_number($count)));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $count and not ref $count and &Scalar::Util::looks_like_number($count) 5071 211 5282
Condition100%6/6
defined $count and not ref $count and &Scalar::Util::looks_like_number($count)
!ll&&!rl&&r
505120211
defined $count and not ref $count
!ll&&!rl&&r
503615231
MC/DC100%3/3
defined $count and not ref $count and &Scalar::Util::looks_like_number($count)
defined $count not ref $count &Scalar::Util::looks_like_number($count)
Truth table100%4/4
A and not(B) and C
A= defined $countB= not ref $countC= &Scalar::Util::looks_like_number($count)
ABCresult
0XX0
10X0
1100
1111
3156  
3157 # Premise 1: 'zero' is chosen only when the template has it.
3158 # Premise 2: a form the template has is returned as it is.
3159 # Conclusion: 'zero' needs no second look.
3160 211 ▶ return 'zero' if(($count == 0) && exists($template->{'zero'}));
Branch: 1 branch
BranchTrueFalseTotal
if $count == 0 and exists $template->{"zero"} 32 179 211
Condition100%3/3
$count == 0 and exists $template->{"zero"}
!ll&&!rl&&r
1681132
MC/DC100%2/2
$count == 0 and exists $template->{"zero"}
$count == 0 exists $template->{"zero"}
Truth table100%3/3
A and B
A= $count == 0B= exists $template->{"zero"}
ABresult
0X0
100
111
3161  
3162 # Only the language's rule can name a form the template lacks
3163 179 ▶ my $rule = (defined($lang) && exists($PLURAL{$lang})) ? $PLURAL{$lang} : $PLURAL{$FALLBACK_LANG};
Branch: 1 branch
BranchTrueFalseTotal
defined $lang && exists $PLURAL{$lang} ? : 171 8 179
Condition100%3/3
defined $lang and exists $PLURAL{$lang}
!ll&&!rl&&r
26171
MC/DC100%2/2
defined $lang and exists $PLURAL{$lang}
defined $lang exists $PLURAL{$lang}
Truth table100%3/3
A and B
A= defined $langB= exists $PLURAL{$lang}
ABresult
0X0
100
111
3164 179 my $form = $rule->($count);
3165  
3166 179 ▶ return exists($template->{$form}) ? $form : 'other';
Branch: 1 branch
BranchTrueFalseTotal
exists $template->{$form} ? : 169 10 179
3167 }
3168  
3169 # _interpolate - fill a template's %{name}s placeholders
3170 #
3171 # Purpose: Named sprintf, so translators can reorder placeholders.
3172 # Entry: $template - string.
3173 # $args - hash reference of values.
3174 # Exit: Returns the rendered string; a non-ASCII template yields a
3175 # character (UTF-8 flagged) string.
3176 # Side effects: None. Missing values become 'undef' without warning, and a
3177 # non-numeric value for a numeric conversion is rendered as
3178 # it is rather than as 0, as is a number too big for an
3179 # integer conversion.
3180 5806 ▶sub _interpolate {
Subroutine _interpolate: called CC=3 SCAR=11.0
3181 5806 my ($template, $args) = @_;
3182  
3183 # Mark a translated template as characters, so _emit() encodes it even
3184 # when every character is below 0x100, as in French and German
3185 5806 ▶ utf8::upgrade($template) if($template =~ /[^\x00-\x7F]/);
Branch: 1 branch
BranchTrueFalseTotal
if $template =~ /[^\x00-\x7F]/u 4127 1679 5806
3186  
3187 # Only data conversions are allowed: %n and vectors have no place in a
3188 # message, and an unknown conversion is left as literal text
3189 5806 $template =~ s{
3190 %
3191 (?:
3192 (%) # $1: '%%', a literal percent sign
3193 |
3194 \{ (\w+) \} # $2: the placeholder's name
3195 ( # $3: the sprintf conversion:
3196 [-+\ 0\#]*+ # flags, possessive: the width
3197 # below is optional, so never
3198 # needs a '0' back from here
3199 \d{0,3} # width, at most 3 digits
3200 (?: \. \d{1,3} )? # precision, at most 3 digits
3201 [sdiufeEgGxXobc] # a data conversion only
3202 )
3203 )
3204 11277 ▶ }{_format($1, $3, defined($2) ? $args->{$2} : undef)}gex;
Branch: 1 branch
BranchTrueFalseTotal
defined $2 ? : 11274 3 11277
3205  
3206 5806 return $template;
3207 }
3208  
3209 # _format - render one placeholder of _interpolate()
3210 #
3211 # Purpose: Keep the substitution free of nested matches, which would
3212 # reset $1..$3 in the middle of the replacement.
3213 # Entry: $percent - '%' for a '%%' escape, else undef.
3214 # $conversion - sprintf conversion, such as 's' or '.2f'.
3215 # $value - the value to render, or undef.
3216 # Exit: Returns the rendered text.
3217 # Side effects: None; never warns or dies, and leaves $@ alone.
3218 11407 ▶sub _format {
Subroutine _format: called CC=16 SCAR=27.7
3219 11407 my ($percent, $conversion, $value) = @_;
3220  
3221 # Infinity and NaN look like numbers, but %d would print them as -1.
3222 # References are never numbers: looks_like_number() would call an
3223 # object's overloading, which may die
3224 11407 ▶ return '%' if(defined($percent));
Branch: 1 branch
BranchTrueFalseTotal
if defined $percent 15 11392 11407
3225 11392 ▶ return 'undef' if(!defined($value));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 20 11372 11392
3226  
3227 # Numbers are tested on a copy. abs(), <, sprintf and int() cache an
3228 # integer in their argument, and where a float holds that integer
3229 # exactly (long doubles hold 64 bits) perl then writes the value from
3230 # the integer: 1e19 would become 10000000000000000000, not be shown as
3231 # written
3232 11372 my $number = $value;
3233 11372 ▶ my $numeric = !ref($number) && Scalar::Util::looks_like_number($number) && ($number == $number) && (abs($number) != 9**9**9);
Condition100%9/9
!ref($number) && &Scalar::Util::looks_like_number($number) && $number == $number && abs $number != 9**9**9
!ll&&!rl&&r
1086839465
not ref $number and &Scalar::Util::looks_like_number($number) and $number == $number
!ll&&!rl&&r
1085810504
not ref $number and &Scalar::Util::looks_like_number($number)
!ll&&!rl&&r
1510843514
MC/DC100%4/4
!ref($number) && &Scalar::Util::looks_like_number($number) && $number == $number && abs $number != 9**9**9
not ref $number &Scalar::Util::looks_like_number($number) $number == $number abs $number != 9**9**9
Truth table100%5/5
not(A) and B and C && D
A= not ref $numberB= &Scalar::Util::looks_like_number($number)C= $number == $numberD= abs $number != 9**9**9
ABCDresult
0XXX0
10XX0
110X0
11100
11111
3234 # A finite number too big for an integer conversion would be cut to
3235 # -1, ffffffffffffffff or the most negative integer, so it is shown as
3236 # written unless sprintf reads it as itself. Checking against Inf alone
3237 # is not enough: 1e400 is Inf with doubles, but finite with long doubles.
3238 # %d and %i read the value as signed; the others as unsigned, unless it
3239 # is negative, which they print in two's complement
3240 11372 ▶ if($numeric && ($conversion =~ /[diuoxXbc]\z/)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($numeric and $conversion =~ /[diuoxXbc]\z/u) 218 11154 11372
Condition100%3/3
$numeric and $conversion =~ /[diuoxXbc]\z/u
!ll&&!rl&&r
10907247218
MC/DC100%2/2
$numeric and $conversion =~ /[diuoxXbc]\z/u
$numeric $conversion =~ /[diuoxXbc]\z/u
Truth table100%3/3
A and B
A= $numericB= $conversion =~ /[diuoxXbc]\z/u
ABresult
0X0
100
111
3241 218 ▶ my $as = (($conversion =~ /[di]\z/) || ($number < 0)) ? '%d' : '%u';
Branch: 1 branch
BranchTrueFalseTotal
$conversion =~ /[di]\z/u || $number < 0 ? : 180 38 218
Condition100%3/3
$conversion =~ /[di]\z/u or $number < 0
l!l&&r!l&&!r
1631738
MC/DC100%2/2
$conversion =~ /[di]\z/u or $number < 0
$conversion =~ /[di]\z/u $number < 0
Truth table100%3/3
A or B
A= $conversion =~ /[di]\z/uB= $number < 0
ABresult
1X1
011
000
3242 218 my $read = sprintf($as, $number);
3243 # Compared as text, never as numbers: a number would first become a
3244 # float, which rounds 2**64 down onto the largest integer and so
3245 # hides that it does not fit. A string of digits can hold more
3246 # precision than a float, so it is compared digit for digit;
3247 # anything else is compared with the exact integer value of its
3248 # float, which %.0f writes out without rounding
3249 # The leading zeros are atomic. 0* and \d both match '0', so on a
3250 # number that is not all digits, such as '000...0.5' (which
3251 # looks_like_number() accepts), perl would otherwise try every way
3252 # of sharing the zeros between them, and rescan the rest each time:
3253 # quadratic, 2.3s for 20,000 zeros. /a: only ASCII digits are
3254 # digits; looks_like_number() rejects any other kind anyway
3255 218 ▶ if($value =~ m{
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ / \A ([+-]?+) # $1: the sign, if any (?> 0* (?=\d) ) # leading zeros, keeping one digit back; never revisited (\d++) # $2: the digits that are left, at least one ('0' stays '0') \z /ax) { } 190 28 218
3256 \A
3257 ([+-]?+) # $1: the sign, if any
3258 (?> 0* (?=\d) ) # leading zeros, keeping one digit back; never revisited
3259 (\d++) # $2: the digits that are left, at least one ('0' stays '0')
3260 \z
3261 }ax) {
3262 190 ▶ $numeric = ($read eq ((($1 eq '-') && ($2 ne '0')) ? "-$2" : $2));
Branch: 1 branch
BranchTrueFalseTotal
$1 eq '-' && $2 ne '0' ? : 23 167 190
Condition100%3/3
$1 eq "-" and $2 ne 0
!ll&&!rl&&r
163423
MC/DC100%2/2
$1 eq "-" and $2 ne 0
$1 eq "-" $2 ne 0
Truth table100%3/3
A and B
A= $1 eq "-"B= $2 ne 0
ABresult
0X0
100
111
3263 } else {
3264 28 $numeric = ($read eq sprintf('%.0f', int($number)));
3265 }
3266 }
3267 # An object whose overloaded "" dies is shown in plain form, as in
3268 # _stringify(), so a message can always be built. A value shown as
3269 # written goes through _string() for the same reason: returned as it
3270 # is, an object would be stringified by the caller's s///e, outside any
3271 # eval
3272 11372 local $@;
3273 30 ▶ my $text = ($numeric || ($conversion =~ /s\z/)) ? eval { no warnings qw(uninitialized); sprintf("%$conversion", $value) } ## no critic (ProhibitNoWarnings)
Subroutine BEGIN: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$numeric || $conversion =~ /s\z/u ? : 11254 118 11372
Condition100%3/3
$numeric or $conversion =~ /s\z/u
l!l&&r!l&&!r
41710837118
MC/DC100%2/2
$numeric or $conversion =~ /s\z/u
$numeric $conversion =~ /s\z/u
Truth table100%3/3
A or B
A= $numericB= $conversion =~ /s\z/u
ABresult
1X1
011
000
3274 : _string($value);
3275  
3276 11372 ▶ return defined($text) ? $text : overload::StrVal($value);
Branch: 1 branch
BranchTrueFalseTotal
defined $text ? : 11368 4 11372
3277 }
3278  
3279 # _croak - throw a translated error from the caller's point of view
3280 #
3281 # Purpose: The one way this module dies, so every fatal message is
3282 # translatable and reported at the caller's file and line.
3283 # Entry: $self - logger or class name.
3284 # $key - message key.
3285 # $args - optional placeholder values.
3286 # Exit: Does not return.
3287 # Side effects: Croaks.
3288 2768 ▶sub _croak {
Subroutine _croak: called CC=1 SCAR=0.0
3289 2768 my ($self, $key, $args) = @_;
3290  
3291 # Carp formats every argument of the caller's frame, even for a croak
3292 # that shows none of them, and its formatter dies on a character string
3293 # that is not valid UTF-8: level($malformed) died inside Carp. -1 tells
3294 # it to format none, which changes nothing that a croak prints
3295 2768 local $Carp::MaxArgNums = -1;
3296 2768 Carp::croak($self->i18n($key, $args));
3297 }
3298  
3299 =head1 LIMITATIONS
3300  
3301 =over 4
3302  
3303 =item * B<It accepts more than the real logger.> The syslog names
3304 (C<warning>, C<err>, C<crit>, C<emerg>, C<panic>, C<informational>) are
3305 methods here, but not in L<Log::Abstraction> (checked up to version
3306 0.41). Code that calls them passes its tests, and then stops with an
3307 error in production.
3308 A C<strict> option, which allows only the
3309 real L<Log::Abstraction> methods, would be safer.
3310  
3311 =item * B<A misspelt level in C<count()> is not caught.> C<count('wran')>
3312 returns 0, so C<is($logger-E<gt>count('wran'), 0)> passes whatever was
3313 logged. Any name is accepted because L</AUTOLOAD> stores messages under
3314 names that are not levels. C<has_level('wran')> fails, so the typo shows
3315 there. Prefer C<empty()>, or C<count()> with no level, when checking that
3316 nothing was logged.
3317  
3318 =item * B<Messages are stored under the name that was called.> See
3319 L</COMMON PITFALLS>. Your test must use the same name as the code under
3320 test.
3321  
3322 =item * B<C<level()> does not hide messages.> L<Log::Abstraction> drops
3323 messages below its level. This module stores them all, which is usually
3324 what a test wants.
3325  
3326 =item * B<Message text is not always the same as in L<Log::Abstraction>.>
3327 C<undef> becomes C<undef> instead of being dropped, and hashes and arrays
3328 are written out as data. A test that compares the exact text may give a
3329 different result with the real logger.
3330  
3331 =item * B<Mixed encodings in translated output.> See L</ENCODING>.
3332  
3333 =item * B<Internal methods are not locked.> Methods whose names start
3334 with C<_>, and the subclass methods C<_emit> and C<i18n>, can be called by
3335 any code. Nothing checks the caller: a test helper should not need
3336 compiled modules to do that. Do not rely on them outside a subclass.
3337  
3338 =item * B<Many modules are needed.> L<Params::Validate::Strict>,
3339 L<Params::Get>, L<Readonly> and L<Readonly::Values::Syslog> must be
3340 installed, for what is a small test helper. L<Object::Configure> is not used, because it loads
3341 L<Log::Abstraction>, and a test logger should not need that.
3342  
3343 =item * B<Simple translation system.> L<Locale::Maketext> uses numbered
3344 placeholders and has no gender forms. Modules based on gettext need
3345 compiled files. Neither fits a small table with named placeholders, so
3346 this module has its own. Native speakers have not yet checked the
3347 German, French and Chinese texts.
3348  
3349 =item * B<Slow patterns are not stopped.> C<like> and C<unlike> run the
3350 pattern against every stored message. A pattern with nested quantifiers,
3351 such as C<qr/(a+)+$/>, can take a very long time on some messages. This
3352 module does not limit the time.
3353  
3354 =item * B<How long things take.> C<like()> and C<has_level()> stop at
3355 the first message that matches. C<unlike()> that passes, C<count()> with
3356 a level, and C<messages()> look at every stored message, so their time
3357 grows with the number of messages (about 0.1 to 0.25 microseconds a
3358 message on a typical machine). A log call costs about 3 microseconds.
3359 For tests that log hundreds of thousands of messages, call C<clear()>
3360 between phases.
3361  
3362 =item * B<One process only.> Messages are kept in the memory of the
3363 logger object. Messages logged in a child process (after C<fork>) are not
3364 seen by the parent.
3365  
3366 =back
3367  
3368 =head1 DIAGNOSTICS
3369  
3370 Each method lists its messages under C<MESSAGES>. All messages can be
3371 translated or changed; see L</i18n>.
3372  
3373 The text after C<invalid argument:> explains what was wrong, and may show
3374 the value that was given. Other errors, warnings and notices repeat a name
3375 you gave: a level name, a diag name, or a method name. Every value repeated
3376 like this is cut to 200 characters, and control characters in it (such as
3377 a newline, or the escape character that starts a terminal control
3378 sequence) are shown as C<\xNN>. In a character string, the C1 controls
3379 U+0080 to U+009F are shown as C<\xNN> too; in a byte string those bytes
3380 are kept, because they are usually part of UTF-8 text. The bidi controls
3381 (U+200E, U+200F, U+202A to U+202E and U+2066 to U+2069), which change the
3382 order in which text is shown, are shown as C<\x{NNNN}>. So a hostile
3383 value cannot make an error message enormous, add a forged C<ok> line to
3384 the output, control your terminal, or make the message read differently
3385 on screen from what it says. An object whose text form (overloaded C<"">) dies is shown in
3386 Perl's plain form, such as C<My::Class=HASH(0x55d0c8a1e2f8)>: the error
3387 or warning you get is this module's, not the object's.
3388  
3389 =head1 SEE ALSO
3390  
3391 =over 4
3392  
3393 =item * L<Test Dashboard|https://nigelhorne.github.io/Test-Log-Abstraction/coverage/>
3394  
3395 =back
3396  
3397 L<Log::Abstraction>, L<Test::Builder>, L<Test::Most>
3398  
3399 =head1 AUTHOR
3400  
3401 Nigel Horne, C<< <njh at nigelhorne.com> >>
3402  
3403 =encoding utf8
3404  
3405 =head1 FORMAL SPECIFICATION
3406  
3407 This section describes each method in the Z notation. You do not need it
3408 to use the module. It is here so that the behaviour is exact.
3409  
3410 =head2 State
3411  
3412 [TEXT, NAME, KEY, TEMPLATE, TAG, VALUE]
3413 BOOL ::= true | false
3414 SEVERITY == 0 .. 7
3415 BUILTIN == { en, de, fr, zh }
3416  
3417 severity : NAME ⇸ SEVERITY
3418 lower : NAME → NAME
3419 catalogue : TAG ⇸ (KEY ⇸ TEMPLATE)
3420 render : seq VALUE → TEXT
3421 ─────────
3422 dom catalogue = BUILTIN
3423 ∀ n : dom severity • lower n = n
3424  
3425 Entry ≙ [ level : NAME; message : TEXT; fields : TEXT ⇸ VALUE ]
3426  
3427 Rule ::= all | none | levels⟨⟨ℙ NAME⟩⟩ | atleast⟨⟨SEVERITY⟩⟩
3428  
3429 Logger
3430 log : seq Entry
3431 verbose : BOOL
3432 threshold : SEVERITY
3433 lang : TAG
3434 overrides : TAG ⇸ (KEY ⇸ TEMPLATE)
3435 rule : Rule
3436 ─────────
3437 lang ∈ BUILTIN ∪ dom overrides
3438 ∀ e : ran log • e.level = lower e.level
3439  
3440 ΔLogger ≙ [ Logger; Logger' | overrides' = overrides ∧ rule' = rule ]
3441  
3442 printed : Logger × NAME → BOOL
3443 ─────────
3444 ∀ L : Logger; n : NAME •
3445 printed (L, n) = true ⇔
3446 L.verbose = true ∨ L.rule = all
3447 ∨ (∃ S : ℙ NAME • L.rule = levels S ∧ n ∈ S)
3448 ∨ (∃ t : SEVERITY • L.rule = atleast t ∧ n ∈ dom severity ∧ severity n ≤ t)
3449  
3450 C<severity> is the level table under L</Levels and how serious they are>.
3451 C<lower> is Perl's C<lc>. C<catalogue> is the built-in message table, and
3452 C<overrides> is the logger's C<i18n> option; so a logger's language may be
3453 one that only C<overrides> has. C<render> turns a log call's arguments
3454 into its message text (see the level methods' L</Args>). C<rule> is the
3455 C<diag> option, and C<printed> says whether a stored message is also
3456 printed. C<ΔLogger> means the method may change the log and the settings,
3457 but never C<overrides> or C<rule>; C<ΞLogger> means it changes nothing.
3458  
3459 =head2 new
3460  
3461 New
3462 Logger'
3463 opts? : NAME ⇸ VALUE
3464 config : NAME ⇸ VALUE
3465 env : NAME ⇸ TEXT
3466 ─────────
3467 let get ≙ λ k : NAME • (if k ∈ dom opts? then opts? k else config k) •
3468 lower (get level) ∈ dom severity
3469 log' = ⟨⟩
3470 verbose' = (if verbose ∈ dom opts? then opts? verbose
3471 else env TEST_VERBOSE ∨ env VERBOSE)
3472 threshold' = severity (lower (get level))
3473 overrides' = (if i18n ∈ dom opts? then opts? i18n else ∅)
3474 rule' = rule_of (get diag)
3475 lang' = language (opts?, config, env, overrides')
3476  
3477 Clone
3478 ΞLogger
3479 clone! : Logger
3480 ─────────
3481 clone!.log = log
3482 clone!.verbose = verbose
3483 clone!.threshold = threshold
3484 clone!.lang = lang
3485  
3486 C<config> is L</Default settings> and C<env> is C<%ENV>. C<rule_of>
3487 turns the C<diag> option into a C<Rule>, and fails (croaks) for anything
3488 else. C<language> applies the order under L</Language of this module's
3489 messages>: C<lang>, then C<country>, then (for C<lang =E<gt> 'auto'>) the
3490 locale variables in C<env>, then C<config>; the result is the first two or
3491 three letters, if C<BUILTIN> or C<overrides'> has that language, and
3492 otherwise C<en>.
3493  
3494 C<Clone> is C<< $logger->new() >> with no options. Options that are given
3495 replace the matching values, as in C<New>.
3496  
3497 =head2 trace, debug, info, notice, warn, error, fatal, critical, alert, emergency
3498  
3499 Log
3500 ΔLogger
3501 name? : NAME
3502 args? : seq VALUE
3503 ─────────
3504 name? ∈ dom severity
3505 args? = ⟨⟩ ∧ severity name? ≤ severity warn ⇒ log' = log
3506 ¬ (args? = ⟨⟩ ∧ severity name? ≤ severity warn) ⇒
3507 log' = log ⁀ ⟨⟨ level ↦ name?, message ↦ render args? ⟩⟩
3508 verbose' = verbose ∧ threshold' = threshold ∧ lang' = lang
3509  
3510 A stored entry is also printed exactly when C<printed (θLogger, name?)>.
3511  
3512 =head2 is_trace, is_debug, is_info, is_notice, is_warn, is_error, is_critical, is_alert, is_emergency
3513  
3514 IsLevel
3515 ΞLogger
3516 name? : NAME
3517 result! : BOOL
3518 ─────────
3519 name? ∈ dom severity
3520 result! = true ⇔ severity name? ≤ threshold
3521  
3522 =head2 AUTOLOAD
3523  
3524 Unknown
3525 ΔLogger
3526 name? : NAME
3527 args? : seq VALUE
3528 ─────────
3529 name? ∉ dom severity
3530 log' = log ⁀ ⟨⟨ level ↦ lower name?, message ↦ render args? ⟩⟩
3531 verbose' = verbose ∧ threshold' = threshold ∧ lang' = lang
3532  
3533 The notice C<no method 'name?'> is always printed. The name in it is
3534 escaped and cut, as described under L</DIAGNOSTICS>; the stored C<level>
3535 is not. A name in another case,
3536 such as C<INFO>, is not a method, so it comes here, and is stored as
3537 C<info>.
3538  
3539 =head2 messages
3540  
3541 Messages
3542 ΞLogger
3543 result! : seq Entry
3544 ─────────
3545 result! = log
3546  
3547 =head2 clear
3548  
3549 Clear
3550 ΔLogger
3551 ─────────
3552 log' = ⟨⟩
3553 verbose' = verbose ∧ threshold' = threshold ∧ lang' = lang
3554  
3555 =head2 count
3556  
3557 Count
3558 ΞLogger
3559 level? : NAME
3560 result! : ℕ
3561 ─────────
3562 result! = # (log ↾ { e : Entry | e.level = lower level? })
3563  
3564 CountAll
3565 ΞLogger
3566 result! : ℕ
3567 ─────────
3568 result! = # log
3569  
3570 =head2 like
3571  
3572 Like
3573 ΞLogger
3574 pattern? : ℙ TEXT
3575 result! : BOOL
3576 ─────────
3577 result! = true ⇔ (∃ e : ran log • e.message ∈ pattern?)
3578  
3579 =head2 unlike
3580  
3581 Unlike
3582 ΞLogger
3583 pattern? : ℙ TEXT
3584 result! : BOOL
3585 ─────────
3586 result! = true ⇔ (∀ e : ran log • e.message ∉ pattern?)
3587  
3588 =head2 has_level
3589  
3590 HasLevel
3591 ΞLogger
3592 level? : NAME
3593 result! : BOOL
3594 ─────────
3595 result! = true ⇔ (∃ e : ran log • e.level = lower level?)
3596  
3597 =head2 empty
3598  
3599 Empty
3600 ΞLogger
3601 result! : BOOL
3602 ─────────
3603 result! = true ⇔ log = ⟨⟩
3604  
3605 =head2 verbose
3606  
3607 SetVerbose
3608 ΔLogger
3609 value? : BOOL
3610 result! : BOOL
3611 ─────────
3612 verbose' = value?
3613 result! = verbose'
3614 log' = log ∧ threshold' = threshold ∧ lang' = lang
3615  
3616 GetVerbose
3617 ΞLogger
3618 result! : BOOL
3619 ─────────
3620 result! = verbose
3621  
3622 =head2 level
3623  
3624 SetLevel
3625 ΔLogger
3626 name? : NAME
3627 ─────────
3628 name? ∈ dom severity ⇒ threshold' = severity name?
3629 name? ∉ dom severity ⇒ threshold' = threshold
3630 log' = log ∧ verbose' = verbose ∧ lang' = lang
3631  
3632 GetLevel
3633 ΞLogger
3634 result! : SEVERITY
3635 ─────────
3636 result! = threshold
3637  
3638 =head2 flush
3639  
3640 Flush
3641 ΞLogger
3642  
3643 =head2 reopen
3644  
3645 Reopen
3646 ΞLogger
3647  
3648 =head2 lang
3649  
3650 Lang
3651 ΞLogger
3652 result! : LANG
3653 ─────────
3654 result! = lang
3655  
3656 =head2 i18n
3657  
3658 I18n
3659 ΞLogger
3660 key? : KEY
3661 result! : TEXT
3662 ─────────
3663 let find ≙ λ t : TAG •
3664 { m : (TAG ⇸ (KEY ⇸ TEMPLATE)) | m ∈ { overrides, catalogue }
3665 ∧ t ∈ dom m ∧ key? ∈ dom (m t) } •
3666 find lang ≠ ∅ ⇒ result! = fill (first (find lang) lang key?)
3667 find lang = ∅ ∧ find en ≠ ∅ ⇒ result! = fill (first (find en) en key?)
3668 find lang = ∅ ∧ find en = ∅ ⇒ result! = key?
3669  
3670 C<fill> chooses the gender or plural form and fills in the placeholders.
3671 C<first> takes C<overrides> before C<catalogue> when both have the key: the
3672 C<i18n> option is searched first in each language.
3673  
3674 =head1 STATE DIAGRAM
3675  
3676 A logger has two main states: B<EMPTY> (no stored messages) and
3677 B<CAPTURING> (one or more stored messages). Two settings, B<verbose> and
3678 B<level>, can change in either state; they do not move the logger between
3679 states. Methods that only read or test (C<like>, C<count>, C<is_debug>,
3680 and so on) never change the state.
3681  
3682 new(%options)
3683 [check options; choose language,
3684 diag rule and level]
3685 |
3686 | invalid option
3687 +----------------------> croak, no logger made
3688 |
3689 v
3690 +-----------------------------------------+
3691 | EMPTY |<----------------+
3692 | messages = () | |
3693 +-----------------------------------------+ |
3694 | ^ |
3695 | | clear() |
3696 +-------+ [nothing to delete; return the logger] |
3697 | |
3698 | trace() ... emergency(), warning() ... panic() | clear()
3699 | [store the message; print it if the diag rule | [delete all
3700 | or verbose allows; $@ and $! are kept. With no | messages;
3701 | arguments, warn() and above store nothing and stay | return the
3702 | in EMPTY (or CAPTURING), as in Log::Abstraction] | logger]
3703 | |
3704 | wran() or any unknown method (AUTOLOAD) |
3705 | [store under that name; always print |
3706 | "no method 'wran'", the name escaped and cut to |
3707 | 200 characters] |
3708 v |
3709 +-----------------------------------------+ |
3710 | CAPTURING |-----------------+
3711 | messages = (m1, m2, ...) |
3712 +-----------------------------------------+
3713 | ^
3714 | | any level method, or an unknown method
3715 +-------+ [store one more message; maybe print it]
3716  
3717 Changes allowed in BOTH states (the state stays the same):
3718  
3719 verbose(1) / verbose(0) verbose on / off
3720 [from now on: print every message / use
3721 the diag rule]
3722 level('error') level number = 3
3723 [the is_* answers change; nothing is
3724 hidden]
3725 level('bogus') no change [warning; returns undef]
3726  
3727 Read-only calls in BOTH states (the state stays the same):
3728  
3729 like, unlike, has_level, empty
3730 [one TAP result; on failure, print the
3731 messages that explain it]
3732 count, messages, lang, is_trace ... is_emergency, flush, reopen,
3733 i18n
3734 [return a value only]
3735 _emit [print the text; return the logger]
3736 DESTROY() called directly [does nothing; the logger stays]
3737 like(undef), has_level(undef), a bad argument, or any method
3738 called on something that is not a logger (the class name, undef,
3739 a plain reference, or another class's object)
3740 [croak; no change]
3741  
3742 On the class name, with no logger at all (see METHODS FOR
3743 SUBCLASSES):
3744  
3745 i18n [return the text, in the configured
3746 language]
3747 _emit [print the text; return the class name]
3748  
3749 Copying (the original logger does not change):
3750  
3751 EMPTY --- $logger->new(%options) ---> a new logger in EMPTY
3752 CAPTURING --- $logger->new(%options) ---> a new logger in CAPTURING
3753 [the new logger has copies of the messages, and the
3754 same verbose and level, unless new values are given]
3755  
3756 End:
3757  
3758 EMPTY or CAPTURING --- the last reference goes away ---> destroyed
3759 [DESTROY does nothing; nothing is stored or printed]
3760  
3761 =head1 LICENCE AND COPYRIGHT
3762  
3763 Copyright 2026 Nigel Horne.
3764  
3765 Usage is subject to the GPL2 licence terms.
3766 If you use it,
3767 please let me know.
3768  
3769 =cut
3770  
3771 30 1;
↑ Summary