Initial import to Tizen
[profile/ivi/python-twisted.git] / twisted / test / time_helpers.py
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 Helper class to writing deterministic time-based unit tests.
6
7 Do not use this module.  It is a lie.  See L{twisted.internet.task.Clock}
8 instead.
9 """
10
11 import warnings
12 warnings.warn(
13     "twisted.test.time_helpers is deprecated since Twisted 10.0.  "
14     "See twisted.internet.task.Clock instead.",
15     category=DeprecationWarning, stacklevel=2)
16
17
18 class Clock(object):
19     """
20     A utility for monkey-patches various parts of Twisted to use a
21     simulated timing mechanism. DO NOT use this class. Use
22     L{twisted.internet.task.Clock}.
23     """
24     rightNow = 0.0
25
26     def __call__(self):
27         """
28         Return the current simulated time.
29         """
30         return self.rightNow
31
32     def install(self):
33         """
34         Monkeypatch L{twisted.internet.reactor.seconds} to use
35         L{__call__} as a time source
36         """
37         # Violation is fun.
38         from twisted.internet import reactor
39         self.reactor_original = reactor.seconds
40         reactor.seconds = self
41
42     def uninstall(self):
43         """
44         Remove the monkeypatching of L{twisted.internet.reactor.seconds}.
45         """
46         from twisted.internet import reactor
47         reactor.seconds = self.reactor_original
48
49     def adjust(self, amount):
50         """
51         Adjust the current simulated time upward by the given C{amount}.
52
53         Note that this does not cause any scheduled calls to be run.
54         """
55         self.rightNow += amount
56
57     def pump(self, reactor, timings):
58         """
59         Iterate the given C{reactor} with increments of time specified
60         by C{timings}.
61
62         For each timing, the simulated time will be L{adjust}ed and
63         the reactor will be iterated twice.
64         """
65         timings = list(timings)
66         timings.reverse()
67         self.adjust(timings.pop())
68         while timings:
69             self.adjust(timings.pop())
70             reactor.iterate()
71             reactor.iterate()
72