test_base.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. from __future__ import absolute_import, unicode_literals
  2. import os
  3. import pytest
  4. from case import Mock, mock, patch
  5. from celery.five import bytes_if_py2
  6. from celery.bin.base import (
  7. Command,
  8. Option,
  9. Extensions,
  10. )
  11. class MyApp(object):
  12. user_options = {'preload': None}
  13. APP = MyApp() # <-- Used by test_with_custom_app
  14. class MockCommand(Command):
  15. mock_args = ('arg1', 'arg2', 'arg3')
  16. def parse_options(self, prog_name, arguments, command=None):
  17. options = dict(foo='bar', prog_name=prog_name)
  18. return options, self.mock_args
  19. def run(self, *args, **kwargs):
  20. return args, kwargs
  21. class test_Extensions:
  22. def test_load(self):
  23. with patch('pkg_resources.iter_entry_points') as iterep:
  24. with patch('celery.utils.imports.symbol_by_name') as symbyname:
  25. ep = Mock()
  26. ep.name = 'ep'
  27. ep.module_name = 'foo'
  28. ep.attrs = ['bar', 'baz']
  29. iterep.return_value = [ep]
  30. cls = symbyname.return_value = Mock()
  31. register = Mock()
  32. e = Extensions('unit', register)
  33. e.load()
  34. symbyname.assert_called_with('foo:bar')
  35. register.assert_called_with(cls, name='ep')
  36. with patch('celery.utils.imports.symbol_by_name') as symbyname:
  37. symbyname.side_effect = SyntaxError()
  38. with patch('warnings.warn') as warn:
  39. e.load()
  40. warn.assert_called()
  41. with patch('celery.utils.imports.symbol_by_name') as symbyname:
  42. symbyname.side_effect = KeyError('foo')
  43. with pytest.raises(KeyError):
  44. e.load()
  45. class test_Command:
  46. def test_get_options(self):
  47. cmd = Command()
  48. cmd.option_list = (1, 2, 3)
  49. assert cmd.get_options() == (1, 2, 3)
  50. def test_custom_description(self):
  51. class C(Command):
  52. description = 'foo'
  53. c = C()
  54. assert c.description == 'foo'
  55. def test_format_epilog(self):
  56. assert Command()._format_epilog('hello')
  57. assert not Command()._format_epilog('')
  58. def test_format_description(self):
  59. assert Command()._format_description('hello')
  60. def test_register_callbacks(self):
  61. c = Command(on_error=8, on_usage_error=9)
  62. assert c.on_error == 8
  63. assert c.on_usage_error == 9
  64. def test_run_raises_UsageError(self):
  65. cb = Mock()
  66. c = Command(on_usage_error=cb)
  67. c.verify_args = Mock()
  68. c.run = Mock()
  69. exc = c.run.side_effect = c.UsageError('foo', status=3)
  70. assert c() == exc.status
  71. cb.assert_called_with(exc)
  72. c.verify_args.assert_called_with(())
  73. def test_default_on_usage_error(self):
  74. cmd = Command()
  75. cmd.handle_error = Mock()
  76. exc = Exception()
  77. cmd.on_usage_error(exc)
  78. cmd.handle_error.assert_called_with(exc)
  79. def test_verify_args_missing(self):
  80. c = Command()
  81. def run(a, b, c):
  82. pass
  83. c.run = run
  84. with pytest.raises(c.UsageError):
  85. c.verify_args((1,))
  86. c.verify_args((1, 2, 3))
  87. def test_run_interface(self):
  88. with pytest.raises(NotImplementedError):
  89. Command().run()
  90. @patch('sys.stdout')
  91. def test_early_version(self, stdout):
  92. cmd = Command()
  93. with pytest.raises(SystemExit):
  94. cmd.early_version(['--version'])
  95. def test_execute_from_commandline(self, app):
  96. cmd = MockCommand(app=app)
  97. args1, kwargs1 = cmd.execute_from_commandline() # sys.argv
  98. assert args1 == cmd.mock_args
  99. assert kwargs1['foo'] == 'bar'
  100. assert kwargs1.get('prog_name')
  101. args2, kwargs2 = cmd.execute_from_commandline(['foo']) # pass list
  102. assert args2 == cmd.mock_args
  103. assert kwargs2['foo'] == 'bar'
  104. assert kwargs2['prog_name'] == 'foo'
  105. def test_with_bogus_args(self, app):
  106. with mock.stdouts() as (_, stderr):
  107. cmd = MockCommand(app=app)
  108. cmd.supports_args = False
  109. with pytest.raises(SystemExit):
  110. cmd.execute_from_commandline(argv=['--bogus'])
  111. assert stderr.getvalue()
  112. assert 'Unrecognized' in stderr.getvalue()
  113. def test_with_custom_config_module(self, app):
  114. prev = os.environ.pop('CELERY_CONFIG_MODULE', None)
  115. try:
  116. cmd = MockCommand(app=app)
  117. cmd.setup_app_from_commandline(['--config=foo.bar.baz'])
  118. assert os.environ.get('CELERY_CONFIG_MODULE') == 'foo.bar.baz'
  119. finally:
  120. if prev:
  121. os.environ['CELERY_CONFIG_MODULE'] = prev
  122. else:
  123. os.environ.pop('CELERY_CONFIG_MODULE', None)
  124. def test_with_custom_broker(self, app):
  125. prev = os.environ.pop('CELERY_BROKER_URL', None)
  126. try:
  127. cmd = MockCommand(app=app)
  128. cmd.setup_app_from_commandline(['--broker=xyzza://'])
  129. assert os.environ.get('CELERY_BROKER_URL') == 'xyzza://'
  130. finally:
  131. if prev:
  132. os.environ['CELERY_BROKER_URL'] = prev
  133. else:
  134. os.environ.pop('CELERY_BROKER_URL', None)
  135. def test_with_custom_app(self, app):
  136. cmd = MockCommand(app=app)
  137. appstr = '.'.join([__name__, 'APP'])
  138. cmd.setup_app_from_commandline(['--app=%s' % (appstr,),
  139. '--loglevel=INFO'])
  140. assert cmd.app is APP
  141. cmd.setup_app_from_commandline(['-A', appstr,
  142. '--loglevel=INFO'])
  143. assert cmd.app is APP
  144. def test_setup_app_sets_quiet(self, app):
  145. cmd = MockCommand(app=app)
  146. cmd.setup_app_from_commandline(['-q'])
  147. assert cmd.quiet
  148. cmd2 = MockCommand(app=app)
  149. cmd2.setup_app_from_commandline(['--quiet'])
  150. assert cmd2.quiet
  151. def test_setup_app_sets_chdir(self, app):
  152. with patch('os.chdir') as chdir:
  153. cmd = MockCommand(app=app)
  154. cmd.setup_app_from_commandline(['--workdir=/opt'])
  155. chdir.assert_called_with('/opt')
  156. def test_setup_app_sets_loader(self, app):
  157. prev = os.environ.get('CELERY_LOADER')
  158. try:
  159. cmd = MockCommand(app=app)
  160. cmd.setup_app_from_commandline(['--loader=X.Y:Z'])
  161. assert os.environ['CELERY_LOADER'] == 'X.Y:Z'
  162. finally:
  163. if prev is not None:
  164. os.environ['CELERY_LOADER'] = prev
  165. else:
  166. del(os.environ['CELERY_LOADER'])
  167. def test_setup_app_no_respect(self, app):
  168. cmd = MockCommand(app=app)
  169. cmd.respects_app_option = False
  170. with patch('celery.bin.base.Celery') as cp:
  171. cmd.setup_app_from_commandline(['--app=x.y:z'])
  172. cp.assert_called()
  173. def test_setup_app_custom_app(self, app):
  174. cmd = MockCommand(app=app)
  175. app = cmd.app = Mock()
  176. app.user_options = {'preload': None}
  177. cmd.setup_app_from_commandline([])
  178. assert cmd.app == app
  179. def test_find_app_suspects(self, app):
  180. cmd = MockCommand(app=app)
  181. assert cmd.find_app('t.unit.bin.proj.app')
  182. assert cmd.find_app('t.unit.bin.proj')
  183. assert cmd.find_app('t.unit.bin.proj:hello')
  184. assert cmd.find_app('t.unit.bin.proj.hello')
  185. assert cmd.find_app('t.unit.bin.proj.app:app')
  186. assert cmd.find_app('t.unit.bin.proj.app.app')
  187. with pytest.raises(AttributeError):
  188. cmd.find_app('t.unit.bin')
  189. with pytest.raises(AttributeError):
  190. cmd.find_app(__name__)
  191. def test_ask(self, app, patching):
  192. try:
  193. input = patching('celery.bin.base.input')
  194. except AttributeError:
  195. input = patching('builtins.input')
  196. cmd = MockCommand(app=app)
  197. input.return_value = 'yes'
  198. assert cmd.ask('q', ('yes', 'no'), 'no') == 'yes'
  199. input.return_value = 'nop'
  200. assert cmd.ask('q', ('yes', 'no'), 'no') == 'no'
  201. def test_host_format(self, app):
  202. cmd = MockCommand(app=app)
  203. with patch('celery.utils.nodenames.gethostname') as hn:
  204. hn.return_value = 'blacktron.example.com'
  205. assert cmd.host_format('') == ''
  206. assert (cmd.host_format('celery@%h') ==
  207. 'celery@blacktron.example.com')
  208. assert cmd.host_format('celery@%d') == 'celery@example.com'
  209. assert cmd.host_format('celery@%n') == 'celery@blacktron'
  210. def test_say_chat_quiet(self, app):
  211. cmd = MockCommand(app=app)
  212. cmd.quiet = True
  213. assert cmd.say_chat('<-', 'foo', 'foo') is None
  214. def test_say_chat_show_body(self, app):
  215. cmd = MockCommand(app=app)
  216. cmd.out = Mock()
  217. cmd.show_body = True
  218. cmd.say_chat('->', 'foo', 'body')
  219. cmd.out.assert_called_with('body')
  220. def test_say_chat_no_body(self, app):
  221. cmd = MockCommand(app=app)
  222. cmd.out = Mock()
  223. cmd.show_body = False
  224. cmd.say_chat('->', 'foo', 'body')
  225. @pytest.mark.usefixtures('depends_on_current_app')
  226. def test_with_cmdline_config(self, app):
  227. cmd = MockCommand(app=app)
  228. cmd.enable_config_from_cmdline = True
  229. cmd.namespace = 'worker'
  230. rest = cmd.setup_app_from_commandline(argv=[
  231. '--loglevel=INFO', '--',
  232. 'broker.url=amqp://broker.example.com',
  233. '.prefetch_multiplier=100'])
  234. assert cmd.app.conf.broker_url == 'amqp://broker.example.com'
  235. assert cmd.app.conf.worker_prefetch_multiplier == 100
  236. assert rest == ['--loglevel=INFO']
  237. cmd.app = None
  238. cmd.get_app = Mock(name='get_app')
  239. cmd.get_app.return_value = app
  240. app.user_options['preload'] = [
  241. Option('--foo', action='store_true'),
  242. ]
  243. cmd.setup_app_from_commandline(argv=[
  244. '--foo', '--loglevel=INFO', '--',
  245. 'broker.url=amqp://broker.example.com',
  246. '.prefetch_multiplier=100'])
  247. assert cmd.app is cmd.get_app()
  248. def test_get_default_app(self, app, patching):
  249. patching('celery._state.get_current_app')
  250. cmd = MockCommand(app=app)
  251. from celery._state import get_current_app
  252. assert cmd._get_default_app() is get_current_app()
  253. def test_set_colored(self, app):
  254. cmd = MockCommand(app=app)
  255. cmd.colored = 'foo'
  256. assert cmd.colored == 'foo'
  257. def test_set_no_color(self, app):
  258. cmd = MockCommand(app=app)
  259. cmd.no_color = False
  260. _ = cmd.colored # noqa
  261. cmd.no_color = True
  262. assert not cmd.colored.enabled
  263. def test_find_app(self, app):
  264. cmd = MockCommand(app=app)
  265. with patch('celery.utils.imports.symbol_by_name') as sbn:
  266. from types import ModuleType
  267. x = ModuleType(bytes_if_py2('proj'))
  268. def on_sbn(*args, **kwargs):
  269. def after(*args, **kwargs):
  270. x.app = 'quick brown fox'
  271. x.__path__ = None
  272. return x
  273. sbn.side_effect = after
  274. return x
  275. sbn.side_effect = on_sbn
  276. x.__path__ = [True]
  277. assert cmd.find_app('proj') == 'quick brown fox'
  278. def test_parse_preload_options_shortopt(self):
  279. class TestCommand(Command):
  280. def add_preload_arguments(self, parser):
  281. parser.add_argument('-s', action='store', dest='silent')
  282. cmd = TestCommand()
  283. acc = cmd.parse_preload_options(['-s', 'yes'])
  284. assert acc.get('silent') == 'yes'
  285. def test_parse_preload_options_with_equals_and_append(self):
  286. class TestCommand(Command):
  287. def add_preload_arguments(self, parser):
  288. parser.add_argument('--zoom', action='append', default=[])
  289. cmd = Command()
  290. acc = cmd.parse_preload_options(['--zoom=1', '--zoom=2'])
  291. assert acc, {'zoom': ['1' == '2']}
  292. def test_parse_preload_options_without_equals_and_append(self):
  293. cmd = Command()
  294. opt = Option('--zoom', action='append', default=[])
  295. cmd.preload_options = (opt,)
  296. acc = cmd.parse_preload_options(['--zoom', '1', '--zoom', '2'])
  297. assert acc, {'zoom': ['1' == '2']}