test_redis.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. from __future__ import absolute_import, unicode_literals
  2. import random
  3. import ssl
  4. from contextlib import contextmanager
  5. from datetime import timedelta
  6. from pickle import dumps, loads
  7. import pytest
  8. from case import ANY, ContextMock, Mock, call, mock, patch, skip
  9. from celery import signature, states, uuid
  10. from celery.canvas import Signature
  11. from celery.exceptions import (ChordError, CPendingDeprecationWarning,
  12. ImproperlyConfigured)
  13. from celery.utils.collections import AttributeDict
  14. def raise_on_second_call(mock, exc, *retval):
  15. def on_first_call(*args, **kwargs):
  16. mock.side_effect = exc
  17. return mock.return_value
  18. mock.side_effect = on_first_call
  19. if retval:
  20. mock.return_value, = retval
  21. class Connection(object):
  22. connected = True
  23. def disconnect(self):
  24. self.connected = False
  25. class Pipeline(object):
  26. def __init__(self, client):
  27. self.client = client
  28. self.steps = []
  29. def __getattr__(self, attr):
  30. def add_step(*args, **kwargs):
  31. self.steps.append((getattr(self.client, attr), args, kwargs))
  32. return self
  33. return add_step
  34. def __enter__(self):
  35. return self
  36. def __exit__(self, type, value, traceback):
  37. pass
  38. def execute(self):
  39. return [step(*a, **kw) for step, a, kw in self.steps]
  40. class Redis(mock.MockCallbacks):
  41. Connection = Connection
  42. Pipeline = Pipeline
  43. def __init__(self, host=None, port=None, db=None, password=None, **kw):
  44. self.host = host
  45. self.port = port
  46. self.db = db
  47. self.password = password
  48. self.keyspace = {}
  49. self.expiry = {}
  50. self.connection = self.Connection()
  51. def get(self, key):
  52. return self.keyspace.get(key)
  53. def setex(self, key, expires, value):
  54. self.set(key, value)
  55. self.expire(key, expires)
  56. def set(self, key, value):
  57. self.keyspace[key] = value
  58. def expire(self, key, expires):
  59. self.expiry[key] = expires
  60. return expires
  61. def delete(self, key):
  62. return bool(self.keyspace.pop(key, None))
  63. def pipeline(self):
  64. return self.Pipeline(self)
  65. def _get_list(self, key):
  66. try:
  67. return self.keyspace[key]
  68. except KeyError:
  69. l = self.keyspace[key] = []
  70. return l
  71. def rpush(self, key, value):
  72. self._get_list(key).append(value)
  73. def lrange(self, key, start, stop):
  74. return self._get_list(key)[start:stop]
  75. def llen(self, key):
  76. return len(self.keyspace.get(key) or [])
  77. class Sentinel(mock.MockCallbacks):
  78. def __init__(self, sentinels, min_other_sentinels=0, sentinel_kwargs=None,
  79. **connection_kwargs):
  80. self.sentinel_kwargs = sentinel_kwargs
  81. self.sentinels = [Redis(hostname, port, **self.sentinel_kwargs)
  82. for hostname, port in sentinels]
  83. self.min_other_sentinels = min_other_sentinels
  84. self.connection_kwargs = connection_kwargs
  85. def master_for(self, service_name, redis_class):
  86. return random.choice(self.sentinels)
  87. class redis(object):
  88. StrictRedis = Redis
  89. class ConnectionPool(object):
  90. def __init__(self, **kwargs):
  91. pass
  92. class UnixDomainSocketConnection(object):
  93. def __init__(self, **kwargs):
  94. pass
  95. class sentinel(object):
  96. Sentinel = Sentinel
  97. class test_RedisBackend:
  98. def get_backend(self):
  99. from celery.backends.redis import RedisBackend
  100. class _RedisBackend(RedisBackend):
  101. redis = redis
  102. return _RedisBackend
  103. def get_E_LOST(self):
  104. from celery.backends.redis import E_LOST
  105. return E_LOST
  106. def setup(self):
  107. self.Backend = self.get_backend()
  108. self.E_LOST = self.get_E_LOST()
  109. self.b = self.Backend(app=self.app)
  110. @pytest.mark.usefixtures('depends_on_current_app')
  111. @skip.unless_module('redis')
  112. def test_reduce(self):
  113. from celery.backends.redis import RedisBackend
  114. x = RedisBackend(app=self.app)
  115. assert loads(dumps(x))
  116. def test_no_redis(self):
  117. self.Backend.redis = None
  118. with pytest.raises(ImproperlyConfigured):
  119. self.Backend(app=self.app)
  120. def test_url(self):
  121. self.app.conf.redis_socket_timeout = 30.0
  122. self.app.conf.redis_socket_connect_timeout = 100.0
  123. x = self.Backend(
  124. 'redis://:bosco@vandelay.com:123//1', app=self.app,
  125. )
  126. assert x.connparams
  127. assert x.connparams['host'] == 'vandelay.com'
  128. assert x.connparams['db'] == 1
  129. assert x.connparams['port'] == 123
  130. assert x.connparams['password'] == 'bosco'
  131. assert x.connparams['socket_timeout'] == 30.0
  132. assert x.connparams['socket_connect_timeout'] == 100.0
  133. def test_socket_url(self):
  134. self.app.conf.redis_socket_timeout = 30.0
  135. self.app.conf.redis_socket_connect_timeout = 100.0
  136. x = self.Backend(
  137. 'socket:///tmp/redis.sock?virtual_host=/3', app=self.app,
  138. )
  139. assert x.connparams
  140. assert x.connparams['path'] == '/tmp/redis.sock'
  141. assert (x.connparams['connection_class'] is
  142. redis.UnixDomainSocketConnection)
  143. assert 'host' not in x.connparams
  144. assert 'port' not in x.connparams
  145. assert x.connparams['socket_timeout'] == 30.0
  146. assert 'socket_connect_timeout' not in x.connparams
  147. assert x.connparams['db'] == 3
  148. @skip.unless_module('redis')
  149. def test_backend_ssl(self):
  150. self.app.conf.redis_backend_use_ssl = {
  151. 'ssl_cert_reqs': ssl.CERT_REQUIRED,
  152. 'ssl_ca_certs': '/path/to/ca.crt',
  153. 'ssl_certfile': '/path/to/client.crt',
  154. 'ssl_keyfile': '/path/to/client.key',
  155. }
  156. self.app.conf.redis_socket_timeout = 30.0
  157. self.app.conf.redis_socket_connect_timeout = 100.0
  158. x = self.Backend(
  159. 'redis://:bosco@vandelay.com:123//1', app=self.app,
  160. )
  161. assert x.connparams
  162. assert x.connparams['host'] == 'vandelay.com'
  163. assert x.connparams['db'] == 1
  164. assert x.connparams['port'] == 123
  165. assert x.connparams['password'] == 'bosco'
  166. assert x.connparams['socket_timeout'] == 30.0
  167. assert x.connparams['socket_connect_timeout'] == 100.0
  168. assert x.connparams['ssl_cert_reqs'] == ssl.CERT_REQUIRED
  169. assert x.connparams['ssl_ca_certs'] == '/path/to/ca.crt'
  170. assert x.connparams['ssl_certfile'] == '/path/to/client.crt'
  171. assert x.connparams['ssl_keyfile'] == '/path/to/client.key'
  172. from redis.connection import SSLConnection
  173. assert x.connparams['connection_class'] is SSLConnection
  174. def test_compat_propertie(self):
  175. x = self.Backend(
  176. 'redis://:bosco@vandelay.com:123//1', app=self.app,
  177. )
  178. with pytest.warns(CPendingDeprecationWarning):
  179. assert x.host == 'vandelay.com'
  180. with pytest.warns(CPendingDeprecationWarning):
  181. assert x.db == 1
  182. with pytest.warns(CPendingDeprecationWarning):
  183. assert x.port == 123
  184. with pytest.warns(CPendingDeprecationWarning):
  185. assert x.password == 'bosco'
  186. def test_conf_raises_KeyError(self):
  187. self.app.conf = AttributeDict({
  188. 'result_serializer': 'json',
  189. 'result_cache_max': 1,
  190. 'result_expires': None,
  191. 'accept_content': ['json'],
  192. })
  193. self.Backend(app=self.app)
  194. @patch('celery.backends.redis.logger')
  195. def test_on_connection_error(self, logger):
  196. intervals = iter([10, 20, 30])
  197. exc = KeyError()
  198. assert self.b.on_connection_error(None, exc, intervals, 1) == 10
  199. logger.error.assert_called_with(
  200. self.E_LOST, 1, 'Inf', 'in 10.00 seconds')
  201. assert self.b.on_connection_error(10, exc, intervals, 2) == 20
  202. logger.error.assert_called_with(self.E_LOST, 2, 10, 'in 20.00 seconds')
  203. assert self.b.on_connection_error(10, exc, intervals, 3) == 30
  204. logger.error.assert_called_with(self.E_LOST, 3, 10, 'in 30.00 seconds')
  205. def test_incr(self):
  206. self.b.client = Mock(name='client')
  207. self.b.incr('foo')
  208. self.b.client.incr.assert_called_with('foo')
  209. def test_expire(self):
  210. self.b.client = Mock(name='client')
  211. self.b.expire('foo', 300)
  212. self.b.client.expire.assert_called_with('foo', 300)
  213. def test_apply_chord(self):
  214. header = Mock(name='header')
  215. header.results = [Mock(name='t1'), Mock(name='t2')]
  216. self.b.apply_chord(
  217. header, (1, 2), 'gid', None,
  218. options={'max_retries': 10},
  219. )
  220. header.assert_called_with(1, 2, max_retries=10, task_id='gid')
  221. def test_unpack_chord_result(self):
  222. self.b.exception_to_python = Mock(name='etp')
  223. decode = Mock(name='decode')
  224. exc = KeyError()
  225. tup = decode.return_value = (1, 'id1', states.FAILURE, exc)
  226. with pytest.raises(ChordError):
  227. self.b._unpack_chord_result(tup, decode)
  228. decode.assert_called_with(tup)
  229. self.b.exception_to_python.assert_called_with(exc)
  230. exc = ValueError()
  231. tup = decode.return_value = (2, 'id2', states.RETRY, exc)
  232. ret = self.b._unpack_chord_result(tup, decode)
  233. self.b.exception_to_python.assert_called_with(exc)
  234. assert ret is self.b.exception_to_python()
  235. def test_on_chord_part_return_no_gid_or_tid(self):
  236. request = Mock(name='request')
  237. request.id = request.group = None
  238. assert self.b.on_chord_part_return(request, 'SUCCESS', 10) is None
  239. def test_ConnectionPool(self):
  240. self.b.redis = Mock(name='redis')
  241. assert self.b._ConnectionPool is None
  242. assert self.b.ConnectionPool is self.b.redis.ConnectionPool
  243. assert self.b.ConnectionPool is self.b.redis.ConnectionPool
  244. def test_expires_defaults_to_config(self):
  245. self.app.conf.result_expires = 10
  246. b = self.Backend(expires=None, app=self.app)
  247. assert b.expires == 10
  248. def test_expires_is_int(self):
  249. b = self.Backend(expires=48, app=self.app)
  250. assert b.expires == 48
  251. def test_add_to_chord(self):
  252. b = self.Backend('redis://', app=self.app)
  253. gid = uuid()
  254. b.add_to_chord(gid, 'sig')
  255. b.client.incr.assert_called_with(b.get_key_for_group(gid, '.t'), 1)
  256. def test_expires_is_None(self):
  257. b = self.Backend(expires=None, app=self.app)
  258. assert b.expires == self.app.conf.result_expires.total_seconds()
  259. def test_expires_is_timedelta(self):
  260. b = self.Backend(expires=timedelta(minutes=1), app=self.app)
  261. assert b.expires == 60
  262. def test_mget(self):
  263. assert self.b.mget(['a', 'b', 'c'])
  264. self.b.client.mget.assert_called_with(['a', 'b', 'c'])
  265. def test_set_no_expire(self):
  266. self.b.expires = None
  267. self.b.set('foo', 'bar')
  268. def create_task(self):
  269. tid = uuid()
  270. task = Mock(name='task-{0}'.format(tid))
  271. task.name = 'foobarbaz'
  272. self.app.tasks['foobarbaz'] = task
  273. task.request.chord = signature(task)
  274. task.request.id = tid
  275. task.request.chord['chord_size'] = 10
  276. task.request.group = 'group_id'
  277. return task
  278. @patch('celery.result.GroupResult.restore')
  279. def test_on_chord_part_return(self, restore):
  280. tasks = [self.create_task() for i in range(10)]
  281. for i in range(10):
  282. self.b.on_chord_part_return(tasks[i].request, states.SUCCESS, i)
  283. assert self.b.client.rpush.call_count
  284. self.b.client.rpush.reset_mock()
  285. assert self.b.client.lrange.call_count
  286. jkey = self.b.get_key_for_group('group_id', '.j')
  287. tkey = self.b.get_key_for_group('group_id', '.t')
  288. self.b.client.delete.assert_has_calls([call(jkey), call(tkey)])
  289. self.b.client.expire.assert_has_calls([
  290. call(jkey, 86400), call(tkey, 86400),
  291. ])
  292. def test_on_chord_part_return__success(self):
  293. with self.chord_context(2) as (_, request, callback):
  294. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  295. callback.delay.assert_not_called()
  296. self.b.on_chord_part_return(request, states.SUCCESS, 20)
  297. callback.delay.assert_called_with([10, 20])
  298. def test_on_chord_part_return__callback_raises(self):
  299. with self.chord_context(1) as (_, request, callback):
  300. callback.delay.side_effect = KeyError(10)
  301. task = self.app._tasks['add'] = Mock(name='add_task')
  302. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  303. task.backend.fail_from_current_stack.assert_called_with(
  304. callback.id, exc=ANY,
  305. )
  306. def test_on_chord_part_return__ChordError(self):
  307. with self.chord_context(1) as (_, request, callback):
  308. self.b.client.pipeline = ContextMock()
  309. raise_on_second_call(self.b.client.pipeline, ChordError())
  310. self.b.client.pipeline.return_value.rpush().llen().get().expire(
  311. ).expire().execute.return_value = (1, 1, 0, 4, 5)
  312. task = self.app._tasks['add'] = Mock(name='add_task')
  313. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  314. task.backend.fail_from_current_stack.assert_called_with(
  315. callback.id, exc=ANY,
  316. )
  317. def test_on_chord_part_return__other_error(self):
  318. with self.chord_context(1) as (_, request, callback):
  319. self.b.client.pipeline = ContextMock()
  320. raise_on_second_call(self.b.client.pipeline, RuntimeError())
  321. self.b.client.pipeline.return_value.rpush().llen().get().expire(
  322. ).expire().execute.return_value = (1, 1, 0, 4, 5)
  323. task = self.app._tasks['add'] = Mock(name='add_task')
  324. self.b.on_chord_part_return(request, states.SUCCESS, 10)
  325. task.backend.fail_from_current_stack.assert_called_with(
  326. callback.id, exc=ANY,
  327. )
  328. @contextmanager
  329. def chord_context(self, size=1):
  330. with patch('celery.backends.redis.maybe_signature') as ms:
  331. tasks = [self.create_task() for i in range(size)]
  332. request = Mock(name='request')
  333. request.id = 'id1'
  334. request.group = 'gid1'
  335. callback = ms.return_value = Signature('add')
  336. callback.id = 'id1'
  337. callback['chord_size'] = size
  338. callback.delay = Mock(name='callback.delay')
  339. yield tasks, request, callback
  340. def test_process_cleanup(self):
  341. self.b.process_cleanup()
  342. def test_get_set_forget(self):
  343. tid = uuid()
  344. self.b.store_result(tid, 42, states.SUCCESS)
  345. assert self.b.get_state(tid) == states.SUCCESS
  346. assert self.b.get_result(tid) == 42
  347. self.b.forget(tid)
  348. assert self.b.get_state(tid) == states.PENDING
  349. def test_set_expires(self):
  350. self.b = self.Backend(expires=512, app=self.app)
  351. tid = uuid()
  352. key = self.b.get_key_for_task(tid)
  353. self.b.store_result(tid, 42, states.SUCCESS)
  354. self.b.client.expire.assert_called_with(
  355. key, 512,
  356. )
  357. class test_SentinelBackend:
  358. def get_backend(self):
  359. from celery.backends.redis import SentinelBackend
  360. class _SentinelBackend(SentinelBackend):
  361. redis = redis
  362. sentinel = sentinel
  363. return _SentinelBackend
  364. def get_E_LOST(self):
  365. from celery.backends.redis import E_LOST
  366. return E_LOST
  367. def setup(self):
  368. self.Backend = self.get_backend()
  369. self.E_LOST = self.get_E_LOST()
  370. self.b = self.Backend(app=self.app)
  371. @pytest.mark.usefixtures('depends_on_current_app')
  372. @skip.unless_module('redis')
  373. def test_reduce(self):
  374. from celery.backends.redis import SentinelBackend
  375. x = SentinelBackend(app=self.app)
  376. assert loads(dumps(x))
  377. def test_no_redis(self):
  378. self.Backend.redis = None
  379. with pytest.raises(ImproperlyConfigured):
  380. self.Backend(app=self.app)
  381. def test_url(self):
  382. self.app.conf.redis_socket_timeout = 30.0
  383. self.app.conf.redis_socket_connect_timeout = 100.0
  384. x = self.Backend(
  385. 'sentinel://:test@github.com:123/1;'
  386. 'sentinel://:test@github.com:124/1',
  387. app=self.app,
  388. )
  389. assert x.connparams
  390. assert "host" not in x.connparams
  391. assert x.connparams['db'] == 1
  392. assert "port" not in x.connparams
  393. assert x.connparams['password'] == "test"
  394. assert len(x.connparams['hosts']) == 2
  395. expected_hosts = ["github.com", "github.com"]
  396. found_hosts = [cp['host'] for cp in x.connparams['hosts']]
  397. assert found_hosts == expected_hosts
  398. expected_ports = [123, 124]
  399. found_ports = [cp['port'] for cp in x.connparams['hosts']]
  400. assert found_ports == expected_ports
  401. expected_passwords = ["test", "test"]
  402. found_passwords = [cp['password'] for cp in x.connparams['hosts']]
  403. assert found_passwords == expected_passwords
  404. expected_dbs = [1, 1]
  405. found_dbs = [cp['db'] for cp in x.connparams['hosts']]
  406. assert found_dbs == expected_dbs
  407. def test_get_sentinel_instance(self):
  408. x = self.Backend(
  409. 'sentinel://:test@github.com:123/1;'
  410. 'sentinel://:test@github.com:124/1',
  411. app=self.app,
  412. )
  413. sentinel_instance = x._get_sentinel_instance(**x.connparams)
  414. assert sentinel_instance.sentinel_kwargs == {}
  415. assert sentinel_instance.connection_kwargs['db'] == 1
  416. assert sentinel_instance.connection_kwargs['password'] == "test"
  417. assert len(sentinel_instance.sentinels) == 2
  418. def test_get_pool(self):
  419. x = self.Backend(
  420. 'sentinel://:test@github.com:123/1;'
  421. 'sentinel://:test@github.com:124/1',
  422. app=self.app,
  423. )
  424. pool = x._get_pool(**x.connparams)
  425. assert pool