How do I run a test in my test suite of Perl modules only if the required module is installed?

I want to add a test to my Perl distribution that requires the Foo module, but my distribution does not require Foo; test only requires foo. So I don’t want to add a module depending, but instead I just want to skip tests that require Foo if Foo is not available at build time.

What is the right way to do this? Should I just transfer my Foo tests to the eval block along with use Foo;so that the tests do not run when Foo loads? Or is there a more elegant way to do this?

+5
source share
4 answers

Test:: More , - , .

SKIP: {
    eval { require Foo };

    skip "Foo not installed", 2 if $@;

    ## do something if Foo is installed
};
+6

, Some::Module, , :

use Test::More;

BEGIN {
    eval {
        require Some::Module;
        1;
    } or do {
        plan skip_all => "Some::Module is not available";
    };
}

( , use Test::More tests => 42;, plan tests => 42;, .)

, , - :

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
}
+8

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" );
}
+2

In addition, declare a test or recommendation requirement (there is a difference) in the distro meta file. This will be perceived by the client performing the installation. During installation, the user can decide whether to constantly install such a requirement or refuse it, because it was used only for testing.

+2
source

All Articles