I'm writing a perl module that interfaces with an API and I would like to write a test suite for it before putting it up on CPAN. However, because this module is basically just an interface for an API, all tests would require a valid API key and user. Obviously I can't release this module with my API key and username in the test suite, so what is the best way to handle something like this? Should I just test locally and then put it up on CPAN with no tests? Has anyone run into this before and come up with a good solution? I know that writing tests is best practice, so I'd like to do it if I can. Thanks!
Why not wrap the API calls into small functions (e.g. the function does NOTHING but the API call), and then mock those functions in your tests as needed using Test::MockObject
or similar?
This would be even better, as you would be able to have tests that test different results from API (failure, auth failure, etc...)
I made it clear in my documentation that my module was useless without an API key, and used skip:{} constructs of Test::More to skip all the tests if the key was not present. You can choose too bail_out instead of skip.
Just insure that your docs explain how to communicate the API key to the module.
I22r-Translate
–
Scorpaenoid The usual way I handle this sort of thing is to require an environment variable in order to run the test suite. The environment variable will contain the useful bit of information (e.g. an API key, a hostname to connect to, etc.)
Here's an example of how you might handle this sort of thing from within a test file. We use this for the MongoDB distribution to check if there's an available server to run against:
BEGIN {
eval {
my $host = exists $ENV{MONGOD} ? $ENV{MONGOD} : 'localhost';
$conn = MongoDB::MongoClient->new( host => $host, ssl => $ENV{MONGO_SSL} );
};
if ( $@ ) {
plan skip_all => $@;
exit 0;
}
};
All this does is try to connect to a host specified in the MONGOD
environment variable (or else localhost.) If it can't, it skips all the tests and tells the reason why. The skips still count as a non-failure, so it won't prevent installation of the module if no test server is available.
I have this code in a .pm file which I use
in every .t file in the distribution.
© 2022 - 2024 — McMap. All rights reserved.