| 1 |
import copy |
| 2 |
import re |
| 3 |
from contextlib import contextmanager |
| 4 |
from unittest.mock import ANY, MagicMock, Mock, call, patch, sentinel |
| 5 |
|
| 6 |
import pytest |
| 7 |
from kombu.serialization import prepare_accept_content |
| 8 |
from kombu.utils.encoding import bytes_to_str, ensure_bytes |
| 9 |
|
| 10 |
import celery |
| 11 |
from celery import chord, group, signature, states, uuid |
| 12 |
from celery.app.task import Context, Task |
| 13 |
from celery.backends.base import (BaseBackend, DisabledBackend, KeyValueStoreBackend, _create_chord_error_with_cause, |
| 14 |
_create_fake_task_request, _nulldict) |
| 15 |
from celery.exceptions import BackendGetMetaError, BackendStoreError, ChordError, SecurityError, TimeoutError |
| 16 |
from celery.result import GroupResult, result_from_tuple |
| 17 |
from celery.utils import serialization |
| 18 |
from celery.utils.functional import pass1 |
| 19 |
from celery.utils.serialization import UnpickleableExceptionWrapper |
| 20 |
from celery.utils.serialization import find_pickleable_exception as fnpe |
| 21 |
from celery.utils.serialization import get_pickleable_exception as gpe |
| 22 |
from celery.utils.serialization import subclass_exception |
| 23 |
|
| 24 |
|
| 25 |
class wrapobject: |
| 26 |
|
| 27 |
def __init__(self, *args, **kwargs): |
| 28 |
self.args = args |
| 29 |
|
| 30 |
|
| 31 |
class paramexception(Exception): |
| 32 |
|
| 33 |
def __init__(self, param): |
| 34 |
self.param = param |
| 35 |
|
| 36 |
|
| 37 |
class objectexception: |
| 38 |
class Nested(Exception): |
| 39 |
pass |
| 40 |
|
| 41 |
|
| 42 |
Oldstyle = None |
| 43 |
|
| 44 |
Unpickleable = subclass_exception( |
| 45 |
'Unpickleable', KeyError, 'foo.module', |
| 46 |
) |
| 47 |
Impossible = subclass_exception( |
| 48 |
'Impossible', object, 'foo.module', |
| 49 |
) |
| 50 |
Lookalike = subclass_exception( |
| 51 |
'Lookalike', wrapobject, 'foo.module', |
| 52 |
) |
| 53 |
|
| 54 |
|
| 55 |
class test_nulldict: |
| 56 |
|
| 57 |
def test_nulldict(self): |
| 58 |
x = _nulldict() |
| 59 |
x['foo'] = 1 |
| 60 |
x.update(foo=1, bar=2) |
| 61 |
x.setdefault('foo', 3) |
| 62 |
|
| 63 |
|
| 64 |
class test_serialization: |
| 65 |
|
| 66 |
def test_create_exception_cls(self): |
| 67 |
assert serialization.create_exception_cls('FooError', 'm') |
| 68 |
assert serialization.create_exception_cls('FooError', 'm', KeyError) |
| 69 |
|
| 70 |
|
| 71 |
class test_Backend_interface: |
| 72 |
|
| 73 |
def setup_method(self): |
| 74 |
self.app.conf.accept_content = ['json'] |
| 75 |
|
| 76 |
def test_accept_precedence(self): |
| 77 |
|
| 78 |
# default is app.conf.accept_content |
| 79 |
accept_content = self.app.conf.accept_content |
| 80 |
b1 = BaseBackend(self.app) |
| 81 |
assert prepare_accept_content(accept_content) == b1.accept |
| 82 |
|
| 83 |
# accept parameter |
| 84 |
b2 = BaseBackend(self.app, accept=['yaml']) |
| 85 |
assert len(b2.accept) == 1 |
| 86 |
assert list(b2.accept)[0] == 'application/x-yaml' |
| 87 |
assert prepare_accept_content(['yaml']) == b2.accept |
| 88 |
|
| 89 |
# accept parameter over result_accept_content |
| 90 |
self.app.conf.result_accept_content = ['json'] |
| 91 |
b3 = BaseBackend(self.app, accept=['yaml']) |
| 92 |
assert len(b3.accept) == 1 |
| 93 |
assert list(b3.accept)[0] == 'application/x-yaml' |
| 94 |
assert prepare_accept_content(['yaml']) == b3.accept |
| 95 |
|
| 96 |
# conf.result_accept_content if specified |
| 97 |
self.app.conf.result_accept_content = ['yaml'] |
| 98 |
b4 = BaseBackend(self.app) |
| 99 |
assert len(b4.accept) == 1 |
| 100 |
assert list(b4.accept)[0] == 'application/x-yaml' |
| 101 |
assert prepare_accept_content(['yaml']) == b4.accept |
| 102 |
|
| 103 |
def test_get_result_meta(self): |
| 104 |
b1 = BaseBackend(self.app) |
| 105 |
meta = b1._get_result_meta(result={'fizz': 'buzz'}, |
| 106 |
state=states.SUCCESS, traceback=None, |
| 107 |
request=None) |
| 108 |
assert meta['status'] == states.SUCCESS |
| 109 |
assert meta['result'] == {'fizz': 'buzz'} |
| 110 |
assert meta['traceback'] is None |
| 111 |
|
| 112 |
self.app.conf.result_extended = True |
| 113 |
args = ['a', 'b'] |
| 114 |
kwargs = {'foo': 'bar'} |
| 115 |
task_name = 'mytask' |
| 116 |
|
| 117 |
b2 = BaseBackend(self.app) |
| 118 |
request = Context(args=args, kwargs=kwargs, |
| 119 |
task=task_name, |
| 120 |
delivery_info={'routing_key': 'celery'}) |
| 121 |
meta = b2._get_result_meta(result={'fizz': 'buzz'}, |
| 122 |
state=states.SUCCESS, traceback=None, |
| 123 |
request=request, encode=False) |
| 124 |
assert meta['name'] == task_name |
| 125 |
assert meta['args'] == args |
| 126 |
assert meta['kwargs'] == kwargs |
| 127 |
assert meta['queue'] == 'celery' |
| 128 |
|
| 129 |
def test_get_result_meta_stamps_attribute_error(self): |
| 130 |
class Request: |
| 131 |
pass |
| 132 |
self.app.conf.result_extended = True |
| 133 |
b1 = BaseBackend(self.app) |
| 134 |
meta = b1._get_result_meta(result={'fizz': 'buzz'}, |
| 135 |
state=states.SUCCESS, traceback=None, |
| 136 |
request=Request()) |
| 137 |
assert meta['status'] == states.SUCCESS |
| 138 |
assert meta['result'] == {'fizz': 'buzz'} |
| 139 |
assert meta['traceback'] is None |
| 140 |
|
| 141 |
def test_get_result_meta_encoded(self): |
| 142 |
self.app.conf.result_extended = True |
| 143 |
b1 = BaseBackend(self.app) |
| 144 |
args = ['a', 'b'] |
| 145 |
kwargs = {'foo': 'bar'} |
| 146 |
|
| 147 |
request = Context(args=args, kwargs=kwargs) |
| 148 |
meta = b1._get_result_meta(result={'fizz': 'buzz'}, |
| 149 |
state=states.SUCCESS, traceback=None, |
| 150 |
request=request, encode=True) |
| 151 |
assert meta['args'] == ensure_bytes(b1.encode(args)) |
| 152 |
assert meta['kwargs'] == ensure_bytes(b1.encode(kwargs)) |
| 153 |
|
| 154 |
def test_get_result_meta_with_none(self): |
| 155 |
b1 = BaseBackend(self.app) |
| 156 |
meta = b1._get_result_meta(result=None, |
| 157 |
state=states.SUCCESS, traceback=None, |
| 158 |
request=None) |
| 159 |
assert meta['status'] == states.SUCCESS |
| 160 |
assert meta['result'] is None |
| 161 |
assert meta['traceback'] is None |
| 162 |
|
| 163 |
self.app.conf.result_extended = True |
| 164 |
args = ['a', 'b'] |
| 165 |
kwargs = {'foo': 'bar'} |
| 166 |
task_name = 'mytask' |
| 167 |
|
| 168 |
b2 = BaseBackend(self.app) |
| 169 |
request = Context(args=args, kwargs=kwargs, |
| 170 |
task=task_name, |
| 171 |
delivery_info={'routing_key': 'celery'}) |
| 172 |
meta = b2._get_result_meta(result=None, |
| 173 |
state=states.SUCCESS, traceback=None, |
| 174 |
request=request, encode=False) |
| 175 |
assert meta['name'] == task_name |
| 176 |
assert meta['args'] == args |
| 177 |
assert meta['kwargs'] == kwargs |
| 178 |
assert meta['queue'] == 'celery' |
| 179 |
|
| 180 |
def test_get_result_meta_format_date(self): |
| 181 |
import datetime |
| 182 |
self.app.conf.result_extended = True |
| 183 |
b1 = BaseBackend(self.app) |
| 184 |
args = ['a', 'b'] |
| 185 |
kwargs = {'foo': 'bar'} |
| 186 |
|
| 187 |
request = Context(args=args, kwargs=kwargs) |
| 188 |
meta = b1._get_result_meta(result={'fizz': 'buzz'}, |
| 189 |
state=states.SUCCESS, traceback=None, |
| 190 |
request=request, format_date=True) |
| 191 |
assert isinstance(meta['date_done'], str) |
| 192 |
|
| 193 |
self.app.conf.result_extended = True |
| 194 |
b2 = BaseBackend(self.app) |
| 195 |
args = ['a', 'b'] |
| 196 |
kwargs = {'foo': 'bar'} |
| 197 |
|
| 198 |
request = Context(args=args, kwargs=kwargs) |
| 199 |
meta = b2._get_result_meta(result={'fizz': 'buzz'}, |
| 200 |
state=states.SUCCESS, traceback=None, |
| 201 |
request=request, format_date=False) |
| 202 |
assert isinstance(meta['date_done'], datetime.datetime) |
| 203 |
|
| 204 |
|
| 205 |
class test_BaseBackend_interface: |
| 206 |
|
| 207 |
def setup_method(self): |
| 208 |
self.b = BaseBackend(self.app) |
| 209 |
|
| 210 |
@self.app.task(shared=False) |
| 211 |
def callback(result): |
| 212 |
pass |
| 213 |
|
| 214 |
self.callback = callback |
| 215 |
|
| 216 |
def test__forget(self): |
| 217 |
with pytest.raises(NotImplementedError): |
| 218 |
self.b._forget('SOMExx-N0Nex1stant-IDxx-') |
| 219 |
|
| 220 |
def test_forget(self): |
| 221 |
with pytest.raises(NotImplementedError): |
| 222 |
self.b.forget('SOMExx-N0nex1stant-IDxx-') |
| 223 |
|
| 224 |
def test_on_chord_part_return(self): |
| 225 |
self.b.on_chord_part_return(None, None, None) |
| 226 |
|
| 227 |
def test_apply_chord(self, unlock='celery.chord_unlock'): |
| 228 |
self.app.tasks[unlock] = Mock() |
| 229 |
header_result_args = ( |
| 230 |
uuid(), |
| 231 |
[self.app.AsyncResult(x) for x in range(3)], |
| 232 |
) |
| 233 |
self.b.apply_chord(header_result_args, self.callback.s()) |
| 234 |
assert self.app.tasks[unlock].apply_async.call_count |
| 235 |
|
| 236 |
def test_chord_unlock_queue(self, unlock='celery.chord_unlock'): |
| 237 |
self.app.tasks[unlock] = Mock() |
| 238 |
header_result_args = ( |
| 239 |
uuid(), |
| 240 |
[self.app.AsyncResult(x) for x in range(3)], |
| 241 |
) |
| 242 |
body = self.callback.s() |
| 243 |
|
| 244 |
self.b.apply_chord(header_result_args, body) |
| 245 |
called_kwargs = self.app.tasks[unlock].apply_async.call_args[1] |
| 246 |
assert called_kwargs['queue'] == 'testcelery' |
| 247 |
|
| 248 |
routing_queue = Mock() |
| 249 |
routing_queue.name = "routing_queue" |
| 250 |
self.app.amqp.router.route = Mock(return_value={ |
| 251 |
"queue": routing_queue |
| 252 |
}) |
| 253 |
self.b.apply_chord(header_result_args, body) |
| 254 |
assert self.app.amqp.router.route.call_args[0][1] == body.name |
| 255 |
called_kwargs = self.app.tasks[unlock].apply_async.call_args[1] |
| 256 |
assert called_kwargs["queue"] == "routing_queue" |
| 257 |
|
| 258 |
self.b.apply_chord(header_result_args, body.set(queue='test_queue')) |
| 259 |
called_kwargs = self.app.tasks[unlock].apply_async.call_args[1] |
| 260 |
assert called_kwargs['queue'] == 'test_queue' |
| 261 |
|
| 262 |
@self.app.task(shared=False, queue='test_queue_two') |
| 263 |
def callback_queue(result): |
| 264 |
pass |
| 265 |
|
| 266 |
self.b.apply_chord(header_result_args, callback_queue.s()) |
| 267 |
called_kwargs = self.app.tasks[unlock].apply_async.call_args[1] |
| 268 |
assert called_kwargs['queue'] == 'test_queue_two' |
| 269 |
|
| 270 |
with self.Celery() as app2: |
| 271 |
@app2.task(name='callback_different_app', shared=False) |
| 272 |
def callback_different_app(result): |
| 273 |
pass |
| 274 |
|
| 275 |
callback_different_app_signature = self.app.signature('callback_different_app') |
| 276 |
self.b.apply_chord(header_result_args, callback_different_app_signature) |
| 277 |
called_kwargs = self.app.tasks[unlock].apply_async.call_args[1] |
| 278 |
assert called_kwargs['queue'] == 'routing_queue' |
| 279 |
|
| 280 |
callback_different_app_signature.set(queue='test_queue_three') |
| 281 |
self.b.apply_chord(header_result_args, callback_different_app_signature) |
| 282 |
called_kwargs = self.app.tasks[unlock].apply_async.call_args[1] |
| 283 |
assert called_kwargs['queue'] == 'test_queue_three' |
| 284 |
|
| 285 |
|
| 286 |
class test_exception_pickle: |
| 287 |
def test_BaseException(self): |
| 288 |
assert fnpe(Exception()) is None |
| 289 |
|
| 290 |
def test_get_pickleable_exception(self): |
| 291 |
exc = Exception('foo') |
| 292 |
assert gpe(exc) == exc |
| 293 |
|
| 294 |
def test_unpickleable(self): |
| 295 |
assert isinstance(fnpe(Unpickleable()), KeyError) |
| 296 |
assert fnpe(Impossible()) is None |
| 297 |
|
| 298 |
|
| 299 |
class test_prepare_exception: |
| 300 |
|
| 301 |
def setup_method(self): |
| 302 |
self.b = BaseBackend(self.app) |
| 303 |
|
| 304 |
def test_unpickleable(self): |
| 305 |
self.b.serializer = 'pickle' |
| 306 |
x = self.b.prepare_exception(Unpickleable(1, 2, 'foo')) |
| 307 |
assert isinstance(x, KeyError) |
| 308 |
y = self.b.exception_to_python(x) |
| 309 |
assert isinstance(y, KeyError) |
| 310 |
|
| 311 |
def test_json_exception_arguments(self): |
| 312 |
self.b.serializer = 'json' |
| 313 |
x = self.b.prepare_exception(Exception(object)) |
| 314 |
assert x == { |
| 315 |
'exc_message': serialization.ensure_serializable( |
| 316 |
(object,), self.b.encode), |
| 317 |
'exc_type': Exception.__name__, |
| 318 |
'exc_module': Exception.__module__} |
| 319 |
y = self.b.exception_to_python(x) |
| 320 |
assert isinstance(y, Exception) |
| 321 |
|
| 322 |
def test_json_exception_nested(self): |
| 323 |
self.b.serializer = 'json' |
| 324 |
x = self.b.prepare_exception(objectexception.Nested('msg')) |
| 325 |
assert x == { |
| 326 |
'exc_message': ('msg',), |
| 327 |
'exc_type': 'objectexception.Nested', |
| 328 |
'exc_module': objectexception.Nested.__module__} |
| 329 |
y = self.b.exception_to_python(x) |
| 330 |
assert isinstance(y, objectexception.Nested) |
| 331 |
|
| 332 |
def test_impossible(self): |
| 333 |
self.b.serializer = 'pickle' |
| 334 |
x = self.b.prepare_exception(Impossible()) |
| 335 |
assert isinstance(x, UnpickleableExceptionWrapper) |
| 336 |
assert str(x) |
| 337 |
y = self.b.exception_to_python(x) |
| 338 |
assert y.__class__.__name__ == 'Impossible' |
| 339 |
assert y.__class__.__module__ == 'foo.module' |
| 340 |
|
| 341 |
def test_regular(self): |
| 342 |
self.b.serializer = 'pickle' |
| 343 |
x = self.b.prepare_exception(KeyError('baz')) |
| 344 |
assert isinstance(x, KeyError) |
| 345 |
y = self.b.exception_to_python(x) |
| 346 |
assert isinstance(y, KeyError) |
| 347 |
|
| 348 |
def test_unicode_message(self): |
| 349 |
message = '\u03ac' |
| 350 |
x = self.b.prepare_exception(Exception(message)) |
| 351 |
assert x == {'exc_message': (message,), |
| 352 |
'exc_type': Exception.__name__, |
| 353 |
'exc_module': Exception.__module__} |
| 354 |
|
| 355 |
|
| 356 |
class KVBackend(KeyValueStoreBackend): |
| 357 |
mget_returns_dict = False |
| 358 |
|
| 359 |
def __init__(self, app, *args, **kwargs): |
| 360 |
self.db = {} |
| 361 |
super().__init__(app, *args, **kwargs) |
| 362 |
|
| 363 |
def get(self, key): |
| 364 |
return self.db.get(key) |
| 365 |
|
| 366 |
def _set_with_state(self, key, value, state): |
| 367 |
self.db[key] = value |
| 368 |
|
| 369 |
def mget(self, keys): |
| 370 |
if self.mget_returns_dict: |
| 371 |
return {key: self.get(key) for key in keys} |
| 372 |
else: |
| 373 |
return [self.get(k) for k in keys] |
| 374 |
|
| 375 |
def delete(self, key): |
| 376 |
self.db.pop(key, None) |
| 377 |
|
| 378 |
|
| 379 |
class DictBackend(BaseBackend): |
| 380 |
|
| 381 |
def __init__(self, *args, **kwargs): |
| 382 |
super().__init__(*args, **kwargs) |
| 383 |
self._data = {'can-delete': {'result': 'foo'}} |
| 384 |
|
| 385 |
def _restore_group(self, group_id): |
| 386 |
if group_id == 'exists': |
| 387 |
return {'result': 'group'} |
| 388 |
|
| 389 |
def _get_task_meta_for(self, task_id): |
| 390 |
if task_id == 'task-exists': |
| 391 |
return {'result': 'task'} |
| 392 |
|
| 393 |
def _delete_group(self, group_id): |
| 394 |
self._data.pop(group_id, None) |
| 395 |
|
| 396 |
|
| 397 |
class test_BaseBackend_dict: |
| 398 |
|
| 399 |
def setup_method(self): |
| 400 |
self.b = DictBackend(app=self.app) |
| 401 |
|
| 402 |
@self.app.task(shared=False, bind=True) |
| 403 |
def bound_errback(self, result): |
| 404 |
pass |
| 405 |
|
| 406 |
@self.app.task(shared=False) |
| 407 |
def errback(arg1, arg2): |
| 408 |
errback.last_result = arg1 + arg2 |
| 409 |
|
| 410 |
self.bound_errback = bound_errback |
| 411 |
self.errback = errback |
| 412 |
|
| 413 |
def test_delete_group(self): |
| 414 |
self.b.delete_group('can-delete') |
| 415 |
assert 'can-delete' not in self.b._data |
| 416 |
|
| 417 |
def test_prepare_exception_json(self): |
| 418 |
x = DictBackend(self.app, serializer='json') |
| 419 |
e = x.prepare_exception(KeyError('foo')) |
| 420 |
assert 'exc_type' in e |
| 421 |
e = x.exception_to_python(e) |
| 422 |
assert e.__class__.__name__ == 'KeyError' |
| 423 |
assert str(e).strip('u') == "'foo'" |
| 424 |
|
| 425 |
def test_save_group(self): |
| 426 |
b = BaseBackend(self.app) |
| 427 |
b._save_group = Mock() |
| 428 |
b.save_group('foofoo', 'xxx') |
| 429 |
b._save_group.assert_called_with('foofoo', 'xxx') |
| 430 |
|
| 431 |
def test_add_to_chord_interface(self): |
| 432 |
b = BaseBackend(self.app) |
| 433 |
with pytest.raises(NotImplementedError): |
| 434 |
b.add_to_chord('group_id', 'sig') |
| 435 |
|
| 436 |
def test_forget_interface(self): |
| 437 |
b = BaseBackend(self.app) |
| 438 |
with pytest.raises(NotImplementedError): |
| 439 |
b.forget('foo') |
| 440 |
|
| 441 |
def test_restore_group(self): |
| 442 |
assert self.b.restore_group('missing') is None |
| 443 |
assert self.b.restore_group('missing') is None |
| 444 |
assert self.b.restore_group('exists') == 'group' |
| 445 |
assert self.b.restore_group('exists') == 'group' |
| 446 |
assert self.b.restore_group('exists', cache=False) == 'group' |
| 447 |
|
| 448 |
def test_reload_group_result(self): |
| 449 |
self.b._cache = {} |
| 450 |
self.b.reload_group_result('exists') |
| 451 |
self.b._cache['exists'] = {'result': 'group'} |
| 452 |
|
| 453 |
def test_reload_task_result(self): |
| 454 |
self.b._cache = {} |
| 455 |
self.b.reload_task_result('task-exists') |
| 456 |
self.b._cache['task-exists'] = {'result': 'task'} |
| 457 |
|
| 458 |
def test_fail_from_current_stack(self): |
| 459 |
import inspect |
| 460 |
self.b.mark_as_failure = Mock() |
| 461 |
frame_list = [] |
| 462 |
|
| 463 |
def raise_dummy(): |
| 464 |
frame_str_temp = str(inspect.currentframe().__repr__) |
| 465 |
frame_list.append(frame_str_temp) |
| 466 |
raise KeyError('foo') |
| 467 |
try: |
| 468 |
raise_dummy() |
| 469 |
except KeyError as exc: |
| 470 |
self.b.fail_from_current_stack('task_id') |
| 471 |
self.b.mark_as_failure.assert_called() |
| 472 |
args = self.b.mark_as_failure.call_args[0] |
| 473 |
assert args[0] == 'task_id' |
| 474 |
assert args[1] is exc |
| 475 |
assert args[2] |
| 476 |
|
| 477 |
tb_ = exc.__traceback__ |
| 478 |
while tb_ is not None: |
| 479 |
if str(tb_.tb_frame.__repr__) == frame_list[0]: |
| 480 |
assert len(tb_.tb_frame.f_locals) == 0 |
| 481 |
tb_ = tb_.tb_next |
| 482 |
|
| 483 |
def test_prepare_value_serializes_group_result(self): |
| 484 |
self.b.serializer = 'json' |
| 485 |
g = self.app.GroupResult('group_id', [self.app.AsyncResult('foo')]) |
| 486 |
v = self.b.prepare_value(g) |
| 487 |
assert isinstance(v, (list, tuple)) |
| 488 |
assert result_from_tuple(v, app=self.app) == g |
| 489 |
|
| 490 |
v2 = self.b.prepare_value(g[0]) |
| 491 |
assert isinstance(v2, (list, tuple)) |
| 492 |
assert result_from_tuple(v2, app=self.app) == g[0] |
| 493 |
|
| 494 |
self.b.serializer = 'pickle' |
| 495 |
assert isinstance(self.b.prepare_value(g), self.app.GroupResult) |
| 496 |
|
| 497 |
def test_is_cached(self): |
| 498 |
b = BaseBackend(app=self.app, max_cached_results=1) |
| 499 |
b._cache['foo'] = 1 |
| 500 |
assert b.is_cached('foo') |
| 501 |
assert not b.is_cached('false') |
| 502 |
|
| 503 |
def test_mark_as_done__chord(self): |
| 504 |
b = BaseBackend(app=self.app) |
| 505 |
b._store_result = Mock() |
| 506 |
request = Mock(name='request') |
| 507 |
b.on_chord_part_return = Mock() |
| 508 |
b.mark_as_done('id', 10, request=request) |
| 509 |
b.on_chord_part_return.assert_called_with(request, states.SUCCESS, 10) |
| 510 |
|
| 511 |
def test_mark_as_failure__bound_errback_eager(self): |
| 512 |
b = BaseBackend(app=self.app) |
| 513 |
b._store_result = Mock() |
| 514 |
request = Mock(name='request') |
| 515 |
request.delivery_info = { |
| 516 |
'is_eager': True |
| 517 |
} |
| 518 |
request.errbacks = [ |
| 519 |
self.bound_errback.subtask(args=[1], immutable=True)] |
| 520 |
exc = KeyError() |
| 521 |
group = self.patching('celery.backends.base.group') |
| 522 |
b.mark_as_failure('id', exc, request=request) |
| 523 |
group.assert_called_with(request.errbacks, app=self.app) |
| 524 |
group.return_value.apply.assert_called_with( |
| 525 |
(request.id, ), parent_id=request.id, root_id=request.root_id) |
| 526 |
|
| 527 |
def test_mark_as_failure__bound_errback(self): |
| 528 |
b = BaseBackend(app=self.app) |
| 529 |
b._store_result = Mock() |
| 530 |
request = Mock(name='request') |
| 531 |
request.delivery_info = {} |
| 532 |
request.errbacks = [ |
| 533 |
self.bound_errback.subtask(args=[1], immutable=True)] |
| 534 |
exc = KeyError() |
| 535 |
group = self.patching('celery.backends.base.group') |
| 536 |
b.mark_as_failure('id', exc, request=request) |
| 537 |
group.assert_called_with(request.errbacks, app=self.app) |
| 538 |
group.return_value.apply_async.assert_called_with( |
| 539 |
(request.id, ), parent_id=request.id, root_id=request.root_id) |
| 540 |
|
| 541 |
def test_mark_as_failure__errback(self): |
| 542 |
b = BaseBackend(app=self.app) |
| 543 |
b._store_result = Mock() |
| 544 |
request = Mock(name='request') |
| 545 |
request.errbacks = [self.errback.subtask(args=[2, 3], immutable=True)] |
| 546 |
exc = KeyError() |
| 547 |
b.mark_as_failure('id', exc, request=request) |
| 548 |
assert self.errback.last_result == 5 |
| 549 |
|
| 550 |
@patch('celery.backends.base.group') |
| 551 |
def test_class_based_task_can_be_used_as_error_callback(self, mock_group): |
| 552 |
b = BaseBackend(app=self.app) |
| 553 |
b._store_result = Mock() |
| 554 |
|
| 555 |
class TaskBasedClass(Task): |
| 556 |
def run(self): |
| 557 |
pass |
| 558 |
|
| 559 |
TaskBasedClass = self.app.register_task(TaskBasedClass()) |
| 560 |
|
| 561 |
request = Mock(name='request') |
| 562 |
request.errbacks = [TaskBasedClass.subtask(args=[], immutable=True)] |
| 563 |
exc = KeyError() |
| 564 |
b.mark_as_failure('id', exc, request=request) |
| 565 |
mock_group.assert_called_once_with(request.errbacks, app=self.app) |
| 566 |
|
| 567 |
@patch('celery.backends.base.group') |
| 568 |
def test_unregistered_task_can_be_used_as_error_callback(self, mock_group): |
| 569 |
b = BaseBackend(app=self.app) |
| 570 |
b._store_result = Mock() |
| 571 |
|
| 572 |
request = Mock(name='request') |
| 573 |
request.errbacks = [signature('doesnotexist', |
| 574 |
immutable=True)] |
| 575 |
exc = KeyError() |
| 576 |
b.mark_as_failure('id', exc, request=request) |
| 577 |
mock_group.assert_called_once_with(request.errbacks, app=self.app) |
| 578 |
|
| 579 |
def test_mark_as_failure__chord(self): |
| 580 |
b = BaseBackend(app=self.app) |
| 581 |
b._store_result = Mock() |
| 582 |
request = Mock(name='request') |
| 583 |
request.errbacks = [] |
| 584 |
b.on_chord_part_return = Mock() |
| 585 |
exc = KeyError() |
| 586 |
b.mark_as_failure('id', exc, request=request) |
| 587 |
b.on_chord_part_return.assert_called_with(request, states.FAILURE, exc) |
| 588 |
|
| 589 |
def test_mark_as_revoked__chord(self): |
| 590 |
b = BaseBackend(app=self.app) |
| 591 |
b._store_result = Mock() |
| 592 |
request = Mock(name='request') |
| 593 |
request.errbacks = [] |
| 594 |
b.on_chord_part_return = Mock() |
| 595 |
b.mark_as_revoked('id', 'revoked', request=request) |
| 596 |
b.on_chord_part_return.assert_called_with(request, states.REVOKED, ANY) |
| 597 |
|
| 598 |
def test_chord_error_from_stack_raises(self): |
| 599 |
class ExpectedException(Exception): |
| 600 |
pass |
| 601 |
|
| 602 |
b = BaseBackend(app=self.app) |
| 603 |
callback = MagicMock(name='callback') |
| 604 |
callback.options = {'link_error': []} |
| 605 |
callback.keys.return_value = [] |
| 606 |
task = self.app.tasks[callback.task] = Mock() |
| 607 |
b.fail_from_current_stack = Mock() |
| 608 |
self.patching('celery.group') |
| 609 |
with patch.object( |
| 610 |
b, "_call_task_errbacks", side_effect=ExpectedException() |
| 611 |
) as mock_call_errbacks: |
| 612 |
b.chord_error_from_stack(callback, exc=ValueError()) |
| 613 |
task.backend.fail_from_current_stack.assert_called_with( |
| 614 |
callback.id, exc=mock_call_errbacks.side_effect, |
| 615 |
) |
| 616 |
|
| 617 |
def test_exception_to_python_when_None(self): |
| 618 |
b = BaseBackend(app=self.app) |
| 619 |
assert b.exception_to_python(None) is None |
| 620 |
|
| 621 |
def test_not_an_actual_exc_info(self): |
| 622 |
pass |
| 623 |
|
| 624 |
def test_not_an_exception_but_a_callable(self): |
| 625 |
x = { |
| 626 |
'exc_message': ('echo 1',), |
| 627 |
'exc_type': 'system', |
| 628 |
'exc_module': 'os' |
| 629 |
} |
| 630 |
|
| 631 |
with pytest.raises(SecurityError, |
| 632 |
match=re.escape(r"Expected an exception class, got os.system with payload ('echo 1',)")): |
| 633 |
self.b.exception_to_python(x) |
| 634 |
|
| 635 |
def test_not_an_exception_but_another_object(self): |
| 636 |
x = { |
| 637 |
'exc_message': (), |
| 638 |
'exc_type': 'object', |
| 639 |
'exc_module': 'builtins' |
| 640 |
} |
| 641 |
|
| 642 |
with pytest.raises(SecurityError, |
| 643 |
match=re.escape(r"Expected an exception class, got builtins.object with payload ()")): |
| 644 |
self.b.exception_to_python(x) |
| 645 |
|
| 646 |
def test_exception_to_python_when_attribute_exception(self): |
| 647 |
b = BaseBackend(app=self.app) |
| 648 |
test_exception = {'exc_type': 'AttributeDoesNotExist', |
| 649 |
'exc_module': 'celery', |
| 650 |
'exc_message': ['Raise Custom Message']} |
| 651 |
|
| 652 |
result_exc = b.exception_to_python(test_exception) |
| 653 |
assert str(result_exc) == 'Raise Custom Message' |
| 654 |
|
| 655 |
def test_exception_to_python_when_type_error(self): |
| 656 |
b = BaseBackend(app=self.app) |
| 657 |
celery.TestParamException = paramexception |
| 658 |
test_exception = {'exc_type': 'TestParamException', |
| 659 |
'exc_module': 'celery', |
| 660 |
'exc_message': []} |
| 661 |
|
| 662 |
result_exc = b.exception_to_python(test_exception) |
| 663 |
del celery.TestParamException |
| 664 |
assert str(result_exc) == "<class 't.unit.backends.test_base.paramexception'>([])" |
| 665 |
|
| 666 |
def test_wait_for__on_interval(self): |
| 667 |
self.patching('time.sleep') |
| 668 |
b = BaseBackend(app=self.app) |
| 669 |
b._get_task_meta_for = Mock() |
| 670 |
b._get_task_meta_for.return_value = {'status': states.PENDING} |
| 671 |
callback = Mock(name='callback') |
| 672 |
with pytest.raises(TimeoutError): |
| 673 |
b.wait_for(task_id='1', on_interval=callback, timeout=1) |
| 674 |
callback.assert_called_with() |
| 675 |
|
| 676 |
b._get_task_meta_for.return_value = {'status': states.SUCCESS} |
| 677 |
b.wait_for(task_id='1', timeout=None) |
| 678 |
|
| 679 |
def test_get_children(self): |
| 680 |
b = BaseBackend(app=self.app) |
| 681 |
b._get_task_meta_for = Mock() |
| 682 |
b._get_task_meta_for.return_value = {} |
| 683 |
assert b.get_children('id') is None |
| 684 |
b._get_task_meta_for.return_value = {'children': 3} |
| 685 |
assert b.get_children('id') == 3 |
| 686 |
|
| 687 |
@pytest.mark.parametrize( |
| 688 |
"message,original_exc,expected_cause_behavior", |
| 689 |
[ |
| 690 |
# With exception - should preserve original exception |
| 691 |
( |
| 692 |
"Dependency failed", |
| 693 |
ValueError("original error"), |
| 694 |
"has_cause", |
| 695 |
), |
| 696 |
# Without exception (None) - should not have __cause__ |
| 697 |
( |
| 698 |
"Dependency failed", |
| 699 |
None, |
| 700 |
"no_cause", |
| 701 |
), |
| 702 |
# With non-exception - should not have __cause__ |
| 703 |
( |
| 704 |
"Dependency failed", |
| 705 |
"not an exception", |
| 706 |
"no_cause", |
| 707 |
), |
| 708 |
], |
| 709 |
ids=( |
| 710 |
"with_exception", |
| 711 |
"without_exception", |
| 712 |
"with_non_exception", |
| 713 |
) |
| 714 |
) |
| 715 |
def test_create_chord_error_with_cause( |
| 716 |
self, message, original_exc, expected_cause_behavior |
| 717 |
): |
| 718 |
"""Test _create_chord_error_with_cause with various parameter combinations.""" |
| 719 |
chord_error = _create_chord_error_with_cause(message, original_exc) |
| 720 |
|
| 721 |
# Verify basic ChordError properties |
| 722 |
assert isinstance(chord_error, ChordError) |
| 723 |
assert str(chord_error) == message |
| 724 |
|
| 725 |
# Verify __cause__ behavior based on test case |
| 726 |
if expected_cause_behavior == "has_cause": |
| 727 |
assert chord_error.__cause__ is original_exc |
| 728 |
elif expected_cause_behavior == "no_cause": |
| 729 |
assert not hasattr(chord_error, '__cause__') or chord_error.__cause__ is None |
| 730 |
|
| 731 |
@pytest.mark.parametrize( |
| 732 |
"task_id,errbacks,task_name,extra_kwargs,expected_attrs", |
| 733 |
[ |
| 734 |
# Basic parameters test |
| 735 |
( |
| 736 |
"test-task-id", |
| 737 |
["errback1", "errback2"], |
| 738 |
"test.task", |
| 739 |
{}, |
| 740 |
{ |
| 741 |
"id": "test-task-id", |
| 742 |
"errbacks": ["errback1", "errback2"], |
| 743 |
"task": "test.task", |
| 744 |
"delivery_info": {}, |
| 745 |
}, |
| 746 |
), |
| 747 |
# Default parameters test |
| 748 |
( |
| 749 |
"test-task-id", |
| 750 |
None, |
| 751 |
None, |
| 752 |
{}, |
| 753 |
{ |
| 754 |
"id": "test-task-id", |
| 755 |
"errbacks": [], |
| 756 |
"task": "unknown", |
| 757 |
"delivery_info": {}, |
| 758 |
}, |
| 759 |
), |
| 760 |
# Extra parameters test |
| 761 |
( |
| 762 |
"test-task-id", |
| 763 |
None, |
| 764 |
None, |
| 765 |
{"extra_param": "extra_value"}, |
| 766 |
{ |
| 767 |
"id": "test-task-id", |
| 768 |
"errbacks": [], |
| 769 |
"task": "unknown", |
| 770 |
"delivery_info": {}, |
| 771 |
"extra_param": "extra_value", |
| 772 |
}, |
| 773 |
), |
| 774 |
], |
| 775 |
ids=( |
| 776 |
"basic_parameters", |
| 777 |
"default_parameters", |
| 778 |
"extra_parameters", |
| 779 |
) |
| 780 |
) |
| 781 |
def test_create_fake_task_request( |
| 782 |
self, task_id, errbacks, task_name, extra_kwargs, expected_attrs |
| 783 |
): |
| 784 |
"""Test _create_fake_task_request with various parameter combinations.""" |
| 785 |
# Build call arguments |
| 786 |
args = [task_id] |
| 787 |
if errbacks is not None: |
| 788 |
args.append(errbacks) |
| 789 |
if task_name is not None: |
| 790 |
args.append(task_name) |
| 791 |
|
| 792 |
fake_request = _create_fake_task_request(*args, **extra_kwargs) |
| 793 |
|
| 794 |
# Verify all expected attributes |
| 795 |
for attr_name, expected_value in expected_attrs.items(): |
| 796 |
assert getattr(fake_request, attr_name) == expected_value |
| 797 |
|
| 798 |
def _create_mock_callback(self, task_name="test.task", spec=None, **options): |
| 799 |
"""Helper to create mock callbacks with common setup.""" |
| 800 |
from collections.abc import Mapping |
| 801 |
|
| 802 |
# Create a mock that properly implements the |
| 803 |
# mapping protocol for PyPy env compatibility |
| 804 |
class MockCallback(Mock, Mapping): |
| 805 |
def __init__(self, *args, **kwargs): |
| 806 |
super().__init__(*args, **kwargs) |
| 807 |
self._mapping_data = {} |
| 808 |
|
| 809 |
def __getitem__(self, key): |
| 810 |
return self._mapping_data[key] |
| 811 |
|
| 812 |
def __iter__(self): |
| 813 |
return iter(self._mapping_data) |
| 814 |
|
| 815 |
def __len__(self): |
| 816 |
return len(self._mapping_data) |
| 817 |
|
| 818 |
def keys(self): |
| 819 |
return self._mapping_data.keys() |
| 820 |
|
| 821 |
def items(self): |
| 822 |
return self._mapping_data.items() |
| 823 |
|
| 824 |
callback = MockCallback(spec=spec) |
| 825 |
callback.task = task_name |
| 826 |
callback.options = {"link_error": [], **options} |
| 827 |
|
| 828 |
return callback |
| 829 |
|
| 830 |
def _setup_task_backend(self, task_name, backend=None): |
| 831 |
"""Helper to set up task with backend in app registry.""" |
| 832 |
if backend is None: |
| 833 |
backend = Mock() |
| 834 |
backend.fail_from_current_stack = Mock(return_value="backend_result") |
| 835 |
|
| 836 |
self.app.tasks[task_name] = Mock() |
| 837 |
self.app.tasks[task_name].backend = backend |
| 838 |
return backend |
| 839 |
|
| 840 |
@pytest.mark.parametrize( |
| 841 |
"callback_type,task_name,expected_group_handler_called", |
| 842 |
[ |
| 843 |
("group", "test.group.task", True), |
| 844 |
("regular", "test.task", False), |
| 845 |
], |
| 846 |
ids=["group_callback", "regular_callback"] |
| 847 |
) |
| 848 |
def test_chord_error_from_stack_callback_dispatch(self, callback_type, task_name, expected_group_handler_called): |
| 849 |
"""Test chord_error_from_stack dispatches to correct handler based on callback type.""" |
| 850 |
backend = self.b |
| 851 |
|
| 852 |
# Create callback based on type |
| 853 |
spec = group if callback_type == "group" else None |
| 854 |
callback = self._create_mock_callback(task_name, spec=spec) |
| 855 |
|
| 856 |
# Setup backend resolution |
| 857 |
mock_backend = self._setup_task_backend(task_name) |
| 858 |
|
| 859 |
# Mock handlers |
| 860 |
backend._handle_group_chord_error = Mock(return_value="group_result") |
| 861 |
backend._call_task_errbacks = Mock() |
| 862 |
|
| 863 |
exc = ValueError("test exception") |
| 864 |
result = backend.chord_error_from_stack(callback, exc) |
| 865 |
|
| 866 |
if expected_group_handler_called: |
| 867 |
backend._handle_group_chord_error.assert_called_once_with( |
| 868 |
group_callback=callback, backend=mock_backend, exc=exc |
| 869 |
) |
| 870 |
assert result == "group_result" |
| 871 |
else: |
| 872 |
mock_backend.fail_from_current_stack.assert_called_once() |
| 873 |
|
| 874 |
def test_chord_error_from_stack_backend_fallback(self): |
| 875 |
"""Test chord_error_from_stack falls back to self when task not found.""" |
| 876 |
backend = self.b |
| 877 |
|
| 878 |
callback = self._create_mock_callback("nonexistent.task") |
| 879 |
|
| 880 |
# Ensure task doesn't exist |
| 881 |
if "nonexistent.task" in self.app.tasks: |
| 882 |
del self.app.tasks["nonexistent.task"] |
| 883 |
|
| 884 |
backend._call_task_errbacks = Mock() |
| 885 |
backend.fail_from_current_stack = Mock(return_value="self_result") |
| 886 |
|
| 887 |
_ = backend.chord_error_from_stack(callback, ValueError("test")) |
| 888 |
|
| 889 |
# Verify self was used as fallback backend |
| 890 |
backend.fail_from_current_stack.assert_called_once() |
| 891 |
|
| 892 |
def _create_mock_frozen_group(self, group_id="group-id", task_ids=None, task_names=None): |
| 893 |
"""Helper to create mock frozen group with results.""" |
| 894 |
if task_ids is None: |
| 895 |
task_ids = ["task-id-1"] |
| 896 |
if task_names is None: |
| 897 |
task_names = ["test.task"] * len(task_ids) |
| 898 |
|
| 899 |
results = [] |
| 900 |
for task_id, task_name in zip(task_ids, task_names): |
| 901 |
result = Mock() |
| 902 |
result.id = task_id |
| 903 |
result.task = task_name |
| 904 |
results.append(result) |
| 905 |
|
| 906 |
frozen_group = Mock(spec=GroupResult) |
| 907 |
frozen_group.results = results |
| 908 |
frozen_group.id = group_id |
| 909 |
frozen_group.revoke = Mock() |
| 910 |
return frozen_group |
| 911 |
|
| 912 |
def _setup_group_chord_error_test(self, exc=None, errbacks=None, task_ids=None): |
| 913 |
"""Common setup for group chord error tests.""" |
| 914 |
if exc is None: |
| 915 |
exc = ValueError("test error") |
| 916 |
if errbacks is None: |
| 917 |
errbacks = [] |
| 918 |
if task_ids is None: |
| 919 |
task_ids = ["task-id-1"] |
| 920 |
|
| 921 |
backend = Mock() |
| 922 |
backend._call_task_errbacks = Mock() |
| 923 |
backend.fail_from_current_stack = Mock() |
| 924 |
backend.mark_as_failure = Mock() |
| 925 |
|
| 926 |
group_callback = Mock(spec=group) |
| 927 |
group_callback.options = {"link_error": errbacks} |
| 928 |
|
| 929 |
frozen_group = self._create_mock_frozen_group(task_ids=task_ids) |
| 930 |
group_callback.freeze.return_value = frozen_group |
| 931 |
|
| 932 |
return self.b, backend, group_callback, frozen_group, exc |
| 933 |
|
| 934 |
@pytest.mark.parametrize( |
| 935 |
"exception_setup,expected_exc_used", |
| 936 |
[ |
| 937 |
("with_cause", "original"), |
| 938 |
("without_cause", "direct"), |
| 939 |
], |
| 940 |
ids=["extracts_cause", "without_cause"] |
| 941 |
) |
| 942 |
def test_handle_group_chord_error_exception_handling(self, exception_setup, expected_exc_used): |
| 943 |
"""Test _handle_group_chord_error handles exceptions with and without __cause__.""" |
| 944 |
# Setup exceptions based on test case |
| 945 |
if exception_setup == "with_cause": |
| 946 |
original_exc = ValueError("original error") |
| 947 |
exc = ChordError("wrapped error") |
| 948 |
exc.__cause__ = original_exc |
| 949 |
expected_exc = original_exc |
| 950 |
else: |
| 951 |
exc = ValueError("direct error") |
| 952 |
expected_exc = exc |
| 953 |
|
| 954 |
b, backend, group_callback, frozen_group, _ = self._setup_group_chord_error_test(exc=exc) |
| 955 |
|
| 956 |
# Call the method |
| 957 |
_ = b._handle_group_chord_error(group_callback, backend, exc) |
| 958 |
|
| 959 |
# Verify correct exception was used |
| 960 |
backend.fail_from_current_stack.assert_called_with("task-id-1", exc=expected_exc) |
| 961 |
backend.mark_as_failure.assert_called_with("group-id", expected_exc) |
| 962 |
frozen_group.revoke.assert_called_once() |
| 963 |
|
| 964 |
def test_handle_group_chord_error_multiple_tasks(self): |
| 965 |
"""Test _handle_group_chord_error handles multiple tasks in group.""" |
| 966 |
task_ids = ["task-id-1", "task-id-2"] |
| 967 |
b, backend, group_callback, frozen_group, exc = self._setup_group_chord_error_test(task_ids=task_ids) |
| 968 |
|
| 969 |
# Call the method |
| 970 |
b._handle_group_chord_error(group_callback, backend, exc) |
| 971 |
|
| 972 |
# Verify group revocation and all tasks handled |
| 973 |
frozen_group.revoke.assert_called_once() |
| 974 |
assert backend.fail_from_current_stack.call_count == 2 |
| 975 |
backend.fail_from_current_stack.assert_any_call("task-id-1", exc=exc) |
| 976 |
backend.fail_from_current_stack.assert_any_call("task-id-2", exc=exc) |
| 977 |
|
| 978 |
def test_handle_group_chord_error_with_errbacks(self): |
| 979 |
"""Test _handle_group_chord_error calls error callbacks for each task.""" |
| 980 |
errbacks = ["errback1", "errback2"] |
| 981 |
b, backend, group_callback, frozen_group, exc = self._setup_group_chord_error_test(errbacks=errbacks) |
| 982 |
|
| 983 |
# Call the method |
| 984 |
b._handle_group_chord_error(group_callback, backend, exc) |
| 985 |
|
| 986 |
# Verify error callbacks were called |
| 987 |
backend._call_task_errbacks.assert_called_once() |
| 988 |
call_args = backend._call_task_errbacks.call_args |
| 989 |
fake_request = call_args[0][0] |
| 990 |
|
| 991 |
# Verify fake request was created correctly |
| 992 |
assert fake_request.id == "task-id-1" |
| 993 |
assert fake_request.errbacks == errbacks |
| 994 |
assert fake_request.task == "test.task" |
| 995 |
|
| 996 |
def test_handle_group_chord_error_cleanup_exception_handling(self): |
| 997 |
"""Test _handle_group_chord_error handles cleanup exceptions gracefully.""" |
| 998 |
b = self.b |
| 999 |
backend = Mock() |
| 1000 |
|
| 1001 |
exc = ValueError("test error") |
| 1002 |
|
| 1003 |
# Mock group callback that raises exception during freeze |
| 1004 |
group_callback = Mock(spec=group) |
| 1005 |
group_callback.freeze.side_effect = RuntimeError("freeze failed") |
| 1006 |
|
| 1007 |
# Mock fallback behavior |
| 1008 |
backend.fail_from_current_stack = Mock(return_value="fallback_result") |
| 1009 |
|
| 1010 |
# Should not raise exception, but return fallback result |
| 1011 |
result = b._handle_group_chord_error(group_callback, backend, exc) |
| 1012 |
|
| 1013 |
# Verify fallback was called - the method returns an ExceptionInfo when cleanup fails |
| 1014 |
# and falls back to single task handling |
| 1015 |
assert result is not None # Method returns ExceptionInfo from fail_from_current_stack |
| 1016 |
|
| 1017 |
def test_handle_group_chord__exceptions_paths(self, caplog): |
| 1018 |
"""Test _handle_group_chord handles exceptions in various paths.""" |
| 1019 |
backend = Mock() |
| 1020 |
|
| 1021 |
# Mock group callback |
| 1022 |
group_callback = Mock(spec=group) |
| 1023 |
group_callback.options = {"link_error": []} |
| 1024 |
|
| 1025 |
# Mock frozen group with multiple results |
| 1026 |
mock_result1 = Mock() |
| 1027 |
mock_result1.id = "task-id-1" |
| 1028 |
mock_result2 = Mock() |
| 1029 |
mock_result2.id = "task-id-2" |
| 1030 |
|
| 1031 |
frozen_group = Mock(spec=GroupResult) |
| 1032 |
frozen_group.results = [mock_result1, mock_result2] |
| 1033 |
frozen_group.revoke = Mock() |
| 1034 |
|
| 1035 |
group_callback.freeze.return_value = frozen_group |
| 1036 |
|
| 1037 |
# Test exception during fail_from_current_stack |
| 1038 |
backend._call_task_errbacks.side_effect = RuntimeError("fail on _call_task_errbacks") |
| 1039 |
|
| 1040 |
backend.fail_from_current_stack.side_effect = RuntimeError("fail on fail_from_current_stack") |
| 1041 |
|
| 1042 |
_ = self.b._handle_group_chord_error(group_callback, backend, ValueError("test error")) |
| 1043 |
|
| 1044 |
assert "Failed to handle chord error for task" in caplog.text |
| 1045 |
|
| 1046 |
|
| 1047 |
class test_KeyValueStoreBackend: |
| 1048 |
|
| 1049 |
def setup_method(self): |
| 1050 |
self.b = KVBackend(app=self.app) |
| 1051 |
|
| 1052 |
def test_on_chord_part_return(self): |
| 1053 |
assert not self.b.implements_incr |
| 1054 |
self.b.on_chord_part_return(None, None, None) |
| 1055 |
|
| 1056 |
def test_get_store_delete_result(self): |
| 1057 |
tid = uuid() |
| 1058 |
self.b.mark_as_done(tid, 'Hello world') |
| 1059 |
assert self.b.get_result(tid) == 'Hello world' |
| 1060 |
assert self.b.get_state(tid) == states.SUCCESS |
| 1061 |
self.b.forget(tid) |
| 1062 |
assert self.b.get_state(tid) == states.PENDING |
| 1063 |
|
| 1064 |
@pytest.mark.parametrize('serializer', |
| 1065 |
['json', 'pickle', 'yaml', 'msgpack']) |
| 1066 |
def test_store_result_parent_id(self, serializer): |
| 1067 |
self.app.conf.accept_content = ('json', serializer) |
| 1068 |
self.b = KVBackend(app=self.app, serializer=serializer) |
| 1069 |
tid = uuid() |
| 1070 |
pid = uuid() |
| 1071 |
state = 'SUCCESS' |
| 1072 |
result = 10 |
| 1073 |
request = Context(parent_id=pid) |
| 1074 |
self.b.store_result( |
| 1075 |
tid, state=state, result=result, request=request, |
| 1076 |
) |
| 1077 |
stored_meta = self.b.decode(self.b.get(self.b.get_key_for_task(tid))) |
| 1078 |
assert stored_meta['parent_id'] == request.parent_id |
| 1079 |
|
| 1080 |
def test_store_result_group_id(self): |
| 1081 |
tid = uuid() |
| 1082 |
state = 'SUCCESS' |
| 1083 |
result = 10 |
| 1084 |
request = Context(group='gid', children=[]) |
| 1085 |
self.b.store_result( |
| 1086 |
tid, state=state, result=result, request=request, |
| 1087 |
) |
| 1088 |
stored_meta = self.b.decode(self.b.get(self.b.get_key_for_task(tid))) |
| 1089 |
assert stored_meta['group_id'] == request.group |
| 1090 |
|
| 1091 |
def test_store_result_race_second_write_should_ignore_if_previous_success(self): |
| 1092 |
tid = uuid() |
| 1093 |
state = 'SUCCESS' |
| 1094 |
result = 10 |
| 1095 |
request = Context(group='gid', children=[]) |
| 1096 |
self.b.store_result( |
| 1097 |
tid, state=state, result=result, request=request, |
| 1098 |
) |
| 1099 |
self.b.store_result( |
| 1100 |
tid, state=states.FAILURE, result=result, request=request, |
| 1101 |
) |
| 1102 |
stored_meta = self.b.decode(self.b.get(self.b.get_key_for_task(tid))) |
| 1103 |
assert stored_meta['status'] == states.SUCCESS |
| 1104 |
|
| 1105 |
def test_get_key_for_task_none_task_id(self): |
| 1106 |
with pytest.raises(ValueError): |
| 1107 |
self.b.get_key_for_task(None) |
| 1108 |
|
| 1109 |
def test_get_key_for_group_none_group_id(self): |
| 1110 |
with pytest.raises(ValueError): |
| 1111 |
self.b.get_key_for_task(None) |
| 1112 |
|
| 1113 |
def test_get_key_for_chord_none_group_id(self): |
| 1114 |
with pytest.raises(ValueError): |
| 1115 |
self.b.get_key_for_group(None) |
| 1116 |
|
| 1117 |
def test_strip_prefix(self): |
| 1118 |
x = self.b.get_key_for_task('x1b34') |
| 1119 |
assert self.b._strip_prefix(x) == 'x1b34' |
| 1120 |
assert self.b._strip_prefix('x1b34') == 'x1b34' |
| 1121 |
|
| 1122 |
def test_global_keyprefix(self): |
| 1123 |
global_keyprefix = "test_global_keyprefix" |
| 1124 |
app = copy.deepcopy(self.app) |
| 1125 |
app.conf.get('result_backend_transport_options', {}).update({"global_keyprefix": global_keyprefix}) |
| 1126 |
b = KVBackend(app=app) |
| 1127 |
tid = uuid() |
| 1128 |
assert bytes_to_str(b.get_key_for_task(tid)) == f"{global_keyprefix}_celery-task-meta-{tid}" |
| 1129 |
assert bytes_to_str(b.get_key_for_group(tid)) == f"{global_keyprefix}_celery-taskset-meta-{tid}" |
| 1130 |
assert bytes_to_str(b.get_key_for_chord(tid)) == f"{global_keyprefix}_chord-unlock-{tid}" |
| 1131 |
|
| 1132 |
global_keyprefix = "test_global_keyprefix_" |
| 1133 |
app = copy.deepcopy(self.app) |
| 1134 |
app.conf.get('result_backend_transport_options', {}).update({"global_keyprefix": global_keyprefix}) |
| 1135 |
b = KVBackend(app=app) |
| 1136 |
tid = uuid() |
| 1137 |
assert bytes_to_str(b.get_key_for_task(tid)) == f"{global_keyprefix}celery-task-meta-{tid}" |
| 1138 |
assert bytes_to_str(b.get_key_for_group(tid)) == f"{global_keyprefix}celery-taskset-meta-{tid}" |
| 1139 |
assert bytes_to_str(b.get_key_for_chord(tid)) == f"{global_keyprefix}chord-unlock-{tid}" |
| 1140 |
|
| 1141 |
global_keyprefix = "test_global_keyprefix:" |
| 1142 |
app = copy.deepcopy(self.app) |
| 1143 |
app.conf.get('result_backend_transport_options', {}).update({"global_keyprefix": global_keyprefix}) |
| 1144 |
b = KVBackend(app=app) |
| 1145 |
tid = uuid() |
| 1146 |
assert bytes_to_str(b.get_key_for_task(tid)) == f"{global_keyprefix}celery-task-meta-{tid}" |
| 1147 |
assert bytes_to_str(b.get_key_for_group(tid)) == f"{global_keyprefix}celery-taskset-meta-{tid}" |
| 1148 |
assert bytes_to_str(b.get_key_for_chord(tid)) == f"{global_keyprefix}chord-unlock-{tid}" |
| 1149 |
|
| 1150 |
def test_global_keyprefix_missing(self): |
| 1151 |
tid = uuid() |
| 1152 |
assert bytes_to_str(self.b.get_key_for_task(tid)) == f"celery-task-meta-{tid}" |
| 1153 |
assert bytes_to_str(self.b.get_key_for_group(tid)) == f"celery-taskset-meta-{tid}" |
| 1154 |
assert bytes_to_str(self.b.get_key_for_chord(tid)) == f"chord-unlock-{tid}" |
| 1155 |
|
| 1156 |
def test_get_many(self): |
| 1157 |
for is_dict in True, False: |
| 1158 |
self.b.mget_returns_dict = is_dict |
| 1159 |
ids = {uuid(): i for i in range(10)} |
| 1160 |
for id, i in ids.items(): |
| 1161 |
self.b.mark_as_done(id, i) |
| 1162 |
it = self.b.get_many(list(ids), interval=0.01) |
| 1163 |
for i, (got_id, got_state) in enumerate(it): |
| 1164 |
assert got_state['result'] == ids[got_id] |
| 1165 |
assert i == 9 |
| 1166 |
assert list(self.b.get_many(list(ids), interval=0.01)) |
| 1167 |
|
| 1168 |
self.b._cache.clear() |
| 1169 |
callback = Mock(name='callback') |
| 1170 |
it = self.b.get_many( |
| 1171 |
list(ids), |
| 1172 |
on_message=callback, |
| 1173 |
interval=0.05 |
| 1174 |
) |
| 1175 |
for i, (got_id, got_state) in enumerate(it): |
| 1176 |
assert got_state['result'] == ids[got_id] |
| 1177 |
assert i == 9 |
| 1178 |
assert list( |
| 1179 |
self.b.get_many(list(ids), interval=0.01) |
| 1180 |
) |
| 1181 |
callback.assert_has_calls([ |
| 1182 |
call(ANY) for id in ids |
| 1183 |
]) |
| 1184 |
|
| 1185 |
def test_get_many_times_out(self): |
| 1186 |
tasks = [uuid() for _ in range(4)] |
| 1187 |
self.b._cache[tasks[1]] = {'status': 'PENDING'} |
| 1188 |
with pytest.raises(self.b.TimeoutError): |
| 1189 |
list(self.b.get_many(tasks, timeout=0.01, interval=0.01)) |
| 1190 |
|
| 1191 |
def test_get_many_passes_ready_states(self): |
| 1192 |
tasks_length = 10 |
| 1193 |
ready_states = frozenset({states.SUCCESS}) |
| 1194 |
|
| 1195 |
self.b._cache.clear() |
| 1196 |
ids = {uuid(): i for i in range(tasks_length)} |
| 1197 |
for id, i in ids.items(): |
| 1198 |
if i % 2 == 0: |
| 1199 |
self.b.mark_as_done(id, i) |
| 1200 |
else: |
| 1201 |
self.b.mark_as_failure(id, Exception()) |
| 1202 |
|
| 1203 |
it = self.b.get_many(list(ids), interval=0.01, max_iterations=1, READY_STATES=ready_states) |
| 1204 |
it_list = list(it) |
| 1205 |
|
| 1206 |
assert all([got_state['status'] in ready_states for (got_id, got_state) in it_list]) |
| 1207 |
assert len(it_list) == tasks_length / 2 |
| 1208 |
|
| 1209 |
def test_chord_part_return_no_gid(self): |
| 1210 |
self.b.implements_incr = True |
| 1211 |
task = Mock() |
| 1212 |
state = 'SUCCESS' |
| 1213 |
result = 10 |
| 1214 |
task.request.group = None |
| 1215 |
self.b.get_key_for_chord = Mock() |
| 1216 |
self.b.get_key_for_chord.side_effect = AssertionError( |
| 1217 |
'should not get here', |
| 1218 |
) |
| 1219 |
assert self.b.on_chord_part_return( |
| 1220 |
task.request, state, result) is None |
| 1221 |
|
| 1222 |
@patch('celery.backends.base.GroupResult') |
| 1223 |
@patch('celery.backends.base.maybe_signature') |
| 1224 |
def test_chord_part_return_restore_raises(self, maybe_signature, |
| 1225 |
GroupResult): |
| 1226 |
self.b.implements_incr = True |
| 1227 |
GroupResult.restore.side_effect = KeyError() |
| 1228 |
self.b.chord_error_from_stack = Mock() |
| 1229 |
callback = Mock(name='callback') |
| 1230 |
request = Mock(name='request') |
| 1231 |
request.group = 'gid' |
| 1232 |
maybe_signature.return_value = callback |
| 1233 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1234 |
self.b.chord_error_from_stack.assert_called_with( |
| 1235 |
callback, ANY, |
| 1236 |
) |
| 1237 |
|
| 1238 |
@patch('celery.backends.base.GroupResult') |
| 1239 |
@patch('celery.backends.base.maybe_signature') |
| 1240 |
def test_chord_part_return_restore_empty(self, maybe_signature, |
| 1241 |
GroupResult): |
| 1242 |
self.b.implements_incr = True |
| 1243 |
GroupResult.restore.return_value = None |
| 1244 |
self.b.chord_error_from_stack = Mock() |
| 1245 |
callback = Mock(name='callback') |
| 1246 |
request = Mock(name='request') |
| 1247 |
request.group = 'gid' |
| 1248 |
maybe_signature.return_value = callback |
| 1249 |
self.b.on_chord_part_return(request, states.SUCCESS, 10) |
| 1250 |
self.b.chord_error_from_stack.assert_called_with( |
| 1251 |
callback, ANY, |
| 1252 |
) |
| 1253 |
|
| 1254 |
def test_filter_ready(self): |
| 1255 |
self.b.decode_result = Mock() |
| 1256 |
self.b.decode_result.side_effect = pass1 |
| 1257 |
assert len(list(self.b._filter_ready([ |
| 1258 |
(1, {'status': states.RETRY}), |
| 1259 |
(2, {'status': states.FAILURE}), |
| 1260 |
(3, {'status': states.SUCCESS}), |
| 1261 |
]))) == 2 |
| 1262 |
|
| 1263 |
@contextmanager |
| 1264 |
def _chord_part_context(self, b): |
| 1265 |
|
| 1266 |
@self.app.task(shared=False) |
| 1267 |
def callback(result): |
| 1268 |
pass |
| 1269 |
|
| 1270 |
b.implements_incr = True |
| 1271 |
b.client = Mock() |
| 1272 |
with patch('celery.backends.base.GroupResult') as GR: |
| 1273 |
deps = GR.restore.return_value = Mock(name='DEPS') |
| 1274 |
deps.__len__ = Mock() |
| 1275 |
deps.__len__.return_value = 10 |
| 1276 |
b.incr = Mock() |
| 1277 |
b.incr.return_value = 10 |
| 1278 |
b.expire = Mock() |
| 1279 |
task = Mock() |
| 1280 |
task.request.group = 'grid' |
| 1281 |
cb = task.request.chord = callback.s() |
| 1282 |
task.request.chord.freeze() |
| 1283 |
callback.backend = b |
| 1284 |
callback.backend.fail_from_current_stack = Mock() |
| 1285 |
yield task, deps, cb |
| 1286 |
|
| 1287 |
def test_chord_part_return_timeout(self): |
| 1288 |
with self._chord_part_context(self.b) as (task, deps, _): |
| 1289 |
try: |
| 1290 |
self.app.conf.result_chord_join_timeout += 1.0 |
| 1291 |
self.b.on_chord_part_return(task.request, 'SUCCESS', 10) |
| 1292 |
finally: |
| 1293 |
self.app.conf.result_chord_join_timeout -= 1.0 |
| 1294 |
|
| 1295 |
self.b.expire.assert_not_called() |
| 1296 |
deps.delete.assert_called_with() |
| 1297 |
deps.join_native.assert_called_with(propagate=True, timeout=4.0) |
| 1298 |
|
| 1299 |
def test_chord_part_return_propagate_set(self): |
| 1300 |
with self._chord_part_context(self.b) as (task, deps, _): |
| 1301 |
self.b.on_chord_part_return(task.request, 'SUCCESS', 10) |
| 1302 |
self.b.expire.assert_not_called() |
| 1303 |
deps.delete.assert_called_with() |
| 1304 |
deps.join_native.assert_called_with(propagate=True, timeout=3.0) |
| 1305 |
|
| 1306 |
def test_chord_part_return_propagate_default(self): |
| 1307 |
with self._chord_part_context(self.b) as (task, deps, _): |
| 1308 |
self.b.on_chord_part_return(task.request, 'SUCCESS', 10) |
| 1309 |
self.b.expire.assert_not_called() |
| 1310 |
deps.delete.assert_called_with() |
| 1311 |
deps.join_native.assert_called_with(propagate=True, timeout=3.0) |
| 1312 |
|
| 1313 |
def test_chord_part_return_join_raises_internal(self): |
| 1314 |
with self._chord_part_context(self.b) as (task, deps, callback): |
| 1315 |
deps._failed_join_report = lambda: iter([]) |
| 1316 |
deps.join_native.side_effect = KeyError('foo') |
| 1317 |
self.b.on_chord_part_return(task.request, 'SUCCESS', 10) |
| 1318 |
self.b.fail_from_current_stack.assert_called() |
| 1319 |
args = self.b.fail_from_current_stack.call_args |
| 1320 |
exc = args[1]['exc'] |
| 1321 |
assert isinstance(exc, ChordError) |
| 1322 |
assert 'foo' in str(exc) |
| 1323 |
|
| 1324 |
def test_chord_part_return_join_raises_task(self): |
| 1325 |
b = KVBackend(serializer='pickle', app=self.app) |
| 1326 |
with self._chord_part_context(b) as (task, deps, callback): |
| 1327 |
deps._failed_join_report = lambda: iter([ |
| 1328 |
self.app.AsyncResult('culprit'), |
| 1329 |
]) |
| 1330 |
deps.join_native.side_effect = KeyError('foo') |
| 1331 |
b.on_chord_part_return(task.request, 'SUCCESS', 10) |
| 1332 |
b.fail_from_current_stack.assert_called() |
| 1333 |
args = b.fail_from_current_stack.call_args |
| 1334 |
exc = args[1]['exc'] |
| 1335 |
assert isinstance(exc, ChordError) |
| 1336 |
assert 'Dependency culprit raised' in str(exc) |
| 1337 |
|
| 1338 |
def test_restore_group_from_json(self): |
| 1339 |
b = KVBackend(serializer='json', app=self.app) |
| 1340 |
g = self.app.GroupResult( |
| 1341 |
'group_id', |
| 1342 |
[self.app.AsyncResult('a'), self.app.AsyncResult('b')], |
| 1343 |
) |
| 1344 |
b._save_group(g.id, g) |
| 1345 |
g2 = b._restore_group(g.id)['result'] |
| 1346 |
assert g2 == g |
| 1347 |
|
| 1348 |
def test_restore_group_from_pickle(self): |
| 1349 |
b = KVBackend(serializer='pickle', app=self.app) |
| 1350 |
g = self.app.GroupResult( |
| 1351 |
'group_id', |
| 1352 |
[self.app.AsyncResult('a'), self.app.AsyncResult('b')], |
| 1353 |
) |
| 1354 |
b._save_group(g.id, g) |
| 1355 |
g2 = b._restore_group(g.id)['result'] |
| 1356 |
assert g2 == g |
| 1357 |
|
| 1358 |
def test_chord_apply_fallback(self): |
| 1359 |
self.b.implements_incr = False |
| 1360 |
self.b.fallback_chord_unlock = Mock() |
| 1361 |
header_result_args = ( |
| 1362 |
'group_id', |
| 1363 |
[self.app.AsyncResult(x) for x in range(3)], |
| 1364 |
) |
| 1365 |
self.b.apply_chord( |
| 1366 |
header_result_args, 'body', foo=1, |
| 1367 |
) |
| 1368 |
self.b.fallback_chord_unlock.assert_called_with( |
| 1369 |
self.app.GroupResult(*header_result_args), 'body', foo=1, |
| 1370 |
) |
| 1371 |
|
| 1372 |
def test_get_missing_meta(self): |
| 1373 |
assert self.b.get_result('xxx-missing') is None |
| 1374 |
assert self.b.get_state('xxx-missing') == states.PENDING |
| 1375 |
|
| 1376 |
def test_save_restore_delete_group(self): |
| 1377 |
tid = uuid() |
| 1378 |
tsr = self.app.GroupResult( |
| 1379 |
tid, [self.app.AsyncResult(uuid()) for _ in range(10)], |
| 1380 |
) |
| 1381 |
self.b.save_group(tid, tsr) |
| 1382 |
self.b.restore_group(tid) |
| 1383 |
assert self.b.restore_group(tid) == tsr |
| 1384 |
self.b.delete_group(tid) |
| 1385 |
assert self.b.restore_group(tid) is None |
| 1386 |
|
| 1387 |
def test_restore_missing_group(self): |
| 1388 |
assert self.b.restore_group('xxx-nonexistant') is None |
| 1389 |
|
| 1390 |
|
| 1391 |
class test_KeyValueStoreBackend_interface: |
| 1392 |
|
| 1393 |
def test_get(self): |
| 1394 |
with pytest.raises(NotImplementedError): |
| 1395 |
KeyValueStoreBackend(self.app).get('a') |
| 1396 |
|
| 1397 |
def test_set(self): |
| 1398 |
with pytest.raises(NotImplementedError): |
| 1399 |
KeyValueStoreBackend(self.app)._set_with_state('a', 1, states.SUCCESS) |
| 1400 |
|
| 1401 |
def test_incr(self): |
| 1402 |
with pytest.raises(NotImplementedError): |
| 1403 |
KeyValueStoreBackend(self.app).incr('a') |
| 1404 |
|
| 1405 |
def test_cleanup(self): |
| 1406 |
assert not KeyValueStoreBackend(self.app).cleanup() |
| 1407 |
|
| 1408 |
def test_delete(self): |
| 1409 |
with pytest.raises(NotImplementedError): |
| 1410 |
KeyValueStoreBackend(self.app).delete('a') |
| 1411 |
|
| 1412 |
def test_mget(self): |
| 1413 |
with pytest.raises(NotImplementedError): |
| 1414 |
KeyValueStoreBackend(self.app).mget(['a']) |
| 1415 |
|
| 1416 |
def test_forget(self): |
| 1417 |
with pytest.raises(NotImplementedError): |
| 1418 |
KeyValueStoreBackend(self.app).forget('a') |
| 1419 |
|
| 1420 |
|
| 1421 |
class test_DisabledBackend: |
| 1422 |
|
| 1423 |
def test_store_result(self): |
| 1424 |
DisabledBackend(self.app).store_result() |
| 1425 |
|
| 1426 |
def test_is_disabled(self): |
| 1427 |
with pytest.raises(NotImplementedError): |
| 1428 |
DisabledBackend(self.app).get_state('foo') |
| 1429 |
|
| 1430 |
def test_as_uri(self): |
| 1431 |
assert DisabledBackend(self.app).as_uri() == 'disabled://' |
| 1432 |
|
| 1433 |
@pytest.mark.celery(result_backend='disabled') |
| 1434 |
def test_chord_raises_error(self): |
| 1435 |
with pytest.raises(NotImplementedError): |
| 1436 |
chord(self.add.s(i, i) for i in range(10))(self.add.s([2])) |
| 1437 |
|
| 1438 |
@pytest.mark.celery(result_backend='disabled') |
| 1439 |
def test_chain_with_chord_raises_error(self): |
| 1440 |
with pytest.raises(NotImplementedError): |
| 1441 |
(self.add.s(2, 2) | |
| 1442 |
group(self.add.s(2, 2), |
| 1443 |
self.add.s(5, 6)) | self.add.s()).delay() |
| 1444 |
|
| 1445 |
|
| 1446 |
class test_as_uri: |
| 1447 |
|
| 1448 |
def setup_method(self): |
| 1449 |
self.b = BaseBackend( |
| 1450 |
app=self.app, |
| 1451 |
url='sch://uuuu:[email protected]' |
| 1452 |
) |
| 1453 |
|
| 1454 |
def test_as_uri_include_password(self): |
| 1455 |
assert self.b.as_uri(True) == self.b.url |
| 1456 |
|
| 1457 |
def test_as_uri_exclude_password(self): |
| 1458 |
assert self.b.as_uri() == 'sch://uuuu:**@hostname.dom/' |
| 1459 |
|
| 1460 |
|
| 1461 |
class test_backend_retries: |
| 1462 |
|
| 1463 |
def test_should_retry_exception(self): |
| 1464 |
assert not BaseBackend(app=self.app).exception_safe_to_retry(Exception("test")) |
| 1465 |
|
| 1466 |
def test_get_failed_never_retries(self): |
| 1467 |
self.app.conf.result_backend_always_retry, prev = False, self.app.conf.result_backend_always_retry |
| 1468 |
|
| 1469 |
expected_exc = Exception("failed") |
| 1470 |
try: |
| 1471 |
b = BaseBackend(app=self.app) |
| 1472 |
b.exception_safe_to_retry = lambda exc: True |
| 1473 |
b._sleep = Mock() |
| 1474 |
b._get_task_meta_for = Mock() |
| 1475 |
b._get_task_meta_for.side_effect = [ |
| 1476 |
expected_exc, |
| 1477 |
{'status': states.SUCCESS, 'result': 42} |
| 1478 |
] |
| 1479 |
try: |
| 1480 |
b.get_task_meta(sentinel.task_id) |
| 1481 |
assert False |
| 1482 |
except Exception as exc: |
| 1483 |
assert b._sleep.call_count == 0 |
| 1484 |
assert exc == expected_exc |
| 1485 |
finally: |
| 1486 |
self.app.conf.result_backend_always_retry = prev |
| 1487 |
|
| 1488 |
def test_get_with_retries(self): |
| 1489 |
self.app.conf.result_backend_always_retry, prev = True, self.app.conf.result_backend_always_retry |
| 1490 |
|
| 1491 |
try: |
| 1492 |
b = BaseBackend(app=self.app) |
| 1493 |
b.exception_safe_to_retry = lambda exc: True |
| 1494 |
b._sleep = Mock() |
| 1495 |
b.on_backend_retryable_error = Mock() |
| 1496 |
b._get_task_meta_for = Mock() |
| 1497 |
b._get_task_meta_for.side_effect = [ |
| 1498 |
Exception("failed"), |
| 1499 |
{'status': states.SUCCESS, 'result': 42} |
| 1500 |
] |
| 1501 |
res = b.get_task_meta(sentinel.task_id) |
| 1502 |
assert res == {'status': states.SUCCESS, 'result': 42} |
| 1503 |
assert b._sleep.call_count == 1 |
| 1504 |
b.on_backend_retryable_error.assert_called_once() |
| 1505 |
finally: |
| 1506 |
self.app.conf.result_backend_always_retry = prev |
| 1507 |
|
| 1508 |
def test_get_reaching_max_retries(self): |
| 1509 |
self.app.conf.result_backend_always_retry, prev = True, self.app.conf.result_backend_always_retry |
| 1510 |
self.app.conf.result_backend_max_retries, prev_max_retries = 0, self.app.conf.result_backend_max_retries |
| 1511 |
|
| 1512 |
try: |
| 1513 |
b = BaseBackend(app=self.app) |
| 1514 |
b.exception_safe_to_retry = lambda exc: True |
| 1515 |
b._sleep = Mock() |
| 1516 |
b._get_task_meta_for = Mock() |
| 1517 |
b._get_task_meta_for.side_effect = [ |
| 1518 |
Exception("failed"), |
| 1519 |
{'status': states.SUCCESS, 'result': 42} |
| 1520 |
] |
| 1521 |
try: |
| 1522 |
b.get_task_meta(sentinel.task_id) |
| 1523 |
assert False |
| 1524 |
except BackendGetMetaError: |
| 1525 |
assert b._sleep.call_count == 0 |
| 1526 |
finally: |
| 1527 |
self.app.conf.result_backend_always_retry = prev |
| 1528 |
self.app.conf.result_backend_max_retries = prev_max_retries |
| 1529 |
|
| 1530 |
def test_get_unsafe_exception(self): |
| 1531 |
self.app.conf.result_backend_always_retry, prev = True, self.app.conf.result_backend_always_retry |
| 1532 |
|
| 1533 |
expected_exc = Exception("failed") |
| 1534 |
try: |
| 1535 |
b = BaseBackend(app=self.app) |
| 1536 |
b._sleep = Mock() |
| 1537 |
b._get_task_meta_for = Mock() |
| 1538 |
b._get_task_meta_for.side_effect = [ |
| 1539 |
expected_exc, |
| 1540 |
{'status': states.SUCCESS, 'result': 42} |
| 1541 |
] |
| 1542 |
try: |
| 1543 |
b.get_task_meta(sentinel.task_id) |
| 1544 |
assert False |
| 1545 |
except Exception as exc: |
| 1546 |
assert b._sleep.call_count == 0 |
| 1547 |
assert exc == expected_exc |
| 1548 |
finally: |
| 1549 |
self.app.conf.result_backend_always_retry = prev |
| 1550 |
|
| 1551 |
def test_store_result_never_retries(self): |
| 1552 |
self.app.conf.result_backend_always_retry, prev = False, self.app.conf.result_backend_always_retry |
| 1553 |
|
| 1554 |
expected_exc = Exception("failed") |
| 1555 |
try: |
| 1556 |
b = BaseBackend(app=self.app) |
| 1557 |
b.exception_safe_to_retry = lambda exc: True |
| 1558 |
b._sleep = Mock() |
| 1559 |
b.on_backend_retryable_error = Mock() |
| 1560 |
b._get_task_meta_for = Mock() |
| 1561 |
b._get_task_meta_for.return_value = { |
| 1562 |
'status': states.RETRY, |
| 1563 |
'result': { |
| 1564 |
"exc_type": "Exception", |
| 1565 |
"exc_message": ["failed"], |
| 1566 |
"exc_module": "builtins", |
| 1567 |
}, |
| 1568 |
} |
| 1569 |
b._store_result = Mock() |
| 1570 |
b._store_result.side_effect = [ |
| 1571 |
expected_exc, |
| 1572 |
42 |
| 1573 |
] |
| 1574 |
try: |
| 1575 |
b.store_result(sentinel.task_id, 42, states.SUCCESS) |
| 1576 |
except Exception as exc: |
| 1577 |
assert b._sleep.call_count == 0 |
| 1578 |
assert exc == expected_exc |
| 1579 |
finally: |
| 1580 |
self.app.conf.result_backend_always_retry = prev |
| 1581 |
|
| 1582 |
def test_store_result_with_retries(self): |
| 1583 |
self.app.conf.result_backend_always_retry, prev = True, self.app.conf.result_backend_always_retry |
| 1584 |
|
| 1585 |
try: |
| 1586 |
b = BaseBackend(app=self.app) |
| 1587 |
b.exception_safe_to_retry = lambda exc: True |
| 1588 |
b._sleep = Mock() |
| 1589 |
b.on_backend_retryable_error = Mock() |
| 1590 |
b._get_task_meta_for = Mock() |
| 1591 |
b._get_task_meta_for.return_value = { |
| 1592 |
'status': states.RETRY, |
| 1593 |
'result': { |
| 1594 |
"exc_type": "Exception", |
| 1595 |
"exc_message": ["failed"], |
| 1596 |
"exc_module": "builtins", |
| 1597 |
}, |
| 1598 |
} |
| 1599 |
b._store_result = Mock() |
| 1600 |
b._store_result.side_effect = [ |
| 1601 |
Exception("failed"), |
| 1602 |
42 |
| 1603 |
] |
| 1604 |
res = b.store_result(sentinel.task_id, 42, states.SUCCESS) |
| 1605 |
assert res == 42 |
| 1606 |
assert b._sleep.call_count == 1 |
| 1607 |
b.on_backend_retryable_error.assert_called_once() |
| 1608 |
finally: |
| 1609 |
self.app.conf.result_backend_always_retry = prev |
| 1610 |
|
| 1611 |
def test_get_with_retries_hook_failure_continues(self): |
| 1612 |
self.app.conf.result_backend_always_retry, prev = True, self.app.conf.result_backend_always_retry |
| 1613 |
|
| 1614 |
try: |
| 1615 |
b = BaseBackend(app=self.app) |
| 1616 |
b.exception_safe_to_retry = lambda exc: True |
| 1617 |
b._sleep = Mock() |
| 1618 |
b.on_backend_retryable_error = Mock(side_effect=RuntimeError("hook failed")) |
| 1619 |
b._get_task_meta_for = Mock() |
| 1620 |
b._get_task_meta_for.side_effect = [ |
| 1621 |
Exception("failed"), |
| 1622 |
{'status': states.SUCCESS, 'result': 42} |
| 1623 |
] |
| 1624 |
res = b.get_task_meta(sentinel.task_id) |
| 1625 |
assert res == {'status': states.SUCCESS, 'result': 42} |
| 1626 |
assert b._sleep.call_count == 1 |
| 1627 |
b.on_backend_retryable_error.assert_called_once() |
| 1628 |
finally: |
| 1629 |
self.app.conf.result_backend_always_retry = prev |
| 1630 |
|
| 1631 |
def test_store_result_with_retries_hook_failure_continues(self): |
| 1632 |
self.app.conf.result_backend_always_retry, prev = True, self.app.conf.result_backend_always_retry |
| 1633 |
|
| 1634 |
try: |
| 1635 |
b = BaseBackend(app=self.app) |
| 1636 |
b.exception_safe_to_retry = lambda exc: True |
| 1637 |
b._sleep = Mock() |
| 1638 |
b.on_backend_retryable_error = Mock(side_effect=RuntimeError("hook failed")) |
| 1639 |
b._get_task_meta_for = Mock() |
| 1640 |
b._get_task_meta_for.return_value = { |
| 1641 |
'status': states.RETRY, |
| 1642 |
'result': { |
| 1643 |
"exc_type": "Exception", |
| 1644 |
"exc_message": ["failed"], |
| 1645 |
"exc_module": "builtins", |
| 1646 |
}, |
| 1647 |
} |
| 1648 |
b._store_result = Mock() |
| 1649 |
b._store_result.side_effect = [ |
| 1650 |
Exception("failed"), |
| 1651 |
42 |
| 1652 |
] |
| 1653 |
res = b.store_result(sentinel.task_id, 42, states.SUCCESS) |
| 1654 |
assert res == 42 |
| 1655 |
assert b._sleep.call_count == 1 |
| 1656 |
b.on_backend_retryable_error.assert_called_once() |
| 1657 |
finally: |
| 1658 |
self.app.conf.result_backend_always_retry = prev |
| 1659 |
|
| 1660 |
def test_store_result_reaching_max_retries(self): |
| 1661 |
self.app.conf.result_backend_always_retry, prev = True, self.app.conf.result_backend_always_retry |
| 1662 |
self.app.conf.result_backend_max_retries, prev_max_retries = 0, self.app.conf.result_backend_max_retries |
| 1663 |
|
| 1664 |
try: |
| 1665 |
b = BaseBackend(app=self.app) |
| 1666 |
b.exception_safe_to_retry = lambda exc: True |
| 1667 |
b._sleep = Mock() |
| 1668 |
b._get_task_meta_for = Mock() |
| 1669 |
b._get_task_meta_for.return_value = { |
| 1670 |
'status': states.RETRY, |
| 1671 |
'result': { |
| 1672 |
"exc_type": "Exception", |
| 1673 |
"exc_message": ["failed"], |
| 1674 |
"exc_module": "builtins", |
| 1675 |
}, |
| 1676 |
} |
| 1677 |
b._store_result = Mock() |
| 1678 |
b._store_result.side_effect = [ |
| 1679 |
Exception("failed"), |
| 1680 |
42 |
| 1681 |
] |
| 1682 |
try: |
| 1683 |
b.store_result(sentinel.task_id, 42, states.SUCCESS) |
| 1684 |
assert False |
| 1685 |
except BackendStoreError: |
| 1686 |
assert b._sleep.call_count == 0 |
| 1687 |
finally: |
| 1688 |
self.app.conf.result_backend_always_retry = prev |
| 1689 |
self.app.conf.result_backend_max_retries = prev_max_retries |
| 1690 |
|
| 1691 |
def test_result_backend_thread_safe(self): |
| 1692 |
# Should identify the backend as thread safe |
| 1693 |
self.app.conf.result_backend_thread_safe = True |
| 1694 |
b = BaseBackend(app=self.app) |
| 1695 |
assert b.thread_safe is True |
| 1696 |
|
| 1697 |
def test_result_backend_not_thread_safe(self): |
| 1698 |
# Should identify the backend as not being thread safe |
| 1699 |
self.app.conf.result_backend_thread_safe = False |
| 1700 |
b = BaseBackend(app=self.app) |
| 1701 |
assert b.thread_safe is False |