test_redis.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. from __future__ import absolute_import, unicode_literals
  2. import pytest
  3. from datetime import timedelta
  4. from contextlib import contextmanager
  5. from pickle import loads, dumps
  6. from case import ANY, ContextMock, Mock, mock, call, patch, skip
  7. from celery import signature
  8. from celery import states
  9. from celery import uuid
  10. from celery.canvas import Signature
  11. from celery.exceptions import (
  12. ChordError, CPendingDeprecationWarning, ImproperlyConfigured,
  13. )
  14. from celery.utils.collections import AttributeDict
  15. def raise_on_second_call(mock, exc, *retval):
  16. def on_first_call(*args, **kwargs):
  17. mock.side_effect = exc
  18. return mock.return_value
  19. mock.side_effect = on_first_call
  20. if retval:
  21. mock.return_value, = retval
  22. class Connection(object):
  23. connected = True
  24. def disconnect(self):
  25. self.connected = False
  26. class Pipeline(object):
  27. def __init__(self, client):
  28. self.client = client
  29. self.steps = []
  30. def __getattr__(self, attr):
  31. def add_step(*args, **kwargs):
  32. self.steps.append((getattr(self.client, attr), args, kwargs))
  33. return self
  34. return add_step
  35. def __enter__(self):
  36. return self
  37. def __exit__(self, type, value, traceback):
  38. pass
  39. def execute(self):
  40. return [step(*a, **kw) for step, a, kw in self.steps]
  41. class Redis(mock.MockCallbacks):
  42. Connection = Connection
  43. Pipeline = Pipeline
  44. def __init__(self, host=None, port=None, db=None, password=None, **kw):
  45. self.host = host
  46. self.port = port
  47. self.db = db
  48. self.password = password
  49. self.keyspace = {}
  50. self.expiry = {}
  51. self.connection = self.Connection()
  52. def get(self, key):
  53. return self.keyspace.get(key)
  54. def setex(self, key, expires, value):
  55. self.set(key, value)
  56. self.expire(key, expires)
  57. def set(self, key, value):
  58. self.keyspace[key] = value
  59. def expire(self, key, expires):
  60. self.expiry[key] = expires
  61. return expires
  62. def delete(self, key):
  63. return bool(self.keyspace.pop(key, None))
  64. def pipeline(self):
  65. return self.Pipeline(self)
  66. def _get_list(self, key):
  67. try:
  68. return self.keyspace[key]
  69. except KeyError:
  70. l = self.keyspace[key] = []
  71. return l
  72. def rpush(self, key, value):
  73. self._get_list(key).append(value)
  74. def lrange(self, key, start, stop):
  75. return self._get_list(key)[start:stop]
  76. def llen(self, key):
  77. return len(self.keyspace.get(key) or [])
  78. class redis(object):
  79. StrictRedis = Redis
  80. class ConnectionPool(object):
  81. def __init__(self, **kwargs):
  82. pass
  83. class UnixDomainSocketConnection(object):
  84. def __init__(self, **kwargs):
  85. pass
  86. class test_RedisBackend:
  87. def get_backend(self):
  88. from celery.backends.redis import RedisBackend
  89. class _RedisBackend(RedisBackend):
  90. redis = redis
  91. return _RedisBackend
  92. def get_E_LOST(self):
  93. from celery.backends.redis import E_LOST
  94. return E_LOST
  95. def setup(self):
  96. self.Backend = self.get_backend()
  97. self.E_LOST = self.get_E_LOST()
  98. self.b = self.Backend(app=self.app)
  99. @pytest.mark.usefixtures('depends_on_current_app')
  100. @skip.unless_module('redis')
  101. def test_reduce(self):
  102. from celery.backends.redis import RedisBackend
  103. x = RedisBackend(app=self.app)
  104. assert loads(dumps(x))
  105. def test_no_redis(self):
  106. self.Backend.redis = None
  107. with pytest.raises(ImproperlyConfigured):
  108. self.Backend(app=self.app)
  109. def test_url(self):
  110. self.app.conf.redis_socket_timeout = 30.0
  111. self.app.conf.redis_socket_connect_timeout = 100.0
  112. x = self.Backend(
  113. 'redis://:bosco@vandelay.com:123//1', app=self.app,
  114. )
  115. assert x.connparams
  116. assert x.connparams['host'] == 'vandelay.com'
  117. assert x.connparams['db'] == 1
  118. assert x.connparams['port'] == 123
  119. assert x.connparams['password'] == 'bosco'
  120. assert x.connparams['socket_timeout'] == 30.0
  121. assert x.connparams['socket_connect_timeout'] == 100.0
  122. def test_socket_url(self):
  123. self.app.conf.redis_socket_timeout = 30.0
  124. self.app.conf.redis_socket_connect_timeout = 100.0
  125. x = self.Backend(
  126. 'socket:///tmp/redis.sock?virtual_host=/3', app=self.app,
  127. )
  128. assert x.connparams
  129. assert x.connparams['path'] == '/tmp/redis.sock'
  130. assert (x.connparams['connection_class'] is
  131. redis.UnixDomainSocketConnection)
  132. assert 'host' not in x.connparams
  133. assert 'port' not in x.connparams
  134. assert x.connparams['socket_timeout'] == 30.0
  135. assert 'socket_connect_timeout' not in x.connparams
  136. assert x.connparams['db'] == 3
  137. def test_compat_propertie(self):
  138. x = self.Backend(
  139. 'redis://:bosco@vandelay.com:123//1', app=self.app,
  140. )
  141. with pytest.warns(CPendingDeprecationWarning):
  142. assert x.host == 'vandelay.com'
  143. with pytest.warns(CPendingDeprecationWarning):
  144. assert x.db == 1
  145. with pytest.warns(CPendingDeprecationWarning):
  146. assert x.port == 123
  147. with pytest.warns(CPendingDeprecationWarning):
  148. assert x.password == 'bosco'
  149. def test_conf_raises_KeyError(self):
  150. self.app.conf = AttributeDict({
  151. 'result_serializer': 'json',
  152. 'result_cache_max': 1,
  153. 'result_expires': None,
  154. 'accept_content': ['json'],
  155. })
  156. self.Backend(app=self.app)
  157. @patch('celery.backends.redis.logger')
  158. def test_on_connection_error(self, logger):
  159. intervals = iter([10, 20, 30])
  160. exc = KeyError()
  161. assert self.b.on_connection_error(None, exc, intervals, 1) == 10
  162. logger.error.assert_called_with(
  163. self.E_LOST, 1, 'Inf', 'in 10.00 seconds')
  164. assert self.b.on_connection_error(10, exc, intervals, 2) == 20
  165. logger.error.assert_called_with(self.E_LOST, 2, 10, 'in 20.00 seconds')
  166. assert self.b.on_connection_error(10, exc, intervals, 3) == 30
  167. logger.error.assert_called_with(self.E_LOST, 3, 10, 'in 30.00 seconds')
  168. def test_incr(self):
  169. self.b.client = Mock(name='client')
  170. self.b.incr('foo')
  171. self.b.client.incr.assert_called_with('foo')
  172. def test_expire(self):
  173. self.b.client = Mock(name='client')
  174. self.b.expire('foo', 300)
  175. self.b.client.expire.assert_called_with('foo', 300)
  176. def test_apply_chord(self):
  177. header = Mock(name='header')
  178. header.results = [Mock(name='t1'), Mock(name='t2')]
  179. self.b.apply_chord(
  180. header, (1, 2), 'gid', None,
  181. options={'max_retries': 10},
  182. )
  183. header.assert_called_with(1, 2, max_retries=10, task_id='gid')
  184. def test_unpack_chord_result(self):
  185. self.b.exception_to_python = Mock(name='etp')
  186. decode = Mock(name='decode')
  187. exc = KeyError()
  188. tup = decode.return_value = (1, 'id1', states.FAILURE, exc)
  189. with pytest.raises(ChordError):
  190. self.b._unpack_chord_result(tup, decode)
  191. decode.assert_called_with(tup)
  192. self.b.exception_to_python.assert_called_with(exc)
  193. exc = ValueError()
  194. tup = decode.return_value = (2, 'id2', states.RETRY, exc)
  195. ret = self.b._unpack_chord_result(tup, decode)
  196. self.b.exception_to_python.assert_called_with(exc)
  197. assert ret is self.b.exception_to_python()
  198. def test_on_chord_part_return_no_gid_or_tid(self):
  199. request = Mock(name='request')
  200. request.id = request.group = None
  201. assert self.b.on_chord_part_return(request, 'SUCCESS', 10) is None
  202. def test_ConnectionPool(self):
  203. self.b.redis = Mock(name='redis')
  204. assert self.b._ConnectionPool is None
  205. assert self.b.ConnectionPool is self.b.redis.ConnectionPool
  206. assert self.b.ConnectionPool is self.b.redis.ConnectionPool
  207. def test_expires_defaults_to_config(self):
  208. self.app.conf.result_expires = 10
  209. b = self.Backend(expires=None, app=self.app)
  210. assert b.expires == 10
  211. def test_expires_is_int(self):
  212. b = self.Backend(expires=48, app=self.app)
  213. assert b.expires == 48
  214. def test_add_to_chord(self):
  215. b = self.Backend('redis://', app=self.app)
  216. gid = uuid()
  217. b.add_to_chord(gid, 'sig')
  218. b.client.incr.assert_called_with(b.get_key_for_group(gid, '.t'), 1)
  219. def test_expires_is_None(self):
  220. b = self.Backend(expires=None, app=self.app)
  221. assert b.expires == self.app.conf.result_expires.total_seconds()
  222. def test_expires_is_timedelta(self):
  223. b = self.Backend(expires=timedelta(minutes=1), app=self.app)
  224. assert b.expires == 60
  225. def test_mget(self):
  226. assert self.b.mget(['a', 'b', 'c'])
  227. self.b.client.mget.assert_called_with(['a', 'b', 'c'])
  228. def test_set_no_expire(self):
  229. self.b.expires = None
  230. self.b.set('foo', 'bar')
  231. def create_task(self):
  232. tid = uuid()
  233. task = Mock(name='task-{0}'.format(tid))
  234. task.name = 'foobarbaz'
  235. self.app.tasks['foobarbaz'] = task
  236. task.request.chord = signature(task)
  237. task.request.id = tid
  238. task.request.chord['chord_size'] = 10
  239. task.request.group = 'group_id'
  240. return task
  241. @patch('celery.result.GroupResult.restore')
  242. def test_on_chord_part_return(self, restore):
  243. tasks = [self.create_task() for i in range(10)]
  244. for i in range(10):
  245. self.b.on_chord_part_return(tasks[i].request, states.SUCCESS, i)
  246. assert self.b.client.rpush.call_count
  247. self.b.client.rpush.reset_mock()
  248. assert self.b.client.lrange.call_count
  249. jkey = self.b.get_key_for_group('group_id', '.j')
  250. tkey = self.b.get_key_for_group('group_id', '.t')
  251. self.b.client.delete.assert_has_calls([call(jkey), call(tkey)])
  252. self.b.client.expire.assert_has_calls([
  253. call(jkey, 86400), call(tkey, 86400),
  254. ])
  255. def test_on_chord_part_return__success(self):
  256. with self.chord_context(2) as (_, request, callback):
  257. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  258. callback.delay.assert_not_called()
  259. self.b.on_chord_part_return(request, states.SUCCESS, 20)
  260. callback.delay.assert_called_with([10, 20])
  261. def test_on_chord_part_return__callback_raises(self):
  262. with self.chord_context(1) as (_, request, callback):
  263. callback.delay.side_effect = KeyError(10)
  264. task = self.app._tasks['add'] = Mock(name='add_task')
  265. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  266. task.backend.fail_from_current_stack.assert_called_with(
  267. callback.id, exc=ANY,
  268. )
  269. def test_on_chord_part_return__ChordError(self):
  270. with self.chord_context(1) as (_, request, callback):
  271. self.b.client.pipeline = ContextMock()
  272. raise_on_second_call(self.b.client.pipeline, ChordError())
  273. self.b.client.pipeline.return_value.rpush().llen().get().expire(
  274. ).expire().execute.return_value = (1, 1, 0, 4, 5)
  275. task = self.app._tasks['add'] = Mock(name='add_task')
  276. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  277. task.backend.fail_from_current_stack.assert_called_with(
  278. callback.id, exc=ANY,
  279. )
  280. def test_on_chord_part_return__other_error(self):
  281. with self.chord_context(1) as (_, request, callback):
  282. self.b.client.pipeline = ContextMock()
  283. raise_on_second_call(self.b.client.pipeline, RuntimeError())
  284. self.b.client.pipeline.return_value.rpush().llen().get().expire(
  285. ).expire().execute.return_value = (1, 1, 0, 4, 5)
  286. task = self.app._tasks['add'] = Mock(name='add_task')
  287. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  288. task.backend.fail_from_current_stack.assert_called_with(
  289. callback.id, exc=ANY,
  290. )
  291. @contextmanager
  292. def chord_context(self, size=1):
  293. with patch('celery.backends.redis.maybe_signature') as ms:
  294. tasks = [self.create_task() for i in range(size)]
  295. request = Mock(name='request')
  296. request.id = 'id1'
  297. request.group = 'gid1'
  298. callback = ms.return_value = Signature('add')
  299. callback.id = 'id1'
  300. callback['chord_size'] = size
  301. callback.delay = Mock(name='callback.delay')
  302. yield tasks, request, callback
  303. def test_process_cleanup(self):
  304. self.b.process_cleanup()
  305. def test_get_set_forget(self):
  306. tid = uuid()
  307. self.b.store_result(tid, 42, states.SUCCESS)
  308. assert self.b.get_state(tid) == states.SUCCESS
  309. assert self.b.get_result(tid) == 42
  310. self.b.forget(tid)
  311. assert self.b.get_state(tid) == states.PENDING
  312. def test_set_expires(self):
  313. self.b = self.Backend(expires=512, app=self.app)
  314. tid = uuid()
  315. key = self.b.get_key_for_task(tid)
  316. self.b.store_result(tid, 42, states.SUCCESS)
  317. self.b.client.expire.assert_called_with(
  318. key, 512,
  319. )