test_app.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. import gc
  2. import itertools
  3. import os
  4. import pytest
  5. from copy import deepcopy
  6. from pickle import loads, dumps
  7. from case import ContextMock, Mock, mock, patch
  8. from vine import promise
  9. from celery import Celery
  10. from celery import shared_task, current_app
  11. from celery import app as _app
  12. from celery import _state
  13. from celery.app import base as _appbase
  14. from celery.app import defaults
  15. from celery.exceptions import ImproperlyConfigured
  16. from celery.loaders.base import unconfigured
  17. from celery.platforms import pyimplementation
  18. from celery.utils.collections import DictAttribute
  19. from celery.utils.serialization import pickle
  20. from celery.utils.time import timezone
  21. from celery.utils.objects import Bunch
  22. THIS_IS_A_KEY = 'this is a value'
  23. class ObjectConfig:
  24. FOO = 1
  25. BAR = 2
  26. object_config = ObjectConfig()
  27. dict_config = dict(FOO=10, BAR=20)
  28. class ObjectConfig2:
  29. LEAVE_FOR_WORK = True
  30. MOMENT_TO_STOP = True
  31. CALL_ME_BACK = 123456789
  32. WANT_ME_TO = False
  33. UNDERSTAND_ME = True
  34. class test_module:
  35. def test_default_app(self):
  36. assert _app.default_app == _state.default_app
  37. def test_bugreport(self, app):
  38. assert _app.bugreport(app=app)
  39. class test_task_join_will_block:
  40. def test_task_join_will_block(self, patching):
  41. patching('celery._state._task_join_will_block', 0)
  42. assert _state._task_join_will_block == 0
  43. _state._set_task_join_will_block(True)
  44. assert _state._task_join_will_block is True
  45. # fixture 'app' sets this, so need to use orig_ function
  46. # set there by that fixture.
  47. res = _state.orig_task_join_will_block()
  48. assert res is True
  49. class test_App:
  50. def setup(self):
  51. self.app.add_defaults(deepcopy(self.CELERY_TEST_CONFIG))
  52. @patch('celery.app.base.set_default_app')
  53. def test_set_default(self, set_default_app):
  54. self.app.set_default()
  55. set_default_app.assert_called_with(self.app)
  56. @patch('celery.security.setup_security')
  57. def test_setup_security(self, setup_security):
  58. self.app.setup_security(
  59. {'json'}, 'key', 'cert', 'store', 'digest', 'serializer')
  60. setup_security.assert_called_with(
  61. {'json'}, 'key', 'cert', 'store', 'digest', 'serializer',
  62. app=self.app)
  63. def test_task_autofinalize_disabled(self):
  64. with self.Celery('xyzibari', autofinalize=False) as app:
  65. @app.task
  66. def ttafd():
  67. return 42
  68. with pytest.raises(RuntimeError):
  69. ttafd()
  70. with self.Celery('xyzibari', autofinalize=False) as app:
  71. @app.task
  72. def ttafd2():
  73. return 42
  74. app.finalize()
  75. assert ttafd2() == 42
  76. def test_registry_autofinalize_disabled(self):
  77. with self.Celery('xyzibari', autofinalize=False) as app:
  78. with pytest.raises(RuntimeError):
  79. app.tasks['celery.chain']
  80. app.finalize()
  81. assert app.tasks['celery.chain']
  82. def test_task(self):
  83. with self.Celery('foozibari') as app:
  84. def fun():
  85. pass
  86. fun.__module__ = '__main__'
  87. task = app.task(fun)
  88. assert task.name == app.main + '.fun'
  89. def test_task_too_many_args(self):
  90. with pytest.raises(TypeError):
  91. self.app.task(Mock(name='fun'), True)
  92. with pytest.raises(TypeError):
  93. self.app.task(Mock(name='fun'), True, 1, 2)
  94. def test_with_config_source(self):
  95. with self.Celery(config_source=ObjectConfig) as app:
  96. assert app.conf.FOO == 1
  97. assert app.conf.BAR == 2
  98. @pytest.mark.usefixtures('depends_on_current_app')
  99. def test_task_windows_execv(self):
  100. prev, _appbase.USING_EXECV = _appbase.USING_EXECV, True
  101. try:
  102. @self.app.task(shared=False)
  103. def foo():
  104. pass
  105. assert foo._get_current_object() # is proxy
  106. finally:
  107. _appbase.USING_EXECV = prev
  108. assert not _appbase.USING_EXECV
  109. def test_task_takes_no_args(self):
  110. with pytest.raises(TypeError):
  111. @self.app.task(1)
  112. def foo():
  113. pass
  114. def test_add_defaults(self):
  115. assert not self.app.configured
  116. _conf = {'foo': 300}
  117. def conf():
  118. return _conf
  119. self.app.add_defaults(conf)
  120. assert conf in self.app._pending_defaults
  121. assert not self.app.configured
  122. assert self.app.conf.foo == 300
  123. assert self.app.configured
  124. assert not self.app._pending_defaults
  125. # defaults not pickled
  126. appr = loads(dumps(self.app))
  127. with pytest.raises(AttributeError):
  128. appr.conf.foo
  129. # add more defaults after configured
  130. conf2 = {'foo': 'BAR'}
  131. self.app.add_defaults(conf2)
  132. assert self.app.conf.foo == 'BAR'
  133. assert _conf in self.app.conf.defaults
  134. assert conf2 in self.app.conf.defaults
  135. def test_connection_or_acquire(self):
  136. with self.app.connection_or_acquire(block=True):
  137. assert self.app.pool._dirty
  138. with self.app.connection_or_acquire(pool=False):
  139. assert not self.app.pool._dirty
  140. def test_using_v1_reduce(self):
  141. self.app._using_v1_reduce = True
  142. assert loads(dumps(self.app))
  143. def test_autodiscover_tasks_force(self):
  144. self.app.loader.autodiscover_tasks = Mock()
  145. self.app.autodiscover_tasks(['proj.A', 'proj.B'], force=True)
  146. self.app.loader.autodiscover_tasks.assert_called_with(
  147. ['proj.A', 'proj.B'], 'tasks',
  148. )
  149. self.app.loader.autodiscover_tasks = Mock()
  150. def lazy_list():
  151. return ['proj.A', 'proj.B']
  152. self.app.autodiscover_tasks(
  153. lazy_list,
  154. related_name='george',
  155. force=True,
  156. )
  157. self.app.loader.autodiscover_tasks.assert_called_with(
  158. ['proj.A', 'proj.B'], 'george',
  159. )
  160. def test_autodiscover_tasks_lazy(self):
  161. with patch('celery.signals.import_modules') as import_modules:
  162. def lazy_list():
  163. return [1, 2, 3]
  164. self.app.autodiscover_tasks(lazy_list)
  165. import_modules.connect.assert_called()
  166. prom = import_modules.connect.call_args[0][0]
  167. assert isinstance(prom, promise)
  168. assert prom.fun == self.app._autodiscover_tasks
  169. assert prom.args[0](), [1, 2 == 3]
  170. def test_autodiscover_tasks__no_packages(self):
  171. fixup1 = Mock(name='fixup')
  172. fixup2 = Mock(name='fixup')
  173. self.app._autodiscover_tasks_from_names = Mock(name='auto')
  174. self.app._fixups = [fixup1, fixup2]
  175. fixup1.autodiscover_tasks.return_value = ['A', 'B', 'C']
  176. fixup2.autodiscover_tasks.return_value = ['D', 'E', 'F']
  177. self.app.autodiscover_tasks(force=True)
  178. self.app._autodiscover_tasks_from_names.assert_called_with(
  179. ['A', 'B', 'C', 'D', 'E', 'F'], related_name='tasks',
  180. )
  181. def test_with_broker(self, patching):
  182. patching.setenv('CELERY_BROKER_URL', '')
  183. with self.Celery(broker='foo://baribaz') as app:
  184. assert app.conf.broker_url == 'foo://baribaz'
  185. def test_pending_configuration__setattr(self):
  186. with self.Celery(broker='foo://bar') as app:
  187. app.conf.task_default_delivery_mode = 44
  188. app.conf.worker_agent = 'foo:Bar'
  189. assert not app.configured
  190. assert app.conf.worker_agent == 'foo:Bar'
  191. assert app.conf.broker_url == 'foo://bar'
  192. assert app._preconf['worker_agent'] == 'foo:Bar'
  193. assert app.configured
  194. reapp = pickle.loads(pickle.dumps(app))
  195. assert reapp._preconf['worker_agent'] == 'foo:Bar'
  196. assert not reapp.configured
  197. assert reapp.conf.worker_agent == 'foo:Bar'
  198. assert reapp.configured
  199. assert reapp.conf.broker_url == 'foo://bar'
  200. assert reapp._preconf['worker_agent'] == 'foo:Bar'
  201. def test_pending_configuration__update(self):
  202. with self.Celery(broker='foo://bar') as app:
  203. app.conf.update(
  204. task_default_delivery_mode=44,
  205. worker_agent='foo:Bar',
  206. )
  207. assert not app.configured
  208. assert app.conf.worker_agent == 'foo:Bar'
  209. assert app.conf.broker_url == 'foo://bar'
  210. assert app._preconf['worker_agent'] == 'foo:Bar'
  211. def test_pending_configuration__compat_settings(self):
  212. with self.Celery(broker='foo://bar', backend='foo') as app:
  213. app.conf.update(
  214. CELERY_ALWAYS_EAGER=4,
  215. CELERY_DEFAULT_DELIVERY_MODE=63,
  216. CELERYD_AGENT='foo:Barz',
  217. )
  218. assert app.conf.task_always_eager == 4
  219. assert app.conf.task_default_delivery_mode == 63
  220. assert app.conf.worker_agent == 'foo:Barz'
  221. assert app.conf.broker_url == 'foo://bar'
  222. assert app.conf.result_backend == 'foo'
  223. def test_pending_configuration__compat_settings_mixing(self):
  224. with self.Celery(broker='foo://bar', backend='foo') as app:
  225. app.conf.update(
  226. CELERY_ALWAYS_EAGER=4,
  227. CELERY_DEFAULT_DELIVERY_MODE=63,
  228. CELERYD_AGENT='foo:Barz',
  229. worker_consumer='foo:Fooz',
  230. )
  231. with pytest.raises(ImproperlyConfigured):
  232. assert app.conf.task_always_eager == 4
  233. def test_pending_configuration__django_settings(self):
  234. with self.Celery(broker='foo://bar', backend='foo') as app:
  235. app.config_from_object(DictAttribute(Bunch(
  236. CELERY_TASK_ALWAYS_EAGER=4,
  237. CELERY_TASK_DEFAULT_DELIVERY_MODE=63,
  238. CELERY_WORKER_AGENT='foo:Barz',
  239. CELERY_RESULT_SERIALIZER='pickle',
  240. )), namespace='CELERY')
  241. assert app.conf.result_serializer == 'pickle'
  242. assert app.conf.CELERY_RESULT_SERIALIZER == 'pickle'
  243. assert app.conf.task_always_eager == 4
  244. assert app.conf.task_default_delivery_mode == 63
  245. assert app.conf.worker_agent == 'foo:Barz'
  246. assert app.conf.broker_url == 'foo://bar'
  247. assert app.conf.result_backend == 'foo'
  248. def test_pending_configuration__compat_settings_mixing_new(self):
  249. with self.Celery(broker='foo://bar', backend='foo') as app:
  250. app.conf.update(
  251. task_always_eager=4,
  252. task_default_delivery_mode=63,
  253. worker_agent='foo:Barz',
  254. CELERYD_CONSUMER='foo:Fooz',
  255. CELERYD_AUTOSCALER='foo:Xuzzy',
  256. )
  257. with pytest.raises(ImproperlyConfigured):
  258. assert app.conf.worker_consumer == 'foo:Fooz'
  259. def test_pending_configuration__compat_settings_mixing_alt(self):
  260. with self.Celery(broker='foo://bar', backend='foo') as app:
  261. app.conf.update(
  262. task_always_eager=4,
  263. task_default_delivery_mode=63,
  264. worker_agent='foo:Barz',
  265. CELERYD_CONSUMER='foo:Fooz',
  266. worker_consumer='foo:Fooz',
  267. CELERYD_AUTOSCALER='foo:Xuzzy',
  268. worker_autoscaler='foo:Xuzzy'
  269. )
  270. def test_pending_configuration__setdefault(self):
  271. with self.Celery(broker='foo://bar') as app:
  272. assert not app.configured
  273. app.conf.setdefault('worker_agent', 'foo:Bar')
  274. assert not app.configured
  275. def test_pending_configuration__iter(self):
  276. with self.Celery(broker='foo://bar') as app:
  277. app.conf.worker_agent = 'foo:Bar'
  278. assert not app.configured
  279. assert list(app.conf.keys())
  280. assert app.configured
  281. assert 'worker_agent' in app.conf
  282. assert dict(app.conf)
  283. def test_pending_configuration__raises_ImproperlyConfigured(self):
  284. with self.Celery(set_as_current=False) as app:
  285. app.conf.worker_agent = 'foo://bar'
  286. app.conf.task_default_delivery_mode = 44
  287. app.conf.CELERY_ALWAYS_EAGER = 5
  288. with pytest.raises(ImproperlyConfigured):
  289. app.finalize()
  290. with self.Celery() as app:
  291. assert not self.app.conf.task_always_eager
  292. def test_repr(self):
  293. assert repr(self.app)
  294. def test_custom_task_registry(self):
  295. with self.Celery(tasks=self.app.tasks) as app2:
  296. assert app2.tasks is self.app.tasks
  297. def test_include_argument(self):
  298. with self.Celery(include=('foo', 'bar.foo')) as app:
  299. assert app.conf.include, ('foo' == 'bar.foo')
  300. def test_set_as_current(self):
  301. current = _state._tls.current_app
  302. try:
  303. app = self.Celery(set_as_current=True)
  304. assert _state._tls.current_app is app
  305. finally:
  306. _state._tls.current_app = current
  307. def test_current_task(self):
  308. @self.app.task
  309. def foo(shared=False):
  310. pass
  311. _state._task_stack.push(foo)
  312. try:
  313. assert self.app.current_task.name == foo.name
  314. finally:
  315. _state._task_stack.pop()
  316. def test_task_not_shared(self):
  317. with patch('celery.app.base.connect_on_app_finalize') as sh:
  318. @self.app.task(shared=False)
  319. def foo():
  320. pass
  321. sh.assert_not_called()
  322. def test_task_compat_with_filter(self):
  323. with self.Celery() as app:
  324. check = Mock()
  325. def filter(task):
  326. check(task)
  327. return task
  328. @app.task(filter=filter, shared=False)
  329. def foo():
  330. pass
  331. check.assert_called_with(foo)
  332. def test_task_with_filter(self):
  333. with self.Celery() as app:
  334. check = Mock()
  335. def filter(task):
  336. check(task)
  337. return task
  338. assert not _appbase.USING_EXECV
  339. @app.task(filter=filter, shared=False)
  340. def foo():
  341. pass
  342. check.assert_called_with(foo)
  343. def test_task_sets_main_name_MP_MAIN_FILE(self):
  344. from celery.utils import imports as _imports
  345. _imports.MP_MAIN_FILE = __file__
  346. try:
  347. with self.Celery('xuzzy') as app:
  348. @app.task
  349. def foo():
  350. pass
  351. assert foo.name == 'xuzzy.foo'
  352. finally:
  353. _imports.MP_MAIN_FILE = None
  354. def test_annotate_decorator(self):
  355. from celery.app.task import Task
  356. class adX(Task):
  357. def run(self, y, z, x):
  358. return y, z, x
  359. check = Mock()
  360. def deco(fun):
  361. def _inner(*args, **kwargs):
  362. check(*args, **kwargs)
  363. return fun(*args, **kwargs)
  364. return _inner
  365. self.app.conf.task_annotations = {
  366. adX.name: {'@__call__': deco}
  367. }
  368. adX.bind(self.app)
  369. assert adX.app is self.app
  370. i = adX()
  371. i(2, 4, x=3)
  372. check.assert_called_with(i, 2, 4, x=3)
  373. i.annotate()
  374. i.annotate()
  375. def test_apply_async_has__self__(self):
  376. @self.app.task(__self__='hello', shared=False)
  377. def aawsX(x, y):
  378. pass
  379. with pytest.raises(TypeError):
  380. aawsX.apply_async(())
  381. with pytest.raises(TypeError):
  382. aawsX.apply_async((2,))
  383. with patch('celery.app.amqp.AMQP.create_task_message') as create:
  384. with patch('celery.app.amqp.AMQP.send_task_message') as send:
  385. create.return_value = Mock(), Mock(), Mock(), Mock()
  386. aawsX.apply_async((4, 5))
  387. args = create.call_args[0][2]
  388. assert args, ('hello', 4 == 5)
  389. send.assert_called()
  390. def test_apply_async_adds_children(self):
  391. from celery._state import _task_stack
  392. @self.app.task(bind=True, shared=False)
  393. def a3cX1(self):
  394. pass
  395. @self.app.task(bind=True, shared=False)
  396. def a3cX2(self):
  397. pass
  398. _task_stack.push(a3cX1)
  399. try:
  400. a3cX1.push_request(called_directly=False)
  401. try:
  402. res = a3cX2.apply_async(add_to_parent=True)
  403. assert res in a3cX1.request.children
  404. finally:
  405. a3cX1.pop_request()
  406. finally:
  407. _task_stack.pop()
  408. def test_pickle_app(self):
  409. changes = dict(THE_FOO_BAR='bars',
  410. THE_MII_MAR='jars')
  411. self.app.conf.update(changes)
  412. saved = pickle.dumps(self.app)
  413. assert len(saved) < 2048
  414. restored = pickle.loads(saved)
  415. for key, value in changes.items():
  416. assert restored.conf[key] == value
  417. def test_worker_main(self):
  418. from celery.bin import worker as worker_bin
  419. class worker(worker_bin.worker):
  420. def execute_from_commandline(self, argv):
  421. return argv
  422. prev, worker_bin.worker = worker_bin.worker, worker
  423. try:
  424. ret = self.app.worker_main(argv=['--version'])
  425. assert ret == ['--version']
  426. finally:
  427. worker_bin.worker = prev
  428. def test_config_from_envvar(self):
  429. os.environ['CELERYTEST_CONFIG_OBJECT'] = 't.unit.app.test_app'
  430. self.app.config_from_envvar('CELERYTEST_CONFIG_OBJECT')
  431. assert self.app.conf.THIS_IS_A_KEY == 'this is a value'
  432. def assert_config2(self):
  433. assert self.app.conf.LEAVE_FOR_WORK
  434. assert self.app.conf.MOMENT_TO_STOP
  435. assert self.app.conf.CALL_ME_BACK == 123456789
  436. assert not self.app.conf.WANT_ME_TO
  437. assert self.app.conf.UNDERSTAND_ME
  438. def test_config_from_object__lazy(self):
  439. conf = ObjectConfig2()
  440. self.app.config_from_object(conf)
  441. assert self.app.loader._conf is unconfigured
  442. assert self.app._config_source is conf
  443. self.assert_config2()
  444. def test_config_from_object__force(self):
  445. self.app.config_from_object(ObjectConfig2(), force=True)
  446. assert self.app.loader._conf
  447. self.assert_config2()
  448. def test_config_from_object__compat(self):
  449. class Config:
  450. CELERY_ALWAYS_EAGER = 44
  451. CELERY_DEFAULT_DELIVERY_MODE = 30
  452. CELERY_TASK_PUBLISH_RETRY = False
  453. self.app.config_from_object(Config)
  454. assert self.app.conf.task_always_eager == 44
  455. assert self.app.conf.CELERY_ALWAYS_EAGER == 44
  456. assert not self.app.conf.task_publish_retry
  457. assert self.app.conf.task_default_routing_key == 'testcelery'
  458. def test_config_from_object__supports_old_names(self):
  459. class Config:
  460. task_always_eager = 45
  461. task_default_delivery_mode = 301
  462. self.app.config_from_object(Config())
  463. assert self.app.conf.CELERY_ALWAYS_EAGER == 45
  464. assert self.app.conf.task_always_eager == 45
  465. assert self.app.conf.CELERY_DEFAULT_DELIVERY_MODE == 301
  466. assert self.app.conf.task_default_delivery_mode == 301
  467. assert self.app.conf.task_default_routing_key == 'testcelery'
  468. def test_config_from_object__namespace_uppercase(self):
  469. class Config:
  470. CELERY_TASK_ALWAYS_EAGER = 44
  471. CELERY_TASK_DEFAULT_DELIVERY_MODE = 301
  472. self.app.config_from_object(Config(), namespace='CELERY')
  473. assert self.app.conf.task_always_eager == 44
  474. def test_config_from_object__namespace_lowercase(self):
  475. class Config:
  476. celery_task_always_eager = 44
  477. celery_task_default_delivery_mode = 301
  478. self.app.config_from_object(Config(), namespace='celery')
  479. assert self.app.conf.task_always_eager == 44
  480. def test_config_from_object__mixing_new_and_old(self):
  481. class Config:
  482. task_always_eager = 44
  483. worker_agent = 'foo:Agent'
  484. worker_consumer = 'foo:Consumer'
  485. beat_schedule = '/foo/schedule'
  486. CELERY_DEFAULT_DELIVERY_MODE = 301
  487. with pytest.raises(ImproperlyConfigured) as exc:
  488. self.app.config_from_object(Config(), force=True)
  489. assert exc.args[0].startswith('CELERY_DEFAULT_DELIVERY_MODE')
  490. assert 'task_default_delivery_mode' in exc.args[0]
  491. def test_config_from_object__mixing_old_and_new(self):
  492. class Config:
  493. CELERY_ALWAYS_EAGER = 46
  494. CELERYD_AGENT = 'foo:Agent'
  495. CELERYD_CONSUMER = 'foo:Consumer'
  496. CELERYBEAT_SCHEDULE = '/foo/schedule'
  497. task_default_delivery_mode = 301
  498. with pytest.raises(ImproperlyConfigured) as exc:
  499. self.app.config_from_object(Config(), force=True)
  500. assert exc.args[0].startswith('task_default_delivery_mode')
  501. assert 'CELERY_DEFAULT_DELIVERY_MODE' in exc.args[0]
  502. def test_config_from_cmdline(self):
  503. cmdline = ['task_always_eager=no',
  504. 'result_backend=/dev/null',
  505. 'worker_prefetch_multiplier=368',
  506. '.foobarstring=(string)300',
  507. '.foobarint=(int)300',
  508. 'database_engine_options=(dict){"foo": "bar"}']
  509. self.app.config_from_cmdline(cmdline, namespace='worker')
  510. assert not self.app.conf.task_always_eager
  511. assert self.app.conf.result_backend == '/dev/null'
  512. assert self.app.conf.worker_prefetch_multiplier == 368
  513. assert self.app.conf.worker_foobarstring == '300'
  514. assert self.app.conf.worker_foobarint == 300
  515. assert self.app.conf.database_engine_options == {'foo': 'bar'}
  516. def test_setting__broker_transport_options(self):
  517. _args = {'foo': 'bar', 'spam': 'baz'}
  518. self.app.config_from_object(Bunch())
  519. assert self.app.conf.broker_transport_options == {}
  520. self.app.config_from_object(Bunch(broker_transport_options=_args))
  521. assert self.app.conf.broker_transport_options == _args
  522. def test_Windows_log_color_disabled(self):
  523. self.app.IS_WINDOWS = True
  524. assert not self.app.log.supports_color(True)
  525. def test_WorkController(self):
  526. x = self.app.WorkController
  527. assert x.app is self.app
  528. def test_Worker(self):
  529. x = self.app.Worker
  530. assert x.app is self.app
  531. @pytest.mark.usefixtures('depends_on_current_app')
  532. def test_AsyncResult(self):
  533. x = self.app.AsyncResult('1')
  534. assert x.app is self.app
  535. r = loads(dumps(x))
  536. # not set as current, so ends up as default app after reduce
  537. assert r.app is current_app._get_current_object()
  538. def test_get_active_apps(self):
  539. assert list(_state._get_active_apps())
  540. app1 = self.Celery()
  541. appid = id(app1)
  542. assert app1 in _state._get_active_apps()
  543. app1.close()
  544. del(app1)
  545. gc.collect()
  546. # weakref removed from list when app goes out of scope.
  547. with pytest.raises(StopIteration):
  548. next(app for app in _state._get_active_apps() if id(app) == appid)
  549. def test_config_from_envvar_more(self, key='CELERY_HARNESS_CFG1'):
  550. assert not self.app.config_from_envvar(
  551. 'HDSAJIHWIQHEWQU', force=True, silent=True)
  552. with pytest.raises(ImproperlyConfigured):
  553. self.app.config_from_envvar(
  554. 'HDSAJIHWIQHEWQU', force=True, silent=False,
  555. )
  556. os.environ[key] = __name__ + '.object_config'
  557. assert self.app.config_from_envvar(key, force=True)
  558. assert self.app.conf['FOO'] == 1
  559. assert self.app.conf['BAR'] == 2
  560. os.environ[key] = 'unknown_asdwqe.asdwqewqe'
  561. with pytest.raises(ImportError):
  562. self.app.config_from_envvar(key, silent=False)
  563. assert not self.app.config_from_envvar(key, force=True, silent=True)
  564. os.environ[key] = __name__ + '.dict_config'
  565. assert self.app.config_from_envvar(key, force=True)
  566. assert self.app.conf['FOO'] == 10
  567. assert self.app.conf['BAR'] == 20
  568. @patch('celery.bin.celery.CeleryCommand.execute_from_commandline')
  569. def test_start(self, execute):
  570. self.app.start()
  571. execute.assert_called()
  572. @pytest.mark.parametrize('url,expected_fields', [
  573. ('pyamqp://', {
  574. 'hostname': 'localhost',
  575. 'userid': 'guest',
  576. 'password': 'guest',
  577. 'virtual_host': '/',
  578. }),
  579. ('pyamqp://:1978/foo', {
  580. 'port': 1978,
  581. 'virtual_host': 'foo',
  582. }),
  583. ('pyamqp:////value', {
  584. 'virtual_host': '/value',
  585. })
  586. ])
  587. def test_amqp_get_broker_info(self, url, expected_fields):
  588. info = self.app.connection(url).info()
  589. for key, expected_value in expected_fields.items():
  590. assert info[key] == expected_value
  591. def test_amqp_failover_strategy_selection(self):
  592. # Test passing in a string and make sure the string
  593. # gets there untouched
  594. self.app.conf.broker_failover_strategy = 'foo-bar'
  595. assert self.app.connection('amqp:////value') \
  596. .failover_strategy == 'foo-bar'
  597. # Try passing in None
  598. self.app.conf.broker_failover_strategy = None
  599. assert self.app.connection('amqp:////value') \
  600. .failover_strategy == itertools.cycle
  601. # Test passing in a method
  602. def my_failover_strategy(it):
  603. yield True
  604. self.app.conf.broker_failover_strategy = my_failover_strategy
  605. assert self.app.connection('amqp:////value') \
  606. .failover_strategy == my_failover_strategy
  607. def test_after_fork(self):
  608. self.app._pool = Mock()
  609. self.app.on_after_fork = Mock(name='on_after_fork')
  610. self.app._after_fork()
  611. assert self.app._pool is None
  612. self.app.on_after_fork.send.assert_called_with(sender=self.app)
  613. self.app._after_fork()
  614. def test_global_after_fork(self):
  615. self.app._after_fork = Mock(name='_after_fork')
  616. _appbase._after_fork_cleanup_app(self.app)
  617. self.app._after_fork.assert_called_with()
  618. @patch('celery.app.base.logger')
  619. def test_after_fork_cleanup_app__raises(self, logger):
  620. self.app._after_fork = Mock(name='_after_fork')
  621. exc = self.app._after_fork.side_effect = KeyError()
  622. _appbase._after_fork_cleanup_app(self.app)
  623. logger.info.assert_called_with(
  624. 'after forker raised exception: %r', exc, exc_info=1)
  625. def test_ensure_after_fork__no_multiprocessing(self):
  626. prev, _appbase.register_after_fork = (
  627. _appbase.register_after_fork, None)
  628. try:
  629. self.app._after_fork_registered = False
  630. self.app._ensure_after_fork()
  631. assert self.app._after_fork_registered
  632. finally:
  633. _appbase.register_after_fork = prev
  634. def test_canvas(self):
  635. assert self.app._canvas.Signature
  636. def test_signature(self):
  637. sig = self.app.signature('foo', (1, 2))
  638. assert sig.app is self.app
  639. def test_timezone__none_set(self):
  640. self.app.conf.timezone = None
  641. tz = self.app.timezone
  642. assert tz == timezone.get_timezone('UTC')
  643. def test_compat_on_configure(self):
  644. _on_configure = Mock(name='on_configure')
  645. class CompatApp(Celery):
  646. def on_configure(self, *args, **kwargs):
  647. # on pypy3 if named on_configure the class function
  648. # will be called, instead of the mock defined above,
  649. # so we add the underscore.
  650. _on_configure(*args, **kwargs)
  651. with CompatApp(set_as_current=False) as app:
  652. app.loader = Mock()
  653. app.loader.conf = {}
  654. app._load_config()
  655. _on_configure.assert_called_with()
  656. def test_add_periodic_task(self):
  657. @self.app.task
  658. def add(x, y):
  659. pass
  660. assert not self.app.configured
  661. self.app.add_periodic_task(
  662. 10, self.app.signature('add', (2, 2)),
  663. name='add1', expires=3,
  664. )
  665. assert self.app._pending_periodic_tasks
  666. assert not self.app.configured
  667. sig2 = add.s(4, 4)
  668. assert self.app.configured
  669. self.app.add_periodic_task(20, sig2, name='add2', expires=4)
  670. assert 'add1' in self.app.conf.beat_schedule
  671. assert 'add2' in self.app.conf.beat_schedule
  672. def test_pool_no_multiprocessing(self):
  673. with mock.mask_modules('multiprocessing.util'):
  674. pool = self.app.pool
  675. assert pool is self.app._pool
  676. def test_bugreport(self):
  677. assert self.app.bugreport()
  678. def test_send_task__connection_provided(self):
  679. connection = Mock(name='connection')
  680. router = Mock(name='router')
  681. router.route.return_value = {}
  682. self.app.amqp = Mock(name='amqp')
  683. self.app.amqp.Producer.attach_mock(ContextMock(), 'return_value')
  684. self.app.send_task('foo', (1, 2), connection=connection, router=router)
  685. self.app.amqp.Producer.assert_called_with(
  686. connection, auto_declare=False)
  687. self.app.amqp.send_task_message.assert_called_with(
  688. self.app.amqp.Producer(), 'foo',
  689. self.app.amqp.create_task_message())
  690. def test_send_task_sent_event(self):
  691. class Dispatcher:
  692. sent = []
  693. def publish(self, type, fields, *args, **kwargs):
  694. self.sent.append((type, fields))
  695. conn = self.app.connection()
  696. chan = conn.channel()
  697. try:
  698. for e in ('foo_exchange', 'moo_exchange', 'bar_exchange'):
  699. chan.exchange_declare(e, 'direct', durable=True)
  700. chan.queue_declare(e, durable=True)
  701. chan.queue_bind(e, e, e)
  702. finally:
  703. chan.close()
  704. assert conn.transport_cls == 'memory'
  705. message = self.app.amqp.create_task_message(
  706. 'id', 'footask', (), {}, create_sent_event=True,
  707. )
  708. prod = self.app.amqp.Producer(conn)
  709. dispatcher = Dispatcher()
  710. self.app.amqp.send_task_message(
  711. prod, 'footask', message,
  712. exchange='moo_exchange', routing_key='moo_exchange',
  713. event_dispatcher=dispatcher,
  714. )
  715. assert dispatcher.sent
  716. assert dispatcher.sent[0][0] == 'task-sent'
  717. self.app.amqp.send_task_message(
  718. prod, 'footask', message, event_dispatcher=dispatcher,
  719. exchange='bar_exchange', routing_key='bar_exchange',
  720. )
  721. def test_select_queues(self):
  722. self.app.amqp = Mock(name='amqp')
  723. self.app.select_queues({'foo', 'bar'})
  724. self.app.amqp.queues.select.assert_called_with({'foo', 'bar'})
  725. def test_Beat(self):
  726. from celery.apps.beat import Beat
  727. beat = self.app.Beat()
  728. assert isinstance(beat, Beat)
  729. def test_registry_cls(self):
  730. class TaskRegistry(self.app.registry_cls):
  731. pass
  732. class CustomCelery(type(self.app)):
  733. registry_cls = TaskRegistry
  734. app = CustomCelery(set_as_current=False)
  735. assert isinstance(app.tasks, TaskRegistry)
  736. class test_defaults:
  737. def test_strtobool(self):
  738. for s in ('false', 'no', '0'):
  739. assert not defaults.strtobool(s)
  740. for s in ('true', 'yes', '1'):
  741. assert defaults.strtobool(s)
  742. with pytest.raises(TypeError):
  743. defaults.strtobool('unsure')
  744. class test_debugging_utils:
  745. def test_enable_disable_trace(self):
  746. try:
  747. _app.enable_trace()
  748. assert _state.app_or_default == _state._app_or_default_trace
  749. _app.disable_trace()
  750. assert _state.app_or_default == _state._app_or_default
  751. finally:
  752. _app.disable_trace()
  753. class test_pyimplementation:
  754. def test_platform_python_implementation(self):
  755. with mock.platform_pyimp(lambda: 'Xython'):
  756. assert pyimplementation() == 'Xython'
  757. def test_platform_jython(self):
  758. with mock.platform_pyimp():
  759. with mock.sys_platform('java 1.6.51'):
  760. assert 'Jython' in pyimplementation()
  761. def test_platform_pypy(self):
  762. with mock.platform_pyimp():
  763. with mock.sys_platform('darwin'):
  764. with mock.pypy_version((1, 4, 3)):
  765. assert 'PyPy' in pyimplementation()
  766. with mock.pypy_version((1, 4, 3, 'a4')):
  767. assert 'PyPy' in pyimplementation()
  768. def test_platform_fallback(self):
  769. with mock.platform_pyimp():
  770. with mock.sys_platform('darwin'):
  771. with mock.pypy_version():
  772. assert 'CPython' == pyimplementation()
  773. class test_shared_task:
  774. def test_registers_to_all_apps(self):
  775. with self.Celery('xproj', set_as_current=True) as xproj:
  776. xproj.finalize()
  777. @shared_task
  778. def foo():
  779. return 42
  780. @shared_task()
  781. def bar():
  782. return 84
  783. assert foo.app is xproj
  784. assert bar.app is xproj
  785. assert foo._get_current_object()
  786. with self.Celery('yproj', set_as_current=True) as yproj:
  787. assert foo.app is yproj
  788. assert bar.app is yproj
  789. @shared_task()
  790. def baz():
  791. return 168
  792. assert baz.app is yproj