How to test for 'use' *failure*? - perl

Test::More provides the commonly-used use_ok test to test that a module loads properly. But how do I test that a module fails to load? Test::Exception offers dies_ok and cousins for similar failures, but not at use-time.
This is useful when a module requires specific parameters or a specific environment to load properly, and I want to test for these conditions. As an example, perhaps my 'Foo' module requires a configuration parameter, and should fail to load otherwise:
use Foo 'eat my hat'; # This should work
use Foo; # This should die
I can easily test the first case with Test::More:
BEGIN { use_ok('Foo','eat my hat') }
But how can I test the other?
BEGIN { use_not_ok('Foo') } # use_not_ok doesn't exist

use Foo;
is
BEGIN { require Foo; import Foo; }
so
BEGIN { ok(!eval { require Foo; import Foo; 1 }); }
But I'd just go with
BEGIN { ok(!eval('use Foo; 1')); }

Related

How to handle: Moo::Role's `before` modifier silently skipped due to circular imports?

Using Moo::Role, I'm finding that circular imports are silently preventing the execution of the before modifier of my method.
I have a Moo::Role in MyRole.pm :
package MyRole;
use Moo::Role;
use MyB;
requires 'the_method';
before the_method => sub { die 'This has been correctly executed'; };
1;
...a consumer in MyA.pm :
package MyA;
use Moo;
with ( 'MyRole' );
sub the_method { die; }
1;
..and another in MyB.pm :
package MyB;
use Moo;
with ( 'MyRole' );
sub the_method { die 'The code should have died before this point'; }
1;
When I run this script.pl:
#!/usr/bin/env perl
package main;
use MyA;
use MyB;
MyB->new()->the_method();
...I get The code should have died before this point at MyB.pm line 4. but would expect to see This has been correctly executed at MyRole.pm line 5.
I think this problem is caused by the circular imports. It goes away if I switch the order of the use statements in script.pl or if I change the use MyB; in MyRole.pm to be a require within the_method.
Is this behaviour expected? If so, what is the best way to handle it where circular imports can't be avoided?
I can workaround the problem but it feels worryingly easy to inadvertently trigger (particularly since it causes before functions, which often contain checking code, to be silently skipped).
(I'm using Moo version 2.003004. Obviously the use MyB; in MyRole.pm is superfluous here but only after I've simplified the code for this repro example.)
Circular imports can get rather tricky, but behave consistently. The crucial points are:
use Some::Module behaves like BEGIN { require Some::Module; Some::Module->import }
When a module is loaded, it is compiled and executed. BEGIN blocks are executed during parsing of the surrounding code.
Each module is only require'd once. When it is required again, that require is ignored.
Knowing that, we can combine your four files into a single file that includes the required files in a BEGIN block.
Let's start with your main file:
use MyA;
use MyB;
MyB->new()->the_method();
We can transform the use to BEGIN { require ... } and include the MyA contents. For clarity, I will ignore any ->import calls on MyA and MyB because they are not relevant in this case.
BEGIN { # use MyA;
package MyA;
use Moo;
with ( 'MyRole' );
sub the_method { die; }
}
BEGIN { # use MyB;
require MyB;
}
MyB->new()->the_method();
The with('MyRole') also does a require MyRole, which we can make explicit:
...
require MyRole;
with( 'MyRole ');
So let's expand that:
BEGIN { # use MyA;
package MyA;
use Moo;
{ # require MyRole;
package MyRole;
use Moo::Role;
use MyB;
requires 'the_method';
before the_method => sub { die 'This has been correctly executed'; };
}
with ( 'MyRole' );
sub the_method { die; }
}
BEGIN { # use MyB;
require MyB;
}
MyB->new()->the_method();
We can then expand the use MyB, also expanding MyB's with('MyRole') to a require:
BEGIN { # use MyA;
package MyA;
use Moo;
{ # require MyRole;
package MyRole;
use Moo::Role;
BEGIN { # use MyB;
package MyB;
use Moo;
require MyRole;
with ( 'MyRole' );
sub the_method { die 'The code should have died before this point'; }
}
requires 'the_method';
before the_method => sub { die 'This has been correctly executed'; };
}
with ( 'MyRole' );
sub the_method { die; }
}
BEGIN { # use MyB;
require MyB;
}
MyB->new()->the_method();
Within MyB we have a require MyRole, but that module has already been required. Therefore, this doesn't do anything. At that point during the execution, MyRole only consists of this:
package MyRole;
use Moo::Role;
So the role is empty. The requires 'the_method'; before the_method => sub { ... } has not yet been compiled at that point.
As a consequence MyB composes an empty role, which does not affect the the_method.
How can this be avoided? It is often helpful to avoid a use in these cases because that interrupts parsing, before the current module has been initialized. This leads to unintuitive behaviour.
When the modules you use are just classes and do not affect how your source code is parsed (e.g. by importing subroutines), then you can often defer the require to run time. Not just the run time of the module where top-level code is executed, but to the run time of the main application. This means sticking your require into the subroutine that needs to use the imported class. Since a require still has some overhead even when the required module is already imported, you can guard the require like state $require_once = require Some::Module. That way, the require has no run-time overhead.
In general: you can avoid many problems by doing as little initialization as possible in the top-level code of your modules. Prefer being lazy and deferring that initialization. On the other hand, this laziness can also make your system more dynamic and less predictable: it is difficult to tell what initialization has already happened.
More generally, think hard about your design. Why is this circular dependency needed? You should decide to either stick to a layered architecture where high-level code depends on low-level code, or use dependency inversion where low-level code depends on high-level interfaces. Mixing both will result in a horrible tangled mess (exhibit A: this question).
I do understand that some data models necessarily feature co-recursive classes. In that case it can be clearest to sort out the order manually by placing the interdependent classes in a single file.

