有一个很棒的 Perl 模块 Time::HiRes .我在我的库中大量使用它并想编写一些测试。我找到了 2 个模拟 perl time()
函数的 CPAN 模块,但它们都不支持 Time::HiRes :
我如何模拟 Time::HiRes子 gettimeofday()
?
PS 我想为我的模块修复测试 Time::ETA .现在我使用带有 sleep
“mock”的丑陋 hack,sometimes it works and sometimes it does not .
最佳答案
您可以编写自己的模块with blackjack and hookers 来模拟gettimeofday。通过对 Test::MockTime 的一些修改,我写道:
#!/usr/bin/perl
package myMockTime;
use strict;
use warnings;
use Exporter qw( import );
use Time::HiRes ();
use Carp;
our @fixed = ();
our $accel = 1;
our $otime = Time::HiRes::gettimeofday;
our @EXPORT_OK = qw(
set_fixed_time_of_day
gettimeofday
restore
throttle
);
sub gettimeofday() {
if ( @fixed ) {
return wantarray ? @fixed : "$fixed[0].$fixed[1]";
}
else {
return $otime + ( ( Time::HiRes::gettimeofday - $otime ) * $accel );
}
}
sub set_fixed_time_of_day {
my ( $time1, $time2 ) = @_;
if ( ! defined $time1 || ! defined $time2 ) {
croak('Incorrect usage');
}
@fixed = ( $time1, $time2 );
}
sub throttle {
my $self = shift @_;
return $accel unless @_;
my $new = shift @_;
$new or croak('Can not set throttle to zero');
$accel = $new;
}
sub restore {
@fixed = ();
}
1;
我认为它有很多错误和不完整的功能,朝这个方向努力
关于perl - 如何模拟 Perl 模块 Time::HiRes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17962280/