Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 219
Ryan C. Thompson Avatar asked Dec 13 '11 05:12

Ryan C. Thompson


2 Answers

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
}
like image 160
hobbs Avatar answered Oct 05 '22 12:10

hobbs


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
};
like image 21
Pradeep Avatar answered Oct 05 '22 12:10

Pradeep