Perl package defined in script file, how to have package export subroutines?

Given the following:
package My::Pack;
use Exporter::Easy (
OK => [ qw(pack_func) ],
);
sub pack_func {
...
}
package main;
<script here that uses pack_func>
How do I import the symbol I want?
use doesn't work since it's looking for another file to open.
require doesn't support the syntax that use does for specifying the symbols you want.
Are my only choices to say My::Pac::pack_func() in the script or import the symbol manually through typeglob assignmnet?
The statement:
use Some::Module qw(foo bar);
is exactly equivalent to:
BEGIN {
require Some::Module;
Some::Module->import( qw(foo bar) );
}
in your case, the code for the My::Pack module has already been loaded, so you don't need to require it. Thus, you can just do:
BEGIN { My::Pack->import( qw(pack_func) ) }

Detect compile phase in Perl

I'm working with a module that makes use of some prototypes to allow code blocks. For example:
sub SomeSub (&) { ... }
Since prototypes only work when parsed at compile time, I'd like to throw a warning or even a fatal if the module is not parsed at compile time. For example:
require MyModule; # Prototypes in MyModule won't be parsed correctly
Is there a way to detect if something is being executed at compile or run time/phase in Perl?
If you're running on Perl 5.14 or higher, you can use the special ${^GLOBAL_PHASE} variable which contains the current compiler state. Here's an example.
use strict;
use warnings;
sub foo {
if ( ${^GLOBAL_PHASE} eq 'START' ) {
print "all's good\n";
} else {
print "not in compile-time!\n";
}
}
BEGIN {
foo();
};
foo();
Output:
all's good
not in compile-time!
Before 5.14 (or on or after, too), you can do:
package Foo;
BEGIN {
use warnings 'FATAL' => 'all';
eval 'INIT{} 1' or die "Module must be loaded during global compilation\n";
}
but that (and ${^GLOBAL_PHASE}) doesn't quite check what you want to know, which is whether the code containing the use/require statement was being compiled or run.

How can I run a test in my Perl module's test suite only if the required module is installed?

