| 1 |
import sys |
| 2 |
import types |
| 3 |
from contextlib import contextmanager |
| 4 |
from unittest.mock import Mock, patch |
| 5 |
|
| 6 |
import pytest |
| 7 |
from kombu.utils.encoding import ensure_bytes, str_to_bytes |
| 8 |
|
| 9 |
from celery import signature, states, uuid |
| 10 |
from celery.backends.cache import CacheBackend, DummyClient, backends |
| 11 |
from celery.exceptions import ImproperlyConfigured |
| 12 |
from t.unit import conftest |
| 13 |
|
| 14 |
|
| 15 |
class SomeClass: |
| 16 |
|
| 17 |
def __init__(self, data): |
| 18 |
self.data = data |
| 19 |
|
| 20 |
|
| 21 |
class test_CacheBackend: |
| 22 |
|
| 23 |
def setup_method(self): |
| 24 |
self.app.conf.result_serializer = 'pickle' |
| 25 |
self.tb = CacheBackend(backend='memory://', app=self.app) |
| 26 |
self.tid = uuid() |
| 27 |
self.old_get_best_memcached = backends['memcache'] |
| 28 |
backends['memcache'] = lambda: (DummyClient, ensure_bytes) |
| 29 |
|
| 30 |
def teardown_method(self): |
| 31 |
backends['memcache'] = self.old_get_best_memcached |
| 32 |
|
| 33 |
def test_no_backend(self): |
| 34 |
self.app.conf.cache_backend = None |
| 35 |
with pytest.raises(ImproperlyConfigured): |
| 36 |
CacheBackend(backend=None, app=self.app) |
| 37 |
|
| 38 |
def test_memory_client_is_shared(self): |
| 39 |
"""This test verifies that memory:// backend state is shared over multiple threads""" |
| 40 |
from threading import Thread |
| 41 |
t = Thread( |
| 42 |
target=lambda: CacheBackend(backend='memory://', app=self.app).set('test', 12345) |
| 43 |
) |
| 44 |
t.start() |
| 45 |
t.join() |
| 46 |
assert self.tb.client.get('test') == 12345 |
| 47 |
|
| 48 |
def test_mark_as_done(self): |
| 49 |
assert self.tb.get_state(self.tid) == states.PENDING |
| 50 |
assert self.tb.get_result(self.tid) is None |
| 51 |
|
| 52 |
self.tb.mark_as_done(self.tid, 42) |
| 53 |
assert self.tb.get_state(self.tid) == states.SUCCESS |
| 54 |
assert self.tb.get_result(self.tid) == 42 |
| 55 |
|
| 56 |
def test_is_pickled(self): |
| 57 |
result = {'foo': 'baz', 'bar': SomeClass(12345)} |
| 58 |
self.tb.mark_as_done(self.tid, result) |
| 59 |
# is serialized properly. |
| 60 |
rindb = self.tb.get_result(self.tid) |
| 61 |
assert rindb.get('foo') == 'baz' |
| 62 |
assert rindb.get('bar').data == 12345 |
| 63 |
|
| 64 |
def test_mark_as_failure(self): |
| 65 |
try: |
| 66 |
raise KeyError('foo') |
| 67 |
except KeyError as exception: |
| 68 |
self.tb.mark_as_failure(self.tid, exception) |
| 69 |
assert self.tb.get_state(self.tid) == states.FAILURE |
| 70 |
assert isinstance(self.tb.get_result(self.tid), KeyError) |
| 71 |
|
| 72 |
def test_apply_chord(self): |
| 73 |
tb = CacheBackend(backend='memory://', app=self.app) |
| 74 |
result_args = ( |
| 75 |
uuid(), |
| 76 |
[self.app.AsyncResult(uuid()) for _ in range(3)], |
| 77 |
) |
| 78 |
tb.apply_chord(result_args, None) |
| 79 |
assert self.app.GroupResult.restore(result_args[0], backend=tb) == self.app.GroupResult(*result_args) |
| 80 |
|
| 81 |
@patch('celery.result.GroupResult.restore') |
| 82 |
def test_on_chord_part_return(self, restore): |
| 83 |
tb = CacheBackend(backend='memory://', app=self.app) |
| 84 |
|
| 85 |
deps = Mock() |
| 86 |
deps.__len__ = Mock() |
| 87 |
deps.__len__.return_value = 2 |
| 88 |
restore.return_value = deps |
| 89 |
task = Mock() |
| 90 |
task.name = 'foobarbaz' |
| 91 |
self.app.tasks['foobarbaz'] = task |
| 92 |
task.request.chord = signature(task) |
| 93 |
|
| 94 |
result_args = ( |
| 95 |
uuid(), |
| 96 |
[self.app.AsyncResult(uuid()) for _ in range(3)], |
| 97 |
) |
| 98 |
task.request.group = result_args[0] |
| 99 |
tb.apply_chord(result_args, None) |
| 100 |
|
| 101 |
deps.join_native.assert_not_called() |
| 102 |
tb.on_chord_part_return(task.request, 'SUCCESS', 10) |
| 103 |
deps.join_native.assert_not_called() |
| 104 |
|
| 105 |
tb.on_chord_part_return(task.request, 'SUCCESS', 10) |
| 106 |
deps.join_native.assert_called_with(propagate=True, timeout=3.0) |
| 107 |
deps.delete.assert_called_with() |
| 108 |
|
| 109 |
def test_mget(self): |
| 110 |
self.tb._set_with_state('foo', 1, states.SUCCESS) |
| 111 |
self.tb._set_with_state('bar', 2, states.SUCCESS) |
| 112 |
|
| 113 |
assert self.tb.mget(['foo', 'bar']) == {'foo': 1, 'bar': 2} |
| 114 |
|
| 115 |
def test_forget(self): |
| 116 |
self.tb.mark_as_done(self.tid, {'foo': 'bar'}) |
| 117 |
x = self.app.AsyncResult(self.tid, backend=self.tb) |
| 118 |
x.forget() |
| 119 |
assert x.result is None |
| 120 |
|
| 121 |
def test_process_cleanup(self): |
| 122 |
self.tb.process_cleanup() |
| 123 |
|
| 124 |
def test_expires_as_int(self): |
| 125 |
tb = CacheBackend(backend='memory://', expires=10, app=self.app) |
| 126 |
assert tb.expires == 10 |
| 127 |
|
| 128 |
def test_unknown_backend_raises_ImproperlyConfigured(self): |
| 129 |
with pytest.raises(ImproperlyConfigured): |
| 130 |
CacheBackend(backend='unknown://', app=self.app) |
| 131 |
|
| 132 |
def test_as_uri_no_servers(self): |
| 133 |
assert self.tb.as_uri() == 'memory:///' |
| 134 |
|
| 135 |
def test_as_uri_one_server(self): |
| 136 |
backend = 'memcache://127.0.0.1:11211/' |
| 137 |
b = CacheBackend(backend=backend, app=self.app) |
| 138 |
assert b.as_uri() == backend |
| 139 |
|
| 140 |
def test_as_uri_multiple_servers(self): |
| 141 |
backend = 'memcache://127.0.0.1:11211;127.0.0.2:11211;127.0.0.3/' |
| 142 |
b = CacheBackend(backend=backend, app=self.app) |
| 143 |
assert b.as_uri() == backend |
| 144 |
|
| 145 |
def test_regression_worker_startup_info(self): |
| 146 |
pytest.importorskip('memcache') |
| 147 |
self.app.conf.result_backend = ( |
| 148 |
'cache+memcached://127.0.0.1:11211;127.0.0.2:11211;127.0.0.3/' |
| 149 |
) |
| 150 |
worker = self.app.Worker() |
| 151 |
with conftest.stdouts(): |
| 152 |
worker.on_start() |
| 153 |
assert worker.startup_info() |
| 154 |
|
| 155 |
|
| 156 |
class MyMemcachedStringEncodingError(Exception): |
| 157 |
pass |
| 158 |
|
| 159 |
|
| 160 |
class MemcachedClient(DummyClient): |
| 161 |
|
| 162 |
def set(self, key, value, *args, **kwargs): |
| 163 |
key_t, must_be, not_be, cod = bytes, 'string', 'bytes', 'decode' |
| 164 |
|
| 165 |
if isinstance(key, key_t): |
| 166 |
raise MyMemcachedStringEncodingError( |
| 167 |
f'Keys must be {must_be}, not {not_be}. Convert your ' |
| 168 |
f'strings using mystring.{cod}(charset)!') |
| 169 |
return super().set(key, value, *args, **kwargs) |
| 170 |
|
| 171 |
|
| 172 |
class MockCacheMixin: |
| 173 |
|
| 174 |
@contextmanager |
| 175 |
def mock_memcache(self): |
| 176 |
memcache = types.ModuleType('memcache') |
| 177 |
memcache.Client = MemcachedClient |
| 178 |
memcache.Client.__module__ = memcache.__name__ |
| 179 |
prev, sys.modules['memcache'] = sys.modules.get('memcache'), memcache |
| 180 |
try: |
| 181 |
yield True |
| 182 |
finally: |
| 183 |
if prev is not None: |
| 184 |
sys.modules['memcache'] = prev |
| 185 |
|
| 186 |
@contextmanager |
| 187 |
def mock_pylibmc(self): |
| 188 |
pylibmc = types.ModuleType('pylibmc') |
| 189 |
pylibmc.Client = MemcachedClient |
| 190 |
pylibmc.Client.__module__ = pylibmc.__name__ |
| 191 |
prev = sys.modules.get('pylibmc') |
| 192 |
sys.modules['pylibmc'] = pylibmc |
| 193 |
try: |
| 194 |
yield True |
| 195 |
finally: |
| 196 |
if prev is not None: |
| 197 |
sys.modules['pylibmc'] = prev |
| 198 |
|
| 199 |
|
| 200 |
class test_get_best_memcache(MockCacheMixin): |
| 201 |
|
| 202 |
def test_pylibmc(self): |
| 203 |
with self.mock_pylibmc(): |
| 204 |
with conftest.reset_modules('celery.backends.cache'): |
| 205 |
from celery.backends import cache |
| 206 |
cache._imp = [None] |
| 207 |
assert cache.get_best_memcache()[0].__module__ == 'pylibmc' |
| 208 |
|
| 209 |
@pytest.mark.masked_modules('pylibmc') |
| 210 |
def test_memcache(self, mask_modules): |
| 211 |
with self.mock_memcache(): |
| 212 |
with conftest.reset_modules('celery.backends.cache'): |
| 213 |
from celery.backends import cache |
| 214 |
cache._imp = [None] |
| 215 |
assert (cache.get_best_memcache()[0]().__module__ == |
| 216 |
'memcache') |
| 217 |
|
| 218 |
@pytest.mark.masked_modules('pylibmc', 'memcache') |
| 219 |
def test_no_implementations(self, mask_modules): |
| 220 |
with conftest.reset_modules('celery.backends.cache'): |
| 221 |
from celery.backends import cache |
| 222 |
cache._imp = [None] |
| 223 |
with pytest.raises(ImproperlyConfigured): |
| 224 |
cache.get_best_memcache() |
| 225 |
|
| 226 |
def test_cached(self): |
| 227 |
with self.mock_pylibmc(): |
| 228 |
with conftest.reset_modules('celery.backends.cache'): |
| 229 |
from celery.backends import cache |
| 230 |
cache._imp = [None] |
| 231 |
cache.get_best_memcache()[0](behaviors={'foo': 'bar'}) |
| 232 |
assert cache._imp[0] |
| 233 |
cache.get_best_memcache()[0]() |
| 234 |
|
| 235 |
def test_backends(self): |
| 236 |
from celery.backends.cache import backends |
| 237 |
with self.mock_memcache(): |
| 238 |
for name, fun in backends.items(): |
| 239 |
assert fun() |
| 240 |
|
| 241 |
|
| 242 |
class test_memcache_key(MockCacheMixin): |
| 243 |
|
| 244 |
@pytest.mark.masked_modules('pylibmc') |
| 245 |
def test_memcache_unicode_key(self, mask_modules): |
| 246 |
with self.mock_memcache(): |
| 247 |
with conftest.reset_modules('celery.backends.cache'): |
| 248 |
from celery.backends import cache |
| 249 |
cache._imp = [None] |
| 250 |
task_id, result = str(uuid()), 42 |
| 251 |
b = cache.CacheBackend(backend='memcache', app=self.app) |
| 252 |
b.store_result(task_id, result, state=states.SUCCESS) |
| 253 |
assert b.get_result(task_id) == result |
| 254 |
|
| 255 |
@pytest.mark.masked_modules('pylibmc') |
| 256 |
def test_memcache_bytes_key(self, mask_modules): |
| 257 |
with self.mock_memcache(): |
| 258 |
with conftest.reset_modules('celery.backends.cache'): |
| 259 |
from celery.backends import cache |
| 260 |
cache._imp = [None] |
| 261 |
task_id, result = str_to_bytes(uuid()), 42 |
| 262 |
b = cache.CacheBackend(backend='memcache', app=self.app) |
| 263 |
b.store_result(task_id, result, state=states.SUCCESS) |
| 264 |
assert b.get_result(task_id) == result |
| 265 |
|
| 266 |
def test_pylibmc_unicode_key(self): |
| 267 |
with conftest.reset_modules('celery.backends.cache'): |
| 268 |
with self.mock_pylibmc(): |
| 269 |
from celery.backends import cache |
| 270 |
cache._imp = [None] |
| 271 |
task_id, result = str(uuid()), 42 |
| 272 |
b = cache.CacheBackend(backend='memcache', app=self.app) |
| 273 |
b.store_result(task_id, result, state=states.SUCCESS) |
| 274 |
assert b.get_result(task_id) == result |
| 275 |
|
| 276 |
def test_pylibmc_bytes_key(self): |
| 277 |
with conftest.reset_modules('celery.backends.cache'): |
| 278 |
with self.mock_pylibmc(): |
| 279 |
from celery.backends import cache |
| 280 |
cache._imp = [None] |
| 281 |
task_id, result = str_to_bytes(uuid()), 42 |
| 282 |
b = cache.CacheBackend(backend='memcache', app=self.app) |
| 283 |
b.store_result(task_id, result, state=states.SUCCESS) |
| 284 |
assert b.get_result(task_id) == result |