test_celery.py 16 KB

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