nti.testing.time#

Test support for working with clocks and time.

class nti.testing.time.MonotonicallyIncreasingTimeLayerMixin(granularity=1.0)[source]#

Bases: object

A helper for layers that need time to increase monotonically.

You can either mix this in to a layer object, or instantiate it and call the methods directly.

New in version 2.2.

nti.testing.time.reset_monotonic_time(value=0.0)[source]#

Make the monotonic clock return the real time on its next call.

New in version 2.0.

nti.testing.time.time_monotonically_increases(func_or_granularity)[source]#

Decorate a unittest method with this function to cause the value of time.time() (and time.gmtime()) to monotonically increase by one each time it is called. This ensures things like last modified dates always increase.

We make three guarantees about the value of time.time() returned while the decorated function is running:

  1. It is always at least the value of the real time.time();

  2. Each call returns a value greater than the previous call;

  3. Those two constraints hold across different invocations of functions decorated.

This decorator can be applied to a method in a test case:

class TestThing(unittest.TestCase)
    @time_monotonically_increases
    def test_method(self):
      t = time.time()
       ...

It can also be applied to a bare function taking any number of arguments:

@time_monotonically_increases
def utility_function(a, b, c=1):
   t = time.time()
   ...

By default, the time will be incremented in 1.0 second intervals. You can specify a particular granularity as an argument; this is useful to keep from running too far ahead of the real clock:

@time_monotonically_increases(0.1)
def smaller_increment():
    t1 = time.time()
    t2 = time.time()
    assrt t2 == t1 + 0.1

Changed in version 2.1: Add support for time.gmtime.

Changed in version 2.1: Now thread safe.

Changed in version 2.0: The decorated function returns whatever the passed function returns.

Changed in version 2.0: Properly handle more than one argument to the underlying function.

Changed in version 2.0: Ensure that the values returned are at least the real time. Previously they were integers starting at 0.

Changed in version 2.0: Ensure that the values returned are increasing even across different invocations of a decorated function or different decorated functions. Previously different functions would return the same sequence.

Changed in version 2.0: Allow specifying the granularity of clock increments. Keep at 1.0 seconds for backwards compatibility by default.