2013-07-31 14 views
5

C'è un grande modulo Perl Time::HiRes. Lo uso pesantemente nella mia biblioteca e voglio scrivere alcuni test. Ho trovato 2 moduli CPAN che prende in giro perl funzione time(), ma entrambi non supportano Time::HiRes:Come simulare il modulo Perl Tempo :: HiRes

Come posso prendere in giro Time::HiRes sub gettimeofday()?

PS Voglio correggere i test per il mio modulo Time::ETA. Ora utilizzo un brutto attacco con sleep "simulato", sometimes it works and sometimes it does not.

+0

Vuoi qualcosa come 'sub set_fixed_time_of_day'? – Suic

+0

Stavo pensando a quello che voglio. Voglio essere in grado di fermare il tempo nel mio script di test. Dopo aver eseguito 'my $ ts = CORE :: time(); set_fixed_time ($ ts); '(o qualcosa del genere)' time() 'e' Time :: HiRes :: gettimeofday() 'restituiranno gli stessi valori fino a quando eseguirò esplicitamente' $ ts ++; set_fixed_time ($ ts); ' – bessarabov

risposta

2

È possibile scrivere il proprio modulo con il blackjack e le prostitute per prendere in giro gettimeofday. Con alcune modifiche di Test :: MockTime ho scritto:

#!/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; 

penso che abbia un sacco di bug e functionallity incompleta, lavoro in questa direzione

+0

Sì =) Questa è una soluzione. Ma speravo che questo problema fosse già risolto. E penso che sia meglio non scrivere un nuovo modulo, ma provare a correggere Time :: Mock o Test :: MockTime. – bessarabov

+0

'usare Esportatore; * import = \ & Exporter :: import; import() se 0; 'può essere scritto' usa esportatore qw (importazione); ' – ikegami

+0

grazie, era copia-incolla dal test originale :: MockTime + hack per disabilitare l'avviso) – Suic

Problemi correlati