如何模拟Perl模块Time :: HiRes

时间:2013-07-31 05:28:28

标签: perl testing mocking

有一个很棒的Perl模块Time::HiRes。我在我的库中大量使用它并且想要编写一些测试。我找到了2个模拟perl time()函数的CPAN模块,但它们都不支持Time::HiRes

我如何模仿Time::HiRes sub gettimeofday()

PS我想修复模块Time::ETA的测试。现在我用sleep“mock”,sometimes it works and sometimes it does not使用丑陋的黑客。

2 个答案:

答案 0 :(得分:2)

您可以使用二十一点和妓女编写自己的模块来模拟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;

我认为它有很多错误和不完整的功能,在这方面工作

答案 1 :(得分:1)

试试Test::MockTime::HiRes

<块引用>

Test::MockTime::HiResTime::HiResTest::MockTime 兼容版本。您可以在模拟时间内等待几毫秒。

如果你想模拟 clock_nanosleep 之类的函数,还有 Test::Mock::Time