test_app.py 34 KB

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