I want to add a test to my Perl distribution that requires a module Foo, but my distribution does not require Foo; only the test requires Foo. So I don't want to add the module to the dependencies, but instead I just want to skip the tests that require Foo if Foo is not available at build time.
What is the proper way to do this? Should I just wrap my Foo tests in an eval block along with use Foo;, so that the tests will not run if loading Foo fails? Or is there a more elegant way of doing it?
If all of the tests that require Some::Module are in a single file, it's easy to do:
use Test::More;
BEGIN {
eval {
require Some::Module;
1;
} or do {
plan skip_all => "Some::Module is not available";
};
}
(If you're using a test count like use Test::More tests => 42; then you need to also arrange to do plan tests => 42; if the require does succeed.)
If they're a smaller number of tests in a file that contains other stuff, then you could do something like:
our $HAVE_SOME_MODULE = 0;
BEGIN {
eval {
require Some::Module;
$HAVE_SOME_MODULE = 1;
};
}
# ... some other tests here
SKIP: {
skip "Some::Module is not available", $num_skipped unless $HAVE_SOME_MODULE;
# ... tests using Some::Module here
}
Test::More has an option to skip if some condition is not satisfied, see below
SKIP: {
eval { require Foo };
skip "Foo not installed", 2 if $#;
## do something if Foo is installed
};
From the documentation of Test::More:
SKIP: {
eval { require HTML::Lint };
skip "HTML::Lint not installed", 2 if $#;
my $lint = new HTML::Lint;
isa_ok( $lint, "HTML::Lint" );
$lint->parse( $html );
is( $lint->errors, 0, "No errors found in HTML" );
}
Also, declare your test step requirement or recommendation (there's a difference) in the distro meta file. This will be picked up by a client performing the installation. At install time, the user can decide whether to install such a requirement permanently or discard it because it was only used for testing.

perl: export symbols from module that has > 1 package

module foo/bar.pm
package foo::bar;
stuff
stuff
package foo::wizzy;
require Exporter;
our #ISA=qw(Exporter);
our #EXPORT=qw(x);
use constant
{
x=>1
};
a consumer that does
use Foo::bar;
does not get the foo::wizzy::x export
I know I can make it two separate modules, but still I should be able to make this work, shouldn't I?
You can do it using Exporter's export_to_level method to have the "main package" re-export the "other" package's symbols like so:
sub import {
my $self = shift;
$self->export_to_level(1, #_);
Some::Other::Module->export_to_level(1);
}
though if Some::Other::Module does something more complicated than "export everything" you will probably need fancier handling for #_.
I really have to ask why, though—I can't imagine a use for this that's compatible with the words "good code" :)
When you call use foo::bar, what actually happens is essentially:
BEGIN {
require foo::bar;
foo::bar->import;
}
(see perldoc -f use)
So import is never getting called on foo::wizzy. If you want to import those symbols as well, you can call BEGIN { foo::wizzy->import } yourself (after use foo::bar). Or, as you said, just split these two packages into separate files, which would be much more human-readable.
(By the way, it's not advisable to use lower-cased package names, as those are generally reserved for perl pragmata.)
At the end of the module, put:
BEGIN { $INC{'foo/wizzy.pm'} = 1 }
Then code can just say:
use foo::bar;
use foo::wizzy;
to get foo::wizzy's exports.
First off, I find it helpful to use enclosing braces to control scope when cramming multiple packages into one file. Also, enclosing the package in a BEGIN block makes it work more like a proper use was used to load it, but this is mostly if I am cramming the package into the main script.
use Foo is the same as BEGIN { require Foo; Foo->import }.
So, you have two choices:
call BEGIN{ Foo::Whizzy->import; } in your main script.
make Foo::Bar::import trigger Foo::Whizzy::import on the calling module.
In Foo/Bar.pm:
{ package Foo::Bar;
use Exporter qw( export_to_level );
# Special custom import. Not needed if you call Foo::Whizzy->import
sub import {
shift;
export_to_level('Foo::Whizzy', 1, #_ );
}
# stuff
# stuff
}
{ package Foo::Whizzy;
require Exporter;
our #ISA=qw(Exporter);
our #EXPORT=qw(x);
use constant { x=>1 };
}
1; # return true
In your main code:
use Foo::Bar;
# If you don't do a custom import for Foo::Bar, add this line:
BEGIN { Foo::Whizzy->import };