test_base.py 12 KB

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