test_celery.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. from __future__ import absolute_import, unicode_literals
  2. import sys
  3. from datetime import datetime
  4. from kombu.utils.json import dumps
  5. from celery import __main__
  6. from celery.bin.base import Error
  7. from celery.bin import celery as mod
  8. from celery.bin.celery import (
  9. Command,
  10. list_,
  11. call,
  12. purge,
  13. result,
  14. inspect,
  15. control,
  16. status,
  17. migrate,
  18. help,
  19. report,
  20. CeleryCommand,
  21. determine_exit_status,
  22. multi,
  23. main as mainfun,
  24. _RemoteControl,
  25. command,
  26. )
  27. from celery.five import WhateverIO
  28. from celery.platforms import EX_FAILURE, EX_USAGE, EX_OK
  29. from celery.tests.case import AppCase, Mock, patch
  30. class test__main__(AppCase):
  31. def test_main(self):
  32. with patch('celery.__main__.maybe_patch_concurrency') as mpc:
  33. with patch('celery.bin.celery.main') as main:
  34. __main__.main()
  35. mpc.assert_called_with()
  36. main.assert_called_with()
  37. def test_main__multi(self):
  38. with patch('celery.__main__.maybe_patch_concurrency') as mpc:
  39. with patch('celery.bin.celery.main') as main:
  40. prev, sys.argv = sys.argv, ['foo', 'multi']
  41. try:
  42. __main__.main()
  43. mpc.assert_not_called()
  44. main.assert_called_with()
  45. finally:
  46. sys.argv = prev
  47. class test_Command(AppCase):
  48. def test_Error_repr(self):
  49. x = Error('something happened')
  50. self.assertIsNotNone(x.status)
  51. self.assertTrue(x.reason)
  52. self.assertTrue(str(x))
  53. def setup(self):
  54. self.out = WhateverIO()
  55. self.err = WhateverIO()
  56. self.cmd = Command(self.app, stdout=self.out, stderr=self.err)
  57. def test_error(self):
  58. self.cmd.out = Mock()
  59. self.cmd.error('FOO')
  60. self.cmd.out.assert_called()
  61. def test_out(self):
  62. f = Mock()
  63. self.cmd.out('foo', f)
  64. def test_call(self):
  65. def ok_run():
  66. pass
  67. self.cmd.run = ok_run
  68. self.assertEqual(self.cmd(), EX_OK)
  69. def error_run():
  70. raise Error('error', EX_FAILURE)
  71. self.cmd.run = error_run
  72. self.assertEqual(self.cmd(), EX_FAILURE)
  73. def test_run_from_argv(self):
  74. with self.assertRaises(NotImplementedError):
  75. self.cmd.run_from_argv('prog', ['foo', 'bar'])
  76. def test_pretty_list(self):
  77. self.assertEqual(self.cmd.pretty([])[1], '- empty -')
  78. self.assertIn('bar', self.cmd.pretty(['foo', 'bar'])[1])
  79. def test_pretty_dict(self):
  80. self.assertIn(
  81. 'OK',
  82. str(self.cmd.pretty({'ok': 'the quick brown fox'})[0]),
  83. )
  84. self.assertIn(
  85. 'ERROR',
  86. str(self.cmd.pretty({'error': 'the quick brown fox'})[0]),
  87. )
  88. def test_pretty(self):
  89. self.assertIn('OK', str(self.cmd.pretty('the quick brown')))
  90. self.assertIn('OK', str(self.cmd.pretty(object())))
  91. self.assertIn('OK', str(self.cmd.pretty({'foo': 'bar'})))
  92. class test_list(AppCase):
  93. def test_list_bindings_no_support(self):
  94. l = list_(app=self.app, stderr=WhateverIO())
  95. management = Mock()
  96. management.get_bindings.side_effect = NotImplementedError()
  97. with self.assertRaises(Error):
  98. l.list_bindings(management)
  99. def test_run(self):
  100. l = list_(app=self.app, stderr=WhateverIO())
  101. l.run('bindings')
  102. with self.assertRaises(Error):
  103. l.run(None)
  104. with self.assertRaises(Error):
  105. l.run('foo')
  106. class test_call(AppCase):
  107. def setup(self):
  108. @self.app.task(shared=False)
  109. def add(x, y):
  110. return x + y
  111. self.add = add
  112. @patch('celery.app.base.Celery.send_task')
  113. def test_run(self, send_task):
  114. a = call(app=self.app, stderr=WhateverIO(), stdout=WhateverIO())
  115. a.run(self.add.name)
  116. send_task.assert_called()
  117. a.run(self.add.name,
  118. args=dumps([4, 4]),
  119. kwargs=dumps({'x': 2, 'y': 2}))
  120. self.assertEqual(send_task.call_args[1]['args'], [4, 4])
  121. self.assertEqual(send_task.call_args[1]['kwargs'], {'x': 2, 'y': 2})
  122. a.run(self.add.name, expires=10, countdown=10)
  123. self.assertEqual(send_task.call_args[1]['expires'], 10)
  124. self.assertEqual(send_task.call_args[1]['countdown'], 10)
  125. now = datetime.now()
  126. iso = now.isoformat()
  127. a.run(self.add.name, expires=iso)
  128. self.assertEqual(send_task.call_args[1]['expires'], now)
  129. with self.assertRaises(ValueError):
  130. a.run(self.add.name, expires='foobaribazibar')
  131. class test_purge(AppCase):
  132. def test_run(self):
  133. out = WhateverIO()
  134. a = purge(app=self.app, stdout=out)
  135. a._purge = Mock(name='_purge')
  136. a._purge.return_value = 0
  137. a.run(force=True)
  138. self.assertIn('No messages purged', out.getvalue())
  139. a._purge.return_value = 100
  140. a.run(force=True)
  141. self.assertIn('100 messages', out.getvalue())
  142. a.out = Mock(name='out')
  143. a.ask = Mock(name='ask')
  144. a.run(force=False)
  145. a.ask.assert_called_with(a.warn_prompt, ('yes', 'no'), 'no')
  146. a.ask.return_value = 'yes'
  147. a.run(force=False)
  148. class test_result(AppCase):
  149. def setup(self):
  150. @self.app.task(shared=False)
  151. def add(x, y):
  152. return x + y
  153. self.add = add
  154. def test_run(self):
  155. with patch('celery.result.AsyncResult.get') as get:
  156. out = WhateverIO()
  157. r = result(app=self.app, stdout=out)
  158. get.return_value = 'Jerry'
  159. r.run('id')
  160. self.assertIn('Jerry', out.getvalue())
  161. get.return_value = 'Elaine'
  162. r.run('id', task=self.add.name)
  163. self.assertIn('Elaine', out.getvalue())
  164. with patch('celery.result.AsyncResult.traceback') as tb:
  165. r.run('id', task=self.add.name, traceback=True)
  166. self.assertIn(str(tb), out.getvalue())
  167. class test_status(AppCase):
  168. @patch('celery.bin.celery.inspect')
  169. def test_run(self, inspect_):
  170. out, err = WhateverIO(), WhateverIO()
  171. ins = inspect_.return_value = Mock()
  172. ins.run.return_value = []
  173. s = status(self.app, stdout=out, stderr=err)
  174. with self.assertRaises(Error):
  175. s.run()
  176. ins.run.return_value = ['a', 'b', 'c']
  177. s.run()
  178. self.assertIn('3 nodes online', out.getvalue())
  179. s.run(quiet=True)
  180. class test_migrate(AppCase):
  181. @patch('celery.contrib.migrate.migrate_tasks')
  182. def test_run(self, migrate_tasks):
  183. out = WhateverIO()
  184. m = migrate(app=self.app, stdout=out, stderr=WhateverIO())
  185. with self.assertRaises(TypeError):
  186. m.run()
  187. migrate_tasks.assert_not_called()
  188. m.run('memory://foo', 'memory://bar')
  189. migrate_tasks.assert_called()
  190. state = Mock()
  191. state.count = 10
  192. state.strtotal = 30
  193. m.on_migrate_task(state, {'task': 'tasks.add', 'id': 'ID'}, None)
  194. self.assertIn('10/30', out.getvalue())
  195. class test_report(AppCase):
  196. def test_run(self):
  197. out = WhateverIO()
  198. r = report(app=self.app, stdout=out)
  199. self.assertEqual(r.run(), EX_OK)
  200. self.assertTrue(out.getvalue())
  201. class test_help(AppCase):
  202. def test_run(self):
  203. out = WhateverIO()
  204. h = help(app=self.app, stdout=out)
  205. h.parser = Mock()
  206. self.assertEqual(h.run(), EX_USAGE)
  207. self.assertTrue(out.getvalue())
  208. self.assertTrue(h.usage('help'))
  209. h.parser.print_help.assert_called_with()
  210. class test_CeleryCommand(AppCase):
  211. def test_execute_from_commandline(self):
  212. x = CeleryCommand(app=self.app)
  213. x.handle_argv = Mock()
  214. x.handle_argv.return_value = 1
  215. with self.assertRaises(SystemExit):
  216. x.execute_from_commandline()
  217. x.handle_argv.return_value = True
  218. with self.assertRaises(SystemExit):
  219. x.execute_from_commandline()
  220. x.handle_argv.side_effect = KeyboardInterrupt()
  221. with self.assertRaises(SystemExit):
  222. x.execute_from_commandline()
  223. x.respects_app_option = True
  224. with self.assertRaises(SystemExit):
  225. x.execute_from_commandline(['celery', 'multi'])
  226. self.assertFalse(x.respects_app_option)
  227. x.respects_app_option = True
  228. with self.assertRaises(SystemExit):
  229. x.execute_from_commandline(['manage.py', 'celery', 'multi'])
  230. self.assertFalse(x.respects_app_option)
  231. def test_with_pool_option(self):
  232. x = CeleryCommand(app=self.app)
  233. self.assertIsNone(x.with_pool_option(['celery', 'events']))
  234. self.assertTrue(x.with_pool_option(['celery', 'worker']))
  235. self.assertTrue(x.with_pool_option(['manage.py', 'celery', 'worker']))
  236. def test_load_extensions_no_commands(self):
  237. with patch('celery.bin.celery.Extensions') as Ext:
  238. ext = Ext.return_value = Mock(name='Extension')
  239. ext.load.return_value = None
  240. x = CeleryCommand(app=self.app)
  241. x.load_extension_commands()
  242. def test_load_extensions_commands(self):
  243. with patch('celery.bin.celery.Extensions') as Ext:
  244. prev, mod.command_classes = list(mod.command_classes), Mock()
  245. try:
  246. ext = Ext.return_value = Mock(name='Extension')
  247. ext.load.return_value = ['foo', 'bar']
  248. x = CeleryCommand(app=self.app)
  249. x.load_extension_commands()
  250. mod.command_classes.append.assert_called_with(
  251. ('Extensions', ['foo', 'bar'], 'magenta'),
  252. )
  253. finally:
  254. mod.command_classes = prev
  255. def test_determine_exit_status(self):
  256. self.assertEqual(determine_exit_status('true'), EX_OK)
  257. self.assertEqual(determine_exit_status(''), EX_FAILURE)
  258. def test_relocate_args_from_start(self):
  259. x = CeleryCommand(app=self.app)
  260. self.assertEqual(x._relocate_args_from_start(None), [])
  261. self.assertEqual(
  262. x._relocate_args_from_start(
  263. ['-l', 'debug', 'worker', '-c', '3', '--foo'],
  264. ),
  265. ['worker', '-c', '3', '--foo', '-l', 'debug'],
  266. )
  267. self.assertEqual(
  268. x._relocate_args_from_start(
  269. ['--pool=gevent', '-l', 'debug', 'worker', '--foo', '-c', '3'],
  270. ),
  271. ['worker', '--foo', '-c', '3', '--pool=gevent', '-l', 'debug'],
  272. )
  273. self.assertEqual(
  274. x._relocate_args_from_start(['foo', '--foo=1']),
  275. ['foo', '--foo=1'],
  276. )
  277. def test_register_command(self):
  278. prev, CeleryCommand.commands = dict(CeleryCommand.commands), {}
  279. try:
  280. fun = Mock(name='fun')
  281. CeleryCommand.register_command(fun, name='foo')
  282. self.assertIs(CeleryCommand.commands['foo'], fun)
  283. finally:
  284. CeleryCommand.commands = prev
  285. def test_handle_argv(self):
  286. x = CeleryCommand(app=self.app)
  287. x.execute = Mock()
  288. x.handle_argv('celery', [])
  289. x.execute.assert_called_with('help', ['help'])
  290. x.handle_argv('celery', ['start', 'foo'])
  291. x.execute.assert_called_with('start', ['start', 'foo'])
  292. def test_execute(self):
  293. x = CeleryCommand(app=self.app)
  294. Help = x.commands['help'] = Mock()
  295. help = Help.return_value = Mock()
  296. x.execute('fooox', ['a'])
  297. help.run_from_argv.assert_called_with(x.prog_name, [], command='help')
  298. help.reset()
  299. x.execute('help', ['help'])
  300. help.run_from_argv.assert_called_with(x.prog_name, [], command='help')
  301. Dummy = x.commands['dummy'] = Mock()
  302. dummy = Dummy.return_value = Mock()
  303. exc = dummy.run_from_argv.side_effect = Error(
  304. 'foo', status='EX_FAILURE',
  305. )
  306. x.on_error = Mock(name='on_error')
  307. help.reset()
  308. x.execute('dummy', ['dummy'])
  309. x.on_error.assert_called_with(exc)
  310. dummy.run_from_argv.assert_called_with(
  311. x.prog_name, [], command='dummy',
  312. )
  313. help.run_from_argv.assert_called_with(
  314. x.prog_name, [], command='help',
  315. )
  316. exc = dummy.run_from_argv.side_effect = x.UsageError('foo')
  317. x.on_usage_error = Mock()
  318. x.execute('dummy', ['dummy'])
  319. x.on_usage_error.assert_called_with(exc)
  320. def test_on_usage_error(self):
  321. x = CeleryCommand(app=self.app)
  322. x.error = Mock()
  323. x.on_usage_error(x.UsageError('foo'), command=None)
  324. x.error.assert_called()
  325. x.on_usage_error(x.UsageError('foo'), command='dummy')
  326. def test_prepare_prog_name(self):
  327. x = CeleryCommand(app=self.app)
  328. main = Mock(name='__main__')
  329. main.__file__ = '/opt/foo.py'
  330. with patch.dict(sys.modules, __main__=main):
  331. self.assertEqual(x.prepare_prog_name('__main__.py'), '/opt/foo.py')
  332. self.assertEqual(x.prepare_prog_name('celery'), 'celery')
  333. class test_RemoteControl(AppCase):
  334. def test_call_interface(self):
  335. with self.assertRaises(NotImplementedError):
  336. _RemoteControl(app=self.app).call()
  337. class test_inspect(AppCase):
  338. def test_usage(self):
  339. self.assertTrue(inspect(app=self.app).usage('foo'))
  340. def test_command_info(self):
  341. i = inspect(app=self.app)
  342. self.assertTrue(i.get_command_info(
  343. 'ping', help=True, color=i.colored.red,
  344. ))
  345. def test_list_commands_color(self):
  346. i = inspect(app=self.app)
  347. self.assertTrue(i.list_commands(
  348. help=True, color=i.colored.red,
  349. ))
  350. self.assertTrue(i.list_commands(
  351. help=False, color=None,
  352. ))
  353. def test_epilog(self):
  354. self.assertTrue(inspect(app=self.app).epilog)
  355. def test_do_call_method_sql_transport_type(self):
  356. self.app.connection = Mock()
  357. conn = self.app.connection.return_value = Mock(name='Connection')
  358. conn.transport.driver_type = 'sql'
  359. i = inspect(app=self.app)
  360. with self.assertRaises(i.Error):
  361. i.do_call_method(['ping'])
  362. def test_say_directions(self):
  363. i = inspect(self.app)
  364. i.out = Mock()
  365. i.quiet = True
  366. i.say_chat('<-', 'hello out')
  367. i.out.assert_not_called()
  368. i.say_chat('->', 'hello in')
  369. i.out.assert_called()
  370. i.quiet = False
  371. i.out.reset_mock()
  372. i.say_chat('<-', 'hello out', 'body')
  373. i.out.assert_called()
  374. @patch('celery.app.control.Control.inspect')
  375. def test_run(self, real):
  376. out = WhateverIO()
  377. i = inspect(app=self.app, stdout=out)
  378. with self.assertRaises(Error):
  379. i.run()
  380. with self.assertRaises(Error):
  381. i.run('help')
  382. with self.assertRaises(Error):
  383. i.run('xyzzybaz')
  384. i.run('ping')
  385. real.assert_called()
  386. i.run('ping', destination='foo,bar')
  387. self.assertEqual(real.call_args[1]['destination'], ['foo', 'bar'])
  388. self.assertEqual(real.call_args[1]['timeout'], 0.2)
  389. callback = real.call_args[1]['callback']
  390. callback({'foo': {'ok': 'pong'}})
  391. self.assertIn('OK', out.getvalue())
  392. with patch('celery.bin.celery.json.dumps') as dumps:
  393. i.run('ping', json=True)
  394. dumps.assert_called()
  395. instance = real.return_value = Mock()
  396. instance.ping.return_value = None
  397. with self.assertRaises(Error):
  398. i.run('ping')
  399. out.seek(0)
  400. out.truncate()
  401. i.quiet = True
  402. i.say_chat('<-', 'hello')
  403. self.assertFalse(out.getvalue())
  404. def test_objgraph(self):
  405. i = inspect(app=self.app)
  406. i.call = Mock(name='call')
  407. i.objgraph('Message', foo=1)
  408. i.call.assert_called_with('objgraph', 'Message', foo=1)
  409. def test_conf(self):
  410. i = inspect(app=self.app)
  411. i.call = Mock(name='call')
  412. i.conf(with_defaults=True, foo=1)
  413. i.call.assert_called_with('conf', True, foo=1)
  414. class test_control(AppCase):
  415. def control(self, patch_call, *args, **kwargs):
  416. kwargs.setdefault('app', Mock(name='app'))
  417. c = control(*args, **kwargs)
  418. if patch_call:
  419. c.call = Mock(name='control.call')
  420. return c
  421. def test_call(self):
  422. i = self.control(False)
  423. i.call('foo', 1, kw=2)
  424. i.app.control.foo.assert_called_with(1, kw=2, reply=True)
  425. def test_pool_grow(self):
  426. i = self.control(True)
  427. i.pool_grow('pool_grow', n=2)
  428. i.call.assert_called_with('pool_grow', 2)
  429. def test_pool_shrink(self):
  430. i = self.control(True)
  431. i.pool_shrink('pool_shrink', n=2)
  432. i.call.assert_called_with('pool_shrink', 2)
  433. def test_autoscale(self):
  434. i = self.control(True)
  435. i.autoscale('autoscale', max=3, min=2)
  436. i.call.assert_called_with('autoscale', 3, 2)
  437. def test_rate_limit(self):
  438. i = self.control(True)
  439. i.rate_limit('rate_limit', 'proj.add', '1/s')
  440. i.call.assert_called_with('rate_limit', 'proj.add', '1/s')
  441. def test_time_limit(self):
  442. i = self.control(True)
  443. i.time_limit('time_limit', 'proj.add', 10, 30)
  444. i.call.assert_called_with('time_limit', 'proj.add', 10, 30)
  445. def test_add_consumer(self):
  446. i = self.control(True)
  447. i.add_consumer(
  448. 'add_consumer', 'queue', 'exchange', 'topic', 'rkey',
  449. durable=True,
  450. )
  451. i.call.assert_called_with(
  452. 'add_consumer', 'queue', 'exchange', 'topic', 'rkey',
  453. durable=True,
  454. )
  455. def test_cancel_consumer(self):
  456. i = self.control(True)
  457. i.cancel_consumer('cancel_consumer', 'queue')
  458. i.call.assert_called_with('cancel_consumer', 'queue')
  459. class test_multi(AppCase):
  460. def test_get_options(self):
  461. self.assertIsNone(multi(app=self.app).get_options())
  462. def test_run_from_argv(self):
  463. with patch('celery.bin.multi.MultiTool') as MultiTool:
  464. m = MultiTool.return_value = Mock()
  465. multi(self.app).run_from_argv('celery', ['arg'], command='multi')
  466. m.execute_from_commandline.assert_called_with(
  467. ['multi', 'arg'], 'celery',
  468. )
  469. class test_main(AppCase):
  470. @patch('celery.bin.celery.CeleryCommand')
  471. def test_main(self, Command):
  472. cmd = Command.return_value = Mock()
  473. mainfun()
  474. cmd.execute_from_commandline.assert_called_with(None)
  475. @patch('celery.bin.celery.CeleryCommand')
  476. def test_main_KeyboardInterrupt(self, Command):
  477. cmd = Command.return_value = Mock()
  478. cmd.execute_from_commandline.side_effect = KeyboardInterrupt()
  479. mainfun()
  480. cmd.execute_from_commandline.assert_called_with(None)
  481. class test_compat(AppCase):
  482. def test_compat_command_decorator(self):
  483. with patch('celery.bin.celery.CeleryCommand') as CC:
  484. self.assertEqual(command(), CC.register_command)
  485. fun = Mock(name='fun')
  486. command(fun)
  487. CC.register_command.assert_called_with(fun)