test_hooks.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. from huey import RedisHuey
  2. from huey.exceptions import CancelExecution
  3. from huey.tests.base import HueyTestCase
  4. test_huey = RedisHuey('testing-2', blocking=False, read_timeout=0.1)
  5. @test_huey.task()
  6. def add_values(a, b):
  7. return a + b
  8. @test_huey.task()
  9. def fail():
  10. raise Exception('failed')
  11. ALLOW_TASKS = True
  12. PRE_STATE = []
  13. POST_STATE = []
  14. @test_huey.pre_execute()
  15. def pre_run(task):
  16. if not ALLOW_TASKS:
  17. raise CancelExecution()
  18. @test_huey.pre_execute()
  19. def pre_run2(task):
  20. global PRE_STATE
  21. PRE_STATE.append(task)
  22. @test_huey.post_execute()
  23. def post_run(task, task_value, exc):
  24. global POST_STATE
  25. POST_STATE.append((task, task_value, exc))
  26. class HooksTestCase(HueyTestCase):
  27. def setUp(self):
  28. super(HooksTestCase, self).setUp()
  29. global ALLOW_TASKS
  30. global PRE_STATE
  31. global POST_STATE
  32. ALLOW_TASKS = True
  33. PRE_STATE = []
  34. POST_STATE = []
  35. def get_huey(self):
  36. return test_huey
  37. class TestHooks(HooksTestCase):
  38. def test_hooks_being_run(self):
  39. res = add_values(1, 2)
  40. task = self.huey.dequeue()
  41. self.worker(task)
  42. self.assertEqual(PRE_STATE, [task])
  43. self.assertEqual(POST_STATE, [(task, 3, None)])
  44. def test_cancel_execution(self):
  45. res = add_values(1, 2)
  46. task = self.huey.dequeue()
  47. global ALLOW_TASKS
  48. ALLOW_TASKS = False
  49. self.worker(task)
  50. self.assertEqual(PRE_STATE, [])
  51. self.assertEqual(POST_STATE, [])
  52. def test_capture_error(self):
  53. res = fail()
  54. task = self.huey.dequeue()
  55. self.worker(task)
  56. self.assertEqual(PRE_STATE, [task])
  57. self.assertEqual(len(POST_STATE), 1)
  58. task_obj, ret, exc = POST_STATE[0]
  59. self.assertEqual(task_obj, task)
  60. self.assertTrue(ret is None)
  61. self.assertTrue(exc is not None)