/tests/core/test_timers.py

https://bitbucket.org/prologic/circuits/ · Python · 87 lines · 56 code · 25 blank · 6 comment · 2 complexity · 9ee52cb11f3d28c80c91d4bceb5cd920 MD5 · raw file

  1. # Module: test_timers
  2. # Date: 10th February 2010
  3. # Author: James Mills, prologic at shortcircuit dot net dot au
  4. import time
  5. """Timers Tests"""
  6. import pytest
  7. from datetime import datetime, timedelta
  8. from circuits import Event, Component, Timer
  9. def pytest_funcarg__app(request):
  10. return request.cached_setup(
  11. setup=lambda: setupapp(request),
  12. teardown=lambda app: teardownapp(app),
  13. scope="module"
  14. )
  15. def setupapp(request):
  16. app = App()
  17. app.start()
  18. return app
  19. def teardownapp(app):
  20. app.stop()
  21. class test(Event):
  22. """test Event"""
  23. class App(Component):
  24. def __init__(self):
  25. super(App, self).__init__()
  26. self.flag = False
  27. self.count = 0
  28. self.timestamps = []
  29. def reset(self):
  30. self.timestamps = []
  31. self.flag = False
  32. self.count = 0
  33. def test(self):
  34. self.timestamps.append(time.time())
  35. self.count += 1
  36. self.flag = True
  37. def test_timer(app):
  38. timer = Timer(0.1, test(), "timer")
  39. timer.register(app)
  40. assert pytest.wait_for(app, "flag")
  41. app.reset()
  42. def test_persistentTimer(app):
  43. app.timestamps.append(time.time())
  44. timer = Timer(0.2, test(), "timer", persist=True)
  45. timer.register(app)
  46. wait_res = pytest.wait_for(app, "count", 2)
  47. assert app.count >= 2
  48. assert wait_res
  49. delta = app.timestamps[1] - app.timestamps[0]
  50. # Should be 0.1, but varies depending on timer precision and load
  51. assert delta >= 0.08 and delta < 0.5
  52. delta = app.timestamps[2] - app.timestamps[1]
  53. assert delta >= 0.08 and delta < 0.5
  54. app.reset()
  55. timer.unregister()
  56. def test_datetime(app):
  57. now = datetime.now()
  58. d = now + timedelta(seconds=0.1)
  59. timer = Timer(d, test(), "timer")
  60. timer.register(app)
  61. assert pytest.wait_for(app, "flag")
  62. app.reset()