Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test my module that uses File::ShareDir?

I am writing a module that installs a shared file in the dist directory using File::ShareDir::Install. Inside the main exported function in the module, the file is then located using File::ShareDir.

This function loads the shared file, and looks up a string in the file. In one of my tests, I wanted to check if the function returned the correct values for a few inputs. So, the test looks like:

my @cases = (
    [ 'input1' => 'expected1' ],
    # etc
);

for my $case ( @cases ) {
    my ($input, $expected) = @$case;
    is(
        my_lookup_function($input),
        $expected,
        "$input => $expected",
    );
}

However, the test does not run because

my $dir = dist_dir('My-Dist');

croaks.

My Makefile.PL seems to be correct, because I can find the share file under blib. I just do not know what I need to do to get the File::ShareDir::dist_dir call in my module to find this directory during testing.

I did look at Test::File::ShareDir, but I don't understand if it can be used to do what I am trying to do.

I would appreciate it if you can either tell me how to achieve desired behavior with the current setup, or suggest ways of doing things differently (and presumably correctly ;-)

like image 769
Sinan Ünür Avatar asked Dec 05 '25 05:12

Sinan Ünür


2 Answers

Works for me.

perl Makefile.PL ; make
make test
prove -b

$ tree
.
├── Makefile.PL
├── share
│   └── quux
└── t
    └── foo.t

2 directories, 3 files

$ cat Makefile.PL
use ExtUtils::MakeMaker;
use File::ShareDir::Install;

install_share 'share';
WriteMakefile;

package MY;
use File::ShareDir::Install qw(postamble);


$ cat t/foo.t
use File::ShareDir qw(dist_dir);
use Test::More;

diag dist_dir('My-Dist');

pass;
done_testing;
like image 50
daxim Avatar answered Dec 07 '25 21:12

daxim


You can use the module Test::File::ShareDir to tell your tests where to look for your ShareDir files.

From the documentation:

use Test::More;

# use FindBin; optional

use Test::File::ShareDir
    # -root => "$FindBin::Bin/../" # optional,
    -share => {
        -module => { 'My::Module' => 'share/MyModule' }
        -dist   => { 'My-Dist'    => 'share/somefolder' }
    };

use My::Module;

use File::ShareDir qw( module_dir dist_dir );

module_dir( 'My::Module' ) # dir with files from $dist/share/MyModule

dist_dir( 'My-Dist' ) # dir with files from $dist/share/somefolder
like image 27
Ivan Wills Avatar answered Dec 07 '25 20:12

Ivan Wills



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!