views:

203

answers:

4

I have a Perl module that I have declared some constants:

use constant BASE_PATH => "/data/monitor/";

In live operation the constant will never change but I wish to be able to modify it in my unit tests, e.g. to set it to ~/project/testdata/. Is there a way do do this without having to use "non-constants"?

Could I possibly use Test::MockObject on the constant.pm?

+5  A: 

When using constants they are implemented as constant functions behaving something like:

use subs 'BASE_PATH';
sub BASE_PATH () {"/data/monitor/"}

Any uses of BASE_PATH in the program are inlined and so can't be modified.

To achieve similar you could manually use the subs pragma (to make BASE_PATH behave as a built in function) and declare BASE_PATH as a standard function:

use subs 'BASE_PATH';
sub BASE_PATH {"/data/monitor/"}

print "BASE_PATH is ".BASE_PATH."\n";

*BASE_PATH = sub {"/new/path"};
print "BASE_PATH is ".BASE_PATH."\n";

Although why you would want to do this I'm not too sure.

Callum
Remember to put it in the right package.
Chas. Owens
+1  A: 

Apparently, if your definition of BASE_PATH was used/compiled into another subroutine BEFORE your test does change it (via

*BASE_PATH = sub { ... }

or other stuff) you have no solution (because when the original module used BASE_PATH as a constant, it really defined an INLINE function that was, well, inlined when used in other code)

Massa
The only solution is to monkey patch constant's import subroutine. Install a wrapper around constant's import that intercepts specified constant names to be overridden and the values to apply. If you do this, then only the overriden constant subs will be created and they will be inlined by the compiler. I don't have time to write something like this right now, but it shouldn't be too hard.
daotoad
But in that case, making your own constant.pm that does not let the sub be inlined would be even better/easier, no? put it somewhere early in the test library path and ta-da...
Massa
+1  A: 
package My::Class;

use constant BASE_PATH => "/a/real/value/";

# ..more code here..

1;

Now in your unit tests:

use My::Class;
*{My::Class::BASE_PATH} = sub { "/a/fake/value" };

# do your tests here...
Ether
+1  A: 

Tests often reveal inflexibility in the design. This is one of those times. That constant shouldn't be constant.

If you're doing it for performance reasons I'm willing to bet hard currency that it doesn't make any difference.

Schwern