[Twisted-Python] Simulating time for reactor

Phillip J. Eby pje at telecommunity.com
Mon Jan 12 14:55:09 EST 2004


At 02:06 PM 1/12/04 -0500, Itamar Shtull-Trauring wrote:
>On Mon, 2004-01-12 at 12:35, David Bolen wrote:
>
> > For example, if IReactorCore included a now() or time() method which
> > was the only way it grabbed system time, then tests could mock up a
> > reactor to be installed at the start of a test and just override that
> > one method to control time.  From looking at base.py in the Twisted
> > distribution for example, it only appears that a few uses of
> > time.time() would have to be tweaked.
>
>This still wouldn't alter how long e.g. select() waits, but since that
>has maximum timeouts you'd probably be fine with just changing the time
>to be 30 secs in the future, yeah.

For tests in PEAK that involve reactors, I use a "clock" object with 
time(), select(), and sleep() methods.  The select() and sleep() methods 
just increment the time() value by the given number of seconds.  So, for 
each test, time() starts at zero and we go from there.

One other issue to watch for: the insertion of delayed calls must be 
stable.  That is, if you add two delayed calls with the same target time, 
they must end up in the list in the order that they were added.  Otherwise, 
tests will behave oddly.  It's been a long time since I looked at Twisted's 
base reactor code, but it seems to me that the last time I did, Twisted was 
*not* using a stable insertion algorithm.  Mine uses insort_right and 
pop(0), with an object type that compares equal for equal target times.  If 
this latter constraint isn't met, it's not possible to get a stable 
insertion using the bisect module's insort functions.





More information about the Twisted-Python mailing list