Test::MockTimeとCORE::Globalと

Test::MockTimeの使い方にハマって調べたことをメモっておく。

Test::MockTime

package Test::MockTime;
...
BEGIN {
	*CORE::GLOBAL::time = \&Test::MockTime::time;
	*CORE::GLOBAL::localtime = \&Test::MockTime::localtime;
	*CORE::GLOBAL::gmtime = \&Test::MockTime::gmtime;
}

CORE::GLOBALでbuilt-in関数であるtime/localtime/gmtimeをコンパイル時に上書く。

CORE::GLOBAL?

http://perldoc.perl.org/CORE.htmlによれば...

For all Perl keywords, a CORE:: prefix will force the built-in function to be used, even if it has been overridden or would normally require the feature pragma. Despite appearances, this has nothing to do with the CORE package, but is part of Perl's syntax.

     

To override a built-in globally (that is, in all namespaces), you need to import your function into the CORE::GLOBAL pseudo-namespace at compile time:

だそう。実際に確認してみる。

#!/usr/bin/perl
use strict;
use warnings;

BEGIN {
    *CORE::GLOBAL::time = sub { return 1; }
}

print time, "\n"; # 1
print CORE::time, "\n"; # 1358838023