blib/lib/Test/Cmd.pm

filter: Statementstmt 90.0% 360 / 400 Branchbran 83.5% 172 / 206 Conditioncond 62.1% 23 / 37 MC/DCmcdc 35.0% 7 / 20 Subroutinesub 94.5% 52 / 55 Podpod 96.4% 27 / 28 totaltotal 85.9% 641 / 746 CC 126 SCAR 21.8
CC
126
Cov
86%
BEGIN
34.8
_differ_no_lcs
20.0
run
16.3
CRAP 8.9
↑ Summary blib/lib/Test/Cmd/Common.pm »
1 # Copyright 1999-2001 Steven Knight. All rights reserved. This program
2 # is free software; you can redistribute it and/or modify it under the
3 # same terms as Perl itself.
4 #
5 # This package tests an executable program or script,
6 # managing one or more temporary working directories,
7 # keeping track of standard and error output,
8 # and cleaning up after everything is done.
9  
10 package Test::Cmd;
11 111 $Test::Cmd::VERSION = '1.09';
12 111 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 111 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 111 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 111 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 111 ▶use File::Basename (); # don't import the basename() method, we redefine it
Subroutine BEGIN: called CC=1 SCAR=0.0
17 111 ▶use File::Find;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 111 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 111 our @ISA = qw(Exporter File::Spec);
21 111 our @EXPORT_OK = qw(match_exact match_regex diff_exact diff_regex);
22  
23  
24  
25 =head1 NAME
26  
27 Test::Cmd - Perl module for portable testing of commands and scripts
28  
29 =head1 SYNOPSIS
30  
31 An example using L<Test::More> with this module to run a command
32 and then test the exit code, standard out, and standard error:
33  
34 use Test::Cmd;
35 use Test::More tests => 3;
36  
37 my $test = Test::Cmd->new( prog => 'outerr', workdir => '' );
38 $test->run();
39  
40 is( $test->stdout, "out\n", 'standard out' );
41 is( $test->stderr, "err\n", 'standard error' );
42 is( $? >> 8, 1, 'exit status' );
43  
44 Where C<outerr> is the shell script:
45  
46 $ cat outerr
47 #!/bin/sh
48 echo out
49 echo >&2 err
50 exit 1
51 $ chmod +x outerr
52  
53 See below for other examples. Otherwise, the full list of available
54 methods is:
55  
56 use Test::Cmd;
57  
58 $test = Test::Cmd->new(prog => 'program_or_script_to_test',
59 interpreter => 'script_interpreter',
60 string => 'identifier_string',
61 workdir => '',
62 subdir => 'dir',
63 match_sub => $code_ref,
64 verbose => 1);
65  
66 $test->verbose(1);
67  
68 $test->prog('program_or_script_to_test');
69  
70 $test->basename(@suffixlist);
71  
72 $test->interpreter('script_interpreter');
73  
74 $test->string('identifier string');
75  
76 $test->workdir('prefix');
77  
78 $test->workpath('subdir', 'file');
79  
80 $test->subdir('subdir', ...);
81 $test->subdir(['sub', 'dir'], ...);
82  
83 $test->write('file', <<'EOF');
84 contents of file
85 EOF
86 $test->write(['subdir', 'file'], <<'EOF');
87 contents of file
88 EOF
89  
90 $test->read(\$contents, 'file');
91 $test->read(\@lines, 'file');
92 $test->read(\$contents, ['subdir', 'file']);
93 $test->read(\@lines, ['subdir', 'file']);
94  
95 $test->writable('dir');
96 $test->writable('dir', $rwflag);
97 $test->writable('dir', $rwflag, \%errors);
98  
99 $test->preserve(condition, ...);
100  
101 $test->cleanup(condition);
102  
103 $test->run(prog => 'program_or_script_to_test',
104 interpreter => 'script_interpreter',
105 chdir => 'dir', args => 'arguments', stdin => <<'EOF');
106 input to program
107 EOF
108  
109 $test->pass(condition);
110 $test->pass(condition, \&func);
111  
112 $test->fail(condition);
113 $test->fail(condition, \&func);
114 $test->fail(condition, \&func, $caller);
115  
116 $test->no_result(condition);
117 $test->no_result(condition, \&func);
118 $test->no_result(condition, \&func, $caller);
119  
120 $test->stdout;
121 $test->stdout($run_number);
122  
123 $test->stderr;
124 $test->stderr($run_number);
125  
126 $test->match(\@lines, \@matches);
127 $test->match($lines, $matches);
128  
129 $test->match_exact(\@lines, \@matches);
130 $test->match_exact($lines, $matches);
131  
132 $test->match_regex(\@lines, \@regexes);
133 $test->match_regex($lines, $regexes);
134  
135 $test->diff_exact(\@lines, \@matches, \@output);
136 $test->diff_exact($lines, $matches, \@output);
137  
138 $test->diff_regex(\@lines, \@regexes, \@output);
139 $test->diff_regex($lines, $regexes, \@output);
140  
141 sub func {
142 my ($self, $lines, $matches) = @_;
143 # code to match $lines and $matches
144 }
145 $test->match_sub(\&func);
146 $test->match_sub(sub { code to match $_[1] and $_[2] });
147  
148 $test->here;
149  
150 =head1 DESCRIPTION
151  
152 The C<Test::Cmd> module provides a low-level framework for portable
153 automated testing of executable commands and scripts (in any language,
154 not just Perl), especially commands and scripts that interact with the
155 file system.
156  
157 The C<Test::Cmd> module makes no assumptions about what constitutes
158 a successful or failed test. Attempting to read a file that doesn't
159 exist, for example, may or may not be an error, depending on the
160 software being tested.
161  
162 Consequently, no C<Test::Cmd> methods (including the C<new()> method)
163 exit, die or throw any other sorts of exceptions (but they all do return
164 useful error indications). Exceptions or other error status should
165 be handled by a higher layer: a subclass of L<Test::Cmd>, or another
166 testing framework such as the L<Test> or L<Test::Simple> Perl modules,
167 or by the test itself.
168  
169 (That said, see the L<Test::Cmd::Common> module if you want a similar
170 module that provides exception handling, either to use directly in your
171 own tests, or as an example of how to use C<Test::Cmd>.)
172  
173 In addition to running tests and evaluating conditions, the C<Test::Cmd>
174 module manages and cleans up one or more temporary workspace
175 directories, and provides methods for creating files and directories in
176 those workspace directories from in-line data (that is, here-documents),
177 allowing tests to be completely self-contained. When used in
178 conjunction with another testing framework, the C<Test::Cmd> module can
179 function as a I<fixture> (common startup code for multiple tests) for
180 simple management of command execution and temporary workspaces.
181  
182 The C<Test::Cmd> module inherits L<File::Spec> methods
183 (C<file_name_is_absolute()>, C<catfile()>, etc.) to support writing
184 tests portably across a variety of operating and file systems.
185  
186 A C<Test::Cmd> environment object is created via the usual invocation:
187  
188 $test = Test::Cmd->new();
189  
190 Arguments to the C<Test::Cmd::new> method are keyword-value pairs that
191 may be used to initialize the object, typically by invoking the same-named
192 method as the keyword.
193  
194 =head1 TESTING FRAMEWORKS
195  
196 As mentioned, because the C<Test::Cmd> module makes no assumptions
197 about what constitutes success or failure of a test, it can be used to
198 provide temporary workspaces, other file system interaction, or command
199 execution for a variety of testing frameworks. This section describes
200 how to use the C<Test::Cmd> with several different higher-layer testing
201 frameworks.
202  
203 Note that you should I<not> intermix multiple testing frameworks in a
204 single testing script.
205  
206 =head2 C<Test::Harness>
207  
208 The C<Test::Cmd> module may be used in tests that print results in a
209 format suitable for the standard Perl L<Test::Harness> module:
210  
211 use Test::Cmd;
212  
213 print "1..5\n";
214  
215 $test = Test::Cmd->new(prog => 'test_program', workdir => '');
216 if ($test) { print "ok 1\n"; } else { print "not ok 1\n"; }
217  
218 $input = <<_EOF;
219 test_program should process this input
220 and exit successfully (status 0).
221 _EOF_
222  
223 $wrote_file = $test->write('input_file', $input);
224 if ($wrote_file) { print "ok 2\n"; } else { print "not ok 2\n"; }
225  
226 $test->run(args => '-x input_file');
227 if ($? == 0) { print "ok 3\n"; } else { print "not ok 3\n"; }
228  
229 $wrote_file = $test->write('input_file', $input);
230 if ($wrote_file) { print "ok 4\n"; } else { print "not ok 4\n"; }
231  
232 $test->run(args => '-y input_file');
233 if ($? == 0) { print "ok 5\n"; } else { print "not ok 5\n"; }
234  
235 Several other Perl modules simplify the use of L<Test::Harness>
236 by eliminating the need to hand-code the C<print> statements and
237 test numbers. The L<Test> module, the L<Test::Simple> module, and
238 the L<Test::More> module all export an C<ok()> subroutine to test
239 conditions. Here is how the above example would look rewritten to use
240 L<Test::Simple>:
241  
242 use Test::Simple tests => 5;
243 use Test::Cmd;
244  
245 $test = Test::Cmd->new(prog => 'test_program', workdir => '');
246 ok($test, "creating Test::Cmd object");
247  
248 $input = <<_EOF;
249 test_program should process this input
250 and exit successfully (status 0).
251 _EOF_
252  
253 $wrote_file = $test->write('input_file', $input);
254 ok($wrote_file, "writing input_file");
255  
256 $test->run(args => '-x input_file');
257 ok($? == 0, "executing test_program -x input_file");
258  
259 $wrote_file = $test->write('input_file', $input);
260 ok($wrote_file, "writing input_file");
261  
262 $test->run(args => '-y input_file');
263 ok($? == 0, "executing test_program -y input_file");
264  
265 =head2 C<Test::Unit>
266  
267 The Perl L<Test::Unit> package provides a procedural testing interface
268 modeled after a testing framework widely used in the eXtreme Programming
269 development methodology. The C<Test::Cmd> module can function as part
270 of a L<Test::Unit> fixture that can set up workspaces as needed for a
271 set of tests. This avoids having to repeat code to re-initialize an
272 input file multiple times:
273  
274 use Test::Unit;
275 use Test::Cmd;
276
277 my $test;
278
279 $input = <<'EOF';
280 test_program should process this input
281 and exit successfully (status 0).
282 EOF
283
284 sub set_up {
285 $test = Test::Cmd->new(prog => 'test_program', workdir => '');
286 $test->write('input_file', $input);
287 }
288
289 sub test_x {
290 my $result = $test->run(args => '-x input_file');
291 assert($result == 0, "failed test_x\n");
292 }
293
294 sub test_y {
295 my $result = $test->run(args => '-y input_file');
296 assert($result == 0, "failed test_y\n");
297 }
298
299 create_suite();
300 run_suite;
301  
302 Note that, because the C<Test::Cmd> module takes care of cleaning up
303 temporary workspaces on exit, there is no need to remove explicitly the
304 workspace in a C<tear_down> subroutine. (There may, of course, be other
305 things in the test that need a C<tear_down> subroutine.)
306  
307 =head2 Aegis
308  
309 Alternatively, the C<Test::Cmd> module provides C<pass()>, C<fail()>,
310 and C<no_result()> methods that can be used to provide an appropriate
311 exit status and simple printed indication for a test. These methods
312 terminate the test immediately, reporting C<PASSED>, C<FAILED>, or
313 C<NO RESULT> respectively, and exiting with status 0 (success), 1 or 2
314 respectively.
315  
316 The separate C<fail()> and C<no_result()> methods allow for a
317 distinction between an actual failed test and a test that could not be
318 properly evaluated because of an external condition (such as a full file
319 system or incorrect permissions).
320  
321 The exit status values happen to match the requirements of the Aegis
322 change management system, and the printed strings are based on existing
323 Aegis conventions. They are not really Aegis-specific, however, and
324 provide a simple, useful starting point if you don't already have
325 another testing framework:
326  
327 use Test::Cmd;
328  
329 $test = Test::Cmd->new(prog => 'test_program', workdir => '');
330 Test::Cmd->no_result(! $test);
331  
332 $input = <<EOF;
333 test_program should process this input
334 and exit successfully (status 0).
335 EOF
336  
337 $wrote_file = $test->write('input_file', $input);
338 $test->no_result(! $wrote_file);
339  
340 $test->run(args => '-x input_file');
341 $test->fail($? != 0);
342  
343 $wrote_file = $test->write('input_file', $input);
344 $test->no_result(! $wrote_file);
345  
346 $test->run(args => '-y input_file');
347 $test->fail($? != 0);
348  
349 $test->pass;
350  
351 Note that the separate L<Test::Cmd::Common> wrapper module can simplify
352 the above example even further by taking care of common exception
353 handling cases within the testing object itself.
354  
355 use Test::Cmd::Common;
356  
357 $test = Test::Cmd::Common->new(prog => 'test_program', workdir => '');
358  
359 $input = <<EOF;
360 test_program should process this input
361 and exit successfully (status 0).
362 EOF
363  
364 $wrote_file = $test->write('input_file', $input);
365  
366 $test->run(args => '-x input_file');
367  
368 $wrote_file = $test->write('input_file', $input);
369  
370 $test->run(args => '-y input_file');
371  
372 $test->pass;
373  
374 See the L<Test::Cmd::Common> module for details.
375  
376 =head1 METHODS
377  
378 Methods supported by the C<Test::Cmd> module include:
379  
380 =over 4
381  
382 =cut
383  
384  
385  
386 111 my @Cleanup;
387 my $Run_Count;
388 111 my $Default;
389  
390 # Map exit values to conditions.
391 111 my @Cond = ( 'pass', 'fail', 'no_result' );
392  
393 111 ▶BEGIN {
Subroutine BEGIN: called CC=17 SCAR=35.5
394 111 $Run_Count = 0;
395  
396 # The File::Spec->tmpdir method was only added recently,
397 # so we can't assume it's there.
398 111 $Test::Cmd::TMPDIR = eval("File::Spec->tmpdir");
399  
400 # now we do win32 detection. what a mess :-(
401 # if the version is 5.003, we can check $^O
402 111 my $iswin32;
403 111 ▶ if ($] < 5.003) {
Branch: 1 branch
BranchTrueFalseTotal
if ($] < 5.003) { } 0 111 111
404 0 eval("require Win32");
405 0 $iswin32 = ! $@;
406 } else {
407 111 $iswin32 = $^O eq "MSWin32";
408 }
409  
410 111 my @tmps = ();
411 111 ▶ if ($iswin32) {
Branch: 1 branch
BranchTrueFalseTotal
if ($iswin32) { } 0 111 111
412 0 eval("use Win32;");
413 0 $Test::Cmd::_WIN32 = 1;
414 0 $Test::Cmd::Temp_Prefix = "~testcmd$$-";
415 0 $Test::Cmd::Cwd_Ref = \&Win32::GetCwd;
416 # Test for WIN32 temporary directories.
417 # The following is lifted from the 5.005056
418 # version of File::Spec::Win32::tmpdir.
419 0 push @tmps, (@ENV{qw(TMPDIR TEMP TMP)}, qw(/tmp /));
420 } else {
421 111 ▶ eval("use Cwd");
Subroutine BEGIN: called CC=1 SCAR=0.0
422 111 $Test::Cmd::Temp_Prefix = "testcmd$$.";
423 111 $Test::Cmd::Cwd_Ref = \&Cwd::cwd;
424 # Test for UNIX temporary directories.
425 # The following is lifted from the 5.005056
426 # version of File::Spec::Unix::tmpdir.
427 111 push @tmps, ($ENV{TMPDIR}, "/tmp");
428 }
429  
430 111 ▶ if (! $Test::Cmd::TMPDIR) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Test::Cmd::TMPDIR) 0 111 111
431 0 foreach (@tmps) {
432 0 ▶ next unless defined && -d && -w;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ and -d $_ and -w $_ 0 0 0
Condition0%0/6
defined $_ and -d $_ and -w $_
!ll&&!rl&&r
000
defined $_ and -d $_
!ll&&!rl&&r
000
MC/DC0%0/3
defined $_ and -d $_ and -w $_
defined $_ -d $_ -w $_
Truth table0%0/4
A and B and C
A= defined $_B= -d $_C= -w $_
ABCresult
0XX0
10X0
1100
1111
433 0 $Test::Cmd::TMPDIR = $_;
434 0 last;
435 }
436 }
437  
438 # Get the absolute path to the temporary directory, in case
439 # the TMPDIR specification is affected by symbolic links,
440 # or by lack of a volume name on WIN32.
441 # The following better way isn't available in the Cwd module
442 # until sometime after 5.003:
443 # $Test::Cmd::TMPDIR = Cwd::abs_path($Test::Cmd::TMPDIR);
444 111 my($save) = &$Test::Cmd::Cwd_Ref();
445 111 chdir($Test::Cmd::TMPDIR);
446 111 $Test::Cmd::TMPDIR = &$Test::Cmd::Cwd_Ref();
447 111 chdir($save);
448  
449 111 $Default = {};
450  
451 111 $Default->{'failed'} = 0;
452 111 ▶ $Default->{'verbose'} = $ENV{VERBOSE} || 0;
Condition50%1/2
$ENV{'VERBOSE'} || 0
l!l
0111
MC/DC0%0/1
$ENV{'VERBOSE'} || 0
$ENV{'VERBOSE'}
Truth table50%1/2
A
A= $ENV{'VERBOSE'}
Aresult
11
00
453  
454 111 ▶ if (defined $ENV{PRESERVE}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{'PRESERVE'}) { } 6 105 111
455 6 ▶ $Default->{'preserve'}->{'fail'} = $ENV{PRESERVE} || 0;
Condition50%1/2
$ENV{'PRESERVE'} || 0
l!l
60
MC/DC0%0/1
$ENV{'PRESERVE'} || 0
$ENV{'PRESERVE'}
Truth table50%1/2
A
A= $ENV{'PRESERVE'}
Aresult
11
00
456 6 ▶ $Default->{'preserve'}->{'pass'} = $ENV{PRESERVE} || 0;
Condition50%1/2
$ENV{'PRESERVE'} || 0
l!l
60
MC/DC0%0/1
$ENV{'PRESERVE'} || 0
$ENV{'PRESERVE'}
Truth table50%1/2
A
A= $ENV{'PRESERVE'}
Aresult
11
00
457 6 ▶ $Default->{'preserve'}->{'no_result'} = $ENV{PRESERVE} || 0;
Condition50%1/2
$ENV{'PRESERVE'} || 0
l!l
60
MC/DC0%0/1
$ENV{'PRESERVE'} || 0
$ENV{'PRESERVE'}
Truth table50%1/2
A
A= $ENV{'PRESERVE'}
Aresult
11
00
458 } else {
459 105 ▶ $Default->{'preserve'}->{'fail'} = $ENV{PRESERVE_FAIL} || 0;
Condition100%2/2
$ENV{'PRESERVE_FAIL'} || 0
l!l
4101
MC/DC100%1/1
$ENV{'PRESERVE_FAIL'} || 0
$ENV{'PRESERVE_FAIL'}
Truth table100%2/2
A
A= $ENV{'PRESERVE_FAIL'}
Aresult
11
00
460 105 ▶ $Default->{'preserve'}->{'pass'} = $ENV{PRESERVE_PASS} || 0;
Condition100%2/2
$ENV{'PRESERVE_PASS'} || 0
l!l
4101
MC/DC100%1/1
$ENV{'PRESERVE_PASS'} || 0
$ENV{'PRESERVE_PASS'}
Truth table100%2/2
A
A= $ENV{'PRESERVE_PASS'}
Aresult
11
00
461 105 ▶ $Default->{'preserve'}->{'no_result'} = $ENV{PRESERVE_NO_RESULT} || 0;
Condition100%2/2
$ENV{'PRESERVE_NO_RESULT'} || 0
l!l
3102
MC/DC100%1/1
$ENV{'PRESERVE_NO_RESULT'} || 0
$ENV{'PRESERVE_NO_RESULT'}
Truth table100%2/2
A
A= $ENV{'PRESERVE_NO_RESULT'}
Aresult
11
00
462 }
463  
464 0 ▶ sub handler {
Subroutine handler: not called CC=2 SCAR=17.9
Pod undocumented
465 0 print STDERR "NO RESULT -- SIG$_ received.\n";
466 0 my $test;
467 0 foreach $test (@Cleanup) {
468 0 $test->cleanup('no_result');
469 }
470 0 exit(2);
471 }
472  
473 111 ▶ $SIG{HUP} = \&handler if $SIG{HUP};
Branch: 1 branch
BranchTrueFalseTotal
if $SIG{"HUP"} 0 111 111
474 111 $SIG{INT} = \&handler;
475 111 $SIG{QUIT} = \&handler;
476 111 $SIG{TERM} = \&handler;
477 }
478  
479 111 ▶END {
Subroutine END: called CC=3 SCAR=11.1
480 111 ▶ my $cond = @Cond[$?] || 'no_result';
Condition50%1/2
@Cond[$?] || 'no_result'
l!l
1110
MC/DC0%0/1
@Cond[$?] || 'no_result'
@Cond[$?]
Truth table50%1/2
A
A= @Cond[$?]
Aresult
11
00
481 111 my $test;
482 111 foreach $test (@Cleanup) {
483 134 $test->cleanup($cond);
484 }
485 }
486  
487  
488  
489 =item C<new>
490  
491 Create a new C<Test::Cmd> environment. Arguments with which to initialize
492 the environment are passed in as keyword-value pairs. Fails if a
493 specified temporary working directory or subdirectory cannot be created.
494 Does NOT die or exit on failure, but returns C<undef> if the test environment
495 object cannot be created.
496  
497 =cut
498  
499 135 ▶sub new {
Subroutine new: called CC=7 SCAR=19.5
Pod documented
500 135 my $type = shift;
501 135 my $self = {};
502  
503 135 %$self = %$Default;
504  
505 135 $self->{'cleanup'} = [];
506  
507 135 $self->{'preserve'} = {};
508 135 %{$self->{'preserve'}} = %{$Default->{'preserve'}};
509  
510 135 $self->{'cwd'} = &$Test::Cmd::Cwd_Ref();
511  
512 135 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 186 135 321
513 186 my $keyword = shift;
514 186 $self->{$keyword} = shift;
515 }
516  
517 135 bless $self, $type;
518  
519 135 ▶ if (defined $self->{'workdir'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"workdir"}) 118 17 135
520 118 ▶ if (! $self->workdir($self->{'workdir'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->workdir($self->{"workdir"})) 1 117 118
521 1 return undef;
522 }
523 }
524 134 push @Cleanup, $self;
525 134 ▶ if (defined $self->{'subdir'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"subdir"}) 10 124 134
526 10 ▶ if (! $self->subdir($self->{'subdir'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->subdir($self->{"subdir"})) 1 8 9
527 1 return undef;
528 }
529 }
530  
531 132 $self->prog($self->{'prog'});
532  
533 132 ▶ $self->match_sub($self->{'match_sub'} || \&Test::Cmd::match_regex);
Condition100%2/2
$self->{'match_sub'} || \&Test::Cmd::match_regex
l!l
3129
MC/DC100%1/1
$self->{'match_sub'} || \&Test::Cmd::match_regex
$self->{'match_sub'}
Truth table100%2/2
A
A= $self->{'match_sub'}
Aresult
11
00
534  
535  
536 132 $self;
537 }
538  
539  
540  
541 =item C<verbose>
542  
543 Sets the verbose level for the environment object to the specified value.
544  
545 =cut
546  
547 0 ▶sub verbose {
Subroutine verbose: not called CC=1 SCAR=6.9
Pod documented
548 0 my $self = shift;
549 0 $self->{'verbose'} = $_;
550 }
551  
552  
553  
554 =item C<prog>
555  
556 Specifies the executable program or script to be tested. Returns the
557 absolute path name of the current program or script.
558  
559 =cut
560  
561 140 ▶sub prog {
Subroutine prog: called CC=3 SCAR=11.0
Pod documented
562 140 my ($self, $prog) = @_;
563 140 ▶ if ($prog) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prog) 33 107 140
564 # make sure we're always talking about the same program
565 33 ▶ if (! $self->file_name_is_absolute($prog)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->file_name_is_absolute($prog)) 23 10 33
566 23 $prog = $self->catfile($self->{'cwd'}, $prog);
567 }
568 33 $self->{'prog'} = $prog;
569 }
570 140 return $self->{'prog'};
571 }
572  
573  
574  
575 =item C<basename>
576  
577 Returns the basename of the current program or script. Any specified
578 arguments are a list of file suffixes that may be stripped from the
579 basename.
580  
581 =cut
582  
583 54 ▶sub basename {
Subroutine basename: called CC=2 SCAR=6.9
Pod documented
584 54 my $self = shift;
585 54 ▶ return undef if ! $self->{'prog'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"prog"} 24 30 54
586 30 File::Basename::basename($self->{'prog'}, @_);
587 }
588  
589  
590  
591 =item C<interpreter>
592  
593 Specifies the program to be used to interpret C<prog> as a script.
594 Returns the current value of C<interpreter>.
595  
596 =cut
597  
598 1 ▶sub interpreter {
Subroutine interpreter: called CC=2 SCAR=7.1
Pod documented
599 1 my ($self, $interpreter) = @_;
600 1 ▶ $self->{'interpreter'} = $interpreter if defined $interpreter;
Branch: 1 branch
BranchTrueFalseTotal
if defined $interpreter 1 0 1
601 1 $self->{'interpreter'};
602 }
603  
604  
605  
606 =item C<string>
607  
608 Specifies an identifier string for the functionality being tested to be
609 printed on failure or no result.
610  
611 =cut
612  
613 4 ▶sub string {
Subroutine string: called CC=2 SCAR=6.9
Pod documented
614 4 my ($self, $string) = @_;
615 4 ▶ $self->{'string'} = $string if defined $string;
Branch: 1 branch
BranchTrueFalseTotal
if defined $string 1 3 4
616 4 $self->{'string'};
617 }
618  
619  
620  
621 111 my $counter = 0;
622  
623 118 ▶sub _workdir_name {
Subroutine _workdir_name: called CC=2 SCAR=7.0
624 118 my $self = shift;
625 118 while (1) {
626 118 $counter++;
627 118 my $name = $self->catfile($Test::Cmd::TMPDIR,
628 $Test::Cmd::Temp_Prefix . $counter);
629 118 ▶ return $name if ! -e $name;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $name 118 0 118
630 }
631 }
632  
633 =item C<workdir>
634  
635 When an argument is specified, creates a temporary working directory
636 with the specified name. If the argument is a NULL string (''),
637 the directory is named C<testcmd> by default, followed by the
638 unique ID of the executing process.
639  
640 Returns the absolute pathname to the temporary working directory, or
641 FALSE if the directory could not be created.
642  
643 =cut
644  
645 223 ▶sub workdir {
Subroutine workdir: called CC=4 SCAR=13.9
Pod documented
646 223 my ($self, $workdir) = @_;
647 223 ▶ if (defined($workdir)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $workdir) 123 100 223
648 # return if $workdir && $self->{'workdir'} eq $workdir; # no change
649 123 ▶ my $wdir = $workdir || $self->_workdir_name;
Condition66%2/3
$workdir || $self->_workdir_name
l!l&&r!l&&!r
51180
MC/DC0%0/2
$workdir || $self->_workdir_name
$workdir $self->_workdir_name
Truth table66%2/3
A || B
A= $workdirB= $self->_workdir_name
ABresult
1X1
011
000
650 123 ▶ if (!mkdir($wdir, 0755)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (mkdir $wdir, 493) 2 121 123
651 2 return undef;
652 }
653 # The following better way to fetch the absolute path of the
654 # workdir isn't available in the Cwd module until sometime
655 # after 5.003:
656 # $self->{'workdir'} = Cwd::abs_path($wdir);
657 121 my($save) = &$Test::Cmd::Cwd_Ref();
658 121 chdir($wdir);
659 121 $self->{'workdir'} = &$Test::Cmd::Cwd_Ref();
660 121 chdir($save);
661 121 push(@{$self->{'cleanup'}}, $self->{'workdir'});
662 }
663 221 $self->{'workdir'};
664 }
665  
666  
667  
668 =item C<workpath>
669  
670 Returns the absolute path name to a subdirectory or file under the
671 current temporary working directory by concatenating the temporary
672 working directory name with the specified arguments.
673  
674 =cut
675  
676 30 ▶sub workpath {
Subroutine workpath: called CC=2 SCAR=6.9
Pod documented
677 30 my $self = shift;
678 30 ▶ return undef if ! $self->{'workdir'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"workdir"} 1 29 30
679 29 $self->catfile($self->{'workdir'}, @_);
680 }
681  
682  
683  
684 =item C<subdir>
685  
686 Creates new subdirectories under the temporary working dir, one for
687 each argument. An argument may be an array reference, in which case the
688 array elements are concatenated together using the C<File::Spec-&>catfile>
689 method. Subdirectories multiple levels deep must be created via a
690 separate argument for each level:
691  
692 $test->subdir('sub', ['sub', 'dir'], [qw(sub dir ectory)]);
693  
694 Returns the number of subdirectories actually created.
695  
696 =cut
697  
698 18 ▶sub subdir {
Subroutine subdir: called CC=5 SCAR=16.1
Pod documented
699 18 my $self = shift;
700 18 my $count = 0;
701 18 foreach (@_) {
702 23 ▶ my $newdir = ref $_ ? $self->catfile(@$_) : $_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 10 13 23
703 23 ▶ if (! $self->file_name_is_absolute($newdir)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->file_name_is_absolute($newdir)) 21 2 23
704 21 $newdir = $self->catfile($self->{'workdir'}, $newdir);
705 }
706 23 ▶ if (mkdir($newdir, 0755)) {
Branch: 1 branch
BranchTrueFalseTotal
if (mkdir $newdir, 493) 18 5 23
707 18 $count++;
708 }
709 }
710 18 return $count;
711 }
712  
713  
714  
715 =item C<write>
716  
717 Writes the specified text (second argument) to the specified file name
718 (first argument). The file name may be an array reference, in which
719 case all the array elements except the last are subdirectory names
720 to be concatenated together. The file is created under the temporary
721 working directory. Any subdirectories in the path must already exist.
722  
723 =cut
724  
725 60 ▶sub write {
Subroutine write: called CC=5 SCAR=16.2
Pod documented
726 60 my $self = shift;
727 60 my $file = shift; # the file to write to
728 60 ▶ $file = $self->catfile(@$file) if ref $file;
Branch: 1 branch
BranchTrueFalseTotal
if ref $file 7 53 60
729 60 ▶ if (! $self->file_name_is_absolute($file)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->file_name_is_absolute($file)) 51 9 60
730 51 $file = $self->catfile($self->{'workdir'}, $file);
731 }
732 60 ▶ if (! open(OUT, ">$file")) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open OUT, ">$file") 5 55 60
733 5 return undef;
734 }
735 55 ▶ if (! print OUT @_) {
Branch: 1 branch
BranchTrueFalseTotal
unless (print OUT @_) 0 55 55
736 0 return undef;
737 }
738 55 return close(OUT);
739 }
740  
741  
742  
743 =item C<read>
744  
745 Reads the contents of the specified file name (second argument) into
746 the scalar or array referred to by the first argument. The file name
747 may be an array reference, in which case all the array elements except
748 the last are subdirectory names to be concatenated together. The file
749 is assumed to be under the temporary working directory unless it is an
750 absolute path name.
751  
752 Returns TRUE on successfully opening and reading the file, FALSE
753 otherwise.
754  
755 =cut
756  
757 137 ▶sub read {
Subroutine read: called CC=8 SCAR=21.0
Pod documented
758 137 my ($self, $destref, $file) = @_;
759 137 ▶ return undef if ref $destref ne 'SCALAR' && ref $destref ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $destref ne "SCALAR" and ref $destref ne "ARRAY" 0 137 137
Condition66%2/3
ref $destref ne "SCALAR" and ref $destref ne "ARRAY"
!ll&&!rl&&r
81290
MC/DC0%0/2
ref $destref ne "SCALAR" and ref $destref ne "ARRAY"
ref $destref ne "SCALAR" ref $destref ne "ARRAY"
Truth table66%2/3
A and B
A= ref $destref ne "SCALAR"B= ref $destref ne "ARRAY"
ABresult
0X0
100
111
760 137 ▶ $file = $self->catfile(@$file) if ref $file;
Branch: 1 branch
BranchTrueFalseTotal
if ref $file 4 133 137
761 137 ▶ if (! $self->file_name_is_absolute($file)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->file_name_is_absolute($file)) 18 119 137
762 18 $file = $self->catfile($self->{'workdir'}, $file);
763 }
764 137 ▶ if (! open(IN, "<$file")) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open IN, "<$file") 5 132 137
765 5 return undef;
766 }
767 132 my @lines = <IN>;
768 132 ▶ if (! close(IN)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (close IN) 0 132 132
769 0 return undef;
770 }
771 132 ▶ if (ref $destref eq 'SCALAR') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $destref eq 'SCALAR') { } 6 126 132
772 6 $$destref = join('', @lines);
773 } else {
774 126 @$destref = @lines;
775 }
776 132 return (1);
777 }
778  
779  
780  
781 =item C<writable>
782  
783 Makes every file and directory within the specified directory tree
784 writable (C<rwflag> == TRUE) or not writable (C<rwflag> == FALSE). The
785 default is to make the directory tree writable. Optionally fills in the
786 supplied hash reference with a hash of path names that could not have
787 their permissions set appropriately, with the reason why each could not
788 be set.
789  
790 =cut
791  
792 111 my $_errors;
793  
794 116 ▶sub writable {
Subroutine writable: called CC=4 SCAR=14.1
Pod documented
795 116 my ($self, $dir, $flag, $err) = @_;
796 116 ▶ $flag = 1 if ! defined $flag;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $flag 1 115 116
797 116 ▶ $Test::Cmd::_errors = $err || {};
Condition100%2/2
$err || {}
l!l
1115
MC/DC100%1/1
$err || {}
$err
Truth table100%2/2
A
A= $err
Aresult
11
00
798 116 ▶ if ($flag) {
Branch: 1 branch
BranchTrueFalseTotal
if ($flag) { } 114 2 116
799 413 ▶ sub _writable {
Subroutine _writable: called CC=2 SCAR=9.2
800 413 ▶ if (!chmod 0755, $_) {
Branch: 1 branch
BranchTrueFalseTotal
if (not chmod(0755, $_)) 0 413 413
801 0 $Test::Cmd::_errors->{$_} = $!;
802 }
803 }
804 114 finddepth(\&_writable, $dir);
805 } else {
806 8 ▶ sub _writeprotect {
Subroutine _writeprotect: called CC=2 SCAR=9.2
807 8 ▶ if (!chmod 0555, $_) {
Branch: 1 branch
BranchTrueFalseTotal
if (not chmod(0555, $_)) 0 8 8
808 0 $Test::Cmd::_errors->{$_} = $!;
809 }
810 }
811 2 finddepth(\&_writeprotect, $dir);
812 }
813 116 return 0 + keys %$Test::Cmd::_errors;
814 }
815  
816  
817  
818 =item C<preserve>
819  
820 Arranges for the temporary working directories for the specified
821 C<Test::Cmd> environment to be preserved for one or more conditions.
822 If no conditions are specified, arranges for the temporary working
823 directories to be preserved for all conditions.
824  
825 =cut
826  
827 3 ▶sub preserve {
Subroutine preserve: called CC=3 SCAR=11.1
Pod documented
828 3 my $self = shift;
829 3 ▶ my @cond = (@_) ? @_ : qw(pass fail no_result);
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 3 0 3
830 3 my $cond;
831 3 foreach $cond (@cond) {
832 4 $self->{'preserve'}->{$cond} = 1;
833 }
834 }
835  
836  
837  
838 405 ▶sub _nuke {
Subroutine _nuke: called CC=4 SCAR=13.9
839 # print STDERR "unlink($_)\n" if (!-d $_);
840 # print STDERR "rmdir($_)\n" if (-d $_ && $_ ne ".");
841 405 ▶ unlink($_) if (!-d $_);
Branch: 1 branch
BranchTrueFalseTotal
unless -d $_ 272 133 405
842 405 ▶ rmdir($_) if (-d $_ && $_ ne ".");
Branch: 1 branch
BranchTrueFalseTotal
if -d $_ and $_ ne "." 21 384 405
Condition100%3/3
-d $_ and $_ ne "."
!ll&&!rl&&r
27211221
MC/DC100%2/2
-d $_ and $_ ne "."
-d $_ $_ ne "."
Truth table100%3/3
A and B
A= -d $_B= $_ ne "."
ABresult
0X0
100
111
843 405 1;
844 }
845  
846  
847  
848 =item C<cleanup>
849  
850 Removes any temporary working directories for the specified C<Test::Cmd>
851 environment. If the environment variable C<PRESERVE> was set when
852 the C<Test::Cmd> module was loaded, temporary working directories are
853 not removed. If any of the environment variables C<PRESERVE_PASS>,
854 C<PRESERVE_FAIL>, or C<PRESERVE_NO_RESULT> were set when the C<Test::Cmd>
855 module was loaded, then temporary working directories are not removed
856 if the test passed, failed, or had no result, respectively. Temporary
857 working directories are also preserved for conditions specified via the
858 C<preserve> method.
859  
860 Typically, this method is not called directly, but is used when the
861 script exits to clean up temporary working directories as appropriate
862 for the exit status.
863  
864 =cut
865  
866 150 ▶sub cleanup {
Subroutine cleanup: called CC=6 SCAR=18.0
Pod documented
867 150 my ($self, $cond) = @_;
868 150 ▶ $cond = (($self->{'failed'} == 0) ? 'pass' : 'fail') if !$cond;
Branch: 2 branches
BranchTrueFalseTotal
unless $cond 5 145 150
$self->{'failed'} == 0 ? : 5 0 5
869 150 ▶ if ($self->{'preserve'}->{$cond}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"preserve"}{$cond}) 17 133 150
870 17 ▶ print STDERR "Preserving work directory ".$self->{'workdir'}."\n" if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 17 17
871 17 return;
872 }
873 133 chdir $self->{'cwd'}; # cd out of whatever work dir we're in
874 133 my $dir;
875 133 foreach $dir (@{$self->{'cleanup'}}) {
876 112 $self->writable($dir, "true");
877 112 finddepth(\&_nuke, $dir);
878 112 rmdir($dir);
879 }
880 133 $self->{'cleanup'} = [];
881 }
882  
883  
884  
885 =item C<run>
886  
887 Runs a test of the program or script for the test environment. Standard
888 output and error output are saved for future retrieval via the C<stdout>
889 and C<stderr> methods.
890  
891 Arguments are supplied as keyword-value pairs:
892  
893 =over 4
894  
895 =item C<args>
896  
897 Specifies the command-line arguments to be supplied to the program
898 or script under test for this run:
899  
900 $test->run(args => 'arg1 arg2');
901  
902 =item C<chdir>
903  
904 Changes directory to the path specified as the value argument:
905  
906 $test->run(chdir => 'xyzzy');
907  
908 If the specified path is not an absolute path name (begins with '/'
909 on Unix systems), then the subdirectory is relative to the temporary
910 working directory for the environment (C<$test-&>workdir>). Note that,
911 by default, the C<Test::Cmd> module does NOT chdir to the temporary
912 working directory, so to execute the test under the temporary working
913 directory, you must specify an explicit C<chdir> to the current directory:
914  
915 $test->run(chdir => '.'); # Unix-specific
916  
917 $test->run(chdir => $test->curdir); # portable
918  
919 =item C<interpreter>
920  
921 Specifies the program to be used to interpret C<prog> as a script,
922 for this run only. This does not change the C<$test-&>interpreter>
923 value of the test environment.
924  
925 =item C<prog>
926  
927 Specifies the executable program or script to be run, for this run only.
928 This does not change the C<$test-&>prog> value of the test environment.
929  
930 =item C<stdin>
931  
932 Pipes the specified value (string or array ref) to the program
933 or script under test for this run:
934  
935 $test->run(stdin => <<_EOF_);
936 input to the program under test
937 _EOF_
938  
939 =back
940  
941 Returns the exit status of the program or script.
942  
943 =cut
944  
945 88 ▶sub run {
Subroutine run: called CC=16 SCAR=27.9
Pod documented
946 88 my $self = shift;
947 88 my %args = @_;
948 88 my $oldcwd;
949 88 ▶ if ($args{'chdir'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"chdir"}) 6 82 88
950 6 $oldcwd = &$Test::Cmd::Cwd_Ref();
951 6 ▶ if (! $self->file_name_is_absolute($args{'chdir'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->file_name_is_absolute($args{"chdir"})) 6 0 6
952 6 $args{'chdir'} = $self->catfile($self->{'workdir'}, $args{'chdir'});
953 }
954 6 ▶ print STDERR "Changing to $args{'chdir'}\n" if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 6 6
955 6 ▶ if (!chdir $args{'chdir'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (chdir $args{"chdir"}) 2 4 6
956 2 return undef;
957 }
958 }
959 86 $Run_Count++;
960 86 my $stdout_file = $self->_stdout_file($Run_Count);
961 86 my $stderr_file = $self->_stderr_file($Run_Count);
962 86 my $cmd;
963 86 ▶ if ($args{'prog'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'prog'}) { } 44 42 86
964 44 ▶ if (! $self->file_name_is_absolute($args{'prog'})) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->file_name_is_absolute($args{"prog"})) 7 37 44
965 7 $args{'prog'} = $self->catfile($self->{'cwd'}, $args{'prog'});
966 }
967 44 $cmd = $args{'prog'};
968 44 ▶ $cmd = $args{'interpreter'}." ".$cmd if $args{'interpreter'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"interpreter"} 4 40 44
969 } else {
970 42 $cmd = $self->{'prog'};
971 42 ▶ if ($args{'interpreter'}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'interpreter'}) { } 2 40 42
elsif ($self->{'interpreter'}) { } 36 4 40
972 2 $cmd = $args{'interpreter'}." ".$cmd;
973 } elsif ($self->{'interpreter'}) {
974 36 $cmd = $self->{'interpreter'}." ".$cmd;
975 }
976 }
977 86 ▶ $cmd = $cmd." ".$args{'args'} if $args{'args'};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"args"} 15 71 86
978 86 $cmd =~ s/\$work/$self->{'workdir'}/g;
979 86 $cmd = "|$cmd 1>$stdout_file 2>$stderr_file";
980 86 ▶ print STDERR "Invoking $cmd\n" if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 86 86
981 86 ▶ if (! open(RUN, $cmd)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open RUN, $cmd) 0 86 86
982 0 $? = 2;
983 0 print STDERR "Could not invoke $cmd: $!\n";
984 0 return undef;
985 }
986 86 ▶ if ($args{'stdin'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"stdin"}) 40 46 86
987 40 ▶ print RUN ref $args{'stdin'} ? @{$args{'stdin'}} : $args{'stdin'};
Branch: 1 branch
BranchTrueFalseTotal
ref $args{'stdin'} ? : 1 39 40
988 }
989 86 close(RUN);
990 86 my $return = $?;
991 86 ▶ chdir $oldcwd if $oldcwd;
Branch: 1 branch
BranchTrueFalseTotal
if $oldcwd 4 82 86
992 86 return $return;
993 }
994  
995  
996  
997 243 ▶sub _to_value {
Subroutine _to_value: called CC=3 SCAR=12.0
998 243 my $v = shift;
999 243 ▶ (ref $v or '') eq 'CODE' ? &$v() : $v;
Branch: 1 branch
BranchTrueFalseTotal
(ref $v || '') eq 'CODE' ? : 0 243 243
Condition50%1/2
ref $v || ''
l!l
0243
MC/DC0%0/1
ref $v || ''
ref $v
Truth table50%1/2
A
A= ref $v
Aresult
11
00
1000 }
1001  
1002  
1003  
1004 =item C<pass>
1005  
1006 Exits the test successfully. Reports "PASSED" on the error output and
1007 exits with a status of 0. If a condition is supplied, only exits
1008 the test if the condition evaluates TRUE. If a function reference is
1009 supplied, executes the function before reporting and exiting.
1010  
1011 =cut
1012  
1013 31 ▶sub pass {
Subroutine pass: called CC=4 SCAR=14.0
Pod documented
1014 31 my $self = shift;
1015 31 ▶ @_ = (1) if @_ == 0; # provide default arg
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 30 1 31
1016 31 my ($cond, $funcref) = @_;
1017 31 ▶ return if ! _to_value($cond);
Branch: 1 branch
BranchTrueFalseTotal
unless _to_value($cond) 0 31 31
1018 31 ▶ &$funcref() if $funcref;
Branch: 1 branch
BranchTrueFalseTotal
if $funcref 0 31 31
1019 31 print STDERR "PASSED\n";
1020 # Let END take care of cleanup.
1021 31 exit (0);
1022 }
1023  
1024  
1025  
1026 =item C<fail>
1027  
1028 Exits the test unsuccessfully. Reports "FAILED test of {string} at line
1029 {line} of {file}." on the error output and exits with a status of 1.
1030 If a condition is supplied, only exits the test if the condition evaluates
1031 TRUE. If a function reference is supplied, executes the function before
1032 reporting and exiting. If a caller level is supplied, prints a simple
1033 calling trace N levels deep as part of reporting the failure.
1034  
1035 =cut
1036  
1037 77 ▶sub fail {
Subroutine fail: called CC=9 SCAR=22.0
Pod documented
1038 77 my $self = shift;
1039 77 ▶ @_ = (1) if @_ == 0; # provide default arg
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 5 72 77
1040 77 my ($cond, $funcref, $caller) = @_;
1041 77 ▶ return if ! _to_value($cond);
Branch: 1 branch
BranchTrueFalseTotal
unless _to_value($cond) 59 18 77
1042 18 ▶ &$funcref() if $funcref;
Branch: 1 branch
BranchTrueFalseTotal
if $funcref 9 9 18
1043 18 ▶ $caller = 0 if ! defined($caller);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $caller 9 9 18
1044 18 my $of_str = " ";
1045 18 ▶ if (ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self) 17 1 18
1046 17 my $basename = $self->basename;
1047 17 ▶ if ($basename) {
Branch: 1 branch
BranchTrueFalseTotal
if ($basename) 9 8 17
1048 9 $of_str = " of ".$self->basename;
1049 9 ▶ if ($self->{'string'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"string"}) 1 8 9
1050 1 $of_str .= " [".$self->{'string'}."]";
1051 }
1052 9 $of_str .= "\n\t";
1053 }
1054 }
1055 18 my $c = 0;
1056 18 my ($pkg,$file,$line,$sub) = caller($c++);
1057 18 print STDERR "FAILED test${of_str}at line $line of $file";
1058 18 ▶ while ($c <= $caller) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c <= $caller) 12 18 30
1059 12 ($pkg,$file,$line,$sub) = caller($c++);
1060 12 print STDERR " ($sub)\n\tfrom line $line of $file";
1061 }
1062 18 print STDERR ".\n";
1063 # Let END take care of cleanup.
1064 18 exit (1);
1065 }
1066  
1067  
1068  
1069 =item C<no_result>
1070  
1071 Exits the test with an indeterminate result (the test could not be
1072 performed due to external conditions such as, for example, a full
1073 file system). Reports "NO RESULT for test of {string} at line {line} of
1074 {file}." on the error output and exits with a status of 2. If a condition
1075 is supplied, only exits the test if the condition evaluates TRUE. If a
1076 function reference is supplied, executes the function before reporting
1077 and exiting. If a caller level is supplied, prints a simple calling
1078 trace N levels deep as part of reporting the failure.
1079  
1080 =cut
1081  
1082 135 ▶sub no_result {
Subroutine no_result: called CC=9 SCAR=22.0
Pod documented
1083 135 my $self = shift;
1084 135 ▶ @_ = (1) if @_ == 0; # provide default arg
Branch: 1 branch
BranchTrueFalseTotal
if @_ == 0 5 130 135
1085 135 my ($cond, $funcref, $caller) = @_;
1086 135 ▶ return if ! _to_value($cond);
Branch: 1 branch
BranchTrueFalseTotal
unless _to_value($cond) 115 20 135
1087 20 ▶ &$funcref() if $funcref;
Branch: 1 branch
BranchTrueFalseTotal
if $funcref 11 9 20
1088 20 ▶ $caller = 0 if ! defined($caller);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $caller 9 11 20
1089 20 my $of_str = " ";
1090 20 ▶ if (ref $self) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self) 19 1 20
1091 19 my $basename = $self->basename;
1092 19 ▶ if ($basename) {
Branch: 1 branch
BranchTrueFalseTotal
if ($basename) 4 15 19
1093 4 $of_str = " of ".$self->basename;
1094 4 ▶ if ($self->{'string'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"string"}) 1 3 4
1095 1 $of_str .= " [".$self->{'string'}."]";
1096 }
1097 4 $of_str .= "\n\t";
1098 }
1099 }
1100 20 my $c = 0;
1101 20 my ($pkg,$file,$line,$sub) = caller($c++);
1102 20 print STDERR "NO RESULT for test${of_str}at line $line of $file";
1103 20 ▶ while ($c <= $caller) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c <= $caller) 11 20 31
1104 11 ($pkg,$file,$line,$sub) = caller($c++);
1105 11 print STDERR " ($sub)\n\tfrom line $line of $file";
1106 }
1107 20 print STDERR ".\n";
1108 # Let END take care of cleanup.
1109 20 exit (2);
1110 }
1111  
1112  
1113  
1114 144 ▶sub _stdout_file {
Subroutine _stdout_file: called CC=1 SCAR=0.0
1115 144 my ($self, $count) = @_;
1116 144 $self->catfile($self->{'workdir'}, "stdout.$count");
1117 }
1118  
1119 143 ▶sub _stderr_file {
Subroutine _stderr_file: called CC=1 SCAR=0.0
1120 143 my ($self, $count) = @_;
1121 143 $self->catfile($self->{'workdir'}, "stderr.$count");
1122 }
1123  
1124  
1125  
1126  
1127  
1128  
1129 =item C<stdout>
1130  
1131 Returns the standard output from the specified run number. If there is no
1132 specified run number, then returns the standard output of the last run.
1133 Returns the standard output as either a scalar or an array of output
1134 lines, as appropriate for the calling context. Returns C<undef> if
1135 there has been no test run.
1136  
1137 =cut
1138  
1139 60 ▶sub stdout {
Subroutine stdout: called CC=5 SCAR=16.2
Pod documented
1140 60 my $self = shift;
1141 60 ▶ my $count = @_ ? shift : $Run_Count;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 1 59 60
1142 60 ▶ return undef if ! $Run_Count;
Branch: 1 branch
BranchTrueFalseTotal
unless $Run_Count 2 58 60
1143 58 my @lines;
1144 58 ▶ if (! $self->read(\@lines, $self->_stdout_file($count))) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->read(\@lines, $self->_stdout_file($count))) 0 58 58
1145 0 return undef;
1146 }
1147 58 ▶ return (wantarray ? @lines : join('', @lines));
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 4 54 58
1148 }
1149  
1150  
1151  
1152 =item C<stderr>
1153  
1154 Returns the error output from the specified run number. If there is
1155 no specified run number, then returns the error output of the last run.
1156 Returns the error output as either a scalar or an array of output lines,
1157 as apporpriate for the calling context. Returns C<undef> if there has
1158 been no test run.
1159  
1160 =cut
1161  
1162 58 ▶sub stderr {
Subroutine stderr: called CC=5 SCAR=16.2
Pod documented
1163 58 my $self = shift;
1164 58 ▶ my $count = @_ ? shift : $Run_Count;
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 1 57 58
1165 58 ▶ return undef if ! $Run_Count;
Branch: 1 branch
BranchTrueFalseTotal
unless $Run_Count 1 57 58
1166 57 my @lines;
1167 57 ▶ if (! $self->read(\@lines, $self->_stderr_file($count))) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->read(\@lines, $self->_stderr_file($count))) 0 57 57
1168 0 return undef;
1169 }
1170 57 ▶ return (wantarray ? @lines : join('', @lines));
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 8 49 57
1171 }
1172  
1173  
1174  
1175 74 ▶sub _make_arrays {
Subroutine _make_arrays: called CC=3 SCAR=11.0
1176 74 my ($lines, $matches) = @_;
1177 74 my @line_array;
1178 my @match_array;
1179 74 ▶ if (ref $lines) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $lines) { } 28 46 74
1180 28 chomp(@line_array = @$lines);
1181 } else {
1182 46 @line_array = split(/\n/, $lines, -1);
1183 46 pop(@line_array);
1184 }
1185 74 ▶ if (ref $matches) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $matches) { } 15 59 74
1186 15 chomp(@match_array = @$matches);
1187 } else {
1188 59 @match_array = split(/\n/, $matches, -1);
1189 59 pop(@match_array);
1190 }
1191 74 return (\@line_array, \@match_array);
1192 }
1193  
1194  
1195  
1196 =item C<match>
1197  
1198 Matches one or more input lines against an equal number of expected lines
1199 using the currently-registered line-matching function. The default
1200 line-matching function is the C<match_regex> method, which means that
1201 the default is to match lines against regular expressions.
1202  
1203 =cut
1204  
1205 45 ▶sub match {
Subroutine match: called CC=1 SCAR=0.0
Pod documented
1206 45 my $self = shift;
1207 # We can write this more clearly when we drop support for Perl 5.003:
1208 # $self->{'match_sub'}->($self, @_);
1209 45 &{$self->{'match_sub'}}($self, @_);
1210 }
1211  
1212  
1213  
1214 33 ▶sub _matcher {
Subroutine _matcher: called CC=4 SCAR=13.9
1215 33 my ($lines, $matches, $sub) = @_;
1216 33 ($lines, $matches) = _make_arrays($lines, $matches);
1217 33 ▶ return undef if @$lines != @$matches;
Branch: 1 branch
BranchTrueFalseTotal
if @$lines != @$matches 0 33 33
1218 33 my ($i, $l, $m);
1219 33 ▶ for ($i = 0; $i <= $#{ $matches }; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i <= $#{$matches;}) 45 22 67
1220 # More clearly, but doesn't work in Perl 5.003:
1221 # if (! $sub->($lines->[$i], $matches->[$i]))
1222 45 ▶ if (! &{$sub}($lines->[$i], $matches->[$i])) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&{$sub;}($lines->[$i], $matches->[$i])) 11 34 45
1223 #print STDERR "Line ", $i+1, " does not match:\n";
1224 #print STDERR "Expect: ${\$matches->[\$i]}\n";
1225 #print STDERR "Got: ${\$lines->[\$i]}\n";
1226 11 return undef;
1227 }
1228 }
1229 22 return 1;
1230 }
1231  
1232  
1233  
1234 =item C<match_exact>
1235  
1236 Compares two arrays of lines for exact matches. The arguments are passed
1237 in as either scalars, in which case each is split on newline boundaries,
1238 or as array references. An unequal number of lines in the two arrays
1239 fails immediately and returns FALSE before any comparisons are performed.
1240  
1241 Returns TRUE if each line matched its corresponding line in the other
1242 array, FALSE otherwise.
1243  
1244 =cut
1245  
1246 22 ▶sub match_exact {
Subroutine match_exact: called CC=1 SCAR=0.0
Pod documented
1247 22 my ($self, $lines, $matches) = @_;
1248 22 ▶ _matcher($lines, $matches, sub {$_[0] eq $_[1]});
Subroutine __ANON__: called CC=1 SCAR=0.0
1249 }
1250  
1251  
1252  
1253 =item C<match_regex>
1254  
1255 Matches one or more input lines against an equal number of regular
1256 expressions. The arguments are passed in as either scalars, in which
1257 case each is split on newline boundaries, or as array references.
1258 Trailing newlines are stripped from each line and regular expression.
1259 An unequal number of lines and regular expressions fails immediately
1260 and returns FALSE before any comparisons are performed. Comparison is
1261 performed for each entire line, that is, with each regular expression
1262 anchored at both the start of line (^) and end of line ($).
1263  
1264 Returns TRUE if each line matched each regular expression, FALSE
1265 otherwise.
1266  
1267 =cut
1268  
1269 11 ▶sub match_regex {
Subroutine match_regex: called CC=1 SCAR=0.0
Pod documented
1270 11 my ($self, $lines, $regexes) = @_;
1271 11 ▶ _matcher($lines, $regexes, sub {$_[0] =~ m/^$_[1]$/});
Subroutine __ANON__: called CC=1 SCAR=0.0
1272 }
1273  
1274  
1275  
1276 47 ▶sub _range {
Subroutine _range: called CC=2 SCAR=6.9
1277 47 ▶ ($_[0]->[1] + 1) . ((@_ == 1) ? '' : (',' . ($_[-1]->[1] + 1)))
Branch: 1 branch
BranchTrueFalseTotal
@_ == 1 ? : 31 16 47
1278 }
1279  
1280 my $_differ;
1281  
1282 111 ▶eval("use Algorithm::DiffOld;");
Subroutine BEGIN: called CC=1 SCAR=0.0
1283 111 ▶if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 111 111
1284 0 $_differ = \&_differ_no_lcs;
1285 } else {
1286 111 $_differ = \&_differ_lcs;
1287 }
1288  
1289 41 ▶sub _differ_lcs {
Subroutine _differ_lcs: called CC=7 SCAR=19.5
1290 41 my ($matches, $lines, $output, $sub) = @_;
1291 41 ($lines, $matches) = _make_arrays($lines, $matches);
1292 41 ▶ @$output = () if defined $output;
Branch: 1 branch
BranchTrueFalseTotal
if defined $output 32 9 41
1293 41 my @diffs = Algorithm::DiffOld::diff($matches, $lines, $sub);
1294 41 ▶ return 1 if @diffs == 0;
Branch: 1 branch
BranchTrueFalseTotal
if @diffs == 0 23 18 41
1295 18 ▶ if (defined $output) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output) 15 3 18
1296 15 my $added = 0;
1297 15 my $hunk;
1298 15 foreach $hunk (@diffs) {
1299 35 my @deletions = grep($_->[0] eq '-', @$hunk);
1300 35 my @additions = grep($_->[0] eq '+', @$hunk);
1301 35 ▶ if (! @deletions) {
Branch: 2 branches
BranchTrueFalseTotal
if (not @deletions) { } 11 24 35
elsif (not @additions) { } 12 12 24
1302 11 push @$output, ($additions[0]->[1] - $added) . 'a' .
1303 _range(@additions) . "\n";
1304 11 push @$output, "> " .
1305 join("\n> ", map($_->[2], @additions)) .
1306 "\n";
1307 } elsif (! @additions) {
1308 12 push @$output, _range(@deletions) . 'd' .
1309 ($deletions[0]->[1] + $added) . "\n";
1310 12 push @$output, "< " .
1311 join("\n< ", map($_->[2], @deletions)) .
1312 "\n";
1313 } else {
1314 12 push @$output, _range(@deletions) . 'c' .
1315 _range(@additions) . "\n";
1316 12 push @$output, "< " .
1317 join("\n< ", map($_->[2], @deletions)) .
1318 "\n";
1319 12 push @$output, "---\n";
1320 12 push @$output, "> " .
1321 join("\n> ", map($_->[2], @additions)) .
1322 "\n";
1323 }
1324 35 $added += @additions - @deletions;
1325 }
1326 }
1327 18 return undef;
1328 }
1329  
1330 0 ▶sub _differ_no_lcs {
Subroutine _differ_no_lcs: not called CC=4 SCAR=30.0
1331 0 my ($matches, $lines, $output, $sub) = @_;
1332 0 ($lines, $matches) = _make_arrays($lines, $matches);
1333 0 ▶ @$output = () if defined $output;
Branch: 1 branch
BranchTrueFalseTotal
if defined $output 0 0 0
1334 0 ▶ return 1 if _matcher($matches, $lines, $sub);
Branch: 1 branch
BranchTrueFalseTotal
if _matcher($matches, $lines, $sub) 0 0 0
1335 0 ▶ if (defined $output) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $output) 0 0 0
1336 0 push @$output, "Expected =====\n";
1337 0 push @$output, map { $_ . "\n" } @$matches;
1338 0 push @$output, "Actual =====\n";
1339 0 push @$output, map { $_ . "\n" } @$lines;
1340 }
1341 0 return undef;
1342 }
1343  
1344  
1345  
1346 =item C<diff_exact>
1347  
1348 Diffs two arrays of lines in a manner similar to the UNIX L<diff(1)>
1349 utility.
1350  
1351 If the L<Algorithm::DiffOld> package is installed on the local system,
1352 output describing the differences between the input lines and the
1353 matching lines, in L<diff(1)> format, is saved to the C<$output> array
1354 reference. In the diff output, the expected output lines are considered
1355 the "old" (left-hand) file, and the actual output is considered the
1356 "new" (right-hand) file.
1357  
1358 If the L<Algorithm::DiffOld> package is I<not> installed on the local
1359 system, the Expected and Actual contents are saved as-is to the
1360 C<$output> array reference.
1361  
1362 The C<lines> and C<matches> arguments are passed in as either scalars,
1363 in which case each is split on newline boundaries, or as array
1364 references. Trailing newlines are stripped from each line and regular
1365 expression.
1366  
1367 Returns TRUE if each line matched its corresponding line in the expected
1368 matches, FALSE otherwise, in order to conform to the conventions of the
1369 C<match> method.
1370  
1371 Typical invocation:
1372  
1373 if (! $test->diff_exact($test->stdout,
1374 \@expected_lines,
1375 \@diff)) {
1376 print @diff;
1377 }
1378  
1379 =cut
1380  
1381 30 ▶sub diff_exact {
Subroutine diff_exact: called CC=1 SCAR=0.0
Pod documented
1382 30 my ($self, $lines, $matches, $output) = @_;
1383 30 ▶ return &{$_differ}($matches, $lines, $output, sub {$_[0] eq $_[1]});
Subroutine __ANON__: called CC=1 SCAR=0.0
1384 }
1385  
1386  
1387  
1388 =item C<diff_regex>
1389  
1390 Diffs one or more input lines against one or more regular expressions
1391 in a manner similar to the UNIX L<diff(1)> utility.
1392  
1393 If the L<Algorithm::DiffOld> package is installed on the local system,
1394 output describing the differences between the input lines and the
1395 matching lines, in L<diff(1)> format, is saved to the C<$output> array
1396 reference. In the diff output, the expected output lines are considered
1397 the "old" (left-hand) file, and the actual output is considered the
1398 "new" (right-hand) file.
1399  
1400 If the L<Algorithm::DiffOld> package is I<not> installed on the local
1401 system, the Expected and Actual contents are saved as-is to the
1402 C<$output> array reference.
1403  
1404 The C<lines> and C<regexes> arguments are passed in as either scalars,
1405 in which case each is split on newline boundaries, or as array
1406 references. Trailing newlines are stripped from each line and regular
1407 expression. Comparison is performed for each entire line, that is, with
1408 each regular expression anchored at both the start of line (^) and end
1409 of line ($).
1410  
1411 Returns TRUE if each line matched each regular expression, FALSE
1412 otherwise, in order to conform to the conventions of the C<match>
1413 method.
1414  
1415 Typical invocation:
1416  
1417 if (! $test->diff_regex($test->stdout,
1418 \@expected_lines,
1419 \@diff)) {
1420 print @diff;
1421 }
1422  
1423 =cut
1424  
1425 11 ▶sub diff_regex {
Subroutine diff_regex: called CC=1 SCAR=0.0
Pod documented
1426 11 my ($self, $lines, $regexes, $output) = @_;
1427 11 ▶ return &{$_differ}($regexes, $lines, $output, sub {$_[1] =~ /^$_[0]$/});
Subroutine __ANON__: called CC=1 SCAR=0.0
1428 }
1429  
1430  
1431  
1432 =item C<match_sub>
1433  
1434 Registers the specified code reference as the line-matching function
1435 to be called by the C<match> method. This can be a user-supplied
1436 subroutine, or the C<match_exact>, C<match_regex>, C<diff_exact>, or
1437 C<diff_regex> methods supplied by the C<Test::Cmd> module:
1438  
1439 $test->match_sub(\&Test::Cmd::match_exact);
1440  
1441 $test->match_sub(\&Test::Cmd::match_regex);
1442  
1443 $test->match_sub(\&Test::Cmd::diff_exact);
1444  
1445 $test->match_sub(\&Test::Cmd::diff_regex);
1446  
1447 The C<match_exact>, C<match_regex>, C<diff_exact> and C<diff_regex>
1448 subroutine names are exportable from the C<Test::Cmd> module, and may be
1449 specified at object initialization:
1450  
1451 use Test::Cmd qw(match_exact match_regex diff_exact diff_regex);
1452 $test_exact = Test::Cmd->new(match_sub => \&match_exact);
1453 $test_regex = Test::Cmd->new(match_sub => \&match_regex);
1454 $test_exact = Test::Cmd->new(match_sub => \&diff_exact);
1455 $test_regex = Test::Cmd->new(match_sub => \&diff_regex);
1456  
1457 =cut
1458  
1459 173 ▶sub match_sub {
Subroutine match_sub: called CC=2 SCAR=7.1
Pod documented
1460 173 my ($self, $funcref) = @_;
1461 173 ▶ $self->{'match_sub'} = $funcref if defined $funcref;
Branch: 1 branch
BranchTrueFalseTotal
if defined $funcref 173 0 173
1462 173 $self->{'match_sub'};
1463 }
1464  
1465  
1466  
1467 =item C<here>
1468  
1469 Returns the absolute path name of the current working directory.
1470 (This is essentially the same as the C<Cwd::cwd> method, except that the
1471 C<Test::Cmd::here> method preserves the directory separators exactly
1472 as returned by the underlying operating-system-dependent method.
1473 The C<Cwd::cwd> method canonicalizes all directory separators to '/',
1474 which makes for consistent path name representations within Perl, but may
1475 mess up another program or script to which you try to pass the path name.)
1476  
1477 =cut
1478  
1479 6 ▶sub here {
Subroutine here: called CC=1 SCAR=0.0
Pod documented
1480 6 &$Test::Cmd::Cwd_Ref();
1481 }
1482  
1483  
1484  
1485 111 1;
1486 __END__
↑ Summary blib/lib/Test/Cmd/Common.pm »