fake_timer.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2024 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. class FakeTimer(object):
  15. TIMERS = []
  16. def __init__(self, interval, function):
  17. self.interval = interval
  18. self.function = function
  19. self.started = False
  20. self.expired = False
  21. self.cancelled = False
  22. type(self).TIMERS.append(self)
  23. def __repr__(self):
  24. state_flags = ''.join([
  25. 'S' if self.started else 'N',
  26. 'X' if self.expired else '.',
  27. 'C' if self.cancelled else '.'])
  28. return '<FakeTimer({}, {}) {} at {:#x}>'.format(
  29. self.interval, self.function, state_flags, id(self))
  30. def start(self):
  31. if self.started:
  32. raise RuntimeError("threads can only be started once")
  33. self.started = True
  34. def cancel(self):
  35. self.cancelled = True
  36. def expire(self):
  37. '''Simulate the timeout expiring.'''
  38. assert self.started, 'timer not yet started'
  39. assert not self.expired, 'timer can only expire once'
  40. self.expired = True
  41. self.function()
  42. @property
  43. def is_active(self):
  44. return self.started and not self.expired and not self.cancelled
  45. @classmethod
  46. def clear_timer_list(cls):
  47. cls.TIMERS = []
  48. @classmethod
  49. def get_active_timers(cls):
  50. return [t for t in cls.TIMERS if t.is_active]