如何模拟Perl模块Time :: HiRes

前端之家收集整理的这篇文章主要介绍了如何模拟Perl模块Time :: HiRes前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有一个很棒的Perl模块 Time::HiRes.我在我的库中大量使用它并且想要编写一些测试.我找到了2个模拟perl time()函数的CPAN模块,但它们都不支持 Time::HiRes

> Time::Mock
> Test::MockTime

我怎么能模拟Time::HiRes sub gettimeofday()?

PS我想为我的模块Time::ETA修复测试.现在我使用丑陋的黑客与睡眠“模拟”,sometimes it works and sometimes it does not.

解决方法

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