test_canvas.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. from __future__ import absolute_import, unicode_literals
  2. from datetime import datetime, timedelta
  3. import pytest
  4. from celery import chain, chord, group
  5. from celery.exceptions import TimeoutError
  6. from celery.result import AsyncResult, GroupResult, ResultSet
  7. from .conftest import flaky, get_active_redis_channels, get_redis_connection
  8. from .tasks import (add, add_chord_to_chord, add_replaced, add_to_all,
  9. add_to_all_to_chord, collect_ids, delayed_sum,
  10. delayed_sum_with_soft_guard, identity, ids, print_unicode,
  11. redis_echo, second_order_replace1, tsum)
  12. TIMEOUT = 120
  13. class test_chain:
  14. @flaky
  15. def test_simple_chain(self, manager):
  16. c = add.s(4, 4) | add.s(8) | add.s(16)
  17. assert c().get(timeout=TIMEOUT) == 32
  18. @flaky
  19. def test_complex_chain(self, manager):
  20. c = (
  21. add.s(2, 2) | (
  22. add.s(4) | add_replaced.s(8) | add.s(16) | add.s(32)
  23. ) |
  24. group(add.s(i) for i in range(4))
  25. )
  26. res = c()
  27. assert res.get(timeout=TIMEOUT) == [64, 65, 66, 67]
  28. @flaky
  29. def test_group_results_in_chain(self, manager):
  30. # This adds in an explicit test for the special case added in commit
  31. # 1e3fcaa969de6ad32b52a3ed8e74281e5e5360e6
  32. c = (
  33. group(
  34. add.s(1, 2) | group(
  35. add.s(1), add.s(2)
  36. )
  37. )
  38. )
  39. res = c()
  40. assert res.get(timeout=TIMEOUT) == [4, 5]
  41. @flaky
  42. def test_chain_inside_group_receives_arguments(self, manager):
  43. c = (
  44. add.s(5, 6) |
  45. group((add.s(1) | add.s(2), add.s(3)))
  46. )
  47. res = c()
  48. assert res.get(timeout=TIMEOUT) == [14, 14]
  49. @flaky
  50. def test_eager_chain_inside_task(self, manager):
  51. from .tasks import chain_add
  52. prev = chain_add.app.conf.task_always_eager
  53. chain_add.app.conf.task_always_eager = True
  54. chain_add.apply_async(args=(4, 8), throw=True).get()
  55. chain_add.app.conf.task_always_eager = prev
  56. @flaky
  57. def test_group_chord_group_chain(self, manager):
  58. from celery.five import bytes_if_py2
  59. if not manager.app.conf.result_backend.startswith('redis'):
  60. raise pytest.skip('Requires redis result backend.')
  61. redis_connection = get_redis_connection()
  62. redis_connection.delete('redis-echo')
  63. before = group(redis_echo.si('before {}'.format(i)) for i in range(3))
  64. connect = redis_echo.si('connect')
  65. after = group(redis_echo.si('after {}'.format(i)) for i in range(2))
  66. result = (before | connect | after).delay()
  67. result.get(timeout=TIMEOUT)
  68. redis_messages = list(map(
  69. bytes_if_py2,
  70. redis_connection.lrange('redis-echo', 0, -1)
  71. ))
  72. before_items = \
  73. set(map(bytes_if_py2, (b'before 0', b'before 1', b'before 2')))
  74. after_items = set(map(bytes_if_py2, (b'after 0', b'after 1')))
  75. assert set(redis_messages[:3]) == before_items
  76. assert redis_messages[3] == b'connect'
  77. assert set(redis_messages[4:]) == after_items
  78. redis_connection.delete('redis-echo')
  79. @flaky
  80. def test_second_order_replace(self, manager):
  81. from celery.five import bytes_if_py2
  82. if not manager.app.conf.result_backend.startswith('redis'):
  83. raise pytest.skip('Requires redis result backend.')
  84. redis_connection = get_redis_connection()
  85. redis_connection.delete('redis-echo')
  86. result = second_order_replace1.delay()
  87. result.get(timeout=TIMEOUT)
  88. redis_messages = list(map(
  89. bytes_if_py2,
  90. redis_connection.lrange('redis-echo', 0, -1)
  91. ))
  92. expected_messages = [b'In A', b'In B', b'In/Out C', b'Out B', b'Out A']
  93. assert redis_messages == expected_messages
  94. @flaky
  95. def test_parent_ids(self, manager, num=10):
  96. assert manager.inspect().ping()
  97. c = chain(ids.si(i=i) for i in range(num))
  98. c.freeze()
  99. res = c()
  100. try:
  101. res.get(timeout=TIMEOUT)
  102. except TimeoutError:
  103. print(manager.inspect.active())
  104. print(manager.inspect.reserved())
  105. print(manager.inspect.stats())
  106. raise
  107. self.assert_ids(res, num - 1)
  108. def assert_ids(self, res, size):
  109. i, root = size, res
  110. while root.parent:
  111. root = root.parent
  112. node = res
  113. while node:
  114. root_id, parent_id, value = node.get(timeout=30)
  115. assert value == i
  116. if node.parent:
  117. assert parent_id == node.parent.id
  118. assert root_id == root.id
  119. node = node.parent
  120. i -= 1
  121. def test_chord_soft_timeout_recuperation(self, manager):
  122. """Test that if soft timeout happens in task but is managed by task,
  123. chord still get results normally
  124. """
  125. if not manager.app.conf.result_backend.startswith('redis'):
  126. raise pytest.skip('Requires redis result backend.')
  127. c = chord([
  128. # return 3
  129. add.s(1, 2),
  130. # return 0 after managing soft timeout
  131. delayed_sum_with_soft_guard.s(
  132. [100], pause_time=2
  133. ).set(
  134. soft_time_limit=1
  135. ),
  136. ])
  137. result = c(delayed_sum.s(pause_time=0)).get()
  138. assert result == 3
  139. def test_chain_error_handler_with_eta(self, manager):
  140. try:
  141. manager.app.backend.ensure_chords_allowed()
  142. except NotImplementedError as e:
  143. raise pytest.skip(e.args[0])
  144. eta = datetime.utcnow() + timedelta(seconds=10)
  145. c = chain(
  146. group(
  147. add.s(1, 2),
  148. add.s(3, 4),
  149. ),
  150. tsum.s()
  151. ).on_error(print_unicode.s()).apply_async(eta=eta)
  152. result = c.get()
  153. assert result == 10
  154. class test_result_set:
  155. @flaky
  156. def test_result_set(self, manager):
  157. assert manager.inspect().ping()
  158. rs = ResultSet([add.delay(1, 1), add.delay(2, 2)])
  159. assert rs.get(timeout=TIMEOUT) == [2, 4]
  160. class test_group:
  161. @flaky
  162. def test_empty_group_result(self, manager):
  163. if not manager.app.conf.result_backend.startswith('redis'):
  164. raise pytest.skip('Requires redis result backend.')
  165. task = group([])
  166. result = task.apply_async()
  167. GroupResult.save(result)
  168. task = GroupResult.restore(result.id)
  169. assert task.results == []
  170. @flaky
  171. def test_parent_ids(self, manager):
  172. assert manager.inspect().ping()
  173. g = (
  174. ids.si(i=1) |
  175. ids.si(i=2) |
  176. group(ids.si(i=i) for i in range(2, 50))
  177. )
  178. res = g()
  179. expected_root_id = res.parent.parent.id
  180. expected_parent_id = res.parent.id
  181. values = res.get(timeout=TIMEOUT)
  182. for i, r in enumerate(values):
  183. root_id, parent_id, value = r
  184. assert root_id == expected_root_id
  185. assert parent_id == expected_parent_id
  186. assert value == i + 2
  187. @flaky
  188. def test_nested_group(self, manager):
  189. assert manager.inspect().ping()
  190. c = group(
  191. add.si(1, 10),
  192. group(
  193. add.si(1, 100),
  194. group(
  195. add.si(1, 1000),
  196. add.si(1, 2000),
  197. ),
  198. ),
  199. )
  200. res = c()
  201. assert res.get(timeout=TIMEOUT) == [11, 101, 1001, 2001]
  202. def assert_ids(r, expected_value, expected_root_id, expected_parent_id):
  203. root_id, parent_id, value = r.get(timeout=TIMEOUT)
  204. assert expected_value == value
  205. assert root_id == expected_root_id
  206. assert parent_id == expected_parent_id
  207. class test_chord:
  208. @flaky
  209. def test_redis_subscribed_channels_leak(self, manager):
  210. if not manager.app.conf.result_backend.startswith('redis'):
  211. raise pytest.skip('Requires redis result backend.')
  212. manager.app.backend.result_consumer.on_after_fork()
  213. initial_channels = get_active_redis_channels()
  214. initial_channels_count = len(initial_channels)
  215. total_chords = 10
  216. async_results = [
  217. chord([add.s(5, 6), add.s(6, 7)])(delayed_sum.s())
  218. for _ in range(total_chords)
  219. ]
  220. manager.assert_result_tasks_in_progress_or_completed(async_results)
  221. channels_before = get_active_redis_channels()
  222. channels_before_count = len(channels_before)
  223. assert set(channels_before) != set(initial_channels)
  224. assert channels_before_count > initial_channels_count
  225. # The total number of active Redis channels at this point
  226. # is the number of chord header tasks multiplied by the
  227. # total chord tasks, plus the initial channels
  228. # (existing from previous tests).
  229. chord_header_task_count = 2
  230. assert channels_before_count <= \
  231. chord_header_task_count * total_chords + initial_channels_count
  232. result_values = [
  233. result.get(timeout=TIMEOUT)
  234. for result in async_results
  235. ]
  236. assert result_values == [24] * total_chords
  237. channels_after = get_active_redis_channels()
  238. channels_after_count = len(channels_after)
  239. assert channels_after_count == initial_channels_count
  240. assert set(channels_after) == set(initial_channels)
  241. @flaky
  242. def test_replaced_nested_chord(self, manager):
  243. try:
  244. manager.app.backend.ensure_chords_allowed()
  245. except NotImplementedError as e:
  246. raise pytest.skip(e.args[0])
  247. c1 = chord([
  248. chord(
  249. [add.s(1, 2), add_replaced.s(3, 4)],
  250. add_to_all.s(5),
  251. ) | tsum.s(),
  252. chord(
  253. [add_replaced.s(6, 7), add.s(0, 0)],
  254. add_to_all.s(8),
  255. ) | tsum.s(),
  256. ], add_to_all.s(9))
  257. res1 = c1()
  258. assert res1.get(timeout=TIMEOUT) == [29, 38]
  259. @flaky
  260. def test_add_to_chord(self, manager):
  261. if not manager.app.conf.result_backend.startswith('redis'):
  262. raise pytest.skip('Requires redis result backend.')
  263. c = group([add_to_all_to_chord.s([1, 2, 3], 4)]) | identity.s()
  264. res = c()
  265. assert res.get() == [0, 5, 6, 7]
  266. @flaky
  267. def test_add_chord_to_chord(self, manager):
  268. if not manager.app.conf.result_backend.startswith('redis'):
  269. raise pytest.skip('Requires redis result backend.')
  270. c = group([add_chord_to_chord.s([1, 2, 3], 4)]) | identity.s()
  271. res = c()
  272. assert res.get() == [0, 5 + 6 + 7]
  273. @flaky
  274. def test_group_chain(self, manager):
  275. if not manager.app.conf.result_backend.startswith('redis'):
  276. raise pytest.skip('Requires redis result backend.')
  277. c = (
  278. add.s(2, 2) |
  279. group(add.s(i) for i in range(4)) |
  280. add_to_all.s(8)
  281. )
  282. res = c()
  283. assert res.get(timeout=TIMEOUT) == [12, 13, 14, 15]
  284. @flaky
  285. def test_nested_group_chain(self, manager):
  286. try:
  287. manager.app.backend.ensure_chords_allowed()
  288. except NotImplementedError as e:
  289. raise pytest.skip(e.args[0])
  290. if not manager.app.backend.supports_native_join:
  291. raise pytest.skip('Requires native join support.')
  292. c = chain(
  293. add.si(1, 0),
  294. group(
  295. add.si(1, 100),
  296. chain(
  297. add.si(1, 200),
  298. group(
  299. add.si(1, 1000),
  300. add.si(1, 2000),
  301. ),
  302. ),
  303. ),
  304. add.si(1, 10),
  305. )
  306. res = c()
  307. assert res.get(timeout=TIMEOUT) == 11
  308. @flaky
  309. def test_single_task_header(self, manager):
  310. try:
  311. manager.app.backend.ensure_chords_allowed()
  312. except NotImplementedError as e:
  313. raise pytest.skip(e.args[0])
  314. c1 = chord([add.s(2, 5)], body=add_to_all.s(9))
  315. res1 = c1()
  316. assert res1.get(timeout=TIMEOUT) == [16]
  317. c2 = group([add.s(2, 5)]) | add_to_all.s(9)
  318. res2 = c2()
  319. assert res2.get(timeout=TIMEOUT) == [16]
  320. def test_empty_header_chord(self, manager):
  321. try:
  322. manager.app.backend.ensure_chords_allowed()
  323. except NotImplementedError as e:
  324. raise pytest.skip(e.args[0])
  325. c1 = chord([], body=add_to_all.s(9))
  326. res1 = c1()
  327. assert res1.get(timeout=TIMEOUT) == []
  328. c2 = group([]) | add_to_all.s(9)
  329. res2 = c2()
  330. assert res2.get(timeout=TIMEOUT) == []
  331. @flaky
  332. def test_nested_chord(self, manager):
  333. try:
  334. manager.app.backend.ensure_chords_allowed()
  335. except NotImplementedError as e:
  336. raise pytest.skip(e.args[0])
  337. c1 = chord([
  338. chord([add.s(1, 2), add.s(3, 4)], add.s([5])),
  339. chord([add.s(6, 7)], add.s([10]))
  340. ], add_to_all.s(['A']))
  341. res1 = c1()
  342. assert res1.get(timeout=TIMEOUT) == [[3, 7, 5, 'A'], [13, 10, 'A']]
  343. c2 = group([
  344. group([add.s(1, 2), add.s(3, 4)]) | add.s([5]),
  345. group([add.s(6, 7)]) | add.s([10]),
  346. ]) | add_to_all.s(['A'])
  347. res2 = c2()
  348. assert res2.get(timeout=TIMEOUT) == [[3, 7, 5, 'A'], [13, 10, 'A']]
  349. c = group([
  350. group([
  351. group([
  352. group([
  353. add.s(1, 2)
  354. ]) | add.s([3])
  355. ]) | add.s([4])
  356. ]) | add.s([5])
  357. ]) | add.s([6])
  358. res = c()
  359. assert [[[[3, 3], 4], 5], 6] == res.get(timeout=TIMEOUT)
  360. @flaky
  361. def test_parent_ids(self, manager):
  362. if not manager.app.conf.result_backend.startswith('redis'):
  363. raise pytest.skip('Requires redis result backend.')
  364. root = ids.si(i=1)
  365. expected_root_id = root.freeze().id
  366. g = chain(
  367. root, ids.si(i=2),
  368. chord(
  369. group(ids.si(i=i) for i in range(3, 50)),
  370. chain(collect_ids.s(i=50) | ids.si(i=51)),
  371. ),
  372. )
  373. self.assert_parentids_chord(g(), expected_root_id)
  374. @flaky
  375. def test_parent_ids__OR(self, manager):
  376. if not manager.app.conf.result_backend.startswith('redis'):
  377. raise pytest.skip('Requires redis result backend.')
  378. root = ids.si(i=1)
  379. expected_root_id = root.freeze().id
  380. g = (
  381. root |
  382. ids.si(i=2) |
  383. group(ids.si(i=i) for i in range(3, 50)) |
  384. collect_ids.s(i=50) |
  385. ids.si(i=51)
  386. )
  387. self.assert_parentids_chord(g(), expected_root_id)
  388. def assert_parentids_chord(self, res, expected_root_id):
  389. assert isinstance(res, AsyncResult)
  390. assert isinstance(res.parent, AsyncResult)
  391. assert isinstance(res.parent.parent, GroupResult)
  392. assert isinstance(res.parent.parent.parent, AsyncResult)
  393. assert isinstance(res.parent.parent.parent.parent, AsyncResult)
  394. # first we check the last task
  395. assert_ids(res, 51, expected_root_id, res.parent.id)
  396. # then the chord callback
  397. prev, (root_id, parent_id, value) = res.parent.get(timeout=30)
  398. assert value == 50
  399. assert root_id == expected_root_id
  400. # started by one of the chord header tasks.
  401. assert parent_id in res.parent.parent.results
  402. # check what the chord callback recorded
  403. for i, p in enumerate(prev):
  404. root_id, parent_id, value = p
  405. assert root_id == expected_root_id
  406. assert parent_id == res.parent.parent.parent.id
  407. # ids(i=2)
  408. root_id, parent_id, value = res.parent.parent.parent.get(timeout=30)
  409. assert value == 2
  410. assert parent_id == res.parent.parent.parent.parent.id
  411. assert root_id == expected_root_id
  412. # ids(i=1)
  413. root_id, parent_id, value = res.parent.parent.parent.parent.get(
  414. timeout=30)
  415. assert value == 1
  416. assert root_id == expected_root_id
  417. assert parent_id is None