Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock current time in Perl 6?

Tags:

raku

In Perl 5 one can easily simulate script running at specific timestamp:

BEGIN {
    *CORE::GLOBAL::time = sub () { $::time_mock // CORE::time };
}
use Test;
$::time_mock = 1545667200;
ok is-xmas, 'yay!';
$::time_mock = undef; # back to current time

And this works globally - every package, every method, everything that uses time() will see 1545667200 timestamp. Which is very convenient for testing time sensitive logic.

Is there a way to reproduce such behavior in Perl 6?

like image 700
Pawel Pabian bbkr Avatar asked Nov 16 '18 12:11

Pawel Pabian bbkr


People also ask

How to get current time in Perl?

localtime() function in Perl returns the current date and time of the system, if called without passing any argument.

What is localtime in Perl?

In Perl, localtime is defined as a time function which displays the date and time for the local time zones that usually converts a specified time into a certain list of time elements which are numerical data types for all the elements in the list returned by this localtime() function in Perl.

How do I get yesterday's date in Perl?

If you want yesterday's date: use DateTime qw( ); my $yday_date = DateTime ->now( time_zone => 'local' ) ->set_time_zone('floating') ->truncate( to => 'day' ) ->subtract( days => 1 ) ->strftime('%Y-%m-%d'); For example, in New York on 2019-05-14 at 01:00:00, it would have returned 2019-05-13.


1 Answers

Here's a way to change how the "now" term works, and you may want to do the same thing to "time" (though time returns an Int, not an Instant object).

&term:<now>.wrap(
    -> |, :$set-mock-time {
        state $mock-time;
        $mock-time = Instant.from-posix($_) with $set-mock-time;
        $mock-time // callsame
});
say now; # Instant:1542374103.625357
sleep 0.5;
say now; # Instant:1542374104.127774
term:<now>(set-mock-time => 12345);
say now; # Instant:12355
sleep 0.5;
say now; # Instant:12355

On top of that, depending on what exactly you want to do, perhaps Test::Scheduler could be interesting: https://github.com/jnthn/p6-test-scheduler

like image 153
timotimo Avatar answered Nov 11 '22 06:11

timotimo