Test::MockSleep - Pretend to sleep!
use Test::More; use Test::MockSleep; use Time::HiRes; use Dir::Self; use lib __DIR__; use dummy_module; my $begin_time = time(); sleep(20); is(slept, 20, "in same module (CORE::sleep)"); Time::HiRes::sleep(2.5); is(slept, 2.5, "in same module (Time::HiRes::sleep)"); dummy_module::sleep_core(5); is(slept(), 5, "CORE::sleep"); dummy_module::sleep_time_hires(0.5); is(slept(), 0.5, "Time::HiRes::sleep"); dummy_module_thr::thr_sleep(0.5); is(slept(), 0.5, "Time::HiRes::sleep (implicit)"); sleep(100); sleep(100); is($Test::MockSleep::Slept, 200, "package \$Slept"); Test::MockSleep->restore(); my $begin = Time::HiRes::time(); Time::HiRes::sleep(0.1); my $end = Time::HiRes::time(); ok($begin != $end, "Real Time::HiRes::sleep: ($begin to $end)"); diag "Sleeping 1 second for real"; $begin = time(); sleep(1); $end = time(); ok($begin != $end, "Real CORE::sleep ($begin to $end)"); done_testing();
Test::MockSleep overrides perl's
sleep call. A call to
sleep will not really sleep.
It also provides a facility to check how many seconds a program would have slept.
It has a few bonuses:
sleepmethod as well.
Time::MockSleepis imported with the
Time::MockTime's clock will be adjusted to show the updated time, as-if the program had actually slept, and the clock is advanced.
There are two means to do this. The more convenient is a function called
slept which is exported to your calling code's namespace.
use Test::MockSleep; sleep(5); my $slept = slept();
Test::MockSleep retains an internal counter which increments each time sleep is called. This counter is reset when
slept is called, which is presumably what you want anyway.
If for whatever reason, you do not want the internal counter to be reset, you can access it directly as a package variable:
$Test::MockSleep::Slept, and reset it manually when desired.
This should be done before
useing other modules which might potentially use Time::HiRes's sleep (in which case the calling package's
sleep will be aliased to Time::HiRes' sleep, at the time of import).
If you wish to have your clocked advanced as well, and the module Test::MockTime is installed, you can do
use Test::MockSleep qw(:with_mocktime);
Will restore global sleep's behavior (as well as Time::HiRes').
Copyright (C) 2012 by M. Nunberg
You may use and distribute this software under the same terms and license as Perl itself.