| 1 |
import threading |
| 2 |
from contextlib import contextmanager |
| 3 |
from unittest.mock import patch |
| 4 |
|
| 5 |
import pytest |
| 6 |
|
| 7 |
import celery.contrib.testing.worker as contrib_embed_worker |
| 8 |
from celery.app import backends |
| 9 |
from celery.backends.cache import CacheBackend |
| 10 |
from celery.exceptions import ImproperlyConfigured |
| 11 |
from celery.utils.nodenames import anon_nodename |
| 12 |
|
| 13 |
|
| 14 |
class CachedBackendWithTreadTrucking(CacheBackend): |
| 15 |
test_instance_count = 0 |
| 16 |
test_call_stats = {} |
| 17 |
|
| 18 |
def _track_attribute_access(self, method_name): |
| 19 |
cls = type(self) |
| 20 |
|
| 21 |
instance_no = getattr(self, '_instance_no', None) |
| 22 |
if instance_no is None: |
| 23 |
instance_no = self._instance_no = cls.test_instance_count |
| 24 |
cls.test_instance_count += 1 |
| 25 |
cls.test_call_stats[instance_no] = [] |
| 26 |
|
| 27 |
cls.test_call_stats[instance_no].append({ |
| 28 |
'thread_id': threading.get_ident(), |
| 29 |
'method_name': method_name |
| 30 |
}) |
| 31 |
|
| 32 |
def __getattribute__(self, name): |
| 33 |
if name == '_instance_no' or name == '_track_attribute_access': |
| 34 |
return super().__getattribute__(name) |
| 35 |
|
| 36 |
if name.startswith('__') and name != '__init__': |
| 37 |
return super().__getattribute__(name) |
| 38 |
|
| 39 |
self._track_attribute_access(name) |
| 40 |
return super().__getattribute__(name) |
| 41 |
|
| 42 |
|
| 43 |
@contextmanager |
| 44 |
def embed_worker(app, |
| 45 |
concurrency=1, |
| 46 |
pool='threading', **kwargs): |
| 47 |
""" |
| 48 |
Helper embedded worker for testing. |
| 49 |
|
| 50 |
It's based on a :func:`celery.contrib.testing.worker.start_worker`, |
| 51 |
but doesn't modify logging settings and additionally shutdown |
| 52 |
worker pool. |
| 53 |
""" |
| 54 |
# prepare application for worker |
| 55 |
app.finalize() |
| 56 |
app.set_current() |
| 57 |
|
| 58 |
worker = contrib_embed_worker.TestWorkController( |
| 59 |
app=app, |
| 60 |
concurrency=concurrency, |
| 61 |
hostname=anon_nodename(), |
| 62 |
pool=pool, |
| 63 |
# not allowed to override TestWorkController.on_consumer_ready |
| 64 |
ready_callback=None, |
| 65 |
without_heartbeat=kwargs.pop("without_heartbeat", True), |
| 66 |
without_mingle=True, |
| 67 |
without_gossip=True, |
| 68 |
**kwargs |
| 69 |
) |
| 70 |
|
| 71 |
t = threading.Thread(target=worker.start, daemon=True) |
| 72 |
t.start() |
| 73 |
worker.ensure_started() |
| 74 |
|
| 75 |
yield worker |
| 76 |
|
| 77 |
worker.stop() |
| 78 |
t.join(10.0) |
| 79 |
if t.is_alive(): |
| 80 |
raise RuntimeError( |
| 81 |
"Worker thread failed to exit within the allocated timeout. " |
| 82 |
"Consider raising `shutdown_timeout` if your tasks take longer " |
| 83 |
"to execute." |
| 84 |
) |
| 85 |
|
| 86 |
|
| 87 |
class test_backends: |
| 88 |
|
| 89 |
@pytest.mark.parametrize('url,expect_cls', [ |
| 90 |
('cache+memory://', CacheBackend), |
| 91 |
]) |
| 92 |
def test_get_backend_aliases(self, url, expect_cls, app): |
| 93 |
backend, url = backends.by_url(url, app.loader) |
| 94 |
assert isinstance(backend(app=app, url=url), expect_cls) |
| 95 |
|
| 96 |
def test_unknown_backend(self, app): |
| 97 |
with pytest.raises(ImportError): |
| 98 |
backends.by_name('fasodaopjeqijwqe', app.loader) |
| 99 |
|
| 100 |
def test_backend_by_url(self, app, url='redis://localhost/1'): |
| 101 |
from celery.backends.redis import RedisBackend |
| 102 |
backend, url_ = backends.by_url(url, app.loader) |
| 103 |
assert backend is RedisBackend |
| 104 |
assert url_ == url |
| 105 |
|
| 106 |
def test_sym_raises_ValuError(self, app): |
| 107 |
with patch('celery.app.backends.symbol_by_name') as sbn: |
| 108 |
sbn.side_effect = ValueError() |
| 109 |
with pytest.raises(ImproperlyConfigured): |
| 110 |
backends.by_name('xxx.xxx:foo', app.loader) |
| 111 |
|
| 112 |
def test_backend_can_not_be_module(self, app): |
| 113 |
with pytest.raises(ImproperlyConfigured): |
| 114 |
backends.by_name(pytest, app.loader) |
| 115 |
|
| 116 |
@pytest.mark.celery( |
| 117 |
result_backend=f'{CachedBackendWithTreadTrucking.__module__}.' |
| 118 |
f'{CachedBackendWithTreadTrucking.__qualname__}' |
| 119 |
f'+memory://') |
| 120 |
def test_backend_thread_safety(self): |
| 121 |
@self.app.task |
| 122 |
def dummy_add_task(x, y): |
| 123 |
return x + y |
| 124 |
|
| 125 |
with embed_worker(app=self.app, pool='threads'): |
| 126 |
result = dummy_add_task.delay(6, 9) |
| 127 |
assert result.get(timeout=10) == 15 |
| 128 |
|
| 129 |
call_stats = CachedBackendWithTreadTrucking.test_call_stats |
| 130 |
# check that backend instance is used without same thread |
| 131 |
for backend_call_stats in call_stats.values(): |
| 132 |
thread_ids = set() |
| 133 |
for call_stat in backend_call_stats: |
| 134 |
thread_ids.add(call_stat['thread_id']) |
| 135 |
assert len(thread_ids) <= 1, \ |
| 136 |
"The same celery backend instance is used by multiple threads" |