Reputation: 2209
Suppose I have a Perl module My::Module
and I want it to output some useful information if I'm running inside of a unit test (i.e. something using Test::Builder
or Test2
, but not if I'm running outside of a unit test. How would I do that?
I realize this is a weird edge case, but it's an interesting question.
Upvotes: 0
Views: 242
Reputation: 118605
Specifically for tests, say, to insert some temporary debugging code, I test for a function that would be defined in the test modules. For me, that is &Test::More::diag
.
sub foo {
...
defined(&Test::More::diag) && Test::More::diag("bar is $bar");
...
}
You can also inspect %INC
to see if the test modules have been loaded
if ($INC{"Test/Builder.pm"}) { print STDERR "debugging info"; }
Upvotes: 1
Reputation: 9296
I use environment variables assigned to constants to control these types of things in my modules (as stated in the OP comments). You can set the environment variables at the command line before running your programs/tests, or set the variables within the test files themselves in a BEGIN
block.
Module:
package Module;
use warnings;
use strict;
use constant IN_TEST => $ENV{IN_TEST} || 0;
sub exec {
warn "We're in testing mode!" if IN_TEST;
return 25;
}
1;
Test file:
use warnings;
use strict;
BEGIN {
$ENV{IN_TEST} = 1;
}
use lib 'lib';
use Module;
use Test::More;
is Module::exec(), 25, "exec() returns correct integer";
done_testing();
Normal script:
use warnings;
use strict;
use lib 'lib';
use Module;
Module::exec();
There is no output when running the script, as the function being called simply returns a value. However, when running the test file:
We're in testing mode! at lib/Module.pm line 9.
ok 1 - exec() returns correct integer
1..1
If you set the environment variable at the command line (or otherwise) before running a normal script that doesn't set it, you'll get the debug output all the same.
Upvotes: 2