Boost logo

Boost Users :

Subject: [Boost-users] [asio] How do you fake the time for boost timers?
From: Josh Quigley (0zeroth_at_[hidden])
Date: 2013-01-13 18:13:55


(For those interested this question is also at
http://stackoverflow.com/questions/14191855/how-do-you-fake-the-time-for-boost-timers
)

Hi all,

If possible, how do you fake the time for the purpose of triggering boost
timers in a unit test?

For example, is it possible to achieve something like the following:

#include <iostream>#include <boost/asio.hpp>#include
<boost/date_time/posix_time/posix_time.hpp>
void print(const boost::system::error_code& /*e*/){
  std::cout << "Hello, world!\n";}
int main(){
    boost::asio::io_service io; // Possibly another class
needed here, or a way of setting the clock to be fake

    boost::asio::deadline_timer t(io, boost::posix_time::hours(24));
    t.async_wait(&print);

    io.poll(); // Nothing should happen - no handlers ready

    // PSEUDO-CODE below of what I'd like to happen, jump ahead 24 hours
    io.set_time(io.get_time() + boost::posix_time::hours(24));

    io.poll(); // The timer should go off

    return 0;}

I'm aware I could wrap the io_service and deadline_timer in a wrapper and
write my own test implementation, thus providing the real and test version
to the production code I'm trying to test.

What I'm hoping is the boost framework allows a way to create an io service
that is related to a fake clock rather than the system time, meaning I
don't need to create my own wrappers.

I should also point out that the docs indicate providing something like my
own WaitableTimerService orTimerService may be the way to go, but I can't
see which one (if any) is responsible for providing the clock.

Any tips appreciated!

Josh.



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net