perl - 如何模拟 Perl 模块 Time::HiRes

标签 perl testing mocking

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

我如何模拟 Time::HiResgettimeofday()?

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/

相关文章:

linux - 使用 perl 脚本平铺窗口 - 嵌套数组是个坏主意吗?

perl - 如何在导出器模块中实现 "use 5.010"?

android - 如何通过 Android 的 ant 构建脚本运行单个测试用例?

python - 如何模拟对象方法返回值

c# - 单元测试多级异常——在哪里停止?

用于 API 的 perl 测试套件

c - 非常简单的 DNS 服务器

java - 如何禁用 JPA 2 回调方法和实体监听器

testing - 为什么在 Appium 自动化测试中 android debug build 比 android release build 更常用?

unit-testing - 在 CakePHP 中模拟一个 Controller 方法