如何模拟Perl模块Time :: HiRes

bes*_*bov 5 testing perl mocking

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

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

PS我想为我的模块Time :: ETA修复测试.现在我使用丑陋的黑客与sleep"模拟",有时它工作,有时它没有.

Sui*_*uic 2

您可以使用 blackjack 和 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;
Run Code Online (Sandbox Code Playgroud)

我认为它有很多错误和不完整的功能,朝这个方向努力