test_timer2.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. from __future__ import absolute_import, unicode_literals
  2. import sys
  3. import time
  4. from case import Mock, call, patch
  5. import celery.utils.timer2 as timer2
  6. class test_Timer:
  7. def test_enter_after(self):
  8. t = timer2.Timer()
  9. try:
  10. done = [False]
  11. def set_done():
  12. done[0] = True
  13. t.call_after(0.3, set_done)
  14. mss = 0
  15. while not done[0]:
  16. if mss >= 2.0:
  17. raise Exception('test timed out')
  18. time.sleep(0.1)
  19. mss += 0.1
  20. finally:
  21. t.stop()
  22. def test_exit_after(self):
  23. t = timer2.Timer()
  24. t.call_after = Mock()
  25. t.exit_after(0.3, priority=10)
  26. t.call_after.assert_called_with(0.3, sys.exit, 10)
  27. def test_ensure_started_not_started(self):
  28. t = timer2.Timer()
  29. t.running = True
  30. t.start = Mock()
  31. t.ensure_started()
  32. t.start.assert_not_called()
  33. t.running = False
  34. t.on_start = Mock()
  35. t.ensure_started()
  36. t.on_start.assert_called_with(t)
  37. t.start.assert_called_with()
  38. @patch('celery.utils.timer2.sleep')
  39. def test_on_tick(self, sleep):
  40. on_tick = Mock(name='on_tick')
  41. t = timer2.Timer(on_tick=on_tick)
  42. ne = t._next_entry = Mock(name='_next_entry')
  43. ne.return_value = 3.33
  44. ne.on_nth_call_do(t._is_shutdown.set, 3)
  45. t.run()
  46. sleep.assert_called_with(3.33)
  47. on_tick.assert_has_calls([call(3.33), call(3.33), call(3.33)])
  48. @patch('os._exit')
  49. def test_thread_crash(self, _exit):
  50. t = timer2.Timer()
  51. t._next_entry = Mock()
  52. t._next_entry.side_effect = OSError(131)
  53. t.run()
  54. _exit.assert_called_with(1)
  55. def test_gc_race_lost(self):
  56. t = timer2.Timer()
  57. t._is_stopped.set = Mock()
  58. t._is_stopped.set.side_effect = TypeError()
  59. t._is_shutdown.set()
  60. t.run()
  61. t._is_stopped.set.assert_called_with()
  62. def test_test_enter(self):
  63. t = timer2.Timer()
  64. t._do_enter = Mock()
  65. e = Mock()
  66. t.enter(e, 13, 0)
  67. t._do_enter.assert_called_with('enter_at', e, 13, priority=0)
  68. def test_test_enter_after(self):
  69. t = timer2.Timer()
  70. t._do_enter = Mock()
  71. t.enter_after()
  72. t._do_enter.assert_called_with('enter_after')
  73. def test_cancel(self):
  74. t = timer2.Timer()
  75. tref = Mock()
  76. t.cancel(tref)
  77. tref.cancel.assert_called_with()