如何在Perl 6中模拟当前时间?

时间:2018-11-16 12:11:58

标签: perl6

在Perl 5中,可以轻松模拟在特定时间戳记下运行的脚本:

BEGIN {
    *CORE::GLOBAL::time = sub () { $::time_mock // CORE::time };
}
use Test;
$::time_mock = 1545667200;
ok is-xmas, 'yay!';
$::time_mock = undef; # back to current time

这在全局范围内有效-每个程序包,每个方法,所有使用time()的事物都将看到1545667200时间戳。这对于测试时间敏感逻辑非常方便。

有没有办法在Perl 6中重现这种行为?

2 个答案:

答案 0 :(得分:9)

这是一种更改“现在”一词的工作方式的方法,您可能希望对“时间”做同样的事情(尽管时间返回一个Int,而不是Instant对象)。

&term:<now>.wrap(
    -> |, :$set-mock-time {
        state $mock-time;
        $mock-time = Instant.from-posix($_) with $set-mock-time;
        $mock-time // callsame
});
say now; # Instant:1542374103.625357
sleep 0.5;
say now; # Instant:1542374104.127774
term:<now>(set-mock-time => 12345);
say now; # Instant:12355
sleep 0.5;
say now; # Instant:12355

最重要的是,取决于您要执行的操作,也许Test :: Scheduler可能很有趣:https://github.com/jnthn/p6-test-scheduler

答案 1 :(得分:3)

生态系统中有Test :: Time(https://github.com/FCO/test-time