Commits

Georges Racinet committed 76cd888

Have time.time() follow the mock time

Comments (0)

Files changed (4)

 
    >>> import anybox.testing.datetime
    >>> from datetime import datetime
+   >>> import time
 
 Let's keep the real value of ``now`` around::
 
    >>> start = datetime.now()
+   >>> start_t = time.time()
 
 Then you can::
 
-   >>> datetime.set_now(datetime(2001, 01, 01, 3, 57, 00))
+   >>> datetime.set_now(datetime(2001, 01, 01, 3, 57, 0))
    >>> datetime.now()
    datetime(2001, 1, 1, 3, 57)
+   >>> datetime.today()
+   datetime(2001, 1, 1, 3, 57)
+
+The time module goes along::
+
+   >>> datetime.fromtimestamp(time.time())
+   datetime(2001, 1, 1, 3, 57)
+
+Note that you can expect a few microseconds difference (not displayed
+here because ``datetime.fromtimestamp`` ignores them).
+
 
 Don't forget afterwards get back to the regular system clock, otherwise
 many pieces of code might get very suprised if the system clock looks as if 
    >>> from datetime import timedelta
    >>> now - start < timedelta(0, 0, 10000) # 10 ms
    True
+
+And with the ``time`` module::
+
+   >>> now_t = time.time()
+   >>> now_t > start_t
+   True
+   >>> now_t - start_t < 0.01 # 10 ms again
+   True

anybox/testing/datetime/__init__.py

 import sys
 import mock_dt
+sys.modules['datetime'] = mock_dt
+import mock_time
 
-sys.modules['datetime'] = mock_dt
+sys.modules['time'] = mock_time

anybox/testing/datetime/mock_dt.py

 import sys
 from datetime import *
 from datetime import datetime as original_datetime
+from time import time as original_time
+import time
 
 class datetime(original_datetime):
 
         of 'now'.
         """
         cls.set_now(None)
+
+def time():
+    if datetime._current_now is None:
+        return original_time()
+    now = datetime.now()
+    return time.mktime(now.timetuple) + now.microsecond / 1000000
+
+time.time = time
+

anybox/testing/datetime/mock_time.py

+"""Patch of time module to follow datetime.set_now
+
+Note: monkey-patching time.time works within a module or interactive session,
+but not in subsequent imports from other modules.
+Replacing the whole time module by this one does work.
+"""
+
+from time import *
+from time import time as original_time
+
+from datetime import datetime
+
+def time():
+    if datetime._current_now is None:
+        return original_time()
+    now = datetime.now()
+    return mktime(now.timetuple()) + now.microsecond / 1000000