blib/lib/Test/Without.pm untested

filter: Statementstmt 0.0% 0 / 89 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 144 CC 12 SCAR 39.4
CC
12
Cov
0%
run
132.0
_create_masking_coderef
6.0
module
2.0
CRAP 51.6
1 ###############################################################################
2 #
3 # This file copyright (c) 2009 by Randy J. Ray, all rights reserved
4 #
5 # Copying and distribution are permitted under the terms of the Artistic
6 # License 2.0 (http://www.opensource.org/licenses/artistic-license-2.0.php) or
7 # the GNU LGPL (http://www.opensource.org/licenses/lgpl-2.1.php).
8 #
9 ###############################################################################
10 #
11 # Description: Run tests in a localized scope
12 #
13 # Functions: run
14 # without
15 # with
16 # modules
17 # module
18 # libs
19 # lib
20 # params
21 # param
22 #
23 # Libraries: Exporter
24 # Scalar::Util
25 #
26 # Global Consts: $VERSION
27 #
28 ###############################################################################
29  
30 package Test::Without;
31  
32 use 5.008;
33 use strict;
34 use warnings;
35 use vars qw($VERSION %CURRENT_LIST @EXPORT @EXPORT_OK %EXPORT_TAGS);
36 use subs qw(run without with modules module libs lib params param);
37 use base 'Exporter';
38 require lib; # This is used to manually invoke lib->import and lib->unimport
39  
40 use Scalar::Util 'blessed';
41  
42 $VERSION = '0.100';
43 $VERSION = eval $VERSION; ## no critic
44 @EXPORT = qw(run without with modules module libs lib params param);
45 @EXPORT_OK = @EXPORT;
46 %EXPORT_TAGS = (all => [@EXPORT]);
47  
48 ## no critic (ProhibitSubroutinePrototypes)
49  
50 # These are all the exact same code except for the leading label. Also
51 # manage the plural/singular sugary formations:
52 sub module (@) { (-modules => @_) }
53 sub modules (@) { (-modules => @_) }
54 sub lib (@) { (-libs => @_) }
55 sub libs (@) { (-libs => @_) }
56 sub param (@) { (-params => @_) }
57 sub params (@) { (-params => @_) }
58  
59 ###############################################################################
60 #
61 # Sub Name: without
62 #
63 # Description: Mark all the arguments to this as being elements that
64 # should be masked from view when the enclosing "run"
65 # executes its BLOCK.
66 #
67 # Arguments: NAME IN/OUT TYPE DESCRIPTION
68 # @list in list Items to be marked
69 #
70 # Returns: list
71 #
72 ###############################################################################
73 sub without (@)
74 {
75 (-without => @_);
76 }
77  
78 ###############################################################################
79 #
80 # Sub Name: with
81 #
82 # Description: As above, but marks any elements as being things that
83 # must be located/present before the block can be run.
84 #
85 # Arguments: NAME IN/OUT TYPE DESCRIPTION
86 # @list in list Items to be marked
87 #
88 # Returns: list
89 #
90 ###############################################################################
91 sub with (@)
92 {
93 (-with => @_);
94 }
95  
96 ###############################################################################
97 #
98 # Sub Name: run
99 #
100 # Description: Execute the given block after localizing @INC and %INC so
101 # that any changes made are auto-rolled-back upon exit.
102 #
103 # Arguments: NAME IN/OUT TYPE DESCRIPTION
104 # $block in coderef The block of code to run
105 # @params in list The list of params/directives
106 # to process and apply to @INC
107 # before invoking $block.
108 #
109 # Returns: Whatever $block returns
110 #
111 ###############################################################################
112 sub run (&@)
113 {
114 my ($block, @params) = @_;
115  
116 local @INC = @INC;
117 local %INC = %INC;
118  
119 my ($which, $key, $index);
120 my %params = (
121 with => {libs => [], modules => []},
122 without => {libs => [], modules => []},
123 # Make sure $params{params} exists to avoid undef-tests on last line
124 params => [],
125 );
126 # If they don't specify a "key" (by using one of the syntactic sugar
127 # faux-keywords), default to the "without modules" list since that will
128 # probably be 90% or more of usage.
129 $which = 'without';
130 $key = 'modules';
131  
132 while (my $param = shift(@params))
133 {
134 if (substr($param, 0, 1) eq '-')
135 {
136 # Switching to a different key or selector
137 if (substr($param, 1, 4) eq 'with')
138 {
139 $which = substr($param, 1);
140 }
141 else
142 {
143 $key = substr($param, 1);
144 }
145 }
146 else
147 {
148 $index =
149 ($key eq 'params') ? $params{param} : $params{$which}->{$key};
150 push(@{$index}, $param);
151 }
152 }
153  
154 # Any libraries the user says they need must me loadable. If any of them
155 # cannot load, an exception must be thrown. The caller is responsible for
156 # handling it.
157 if (@{$params{with}->{libs}} + @{$params{with}->{modules}})
158 {
159 # Check libs first, as they're easier
160 lib->import(@{$params{with}->{libs}})
161 if (@{$params{with}->{libs}});
162  
163 for my $required (@{$params{with}->{modules}})
164 {
165 my ($module, $params) = split('=', $required, 2);
166 my $evalstr = "use $module";
167 if ($params)
168 {
169 @params = split(q{,} => $params);
170 $evalstr .= " qw(@params)";
171 }
172  
173 # Try it. Don't forget that we've already localized @INC and %INC
174 eval "$evalstr;"; ## no critic
175 die "Error loading $module: $@" if $@;
176 }
177 }
178  
179 if ($params{without})
180 {
181 # Remove any paths in @INC that (sub-string) match paths in the list
182 # the user provided
183 lib->unimport(@{$params{without}->{libs}})
184 if (@{$params{without}->{libs}});
185  
186 # If there are modules requested for hiding, create a code block that
187 # goes into the head of @INC and masks them.
188 unshift(@INC, _create_masking_coderef(@{$params{without}->{modules}}))
189 if (@{$params{without}->{modules}});
190 }
191  
192 $block->(@{$params{params}});
193 }
194  
195 ###############################################################################
196 #
197 # Sub Name: _create_masking_coderef
198 #
199 # Description: Create a coderef using the list of modules that are to be
200 # hidden from the system during the scope of the enclosing
201 # "run". Bless the coderef so that we can easily find it in
202 # @INC if we need to.
203 #
204 # Arguments: NAME IN/OUT TYPE DESCRIPTION
205 # @list in list List of modules to hide from
206 # the user.
207 #
208 # Returns: Success: coderef
209 # Failure: dies
210 #
211 ###############################################################################
212 sub _create_masking_coderef (@)
213 {
214 my @list = @_;
215 my $package = __PACKAGE__ . '::coderef';
216  
217 my %mask_map = map { (my $key = $_) =~ s{::}{/}g; "$key.pm" => 1 } @list;
218 my @local_inc = grep(!(blessed $_ && $_->isa($package)), @INC);
219  
220 bless sub {
221 my ($self, $module) = @_;
222  
223 die "Can't locate $module in \@INC (\@INC contains @local_inc)."
224 if ($mask_map{$module});
225  
226 undef;
227 }, $package;
228 }
229  
230 1;
231  
232 =head1 NAME
233  
234 Test::Without - Run code while hiding library paths or specific modules
235  
236 =head1 SYNOPSIS
237  
238 use Test::Without;
239  
240 run {
241 eval "require RPC::XML::Client";
242 $client = RPC::XML::Client->new();
243  
244 ok(! $client->compress(), "Client has no compression support");
245 } without 'Compress::Zlib';
246  
247 # Run a block with parameters
248 run {
249 my %args = @_;
250 eval "require RPC::XML::Server";
251 $server = RPC::XML::Server->new(@_);
252  
253 is($server->port, $args{port}, "Port set correctly");
254 is($server->path, $args{path}, "Path set correctly");
255 # Etc.
256 } without 'Compress::Zlib', 'Net::Server',
257 params port => 9000, path => '/RPC';
258  
259 =head1 DESCRIPTION
260  
261 The B<Test::Without> module makes it easy for test scripts to exclude specific
262 modules and/or directories from the Perl search-path during the execution of
263 blocks of code. I wrote this after needing to write a fairly ugly hack for a
264 different CPAN module, in order to test code that would try to load
265 B<Compress::Zlib>, but needed to test the logic paths that only execute when
266 compression is not available. This module is not for testing whether code
267 loads and compiles correctly; see the C<use_ok> function of B<Test::More> for
268 that.
269  
270 The module works by creating a lexical scope in which both C<@INC> and C<%INC>
271 are localized, and executing the given block within that scope. The modules
272 (and possibly direcories) to be hidden are specified at this time. Directories
273 that are given are immediately removed from C<@INC>. Modules are handled by
274 means of a subroutine inserted at the head of C<@INC>.
275  
276 Conversely, the syntax can be used to require the present of specific modules,
277 throwing an exception via C<die> if any request resource is not available, or
278 temporarily add extra paths to C<@INC>. In such a case, none of the code in the
279 provided block will have been run prior to the reporting of the missing
280 resources.
281  
282 A caller can also provide parameters to be passed to the code block when it
283 is called. This is superfluous for inline-defined blocks, but in cases where
284 the block argument is a code-reference scalar that is being reused, this can
285 be useful.
286  
287 =head1 SYNTAX
288  
289 The module defines the following functions:
290  
291 =over 4
292  
293 =item run BLOCK LIST
294  
295 Run the given code in BLOCK, with the context defined by the elements of LIST.
296 The items in list should be built up using the other functions defined below.
297 Exceptions are not inherently caught, so if you expect the that code may
298 C<die> (or otherwise emulate exceptions) you may with to use C<eval>.
299  
300 If C<params> is used (see below) in constructing the context, these values are
301 passed to the code-block in C<@_>, as though it were a function call.
302  
303 =item without LIST
304  
305 Specify a set of resources that should be hidden within the context the
306 associated block is invoked. The contents of LIST should be built up using
307 C<modules> (and/or C<libs>), below. Because it is expected that the majority of
308 usage will be to mask or require modules, a bare list is assumed to be
309 modules. Thus, the following will work, correctly masking B<Net::Server> from
310 being loadable:
311  
312 run { ... } without 'Net::Server';
313  
314 =item with LIST
315  
316 Specify resources that must be present before the block can be invoked. The
317 given LIST should be built up using a combination of C<modules> and C<libs>, as
318 needed. Unlike using C<without>, above, this pre-confirms that modules are
319 available by attempting load them. Directories specified via C<libs> are added
320 the same way they would be with the B<libs> pragma, with the added step that
321 a check is first done to confirm the directory actually exists. If it does not
322 exist, C<die> is called to signal this.
323  
324 Modules specified in a C<with> list may provide import-style arguments in a
325 way similar to Perl's B<-M> command-line argument. See the section for
326 C<modules>, below.
327  
328 As is the case for C<without>, above, a bare list is assumed to be modules.
329 The following works as a counter to the previous example:
330  
331 run { ... } with 'Net::Server';
332  
333 =item modules LIST
334  
335 Build a list of modules for use by C<without> or C<with>. Does no processing of
336 LIST itself.
337  
338 If the modules being specified are for use with the C<with> function, then any
339 elements of list may contain parameters using the same specification syntax
340 used for the B<-M> command-line switch of Perl itself:
341  
342 run {
343 # Create an image, then test that it was correct
344 our $image = ...;
345 ($width, $height) = imgsize($image);
346 # Then test to see if we got what was expected
347 } with 'Image::Size=imgsize';
348 # Requires that Image::Size is present, and imports 'imgsize'
349 # from it.
350  
351 For syntactic-sugar purposes, you can use the singular C<module> as a
352 synonym for this function.
353  
354 =item libs LIST
355  
356 Build a list of directories that should be either excluded or required in the
357 Perl search path for the context being constructed. The way these paths are
358 treated depends on whether the list is being used for inclusion or exclusion:
359  
360 =over 8
361  
362 =item *
363  
364 When the list of directories is given to the C<without> function, each element
365 is I<removed from> C<@INC> by calling the B<unimport> method from the B<lib>
366 module. This will also remove architecture-specific sub-directories related
367 to the directory being removed, just as if you invoked C<no lib $dir>.
368  
369 =item *
370  
371 When the list is given to the C<with> function, each element is I<added to>
372 C<@INC>, along with any related architecture-specific sub-directories, just
373 as if you had invoked C<use lib $dir>.
374  
375 =back
376  
377 For syntactic-sugar purposes, you can use the singular C<lib> as a
378 synonym for this function.
379  
380 =item params LIST
381  
382 Build a list of parameters that are passed in as the arguments-list (via C<@_>)
383 to the code-block when it is invoked. This can be useful for cases where the
384 code argument is a scalar containing a code-reference that is intended to be
385 reused several times over.
386  
387 For syntactic-sugar purposes, you can use the singular C<param> as a
388 synonym for this function.
389  
390 =back
391  
392 See the following section for example usage of all the routines defined here.
393  
394 =head1 EXAMPLES
395  
396 =over 4
397  
398 =item Test that a class acts correctly in absence of Compress::Zlib:
399  
400 run {
401 require RPC::XML::Client;
402 $client = RPC::XML::Client->new('http://test.com');
403 ok(! $client->can_compress(),
404 '$client has no compression support');
405 } without 'Compress::Zlib';
406  
407 =item Semi-emulate the "blib" pragma:
408  
409 run {
410 eval "require Some::Lib;";
411 ok(Some::Lib->can('some_method'), 'Some::Lib loaded OK');
412 } with libs 'lib', 'blib', '../lib', '../blib';
413  
414 =item Load code from a local lib while hiding a module:
415  
416 run {
417 ...
418 } with lib 'local', without module 'HTTP::Daemon';
419  
420 =item Run the same code several times, with varying parameters:
421  
422 $code = sub { ... };
423 $db_credentials = read_all_database_credentials();
424  
425 for my $db_type (keys %$db_credentials)
426 {
427 my ($user, $pass) = @{$db_credentials->{$db_type}};
428  
429 # You could say "with params", but it's redundant for params
430 run $code without 'DBD::DB2', params $db_type, $user, $pass;
431 }
432  
433 =back
434  
435 =head1 DIAGNOSTICS
436  
437 Any problems are signalled with B<die>. The user must catch these with either
438 the C<__DIE__> pseudo-signal handler or by B<eval> (or some other syntactic
439 construct).
440  
441 The code-block that gets inserted into B<@INC> uses B<die> as well, if one of
442 the blocked modules is requested for loading. If your tests are themselves
443 likely to try loading any of these (as opposed to using this framework to hide
444 modules from other code you are loading), you will want to use B<eval> or the
445 signal handler.
446  
447 =head1 CAVEATS
448  
449 If a module loads that also alters B<@INC>, it could interfere with this module
450 catching and blocking the requests modules or libraries.
451  
452 =head1 BUGS
453  
454 Please report any bugs or feature requests to
455 C<bug-test-without at rt.cpan.org>, or through the web interface at
456 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test-Without>. I will be
457 notified, and then you'll automatically be notified of progress on
458 your bug as I make changes.
459  
460 =head1 SUPPORT
461  
462 =over 4
463  
464 =item * RT: CPAN's request tracker
465  
466 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Test-Without>
467  
468 =item * AnnoCPAN: Annotated CPAN documentation
469  
470 L<http://annocpan.org/dist/Test-Without>
471  
472 =item * CPAN Ratings
473  
474 L<http://cpanratings.perl.org/d/Test-Without>
475  
476 =item * Search CPAN
477  
478 L<http://search.cpan.org/dist/Test-Without>
479  
480 =item * Source code on GitHub
481  
482 L<http://github.com/rjray/test-without/tree/master>
483  
484 =back
485  
486 =head1 COPYRIGHT & LICENSE
487  
488 This file and the code within are copyright (c) 2009 by Randy J. Ray.
489  
490 Copying and distribution are permitted under the terms of the Artistic
491 License 2.0 (L<http://www.opensource.org/licenses/artistic-license-2.0.php>) or
492 the GNU LGPL 2.1 (L<http://www.opensource.org/licenses/lgpl-2.1.php>).
493  
494 =head1 CREDITS
495  
496 Thanks to Andy Wardley C<< abw @ cpan.org >> for providing the idea for
497 inverting the control-point of the logic and making the scoping issues with
498 B<@INC> and B<%INC> work.
499  
500 =head1 SEE ALSO
501  
502 L<Module::Mask>, L<Test::Without::Module>, L<Test::More>
503  
504 =head1 AUTHOR
505  
506 Randy J. Ray <rjray@blackperl.com>
507  
508 =cut