| 1 |
import itertools |
| 2 |
import json |
| 3 |
import random |
| 4 |
import ssl |
| 5 |
from contextlib import contextmanager |
| 6 |
from datetime import timedelta |
| 7 |
from pickle import dumps, loads |
| 8 |
from unittest.mock import ANY, Mock, call, patch |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
try: |
| 13 |
from redis import CredentialProvider, exceptions |
| 14 |
except ImportError: |
| 15 |
exceptions = None |
| 16 |
CredentialProvider = None |
| 17 |
|
| 18 |
from celery import signature, states, uuid |
| 19 |
from celery.canvas import Signature |
| 20 |
from celery.contrib.testing.mocks import ContextMock |
| 21 |
from celery.exceptions import BackendStoreError, ChordError, ImproperlyConfigured |
| 22 |
from celery.result import AsyncResult, GroupResult |
| 23 |
from celery.utils.collections import AttributeDict |
| 24 |
from t.unit import conftest |
| 25 |
|
| 26 |
|
| 27 |
def raise_on_second_call(mock, exc, *retval): |
| 28 |
def on_first_call(*args, **kwargs): |
| 29 |
mock.side_effect = exc |
| 30 |
return mock.return_value |
| 31 |
|
| 32 |
mock.side_effect = on_first_call |
| 33 |
if retval: |
| 34 |
mock.return_value, = retval |
| 35 |
|
| 36 |
|
| 37 |
class ConnectionError(Exception): |
| 38 |
pass |
| 39 |
|
| 40 |
|
| 41 |
class Connection: |
| 42 |
connected = True |
| 43 |
|
| 44 |
def disconnect(self): |
| 45 |
self.connected = False |
| 46 |
|
| 47 |
|
| 48 |
class Pipeline: |
| 49 |
def __init__(self, client): |
| 50 |
self.client = client |
| 51 |
self.steps = [] |
| 52 |
|
| 53 |
def __getattr__(self, attr): |
| 54 |
def add_step(*args, **kwargs): |
| 55 |
self.steps.append((getattr(self.client, attr), args, kwargs)) |
| 56 |
return self |
| 57 |
|
| 58 |
return add_step |
| 59 |
|
| 60 |
def __enter__(self): |
| 61 |
return self |
| 62 |
|
| 63 |
def __exit__(self, type, value, traceback): |
| 64 |
pass |
| 65 |
|
| 66 |
def execute(self): |
| 67 |
return [step(*a, **kw) for step, a, kw in self.steps] |
| 68 |
|
| 69 |
|
| 70 |
class PubSub(conftest.MockCallbacks): |
| 71 |
def __init__(self, ignore_subscribe_messages=False): |
| 72 |
self._subscribed_to = set() |
| 73 |
|
| 74 |
def close(self): |
| 75 |
self._subscribed_to = set() |
| 76 |
|
| 77 |
def subscribe(self, *args): |
| 78 |
self._subscribed_to.update(args) |
| 79 |
|
| 80 |
def unsubscribe(self, *args): |
| 81 |
self._subscribed_to.difference_update(args) |
| 82 |
|
| 83 |
def get_message(self, timeout=None): |
| 84 |
pass |
| 85 |
|
| 86 |
|
| 87 |
class Redis(conftest.MockCallbacks): |
| 88 |
Connection = Connection |
| 89 |
Pipeline = Pipeline |
| 90 |
pubsub = PubSub |
| 91 |
|
| 92 |
def __init__(self, host=None, port=None, db=None, password=None, **kw): |
| 93 |
self.host = host |
| 94 |
self.port = port |
| 95 |
self.db = db |
| 96 |
self.password = password |
| 97 |
self.keyspace = {} |
| 98 |
self.expiry = {} |
| 99 |
self.connection = self.Connection() |
| 100 |
|
| 101 |
def get(self, key): |
| 102 |
return self.keyspace.get(key) |
| 103 |
|
| 104 |
def mget(self, keys): |
| 105 |
return [self.get(key) for key in keys] |
| 106 |
|
| 107 |
def setex(self, key, expires, value): |
| 108 |
self.set(key, value) |
| 109 |
self.expire(key, expires) |
| 110 |
|
| 111 |
def set(self, key, value): |
| 112 |
self.keyspace[key] = value |
| 113 |
|
| 114 |
def expire(self, key, expires): |
| 115 |
self.expiry[key] = expires |
| 116 |
return expires |
| 117 |
|
| 118 |
def delete(self, key): |
| 119 |
return bool(self.keyspace.pop(key, None)) |
| 120 |
|
| 121 |
def pipeline(self): |
| 122 |
return self.Pipeline(self) |
| 123 |
|
| 124 |
def _get_unsorted_list(self, key): |
| 125 |
# We simply store the values in append (rpush) order |
| 126 |
return self.keyspace.setdefault(key, list()) |
| 127 |
|
| 128 |
def rpush(self, key, value): |
| 129 |
self._get_unsorted_list(key).append(value) |
| 130 |
|
| 131 |
def lrange(self, key, start, stop): |
| 132 |
return self._get_unsorted_list(key)[start:stop] |
| 133 |
|
| 134 |
def llen(self, key): |
| 135 |
return len(self._get_unsorted_list(key)) |
| 136 |
|
| 137 |
def _get_sorted_set(self, key): |
| 138 |
# We store 2-tuples of (score, value) and sort after each append (zadd) |
| 139 |
return self.keyspace.setdefault(key, list()) |
| 140 |
|
| 141 |
def zadd(self, key, mapping): |
| 142 |
# Store elements as 2-tuples with the score first so we can sort it |
| 143 |
# once the new items have been inserted |
| 144 |
fake_sorted_set = self._get_sorted_set(key) |
| 145 |
fake_sorted_set.extend( |
| 146 |
(score, value) for value, score in mapping.items() |
| 147 |
) |
| 148 |
fake_sorted_set.sort() |
| 149 |
|
| 150 |
def zrange(self, key, start, stop): |
| 151 |
# `stop` is inclusive in Redis so we use `stop + 1` unless that would |
| 152 |
# cause us to move from negative (right-most) indices to positive |
| 153 |
stop = stop + 1 if stop != -1 else None |
| 154 |
return [e[1] for e in self._get_sorted_set(key)[start:stop]] |
| 155 |
|
| 156 |
def zrangebyscore(self, key, min_, max_): |
| 157 |
return [ |
| 158 |
e[1] for e in self._get_sorted_set(key) |
| 159 |
if (min_ == "-inf" or e[0] >= min_) and |
| 160 |
(max_ == "+inf" or e[1] <= max_) |
| 161 |
] |
| 162 |
|
| 163 |
def zcount(self, key, min_, max_): |
| 164 |
return len(self.zrangebyscore(key, min_, max_)) |
| 165 |
|
| 166 |
|
| 167 |
class Sentinel(conftest.MockCallbacks): |
| 168 |
def __init__(self, sentinels, min_other_sentinels=0, sentinel_kwargs=None, |
| 169 |
**connection_kwargs): |
| 170 |
self.sentinel_kwargs = sentinel_kwargs |
| 171 |
self.sentinels = [Redis(hostname, port, **self.sentinel_kwargs) |
| 172 |
for hostname, port in sentinels] |
| 173 |
self.min_other_sentinels = min_other_sentinels |
| 174 |
self.connection_kwargs = connection_kwargs |
| 175 |
|
| 176 |
def master_for(self, service_name, redis_class, **kwargs): |
| 177 |
self.master_for_kwargs = kwargs |
| 178 |
return random.choice(self.sentinels) |
| 179 |
|
| 180 |
|
| 181 |
class redis: |
| 182 |
StrictRedis = Redis |
| 183 |
|
| 184 |
class ConnectionPool: |
| 185 |
def __init__(self, **kwargs): |
| 186 |
pass |
| 187 |
|
| 188 |
class UnixDomainSocketConnection: |
| 189 |
def __init__(self, **kwargs): |
| 190 |
pass |
| 191 |
|
| 192 |
|
| 193 |
class sentinel: |
| 194 |
Sentinel = Sentinel |
| 195 |
|
| 196 |
|
| 197 |
class test_RedisResultConsumer: |
| 198 |
def get_backend(self): |
| 199 |
from celery.backends.redis import RedisBackend |
| 200 |
|
| 201 |
class _RedisBackend(RedisBackend): |
| 202 |
redis = redis |
| 203 |
|
| 204 |
return _RedisBackend(app=self.app) |
| 205 |
|
| 206 |
def get_consumer(self): |
| 207 |
consumer = self.get_backend().result_consumer |
| 208 |
consumer._connection_errors = (ConnectionError,) |
| 209 |
return consumer |
| 210 |
|
| 211 |
@patch('celery.backends.asynchronous.BaseResultConsumer.on_after_fork') |
| 212 |
def test_on_after_fork(self, parent_method): |
| 213 |
consumer = self.get_consumer() |
| 214 |
consumer.start('none') |
| 215 |
consumer.on_after_fork() |
| 216 |
parent_method.assert_called_once() |
| 217 |
consumer.backend.client.connection_pool.reset.assert_called_once() |
| 218 |
consumer._pubsub.close.assert_called_once() |
| 219 |
# PubSub instance not initialized - exception would be raised |
| 220 |
# when calling .close() |
| 221 |
consumer._pubsub = None |
| 222 |
parent_method.reset_mock() |
| 223 |
consumer.backend.client.connection_pool.reset.reset_mock() |
| 224 |
consumer.on_after_fork() |
| 225 |
parent_method.assert_called_once() |
| 226 |
consumer.backend.client.connection_pool.reset.assert_called_once() |
| 227 |
|
| 228 |
# Continues on KeyError |
| 229 |
consumer._pubsub = Mock() |
| 230 |
consumer._pubsub.close = Mock(side_effect=KeyError) |
| 231 |
parent_method.reset_mock() |
| 232 |
consumer.backend.client.connection_pool.reset.reset_mock() |
| 233 |
consumer.on_after_fork() |
| 234 |
parent_method.assert_called_once() |
| 235 |
|
| 236 |
@patch('celery.backends.redis.ResultConsumer.cancel_for') |
| 237 |
@patch('celery.backends.asynchronous.BaseResultConsumer.on_state_change') |
| 238 |
def test_on_state_change(self, parent_method, cancel_for): |
| 239 |
consumer = self.get_consumer() |
| 240 |
meta = {'task_id': 'testing', 'status': states.SUCCESS} |
| 241 |
message = 'hello' |
| 242 |
consumer.on_state_change(meta, message) |
| 243 |
parent_method.assert_called_once_with(meta, message) |
| 244 |
cancel_for.assert_called_once_with(meta['task_id']) |
| 245 |
|
| 246 |
# Does not call cancel_for for other states |
| 247 |
meta = {'task_id': 'testing2', 'status': states.PENDING} |
| 248 |
parent_method.reset_mock() |
| 249 |
cancel_for.reset_mock() |
| 250 |
consumer.on_state_change(meta, message) |
| 251 |
parent_method.assert_called_once_with(meta, message) |
| 252 |
cancel_for.assert_not_called() |
| 253 |
|
| 254 |
def test_drain_events_before_start(self): |
| 255 |
consumer = self.get_consumer() |
| 256 |
# drain_events shouldn't crash when called before start |
| 257 |
consumer.drain_events(0.001) |
| 258 |
|
| 259 |
def test_consume_from_connection_error(self): |
| 260 |
consumer = self.get_consumer() |
| 261 |
consumer.start('initial') |
| 262 |
consumer._pubsub.subscribe.side_effect = (ConnectionError(), None) |
| 263 |
consumer.consume_from('some-task') |
| 264 |
assert consumer._pubsub._subscribed_to == {b'celery-task-meta-initial', b'celery-task-meta-some-task'} |
| 265 |
|
| 266 |
def test_cancel_for_connection_error(self): |
| 267 |
consumer = self.get_consumer() |
| 268 |
consumer.start('initial') |
| 269 |
consumer._pubsub.unsubscribe.side_effect = ConnectionError() |
| 270 |
consumer.consume_from('some-task') |
| 271 |
consumer.cancel_for('some-task') |
| 272 |
assert consumer._pubsub._subscribed_to == {b'celery-task-meta-initial'} |
| 273 |
|
| 274 |
@patch('celery.backends.redis.ResultConsumer.cancel_for') |
| 275 |
@patch('celery.backends.asynchronous.BaseResultConsumer.on_state_change') |
| 276 |
def test_drain_events_connection_error(self, parent_on_state_change, cancel_for): |
| 277 |
meta = {'task_id': 'initial', 'status': states.SUCCESS} |
| 278 |
consumer = self.get_consumer() |
| 279 |
consumer.start('initial') |
| 280 |
consumer.backend._set_with_state(b'celery-task-meta-initial', json.dumps(meta), states.SUCCESS) |
| 281 |
consumer._pubsub.get_message.side_effect = ConnectionError() |
| 282 |
consumer.drain_events() |
| 283 |
parent_on_state_change.assert_called_with(meta, None) |
| 284 |
assert consumer._pubsub._subscribed_to == {b'celery-task-meta-initial'} |
| 285 |
|
| 286 |
def test_drain_events_connection_error_no_patch(self): |
| 287 |
meta = {'task_id': 'initial', 'status': states.SUCCESS} |
| 288 |
consumer = self.get_consumer() |
| 289 |
consumer.start('initial') |
| 290 |
consumer.backend._set_with_state(b'celery-task-meta-initial', json.dumps(meta), states.SUCCESS) |
| 291 |
consumer._pubsub.get_message.side_effect = ConnectionError() |
| 292 |
consumer.drain_events() |
| 293 |
consumer._pubsub.subscribe.assert_not_called() |
| 294 |
|
| 295 |
def test__reconnect_pubsub_no_subscribed(self): |
| 296 |
consumer = self.get_consumer() |
| 297 |
consumer.start('initial') |
| 298 |
consumer.subscribed_to = set() |
| 299 |
consumer._reconnect_pubsub() |
| 300 |
consumer.backend.client.mget.assert_not_called() |
| 301 |
consumer._pubsub.subscribe.assert_not_called() |
| 302 |
consumer._pubsub.connection.register_connect_callback.assert_called_once() |
| 303 |
|
| 304 |
def test__reconnect_pubsub_with_state_change(self): |
| 305 |
meta = {'task_id': 'initial', 'status': states.SUCCESS} |
| 306 |
consumer = self.get_consumer() |
| 307 |
consumer.start('initial') |
| 308 |
consumer.backend._set_with_state(b'celery-task-meta-initial', json.dumps(meta), states.SUCCESS) |
| 309 |
consumer._reconnect_pubsub() |
| 310 |
consumer.backend.client.mget.assert_called_once() |
| 311 |
consumer._pubsub.subscribe.assert_not_called() |
| 312 |
consumer._pubsub.connection.register_connect_callback.assert_called_once() |
| 313 |
|
| 314 |
def test__reconnect_pubsub_without_state_change(self): |
| 315 |
meta = {'task_id': 'initial', 'status': states.STARTED} |
| 316 |
consumer = self.get_consumer() |
| 317 |
consumer.start('initial') |
| 318 |
consumer.backend._set_with_state(b'celery-task-meta-initial', json.dumps(meta), states.SUCCESS) |
| 319 |
consumer._reconnect_pubsub() |
| 320 |
consumer.backend.client.mget.assert_called_once() |
| 321 |
consumer._pubsub.subscribe.assert_called_once() |
| 322 |
consumer._pubsub.connection.register_connect_callback.assert_not_called() |
| 323 |
|
| 324 |
|
| 325 |
class basetest_RedisBackend: |
| 326 |
def get_backend(self): |
| 327 |
from celery.backends.redis import RedisBackend |
| 328 |
|
| 329 |
class _RedisBackend(RedisBackend): |
| 330 |
redis = redis |
| 331 |
|
| 332 |
return _RedisBackend |
| 333 |
|
| 334 |
def get_E_LOST(self): |
| 335 |
from celery.backends.redis import E_LOST |
| 336 |
return E_LOST |
| 337 |
|
| 338 |
def create_task(self, i, group_id="group_id"): |
| 339 |
tid = uuid() |
| 340 |
task = Mock(name=f'task-{tid}') |
| 341 |
task.name = 'foobarbaz' |
| 342 |
self.app.tasks['foobarbaz'] = task |
| 343 |
task.request.chord = signature(task) |
| 344 |
task.request.id = tid |
| 345 |
self.b.set_chord_size(group_id, 10) |
| 346 |
task.request.group = group_id |
| 347 |
task.request.group_index = i |
| 348 |
return task |
| 349 |
|
| 350 |
@contextmanager |
| 351 |
def chord_context(self, size=1): |
| 352 |
with patch('celery.backends.redis.maybe_signature') as ms: |
| 353 |
request = Mock(name='request') |
| 354 |
request.id = 'id1' |
| 355 |
group_id = 'gid1' |
| 356 |
request.group = group_id |
| 357 |
request.group_index = None |
| 358 |
tasks = [ |
| 359 |
self.create_task(i, group_id=request.group) |
| 360 |
for i in range(size) |
| 361 |
] |
| 362 |
callback = ms.return_value = Signature('add') |
| 363 |
callback.id = 'id1' |
| 364 |
self.b.set_chord_size(group_id, size) |
| 365 |
callback.delay = Mock(name='callback.delay') |
| 366 |
yield tasks, request, callback |
| 367 |
|
| 368 |
def setup_method(self): |
| 369 |
self.Backend = self.get_backend() |
| 370 |
self.E_LOST = self.get_E_LOST() |
| 371 |
self.b = self.Backend(app=self.app) |
| 372 |
|
| 373 |
|
| 374 |
class MyCredentialProvider(CredentialProvider): |
| 375 |
pass |
| 376 |
|
| 377 |
|
| 378 |
class NonCredentialProvider: |
| 379 |
pass |
| 380 |
|
| 381 |
|
| 382 |
class test_RedisBackend(basetest_RedisBackend): |
| 383 |
@pytest.mark.usefixtures('depends_on_current_app') |
| 384 |
def test_reduce(self): |
| 385 |
pytest.importorskip('redis') |
| 386 |
|
| 387 |
from celery.backends.redis import RedisBackend |
| 388 |
x = RedisBackend(app=self.app) |
| 389 |
assert loads(dumps(x)) |
| 390 |
|
| 391 |
def test_no_redis(self): |
| 392 |
self.Backend.redis = None |
| 393 |
with pytest.raises(ImproperlyConfigured): |
| 394 |
self.Backend(app=self.app) |
| 395 |
|
| 396 |
def test_username_password_from_redis_conf(self): |
| 397 |
self.app.conf.redis_password = 'password' |
| 398 |
x = self.Backend(app=self.app) |
| 399 |
|
| 400 |
assert x.connparams |
| 401 |
assert 'username' not in x.connparams |
| 402 |
assert x.connparams['password'] == 'password' |
| 403 |
self.app.conf.redis_username = 'username' |
| 404 |
x = self.Backend(app=self.app) |
| 405 |
|
| 406 |
assert x.connparams |
| 407 |
assert x.connparams['username'] == 'username' |
| 408 |
assert x.connparams['password'] == 'password' |
| 409 |
|
| 410 |
def test_credential_provider_from_redis_conf(self): |
| 411 |
self.app.conf.redis_backend_credential_provider = "redis.CredentialProvider" |
| 412 |
x = self.Backend(app=self.app) |
| 413 |
|
| 414 |
assert x.connparams |
| 415 |
assert 'credential_provider' in x.connparams |
| 416 |
assert 'username' not in x.connparams |
| 417 |
assert 'password' not in x.connparams |
| 418 |
|
| 419 |
# with local credential provider |
| 420 |
self.app.conf.redis_backend_credential_provider = MyCredentialProvider() |
| 421 |
x = self.Backend(app=self.app) |
| 422 |
assert x.connparams |
| 423 |
assert 'credential_provider' in x.connparams |
| 424 |
assert 'username' not in x.connparams |
| 425 |
assert 'password' not in x.connparams |
| 426 |
|
| 427 |
# raise ImportError |
| 428 |
self.app.conf.redis_backend_credential_provider = "not_exist.CredentialProvider" |
| 429 |
with pytest.raises(ImportError): |
| 430 |
self.Backend(app=self.app) |
| 431 |
|
| 432 |
# raise value Error |
| 433 |
self.app.conf.redis_backend_credential_provider = NonCredentialProvider() |
| 434 |
with pytest.raises(ValueError): |
| 435 |
self.Backend(app=self.app) |
| 436 |
|
| 437 |
def test_url(self): |
| 438 |
self.app.conf.redis_socket_timeout = 30.0 |
| 439 |
self.app.conf.redis_socket_connect_timeout = 100.0 |
| 440 |
x = self.Backend( |
| 441 |
'redis://:[email protected]:123//1', app=self.app, |
| 442 |
) |
| 443 |
assert x.connparams |
| 444 |
assert x.connparams['host'] == 'vandelay.com' |
| 445 |
assert x.connparams['db'] == 1 |
| 446 |
assert x.connparams['port'] == 123 |
| 447 |
assert x.connparams['password'] == 'bosco' |
| 448 |
assert x.connparams['socket_timeout'] == 30.0 |
| 449 |
assert x.connparams['socket_connect_timeout'] == 100.0 |
| 450 |
assert 'username' not in x.connparams |
| 451 |
|
| 452 |
x = self.Backend( |
| 453 |
'redis://username:[email protected]:123//1', app=self.app, |
| 454 |
) |
| 455 |
assert x.connparams |
| 456 |
assert x.connparams['host'] == 'vandelay.com' |
| 457 |
assert x.connparams['db'] == 1 |
| 458 |
assert x.connparams['port'] == 123 |
| 459 |
assert x.connparams['username'] == 'username' |
| 460 |
assert x.connparams['password'] == 'bosco' |
| 461 |
assert x.connparams['socket_timeout'] == 30.0 |
| 462 |
assert x.connparams['socket_connect_timeout'] == 100.0 |
| 463 |
|
| 464 |
def test_url_with_credential_provider(self): |
| 465 |
self.app.conf.redis_socket_timeout = 30.0 |
| 466 |
self.app.conf.redis_socket_connect_timeout = 100.0 |
| 467 |
x = self.Backend( |
| 468 |
'redis://:[email protected]:123/1?credential_provider=redis.CredentialProvider', app=self.app, |
| 469 |
) |
| 470 |
|
| 471 |
assert x.connparams |
| 472 |
assert x.connparams['host'] == 'vandelay.com' |
| 473 |
assert x.connparams['db'] == 1 |
| 474 |
assert x.connparams['port'] == 123 |
| 475 |
assert x.connparams['socket_timeout'] == 30.0 |
| 476 |
assert x.connparams['socket_connect_timeout'] == 100.0 |
| 477 |
assert isinstance(x.connparams['credential_provider'], CredentialProvider) |
| 478 |
assert "username" not in x.connparams |
| 479 |
assert "password" not in x.connparams |
| 480 |
|
| 481 |
# without username and password |
| 482 |
x = self.Backend( |
| 483 |
'redis://@vandelay.com:123/1?credential_provider=redis.UsernamePasswordCredentialProvider', app=self.app, |
| 484 |
) |
| 485 |
assert x.connparams |
| 486 |
assert x.connparams['host'] == 'vandelay.com' |
| 487 |
assert x.connparams['db'] == 1 |
| 488 |
assert x.connparams['port'] == 123 |
| 489 |
assert isinstance(x.connparams['credential_provider'], CredentialProvider) |
| 490 |
|
| 491 |
# raise importError |
| 492 |
with pytest.raises(ImportError): |
| 493 |
self.Backend( |
| 494 |
'redis://@vandelay.com:123/1?credential_provider=not_exist.CredentialProvider', app=self.app, |
| 495 |
) |
| 496 |
|
| 497 |
# raise valueError |
| 498 |
with pytest.raises(ValueError): |
| 499 |
# some non-credential provider class |
| 500 |
# not ideal but serve purpose |
| 501 |
self.Backend( |
| 502 |
'redis://@vandelay.com:123/1?credential_provider=abc.ABC', app=self.app, |
| 503 |
) |
| 504 |
|
| 505 |
def test_timeouts_in_url_coerced(self): |
| 506 |
pytest.importorskip('redis') |
| 507 |
|
| 508 |
x = self.Backend( |
| 509 |
('redis://:[email protected]:123//1?' |
| 510 |
'socket_timeout=30&socket_connect_timeout=100'), |
| 511 |
app=self.app, |
| 512 |
) |
| 513 |
assert x.connparams |
| 514 |
assert x.connparams['host'] == 'vandelay.com' |
| 515 |
assert x.connparams['db'] == 1 |
| 516 |
assert x.connparams['port'] == 123 |
| 517 |
assert x.connparams['password'] == 'bosco' |
| 518 |
assert x.connparams['socket_timeout'] == 30 |
| 519 |
assert x.connparams['socket_connect_timeout'] == 100 |
| 520 |
|
| 521 |
def test_socket_url(self): |
| 522 |
pytest.importorskip('redis') |
| 523 |
|
| 524 |
self.app.conf.redis_socket_timeout = 30.0 |
| 525 |
self.app.conf.redis_socket_connect_timeout = 100.0 |
| 526 |
x = self.Backend( |
| 527 |
'socket:///tmp/redis.sock?virtual_host=/3', app=self.app, |
| 528 |
) |
| 529 |
assert x.connparams |
| 530 |
assert x.connparams['path'] == '/tmp/redis.sock' |
| 531 |
assert (x.connparams['connection_class'] is |
| 532 |
redis.UnixDomainSocketConnection) |
| 533 |
assert 'host' not in x.connparams |
| 534 |
assert 'port' not in x.connparams |
| 535 |
assert x.connparams['socket_timeout'] == 30.0 |
| 536 |
assert 'socket_connect_timeout' not in x.connparams |
| 537 |
assert 'socket_keepalive' not in x.connparams |
| 538 |
assert x.connparams['db'] == 3 |
| 539 |
|
| 540 |
def test_backend_ssl(self): |
| 541 |
pytest.importorskip('redis') |
| 542 |
|
| 543 |
self.app.conf.redis_backend_use_ssl = { |
| 544 |
'ssl_cert_reqs': ssl.CERT_REQUIRED, |
| 545 |
'ssl_ca_certs': '/path/to/ca.crt', |
| 546 |
'ssl_certfile': '/path/to/client.crt', |
| 547 |
'ssl_keyfile': '/path/to/client.key', |
| 548 |
} |
| 549 |
self.app.conf.redis_socket_timeout = 30.0 |
| 550 |
self.app.conf.redis_socket_connect_timeout = 100.0 |
| 551 |
x = self.Backend( |
| 552 |
'rediss://:[email protected]:123//1', app=self.app, |
| 553 |
) |
| 554 |
assert x.connparams |
| 555 |
assert x.connparams['host'] == 'vandelay.com' |
| 556 |
assert x.connparams['db'] == 1 |
| 557 |
assert x.connparams['port'] == 123 |
| 558 |
assert x.connparams['password'] == 'bosco' |
| 559 |
assert x.connparams['socket_timeout'] == 30.0 |
| 560 |
assert x.connparams['socket_connect_timeout'] == 100.0 |
| 561 |
assert x.connparams['ssl_cert_reqs'] == ssl.CERT_REQUIRED |
| 562 |
assert x.connparams['ssl_ca_certs'] == '/path/to/ca.crt' |
| 563 |
assert x.connparams['ssl_certfile'] == '/path/to/client.crt' |
| 564 |
assert x.connparams['ssl_keyfile'] == '/path/to/client.key' |
| 565 |
|
| 566 |
from redis.connection import SSLConnection |
| 567 |
assert x.connparams['connection_class'] is SSLConnection |
| 568 |
|
| 569 |
def test_backend_health_check_interval_ssl(self): |
| 570 |
pytest.importorskip('redis') |
| 571 |
|
| 572 |
self.app.conf.redis_backend_use_ssl = { |
| 573 |
'ssl_cert_reqs': ssl.CERT_REQUIRED, |
| 574 |
'ssl_ca_certs': '/path/to/ca.crt', |
| 575 |
'ssl_certfile': '/path/to/client.crt', |
| 576 |
'ssl_keyfile': '/path/to/client.key', |
| 577 |
} |
| 578 |
self.app.conf.redis_backend_health_check_interval = 10 |
| 579 |
x = self.Backend( |
| 580 |
'rediss://:[email protected]:123//1', app=self.app, |
| 581 |
) |
| 582 |
assert x.connparams |
| 583 |
assert x.connparams['host'] == 'vandelay.com' |
| 584 |
assert x.connparams['db'] == 1 |
| 585 |
assert x.connparams['port'] == 123 |
| 586 |
assert x.connparams['password'] == 'bosco' |
| 587 |
assert x.connparams['health_check_interval'] == 10 |
| 588 |
|
| 589 |
from redis.connection import SSLConnection |
| 590 |
assert x.connparams['connection_class'] is SSLConnection |
| 591 |
|
| 592 |
def test_backend_health_check_interval(self): |
| 593 |
pytest.importorskip('redis') |
| 594 |
|
| 595 |
self.app.conf.redis_backend_health_check_interval = 10 |
| 596 |
x = self.Backend( |
| 597 |
'redis://vandelay.com:123//1', app=self.app, |
| 598 |
) |
| 599 |
assert x.connparams |
| 600 |
assert x.connparams['host'] == 'vandelay.com' |
| 601 |
assert x.connparams['db'] == 1 |
| 602 |
assert x.connparams['port'] == 123 |
| 603 |
assert x.connparams['health_check_interval'] == 10 |
| 604 |
|
| 605 |
def test_backend_health_check_interval_not_set(self): |
| 606 |
pytest.importorskip('redis') |
| 607 |
|
| 608 |
x = self.Backend( |
| 609 |
'redis://vandelay.com:123//1', app=self.app, |
| 610 |
) |
| 611 |
assert x.connparams |
| 612 |
assert x.connparams['host'] == 'vandelay.com' |
| 613 |
assert x.connparams['db'] == 1 |
| 614 |
assert x.connparams['port'] == 123 |
| 615 |
assert "health_check_interval" not in x.connparams |
| 616 |
|
| 617 |
def test_backend_redis_client_name(self): |
| 618 |
pytest.importorskip('redis') |
| 619 |
|
| 620 |
self.app.conf.redis_client_name = 'celery-worker' |
| 621 |
x = self.Backend( |
| 622 |
'redis://vandelay.com:123//1', app=self.app, |
| 623 |
) |
| 624 |
assert x.connparams |
| 625 |
assert x.connparams['host'] == 'vandelay.com' |
| 626 |
assert x.connparams['db'] == 1 |
| 627 |
assert x.connparams['port'] == 123 |
| 628 |
assert x.connparams['client_name'] == 'celery-worker' |
| 629 |
|
| 630 |
def test_backend_redis_client_name_not_set(self): |
| 631 |
pytest.importorskip('redis') |
| 632 |
|
| 633 |
x = self.Backend( |
| 634 |
'redis://vandelay.com:123//1', app=self.app, |
| 635 |
) |
| 636 |
assert x.connparams |
| 637 |
assert x.connparams['host'] == 'vandelay.com' |
| 638 |
assert x.connparams['db'] == 1 |
| 639 |
assert x.connparams['port'] == 123 |
| 640 |
assert x.connparams['client_name'] is None |
| 641 |
|
| 642 |
@pytest.mark.parametrize('cert_str', [ |
| 643 |
"required", |
| 644 |
"CERT_REQUIRED", |
| 645 |
]) |
| 646 |
def test_backend_ssl_certreq_str(self, cert_str): |
| 647 |
pytest.importorskip('redis') |
| 648 |
|
| 649 |
self.app.conf.redis_backend_use_ssl = { |
| 650 |
'ssl_cert_reqs': cert_str, |
| 651 |
'ssl_ca_certs': '/path/to/ca.crt', |
| 652 |
'ssl_certfile': '/path/to/client.crt', |
| 653 |
'ssl_keyfile': '/path/to/client.key', |
| 654 |
} |
| 655 |
self.app.conf.redis_socket_timeout = 30.0 |
| 656 |
self.app.conf.redis_socket_connect_timeout = 100.0 |
| 657 |
x = self.Backend( |
| 658 |
'rediss://:[email protected]:123//1', app=self.app, |
| 659 |
) |
| 660 |
assert x.connparams |
| 661 |
assert x.connparams['host'] == 'vandelay.com' |
| 662 |
assert x.connparams['db'] == 1 |
| 663 |
assert x.connparams['port'] == 123 |
| 664 |
assert x.connparams['password'] == 'bosco' |
| 665 |
assert x.connparams['socket_timeout'] == 30.0 |
| 666 |
assert x.connparams['socket_connect_timeout'] == 100.0 |
| 667 |
assert x.connparams['ssl_cert_reqs'] == ssl.CERT_REQUIRED |
| 668 |
assert x.connparams['ssl_ca_certs'] == '/path/to/ca.crt' |
| 669 |
assert x.connparams['ssl_certfile'] == '/path/to/client.crt' |
| 670 |
assert x.connparams['ssl_keyfile'] == '/path/to/client.key' |
| 671 |
|
| 672 |
from redis.connection import SSLConnection |
| 673 |
assert x.connparams['connection_class'] is SSLConnection |
| 674 |
|
| 675 |
@pytest.mark.parametrize('cert_str', [ |
| 676 |
"required", |
| 677 |
"CERT_REQUIRED", |
| 678 |
]) |
| 679 |
def test_backend_ssl_url(self, cert_str): |
| 680 |
pytest.importorskip('redis') |
| 681 |
|
| 682 |
self.app.conf.redis_socket_timeout = 30.0 |
| 683 |
self.app.conf.redis_socket_connect_timeout = 100.0 |
| 684 |
x = self.Backend( |
| 685 |
'rediss://:[email protected]:123//1?ssl_cert_reqs=%s' % cert_str, |
| 686 |
app=self.app, |
| 687 |
) |
| 688 |
assert x.connparams |
| 689 |
assert x.connparams['host'] == 'vandelay.com' |
| 690 |
assert x.connparams['db'] == 1 |
| 691 |
assert x.connparams['port'] == 123 |
| 692 |
assert x.connparams['password'] == 'bosco' |
| 693 |
assert x.connparams['socket_timeout'] == 30.0 |
| 694 |
assert x.connparams['socket_connect_timeout'] == 100.0 |
| 695 |
assert x.connparams['ssl_cert_reqs'] == ssl.CERT_REQUIRED |
| 696 |
|
| 697 |
from redis.connection import SSLConnection |
| 698 |
assert x.connparams['connection_class'] is SSLConnection |
| 699 |
|
| 700 |
@pytest.mark.parametrize('cert_str', [ |
| 701 |
"none", |
| 702 |
"CERT_NONE", |
| 703 |
]) |
| 704 |
def test_backend_ssl_url_options(self, cert_str): |
| 705 |
pytest.importorskip('redis') |
| 706 |
|
| 707 |
x = self.Backend( |
| 708 |
( |
| 709 |
'rediss://:[email protected]:123//1' |
| 710 |
'?ssl_cert_reqs={cert_str}' |
| 711 |
'&ssl_ca_certs=%2Fvar%2Fssl%2Fmyca.pem' |
| 712 |
'&ssl_certfile=%2Fvar%2Fssl%2Fredis-server-cert.pem' |
| 713 |
'&ssl_keyfile=%2Fvar%2Fssl%2Fprivate%2Fworker-key.pem' |
| 714 |
).format(cert_str=cert_str), |
| 715 |
app=self.app, |
| 716 |
) |
| 717 |
assert x.connparams |
| 718 |
assert x.connparams['host'] == 'vandelay.com' |
| 719 |
assert x.connparams['db'] == 1 |
| 720 |
assert x.connparams['port'] == 123 |
| 721 |
assert x.connparams['password'] == 'bosco' |
| 722 |
assert x.connparams['ssl_cert_reqs'] == ssl.CERT_NONE |
| 723 |
assert x.connparams['ssl_ca_certs'] == '/var/ssl/myca.pem' |
| 724 |
assert x.connparams['ssl_certfile'] == '/var/ssl/redis-server-cert.pem' |
| 725 |
assert x.connparams['ssl_keyfile'] == '/var/ssl/private/worker-key.pem' |
| 726 |
|
| 727 |
@pytest.mark.parametrize('cert_str', [ |
| 728 |
"optional", |
| 729 |
"CERT_OPTIONAL", |
| 730 |
]) |
| 731 |
def test_backend_ssl_url_cert_none(self, cert_str): |
| 732 |
pytest.importorskip('redis') |
| 733 |
|
| 734 |
x = self.Backend( |
| 735 |
'rediss://:[email protected]:123//1?ssl_cert_reqs=%s' % cert_str, |
| 736 |
app=self.app, |
| 737 |
) |
| 738 |
assert x.connparams |
| 739 |
assert x.connparams['host'] == 'vandelay.com' |
| 740 |
assert x.connparams['db'] == 1 |
| 741 |
assert x.connparams['port'] == 123 |
| 742 |
assert x.connparams['ssl_cert_reqs'] == ssl.CERT_OPTIONAL |
| 743 |
|
| 744 |
from redis.connection import SSLConnection |
| 745 |
assert x.connparams['connection_class'] is SSLConnection |
| 746 |
|
| 747 |
@pytest.mark.parametrize("uri", [ |
| 748 |
'rediss://:[email protected]:123//1?ssl_cert_reqs=CERT_KITTY_CATS', |
| 749 |
'rediss://:[email protected]:123//1' |
| 750 |
]) |
| 751 |
def test_backend_ssl_url_invalid(self, uri): |
| 752 |
pytest.importorskip('redis') |
| 753 |
|
| 754 |
with pytest.raises(ValueError): |
| 755 |
self.Backend( |
| 756 |
uri, |
| 757 |
app=self.app, |
| 758 |
) |
| 759 |
|
| 760 |
def test_conf_raises_KeyError(self): |
| 761 |
self.app.conf = AttributeDict({ |
| 762 |
'result_serializer': 'json', |
| 763 |
'result_cache_max': 1, |
| 764 |
'result_expires': None, |
| 765 |
'accept_content': ['json'], |
| 766 |
'result_accept_content': ['json'], |
| 767 |
}) |
| 768 |
self.Backend(app=self.app) |
| 769 |
|
| 770 |
@patch('celery.backends.redis.logger') |
| 771 |
def test_on_connection_error(self, logger): |
| 772 |
intervals = iter([10, 20, 30]) |
| 773 |
exc = KeyError() |
| 774 |
assert self.b.on_connection_error(None, exc, intervals, 1) == 10 |
| 775 |
logger.error.assert_called_with( |
| 776 |
self.E_LOST, 1, 'Inf', 'in 10.00 seconds') |
| 777 |
assert self.b.on_connection_error(10, exc, intervals, 2) == 20 |
| 778 |
logger.error.assert_called_with(self.E_LOST, 2, 10, 'in 20.00 seconds') |
| 779 |
assert self.b.on_connection_error(10, exc, intervals, 3) == 30 |
| 780 |
logger.error.assert_called_with(self.E_LOST, 3, 10, 'in 30.00 seconds') |
| 781 |
|
| 782 |
@patch('celery.backends.redis.retry_over_time') |
| 783 |
def test_retry_policy_conf(self, retry_over_time): |
| 784 |
self.app.conf.result_backend_transport_options = dict( |
| 785 |
retry_policy=dict( |
| 786 |
max_retries=2, |
| 787 |
interval_start=0, |
| 788 |
interval_step=0.01, |
| 789 |
), |
| 790 |
) |
| 791 |
b = self.Backend(app=self.app) |
| 792 |
|
| 793 |
def fn(): |
| 794 |
return 1 |
| 795 |
|
| 796 |
# We don't want to re-test retry_over_time, just check we called it |
| 797 |
# with the expected args |
| 798 |
b.ensure(fn, (),) |
| 799 |
|
| 800 |
retry_over_time.assert_called_with( |
| 801 |
fn, b.connection_errors, (), {}, ANY, |
| 802 |
max_retries=2, interval_start=0, interval_step=0.01, interval_max=1 |
| 803 |
) |
| 804 |
|
| 805 |
def test_exception_safe_to_retry(self): |
| 806 |
b = self.Backend(app=self.app) |
| 807 |
assert not b.exception_safe_to_retry(Exception("failed")) |
| 808 |
assert not b.exception_safe_to_retry(BaseException("failed")) |
| 809 |
assert not b.exception_safe_to_retry(exceptions.RedisError("redis error")) |
| 810 |
assert b.exception_safe_to_retry(exceptions.ConnectionError("service unavailable")) |
| 811 |
assert b.exception_safe_to_retry(exceptions.TimeoutError("timeout")) |
| 812 |
|
| 813 |
def test_incr(self): |
| 814 |
self.b.client = Mock(name='client') |
| 815 |
self.b.incr('foo') |
| 816 |
self.b.client.incr.assert_called_with('foo') |
| 817 |
|
| 818 |
def test_expire(self): |
| 819 |
self.b.client = Mock(name='client') |
| 820 |
self.b.expire('foo', 300) |
| 821 |
self.b.client.expire.assert_called_with('foo', 300) |
| 822 |
|
| 823 |
def test_apply_chord(self, unlock='celery.chord_unlock'): |
| 824 |
self.app.tasks[unlock] = Mock() |
| 825 |
header_result_args = ( |
| 826 |
uuid(), |
| 827 |
[self.app.AsyncResult(x) for x in range(3)], |
| 828 |
) |
| 829 |
self.b.apply_chord(header_result_args, None) |
| 830 |
assert self.app.tasks[unlock].apply_async.call_count == 0 |
| 831 |
|
| 832 |
def test_unpack_chord_result(self): |
| 833 |
self.b.exception_to_python = Mock(name='etp') |
| 834 |
decode = Mock(name='decode') |
| 835 |
exc = KeyError() |
| 836 |
tup = decode.return_value = (1, 'id1', states.FAILURE, exc) |
| 837 |
with pytest.raises(ChordError): |
| 838 |
self.b._unpack_chord_result(tup, decode) |
| 839 |
decode.assert_called_with(tup) |
| 840 |
self.b.exception_to_python.assert_called_with(exc) |
| 841 |
|
| 842 |
exc = ValueError() |
| 843 |
tup = decode.return_value = (2, 'id2', states.RETRY, exc) |
| 844 |
ret = self.b._unpack_chord_result(tup, decode) |
| 845 |
self.b.exception_to_python.assert_called_with(exc) |
| 846 |
assert ret is self.b.exception_to_python() |
| 847 |
|
| 848 |
def test_on_chord_part_return_no_gid_or_tid(self): |
| 849 |
request = Mock(name='request') |
| 850 |
request.id = request.group = request.group_index = None |
| 851 |
assert self.b.on_chord_part_return(request, 'SUCCESS', 10) is None |
| 852 |
|
| 853 |
def test_ConnectionPool(self): |
| 854 |
self.b.redis = Mock(name='redis') |
| 855 |
assert self.b._ConnectionPool is None |
| 856 |
assert self.b.ConnectionPool is self.b.redis.ConnectionPool |
| 857 |
assert self.b.ConnectionPool is self.b.redis.ConnectionPool |
| 858 |
|
| 859 |
def test_expires_defaults_to_config(self): |
| 860 |
self.app.conf.result_expires = 10 |
| 861 |
b = self.Backend(expires=None, app=self.app) |
| 862 |
assert b.expires == 10 |
| 863 |
|
| 864 |
def test_expires_is_int(self): |
| 865 |
b = self.Backend(expires=48, app=self.app) |
| 866 |
assert b.expires == 48 |
| 867 |
|
| 868 |
def test_add_to_chord(self): |
| 869 |
b = self.Backend('redis://', app=self.app) |
| 870 |
gid = uuid() |
| 871 |
b.add_to_chord(gid, 'sig') |
| 872 |
b.client.incr.assert_called_with(b.get_key_for_group(gid, '.t'), 1) |
| 873 |
|
| 874 |
def test_set_chord_size(self): |
| 875 |
b = self.Backend('redis://', app=self.app) |
| 876 |
gid = uuid() |
| 877 |
b.set_chord_size(gid, 10) |
| 878 |
b.client.set.assert_called_with(b.get_key_for_group(gid, '.s'), 10) |
| 879 |
|
| 880 |
def test_expires_is_None(self): |
| 881 |
b = self.Backend(expires=None, app=self.app) |
| 882 |
assert b.expires == self.app.conf.result_expires.total_seconds() |
| 883 |
|
| 884 |
def test_expires_is_timedelta(self): |
| 885 |
b = self.Backend(expires=timedelta(minutes=1), app=self.app) |
| 886 |
assert b.expires == 60 |
| 887 |
|
| 888 |
def test_mget(self): |
| 889 |
assert self.b.mget(['a', 'b', 'c']) |
| 890 |
self.b.client.mget.assert_called_with(['a', 'b', 'c']) |
| 891 |
|
| 892 |
def test_set_no_expire(self): |
| 893 |
self.b.expires = None |
| 894 |
self.b._set_with_state('foo', 'bar', states.SUCCESS) |
| 895 |
|
| 896 |
def test_process_cleanup(self): |
| 897 |
self.b.process_cleanup() |
| 898 |
|
| 899 |
def test_get_set_forget(self): |
| 900 |
tid = uuid() |
| 901 |
self.b.store_result(tid, 42, states.SUCCESS) |
| 902 |
assert self.b.get_state(tid) == states.SUCCESS |
| 903 |
assert self.b.get_result(tid) == 42 |
| 904 |
self.b.forget(tid) |
| 905 |
assert self.b.get_state(tid) == states.PENDING |
| 906 |
|
| 907 |
def test_set_expires(self): |
| 908 |
self.b = self.Backend(expires=512, app=self.app) |
| 909 |
tid = uuid() |
| 910 |
key = self.b.get_key_for_task(tid) |
| 911 |
self.b.store_result(tid, 42, states.SUCCESS) |
| 912 |
self.b.client.expire.assert_called_with( |
| 913 |
key, 512, |
| 914 |
) |
| 915 |
|
| 916 |
def test_set_raises_error_on_large_value(self): |
| 917 |
with pytest.raises(BackendStoreError): |
| 918 |
self.b.set('key', 'x' * (self.b._MAX_STR_VALUE_SIZE + 1)) |
| 919 |
|
| 920 |
|
| 921 |
class test_RedisBackend_chords_simple(basetest_RedisBackend): |
| 922 |
@pytest.fixture(scope="class", autouse=True) |
| 923 |
def simple_header_result(self): |
| 924 |
with patch( |
| 925 |
"celery.result.GroupResult.restore", return_value=None, |
| 926 |
) as p: |
| 927 |
yield p |
| 928 |
|
| 929 |
def test_on_chord_part_return(self): |
| 930 |
tasks = [self.create_task(i) for i in range(10)] |
| 931 |
random.shuffle(tasks) |
| 932 |
|
| 933 |
for i in range(10): |
| 934 |
self.b.on_chord_part_return(tasks[i].request, states.SUCCESS, i) |
| 935 |
assert self.b.client.zadd.call_count |
| 936 |
self.b.client.zadd.reset_mock() |
| 937 |
assert self.b.client.zrangebyscore.call_count |
| 938 |
jkey = self.b.get_key_for_group('group_id', '.j') |
| 939 |
tkey = self.b.get_key_for_group('group_id', '.t') |
| 940 |
skey = self.b.get_key_for_group('group_id', '.s') |
| 941 |
self.b.client.delete.assert_has_calls([call(jkey), call(tkey), call(skey)]) |
| 942 |
self.b.client.expire.assert_has_calls([ |
| 943 |
call(jkey, 86400), call(tkey, 86400), call(skey, 86400), |
| 944 |
]) |
| 945 |
|
| 946 |
def test_on_chord_part_return__unordered(self): |
| 947 |
self.app.conf.result_backend_transport_options = dict( |
| 948 |
result_chord_ordered=False, |
| 949 |
) |
| 950 |
|
| 951 |
tasks = [self.create_task(i) for i in range(10)] |
| 952 |
random.shuffle(tasks) |
| 953 |
|
| 954 |
for i in range(10): |
| 955 |
self.b.on_chord_part_return(tasks[i].request, states.SUCCESS, i) |
| 956 |
assert self.b.client.rpush.call_count |
| 957 |
self.b.client.rpush.reset_mock() |
| 958 |
assert self.b.client.lrange.call_count |
| 959 |
jkey = self.b.get_key_for_group('group_id', '.j') |
| 960 |
tkey = self.b.get_key_for_group('group_id', '.t') |
| 961 |
self.b.client.delete.assert_has_calls([call(jkey), call(tkey)]) |
| 962 |
self.b.client.expire.assert_has_calls([ |
| 963 |
call(jkey, 86400), call(tkey, 86400), |
| 964 |
]) |
| 965 |
|
| 966 |
def test_on_chord_part_return__ordered(self): |
| 967 |
self.app.conf.result_backend_transport_options = dict( |
| 968 |
result_chord_ordered=True, |
| 969 |
) |
| 970 |
|
| 971 |
tasks = [self.create_task(i) for i in range(10)] |
| 972 |
random.shuffle(tasks) |
| 973 |
|
| 974 |
for i in range(10): |
| 975 |
self.b.on_chord_part_return(tasks[i].request, states.SUCCESS, i) |
| 976 |
assert self.b.client.zadd.call_count |
| 977 |
self.b.client.zadd.reset_mock() |
| 978 |
assert self.b.client.zrangebyscore.call_count |
| 979 |
jkey = self.b.get_key_for_group('group_id', '.j') |
| 980 |
tkey = self.b.get_key_for_group('group_id', '.t') |
| 981 |
self.b.client.delete.assert_has_calls([call(jkey), call(tkey)]) |
| 982 |
self.b.client.expire.assert_has_calls([ |
| 983 |
call(jkey, 86400), call(tkey, 86400), |
| 984 |
]) |
| 985 |
|
| 986 |
def test_on_chord_part_return_no_expiry(self): |
| 987 |
old_expires = self.b.expires |
| 988 |
self.b.expires = None |
| 989 |
tasks = [self.create_task(i) for i in range(10)] |
| 990 |
self.b.set_chord_size('group_id', 10) |
| 991 |
|
| 992 |
for i in range(10): |
| 993 |
self.b.on_chord_part_return(tasks[i].request, states.SUCCESS, i) |
| 994 |
assert self.b.client.zadd.call_count |
| 995 |
self.b.client.zadd.reset_mock() |
| 996 |
assert self.b.client.zrangebyscore.call_count |
| 997 |
jkey = self.b.get_key_for_group('group_id', '.j') |
| 998 |
tkey = self.b.get_key_for_group('group_id', '.t') |
| 999 |
self.b.client.delete.assert_has_calls([call(jkey), call(tkey)]) |
| 1000 |
self.b.client.expire.assert_not_called() |
| 1001 |
|
| 1002 |
self.b.expires = old_expires |
| 1003 |
|
| 1004 |
def test_on_chord_part_return_expire_set_to_zero(self): |
| 1005 |
old_expires = self.b.expires |
| 1006 |
self.b.expires = 0 |
| 1007 |
tasks = [self.create_task(i) for i in range(10)] |
| 1008 |
|
| 1009 |
for i in range(10): |
| 1010 |
self.b.on_chord_part_return(tasks[i].request, states.SUCCESS, i) |
| 1011 |
assert self.b.client.zadd.call_count |
| 1012 |
self.b.client.zadd.reset_mock() |
| 1013 |
assert self.b.client.zrangebyscore.call_count |
| 1014 |
jkey = self.b.get_key_for_group('group_id', '.j') |
| 1015 |
tkey = self.b.get_key_for_group('group_id', '.t') |
| 1016 |
self.b.client.delete.assert_has_calls([call(jkey), call(tkey)]) |
| 1017 |
self.b.client.expire.assert_not_called() |
| 1018 |
|
| 1019 |
self.b.expires = old_expires |
| 1020 |
|
| 1021 |
def test_on_chord_part_return_no_expiry__unordered(self): |
| 1022 |
self.app.conf.result_backend_transport_options = dict( |
| 1023 |
result_chord_ordered=False, |
| 1024 |
) |
| 1025 |
|
| 1026 |
old_expires = self.b.expires |
| 1027 |
self.b.expires = None |
| 1028 |
tasks = [self.create_task(i) for i in range(10)] |
| 1029 |
|
| 1030 |
for i in range(10): |
| 1031 |
self.b.on_chord_part_return(tasks[i].request, states.SUCCESS, i) |
| 1032 |
assert self.b.client.rpush.call_count |
| 1033 |
self.b.client.rpush.reset_mock() |
| 1034 |
assert self.b.client.lrange.call_count |
| 1035 |
jkey = self.b.get_key_for_group('group_id', '.j') |
| 1036 |
tkey = self.b.get_key_for_group('group_id', '.t') |
| 1037 |
self.b.client.delete.assert_has_calls([call(jkey), call(tkey)]) |
| 1038 |
self.b.client.expire.assert_not_called() |
| 1039 |
|
| 1040 |
self.b.expires = old_expires |
| 1041 |
|
| 1042 |
def test_on_chord_part_return_no_expiry__ordered(self): |
| 1043 |
self.app.conf.result_backend_transport_options = dict( |
| 1044 |
result_chord_ordered=True, |
| 1045 |
) |
| 1046 |
|
| 1047 |
old_expires = self.b.expires |
| 1048 |
self.b.expires = None |
| 1049 |
tasks = [self.create_task(i) for i in range(10)] |
| 1050 |
|
| 1051 |
for i in range(10): |
| 1052 |
self.b.on_chord_part_return(tasks[i].request, states.SUCCESS, i) |
| 1053 |
assert self.b.client.zadd.call_count |
| 1054 |
self.b.client.zadd.reset_mock() |
| 1055 |
assert self.b.client.zrangebyscore.call_count |
| 1056 |
jkey = self.b.get_key_for_group('group_id', '.j') |
| 1057 |
tkey = self.b.get_key_for_group('group_id', '.t') |
| 1058 |
self.b.client.delete.assert_has_calls([call(jkey), call(tkey)]) |
| 1059 |
self.b.client.expire.assert_not_called() |
| 1060 |
|
| 1061 |
self.b.expires = old_expires |
| 1062 |
|
| 1063 |
def test_on_chord_part_return__success(self): |
| 1064 |
with self.chord_context(2) as (_, request, callback): |
| 1065 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1066 |
callback.delay.assert_not_called() |
| 1067 |
self.b.on_chord_part_return(request, states.SUCCESS, 20) |
| 1068 |
callback.delay.assert_called_with([10, 20]) |
| 1069 |
|
| 1070 |
def test_on_chord_part_return__success__unordered(self): |
| 1071 |
self.app.conf.result_backend_transport_options = dict( |
| 1072 |
result_chord_ordered=False, |
| 1073 |
) |
| 1074 |
|
| 1075 |
with self.chord_context(2) as (_, request, callback): |
| 1076 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1077 |
callback.delay.assert_not_called() |
| 1078 |
self.b.on_chord_part_return(request, states.SUCCESS, 20) |
| 1079 |
callback.delay.assert_called_with([10, 20]) |
| 1080 |
|
| 1081 |
def test_on_chord_part_return__success__ordered(self): |
| 1082 |
self.app.conf.result_backend_transport_options = dict( |
| 1083 |
result_chord_ordered=True, |
| 1084 |
) |
| 1085 |
|
| 1086 |
with self.chord_context(2) as (_, request, callback): |
| 1087 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1088 |
callback.delay.assert_not_called() |
| 1089 |
self.b.on_chord_part_return(request, states.SUCCESS, 20) |
| 1090 |
callback.delay.assert_called_with([10, 20]) |
| 1091 |
|
| 1092 |
def test_on_chord_part_return__callback_raises(self): |
| 1093 |
with self.chord_context(1) as (_, request, callback): |
| 1094 |
callback.delay.side_effect = KeyError(10) |
| 1095 |
task = self.app._tasks['add'] = Mock(name='add_task') |
| 1096 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1097 |
task.backend.fail_from_current_stack.assert_called_with( |
| 1098 |
callback.id, exc=ANY, |
| 1099 |
) |
| 1100 |
|
| 1101 |
def test_on_chord_part_return__callback_raises__unordered(self): |
| 1102 |
self.app.conf.result_backend_transport_options = dict( |
| 1103 |
result_chord_ordered=False, |
| 1104 |
) |
| 1105 |
|
| 1106 |
with self.chord_context(1) as (_, request, callback): |
| 1107 |
callback.delay.side_effect = KeyError(10) |
| 1108 |
task = self.app._tasks['add'] = Mock(name='add_task') |
| 1109 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1110 |
task.backend.fail_from_current_stack.assert_called_with( |
| 1111 |
callback.id, exc=ANY, |
| 1112 |
) |
| 1113 |
|
| 1114 |
def test_on_chord_part_return__callback_raises__ordered(self): |
| 1115 |
self.app.conf.result_backend_transport_options = dict( |
| 1116 |
result_chord_ordered=True, |
| 1117 |
) |
| 1118 |
|
| 1119 |
with self.chord_context(1) as (_, request, callback): |
| 1120 |
callback.delay.side_effect = KeyError(10) |
| 1121 |
task = self.app._tasks['add'] = Mock(name='add_task') |
| 1122 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1123 |
task.backend.fail_from_current_stack.assert_called_with( |
| 1124 |
callback.id, exc=ANY, |
| 1125 |
) |
| 1126 |
|
| 1127 |
def test_on_chord_part_return__ChordError(self): |
| 1128 |
with self.chord_context(1) as (_, request, callback): |
| 1129 |
self.b.client.pipeline = ContextMock() |
| 1130 |
raise_on_second_call(self.b.client.pipeline, ChordError()) |
| 1131 |
self.b.client.pipeline.return_value.zadd().zcount().get().get().expire( |
| 1132 |
).expire().expire().execute.return_value = (1, 1, 0, b'1', 4, 5, 6) |
| 1133 |
task = self.app._tasks['add'] = Mock(name='add_task') |
| 1134 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1135 |
task.backend.fail_from_current_stack.assert_called_with( |
| 1136 |
callback.id, exc=ANY, |
| 1137 |
) |
| 1138 |
|
| 1139 |
def test_on_chord_part_return__ChordError__unordered(self): |
| 1140 |
self.app.conf.result_backend_transport_options = dict( |
| 1141 |
result_chord_ordered=False, |
| 1142 |
) |
| 1143 |
|
| 1144 |
with self.chord_context(1) as (_, request, callback): |
| 1145 |
self.b.client.pipeline = ContextMock() |
| 1146 |
raise_on_second_call(self.b.client.pipeline, ChordError()) |
| 1147 |
self.b.client.pipeline.return_value.rpush().llen().get().get().expire( |
| 1148 |
).expire().expire().execute.return_value = (1, 1, 0, b'1', 4, 5, 6) |
| 1149 |
task = self.app._tasks['add'] = Mock(name='add_task') |
| 1150 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1151 |
task.backend.fail_from_current_stack.assert_called_with( |
| 1152 |
callback.id, exc=ANY, |
| 1153 |
) |
| 1154 |
|
| 1155 |
def test_on_chord_part_return__ChordError__ordered(self): |
| 1156 |
self.app.conf.result_backend_transport_options = dict( |
| 1157 |
result_chord_ordered=True, |
| 1158 |
) |
| 1159 |
|
| 1160 |
with self.chord_context(1) as (_, request, callback): |
| 1161 |
self.b.client.pipeline = ContextMock() |
| 1162 |
raise_on_second_call(self.b.client.pipeline, ChordError()) |
| 1163 |
self.b.client.pipeline.return_value.zadd().zcount().get().get().expire( |
| 1164 |
).expire().expire().execute.return_value = (1, 1, 0, b'1', 4, 5, 6) |
| 1165 |
task = self.app._tasks['add'] = Mock(name='add_task') |
| 1166 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1167 |
task.backend.fail_from_current_stack.assert_called_with( |
| 1168 |
callback.id, exc=ANY, |
| 1169 |
) |
| 1170 |
|
| 1171 |
def test_on_chord_part_return__other_error(self): |
| 1172 |
with self.chord_context(1) as (_, request, callback): |
| 1173 |
self.b.client.pipeline = ContextMock() |
| 1174 |
raise_on_second_call(self.b.client.pipeline, RuntimeError()) |
| 1175 |
self.b.client.pipeline.return_value.zadd().zcount().get().get().expire( |
| 1176 |
).expire().expire().execute.return_value = (1, 1, 0, b'1', 4, 5, 6) |
| 1177 |
task = self.app._tasks['add'] = Mock(name='add_task') |
| 1178 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1179 |
task.backend.fail_from_current_stack.assert_called_with( |
| 1180 |
callback.id, exc=ANY, |
| 1181 |
) |
| 1182 |
|
| 1183 |
def test_on_chord_part_return__other_error__unordered(self): |
| 1184 |
self.app.conf.result_backend_transport_options = dict( |
| 1185 |
result_chord_ordered=False, |
| 1186 |
) |
| 1187 |
|
| 1188 |
with self.chord_context(1) as (_, request, callback): |
| 1189 |
self.b.client.pipeline = ContextMock() |
| 1190 |
raise_on_second_call(self.b.client.pipeline, RuntimeError()) |
| 1191 |
self.b.client.pipeline.return_value.rpush().llen().get().get().expire( |
| 1192 |
).expire().expire().execute.return_value = (1, 1, 0, b'1', 4, 5, 6) |
| 1193 |
task = self.app._tasks['add'] = Mock(name='add_task') |
| 1194 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1195 |
task.backend.fail_from_current_stack.assert_called_with( |
| 1196 |
callback.id, exc=ANY, |
| 1197 |
) |
| 1198 |
|
| 1199 |
def test_on_chord_part_return__other_error__ordered(self): |
| 1200 |
self.app.conf.result_backend_transport_options = dict( |
| 1201 |
result_chord_ordered=True, |
| 1202 |
) |
| 1203 |
|
| 1204 |
with self.chord_context(1) as (_, request, callback): |
| 1205 |
self.b.client.pipeline = ContextMock() |
| 1206 |
raise_on_second_call(self.b.client.pipeline, RuntimeError()) |
| 1207 |
self.b.client.pipeline.return_value.zadd().zcount().get().get().expire( |
| 1208 |
).expire().expire().execute.return_value = (1, 1, 0, b'1', 4, 5, 6) |
| 1209 |
task = self.app._tasks['add'] = Mock(name='add_task') |
| 1210 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1211 |
task.backend.fail_from_current_stack.assert_called_with( |
| 1212 |
callback.id, exc=ANY, |
| 1213 |
) |
| 1214 |
|
| 1215 |
|
| 1216 |
class test_RedisBackend_chords_complex(basetest_RedisBackend): |
| 1217 |
@pytest.fixture(scope="function", autouse=True) |
| 1218 |
def complex_header_result(self): |
| 1219 |
with patch("celery.result.GroupResult.restore") as p: |
| 1220 |
yield p |
| 1221 |
|
| 1222 |
@pytest.mark.parametrize(['results', 'assert_save_called'], [ |
| 1223 |
# No results in the header at all - won't call `save()` |
| 1224 |
(tuple(), False), |
| 1225 |
# Simple results in the header - won't call `save()` |
| 1226 |
((AsyncResult("foo"), ), False), |
| 1227 |
# Many simple results in the header - won't call `save()` |
| 1228 |
((AsyncResult("foo"), ) * 42, False), |
| 1229 |
# A single complex result in the header - will call `save()` |
| 1230 |
((GroupResult("foo", []),), True), |
| 1231 |
# Many complex results in the header - will call `save()` |
| 1232 |
((GroupResult("foo"), ) * 42, True), |
| 1233 |
# Mixed simple and complex results in the header - will call `save()` |
| 1234 |
(itertools.islice( |
| 1235 |
itertools.cycle(( |
| 1236 |
AsyncResult("foo"), GroupResult("foo"), |
| 1237 |
)), 42, |
| 1238 |
), True), |
| 1239 |
]) |
| 1240 |
def test_apply_chord_complex_header(self, results, assert_save_called): |
| 1241 |
mock_group_result = Mock() |
| 1242 |
mock_group_result.return_value.results = results |
| 1243 |
self.app.GroupResult = mock_group_result |
| 1244 |
header_result_args = ("gid11", results) |
| 1245 |
self.b.apply_chord(header_result_args, None) |
| 1246 |
if assert_save_called: |
| 1247 |
mock_group_result.return_value.save.assert_called_once_with(backend=self.b) |
| 1248 |
else: |
| 1249 |
mock_group_result.return_value.save.assert_not_called() |
| 1250 |
|
| 1251 |
def test_on_chord_part_return_timeout(self, complex_header_result): |
| 1252 |
tasks = [self.create_task(i) for i in range(10)] |
| 1253 |
random.shuffle(tasks) |
| 1254 |
try: |
| 1255 |
self.app.conf.result_chord_join_timeout += 1.0 |
| 1256 |
for task, result_val in zip(tasks, itertools.cycle((42, ))): |
| 1257 |
self.b.on_chord_part_return( |
| 1258 |
task.request, states.SUCCESS, result_val, |
| 1259 |
) |
| 1260 |
finally: |
| 1261 |
self.app.conf.result_chord_join_timeout -= 1.0 |
| 1262 |
|
| 1263 |
join_func = complex_header_result.return_value.join_native |
| 1264 |
join_func.assert_called_once_with(timeout=4.0, propagate=True) |
| 1265 |
|
| 1266 |
@pytest.mark.parametrize("supports_native_join", (True, False)) |
| 1267 |
def test_on_chord_part_return( |
| 1268 |
self, complex_header_result, supports_native_join, |
| 1269 |
): |
| 1270 |
mock_result_obj = complex_header_result.return_value |
| 1271 |
mock_result_obj.supports_native_join = supports_native_join |
| 1272 |
|
| 1273 |
tasks = [self.create_task(i) for i in range(10)] |
| 1274 |
random.shuffle(tasks) |
| 1275 |
|
| 1276 |
with self.chord_context(10) as (tasks, request, callback): |
| 1277 |
for task, result_val in zip(tasks, itertools.cycle((42, ))): |
| 1278 |
self.b.on_chord_part_return( |
| 1279 |
task.request, states.SUCCESS, result_val, |
| 1280 |
) |
| 1281 |
# Confirm that `zadd` was called even though we won't end up |
| 1282 |
# using the data pushed into the sorted set |
| 1283 |
assert self.b.client.zadd.call_count == 1 |
| 1284 |
self.b.client.zadd.reset_mock() |
| 1285 |
# Confirm that neither `zrange` not `lrange` were called |
| 1286 |
self.b.client.zrange.assert_not_called() |
| 1287 |
self.b.client.lrange.assert_not_called() |
| 1288 |
# Confirm that the `GroupResult.restore` mock was called |
| 1289 |
complex_header_result.assert_called_once_with(request.group, app=self.b.app) |
| 1290 |
# Confirm that the callback was called with the `join()`ed group result |
| 1291 |
if supports_native_join: |
| 1292 |
expected_join = mock_result_obj.join_native |
| 1293 |
else: |
| 1294 |
expected_join = mock_result_obj.join |
| 1295 |
callback.delay.assert_called_once_with(expected_join()) |
| 1296 |
|
| 1297 |
|
| 1298 |
class test_SentinelBackend: |
| 1299 |
def get_backend(self): |
| 1300 |
from celery.backends.redis import SentinelBackend |
| 1301 |
|
| 1302 |
class _SentinelBackend(SentinelBackend): |
| 1303 |
redis = redis |
| 1304 |
sentinel = sentinel |
| 1305 |
|
| 1306 |
return _SentinelBackend |
| 1307 |
|
| 1308 |
def get_E_LOST(self): |
| 1309 |
from celery.backends.redis import E_LOST |
| 1310 |
return E_LOST |
| 1311 |
|
| 1312 |
def setup_method(self): |
| 1313 |
self.Backend = self.get_backend() |
| 1314 |
self.E_LOST = self.get_E_LOST() |
| 1315 |
self.b = self.Backend(app=self.app) |
| 1316 |
|
| 1317 |
@pytest.mark.usefixtures('depends_on_current_app') |
| 1318 |
def test_reduce(self): |
| 1319 |
pytest.importorskip('redis') |
| 1320 |
|
| 1321 |
from celery.backends.redis import SentinelBackend |
| 1322 |
x = SentinelBackend(app=self.app) |
| 1323 |
assert loads(dumps(x)) |
| 1324 |
|
| 1325 |
def test_no_redis(self): |
| 1326 |
self.Backend.redis = None |
| 1327 |
with pytest.raises(ImproperlyConfigured): |
| 1328 |
self.Backend(app=self.app) |
| 1329 |
|
| 1330 |
def test_url(self): |
| 1331 |
self.app.conf.redis_socket_timeout = 30.0 |
| 1332 |
self.app.conf.redis_socket_connect_timeout = 100.0 |
| 1333 |
x = self.Backend( |
| 1334 |
'sentinel://:[email protected]:123/1;' |
| 1335 |
'sentinel://:[email protected]:124/1', |
| 1336 |
app=self.app, |
| 1337 |
) |
| 1338 |
assert x.connparams |
| 1339 |
assert "host" not in x.connparams |
| 1340 |
assert x.connparams['db'] == 1 |
| 1341 |
assert "port" not in x.connparams |
| 1342 |
assert x.connparams['password'] == "test" |
| 1343 |
assert len(x.connparams['hosts']) == 2 |
| 1344 |
expected_hosts = ["github.com", "github.com"] |
| 1345 |
found_hosts = [cp['host'] for cp in x.connparams['hosts']] |
| 1346 |
assert found_hosts == expected_hosts |
| 1347 |
|
| 1348 |
expected_ports = [123, 124] |
| 1349 |
found_ports = [cp['port'] for cp in x.connparams['hosts']] |
| 1350 |
assert found_ports == expected_ports |
| 1351 |
|
| 1352 |
expected_passwords = ["test", "test"] |
| 1353 |
found_passwords = [cp['password'] for cp in x.connparams['hosts']] |
| 1354 |
assert found_passwords == expected_passwords |
| 1355 |
|
| 1356 |
expected_dbs = [1, 1] |
| 1357 |
found_dbs = [cp['db'] for cp in x.connparams['hosts']] |
| 1358 |
assert found_dbs == expected_dbs |
| 1359 |
|
| 1360 |
# By default passwords should be sanitized |
| 1361 |
display_url = x.as_uri() |
| 1362 |
assert "test" not in display_url |
| 1363 |
# We can choose not to sanitize with the `include_password` argument |
| 1364 |
unsanitized_display_url = x.as_uri(include_password=True) |
| 1365 |
assert unsanitized_display_url == x.url |
| 1366 |
# or to explicitly sanitize |
| 1367 |
forcibly_sanitized_display_url = x.as_uri(include_password=False) |
| 1368 |
assert forcibly_sanitized_display_url == display_url |
| 1369 |
|
| 1370 |
def test_get_sentinel_instance(self): |
| 1371 |
x = self.Backend( |
| 1372 |
'sentinel://:[email protected]:123/1;' |
| 1373 |
'sentinel://:[email protected]:124/1', |
| 1374 |
app=self.app, |
| 1375 |
) |
| 1376 |
sentinel_instance = x._get_sentinel_instance(**x.connparams) |
| 1377 |
assert sentinel_instance.sentinel_kwargs == {} |
| 1378 |
assert sentinel_instance.connection_kwargs['db'] == 1 |
| 1379 |
assert sentinel_instance.connection_kwargs['password'] == "test" |
| 1380 |
assert len(sentinel_instance.sentinels) == 2 |
| 1381 |
|
| 1382 |
def test_get_pool(self): |
| 1383 |
x = self.Backend( |
| 1384 |
'sentinel://:[email protected]:123/1;' |
| 1385 |
'sentinel://:[email protected]:124/1', |
| 1386 |
app=self.app, |
| 1387 |
) |
| 1388 |
pool = x._get_pool(**x.connparams) |
| 1389 |
assert pool |
| 1390 |
|
| 1391 |
def test_backend_ssl(self): |
| 1392 |
pytest.importorskip('redis') |
| 1393 |
|
| 1394 |
from celery.backends.redis import SentinelBackend |
| 1395 |
self.app.conf.redis_backend_use_ssl = { |
| 1396 |
'ssl_cert_reqs': "CERT_REQUIRED", |
| 1397 |
'ssl_ca_certs': '/path/to/ca.crt', |
| 1398 |
'ssl_certfile': '/path/to/client.crt', |
| 1399 |
'ssl_keyfile': '/path/to/client.key', |
| 1400 |
} |
| 1401 |
self.app.conf.redis_socket_timeout = 30.0 |
| 1402 |
self.app.conf.redis_socket_connect_timeout = 100.0 |
| 1403 |
x = SentinelBackend( |
| 1404 |
'sentinel://:[email protected]:123//1', app=self.app, |
| 1405 |
) |
| 1406 |
assert x.connparams |
| 1407 |
assert len(x.connparams['hosts']) == 1 |
| 1408 |
assert x.connparams['hosts'][0]['host'] == 'vandelay.com' |
| 1409 |
assert x.connparams['hosts'][0]['db'] == 1 |
| 1410 |
assert x.connparams['hosts'][0]['port'] == 123 |
| 1411 |
assert x.connparams['hosts'][0]['password'] == 'bosco' |
| 1412 |
assert x.connparams['socket_timeout'] == 30.0 |
| 1413 |
assert x.connparams['socket_connect_timeout'] == 100.0 |
| 1414 |
assert x.connparams['ssl_cert_reqs'] == ssl.CERT_REQUIRED |
| 1415 |
assert x.connparams['ssl_ca_certs'] == '/path/to/ca.crt' |
| 1416 |
assert x.connparams['ssl_certfile'] == '/path/to/client.crt' |
| 1417 |
assert x.connparams['ssl_keyfile'] == '/path/to/client.key' |
| 1418 |
|
| 1419 |
from celery.backends.redis import SentinelManagedSSLConnection |
| 1420 |
assert x.connparams['connection_class'] is SentinelManagedSSLConnection |
| 1421 |
|
| 1422 |
def test_url_with_acl_credentials(self): |
| 1423 |
x = self.Backend( |
| 1424 |
'sentinel://myuser:[email protected]:123/1;' |
| 1425 |
'sentinel://myuser:[email protected]:124/1', |
| 1426 |
app=self.app, |
| 1427 |
) |
| 1428 |
assert x.connparams |
| 1429 |
assert "host" not in x.connparams |
| 1430 |
assert x.connparams['db'] == 1 |
| 1431 |
assert "port" not in x.connparams |
| 1432 |
assert x.connparams['password'] == "mypass" |
| 1433 |
assert x.connparams['username'] == "myuser" |
| 1434 |
assert len(x.connparams['hosts']) == 2 |
| 1435 |
|
| 1436 |
expected_usernames = ["myuser", "myuser"] |
| 1437 |
found_usernames = [cp['username'] for cp in x.connparams['hosts']] |
| 1438 |
assert found_usernames == expected_usernames |
| 1439 |
|
| 1440 |
def test_get_pool_with_acl_credentials(self): |
| 1441 |
x = self.Backend( |
| 1442 |
'sentinel://myuser:[email protected]:123/1;' |
| 1443 |
'sentinel://myuser:[email protected]:124/1', |
| 1444 |
app=self.app, |
| 1445 |
) |
| 1446 |
with patch.object(x, '_get_sentinel_instance') as mock_get_sentinel: |
| 1447 |
mock_sentinel = Mock() |
| 1448 |
mock_sentinel.master_for.return_value = Mock(connection_pool=Mock()) |
| 1449 |
mock_get_sentinel.return_value = mock_sentinel |
| 1450 |
|
| 1451 |
x._get_pool(**x.connparams) |
| 1452 |
|
| 1453 |
mock_sentinel.master_for.assert_called_once() |
| 1454 |
call_kwargs = mock_sentinel.master_for.call_args[1] |
| 1455 |
assert call_kwargs.get('username') == 'myuser' |
| 1456 |
assert call_kwargs.get('password') == 'mypass' |
| 1457 |
|
| 1458 |
def test_get_pool_with_password_only(self): |
| 1459 |
x = self.Backend( |
| 1460 |
'sentinel://:[email protected]:123/1', |
| 1461 |
app=self.app, |
| 1462 |
) |
| 1463 |
with patch.object(x, '_get_sentinel_instance') as mock_get_sentinel: |
| 1464 |
mock_sentinel = Mock() |
| 1465 |
mock_sentinel.master_for.return_value = Mock(connection_pool=Mock()) |
| 1466 |
mock_get_sentinel.return_value = mock_sentinel |
| 1467 |
|
| 1468 |
x._get_pool(**x.connparams) |
| 1469 |
|
| 1470 |
mock_sentinel.master_for.assert_called_once() |
| 1471 |
call_kwargs = mock_sentinel.master_for.call_args[1] |
| 1472 |
assert 'username' not in call_kwargs |
| 1473 |
assert call_kwargs.get('password') == 'mypass' |