| 1 |
import os |
| 2 |
from datetime import datetime |
| 3 |
from pickle import dumps, loads |
| 4 |
from unittest.mock import Mock, patch |
| 5 |
|
| 6 |
import pytest |
| 7 |
|
| 8 |
from celery import states, uuid |
| 9 |
from celery.app.task import Context |
| 10 |
from celery.exceptions import ImproperlyConfigured |
| 11 |
|
| 12 |
pytest.importorskip('sqlalchemy') |
| 13 |
|
| 14 |
from celery.backends.database import DatabaseBackend, retry, session, session_cleanup # noqa |
| 15 |
from celery.backends.database.models import Task, TaskSet # noqa |
| 16 |
from celery.backends.database.session import PREPARE_MODELS_MAX_RETRIES, ResultModelBase, SessionManager # noqa |
| 17 |
from t import skip # noqa |
| 18 |
|
| 19 |
DB_PATH = "test.db" |
| 20 |
|
| 21 |
|
| 22 |
class SomeClass: |
| 23 |
|
| 24 |
def __init__(self, data): |
| 25 |
self.data = data |
| 26 |
|
| 27 |
def __eq__(self, cmp): |
| 28 |
return self.data == cmp.data |
| 29 |
|
| 30 |
|
| 31 |
class test_session_cleanup: |
| 32 |
|
| 33 |
def test_context(self): |
| 34 |
session = Mock(name='session') |
| 35 |
with session_cleanup(session): |
| 36 |
pass |
| 37 |
session.close.assert_called_with() |
| 38 |
|
| 39 |
def test_context_raises(self): |
| 40 |
session = Mock(name='session') |
| 41 |
with pytest.raises(KeyError): |
| 42 |
with session_cleanup(session): |
| 43 |
raise KeyError() |
| 44 |
session.rollback.assert_called_with() |
| 45 |
session.close.assert_called_with() |
| 46 |
|
| 47 |
|
| 48 |
@skip.if_pypy |
| 49 |
class test_ModelsIdFieldTypeVariations: |
| 50 |
|
| 51 |
def test_for_mssql_dialect(self): |
| 52 |
"""Test that ID columns use BigInteger for MSSQL and Integer for other dialects.""" |
| 53 |
from sqlalchemy import BigInteger, Integer |
| 54 |
from sqlalchemy.dialects import mssql, mysql, oracle, postgresql, sqlite |
| 55 |
|
| 56 |
models = [Task, TaskSet] |
| 57 |
id_columns = [m.__table__.columns['id'] for m in models] |
| 58 |
|
| 59 |
for dialect in [mssql, postgresql, mysql, sqlite, oracle]: |
| 60 |
for id_column in id_columns: |
| 61 |
compiled_type = id_column.type.dialect_impl(dialect.dialect()) |
| 62 |
if dialect == mssql: |
| 63 |
assert isinstance(compiled_type, BigInteger) |
| 64 |
else: |
| 65 |
assert isinstance(compiled_type, Integer) |
| 66 |
|
| 67 |
|
| 68 |
@skip.if_pypy |
| 69 |
class test_DateDoneIndex: |
| 70 |
"""Test that date_done columns have index=True on Task and TaskSet models.""" |
| 71 |
|
| 72 |
def test_task_date_done_has_index(self): |
| 73 |
col = Task.__table__.columns['date_done'] |
| 74 |
assert col.index is True, "Task.date_done should have index=True" |
| 75 |
|
| 76 |
def test_taskset_date_done_has_index(self): |
| 77 |
col = TaskSet.__table__.columns['date_done'] |
| 78 |
assert col.index is True, "TaskSet.date_done should have index=True" |
| 79 |
|
| 80 |
|
| 81 |
class test_DateDoneColumnDefaults: |
| 82 |
"""Test that date_done column defaults are callables, not fixed values. |
| 83 |
|
| 84 |
The default and onupdate values must be callables (lambdas) so that |
| 85 |
datetime.now() is evaluated per-row at INSERT/UPDATE time, not once |
| 86 |
at module import time. |
| 87 |
""" |
| 88 |
|
| 89 |
def test_task_date_done_default_is_callable(self): |
| 90 |
"""Task.date_done default should be a callable.""" |
| 91 |
col = Task.__table__.columns['date_done'] |
| 92 |
assert col.default is not None, \ |
| 93 |
"Task.date_done should have a default" |
| 94 |
assert callable(col.default.arg), \ |
| 95 |
"Task.date_done default should be a callable, not a fixed datetime" |
| 96 |
|
| 97 |
def test_task_date_done_onupdate_is_callable(self): |
| 98 |
"""Task.date_done onupdate should be a callable (lambda).""" |
| 99 |
col = Task.__table__.columns['date_done'] |
| 100 |
assert col.onupdate is not None, \ |
| 101 |
"Task.date_done should have an onupdate" |
| 102 |
assert callable(col.onupdate.arg), \ |
| 103 |
"Task.date_done onupdate should be a callable, not a fixed datetime" |
| 104 |
|
| 105 |
def test_taskset_date_done_default_is_callable(self): |
| 106 |
"""TaskSet.date_done default should be a callable.""" |
| 107 |
col = TaskSet.__table__.columns['date_done'] |
| 108 |
assert col.default is not None, \ |
| 109 |
"TaskSet.date_done should have a default" |
| 110 |
assert callable(col.default.arg), \ |
| 111 |
"TaskSet.date_done default should be a callable, not a fixed datetime" |
| 112 |
|
| 113 |
|
| 114 |
@skip.if_pypy |
| 115 |
class test_DatabaseBackend: |
| 116 |
|
| 117 |
@pytest.fixture(autouse=True) |
| 118 |
def remmove_db(self): |
| 119 |
yield |
| 120 |
if os.path.exists(DB_PATH): |
| 121 |
os.remove(DB_PATH) |
| 122 |
|
| 123 |
def setup_method(self): |
| 124 |
self.uri = 'sqlite:///' + DB_PATH |
| 125 |
self.app.conf.result_serializer = 'pickle' |
| 126 |
|
| 127 |
def test_retry_helper(self): |
| 128 |
from celery.backends.database import DatabaseError |
| 129 |
|
| 130 |
calls = [0] |
| 131 |
|
| 132 |
@retry |
| 133 |
def raises(): |
| 134 |
calls[0] += 1 |
| 135 |
raise DatabaseError(1, 2, 3) |
| 136 |
|
| 137 |
with pytest.raises(DatabaseError): |
| 138 |
raises(max_retries=5) |
| 139 |
assert calls[0] == 5 |
| 140 |
|
| 141 |
def test_retry_helper_calls_on_backend_retryable_error(self): |
| 142 |
from celery.backends.database import DatabaseError |
| 143 |
|
| 144 |
calls = [0] |
| 145 |
hook_calls = [] |
| 146 |
|
| 147 |
mock_backend = Mock() |
| 148 |
mock_backend.on_backend_retryable_error = Mock(side_effect=lambda exc: hook_calls.append(exc)) |
| 149 |
|
| 150 |
@retry |
| 151 |
def raises_with_backend(backend): |
| 152 |
calls[0] += 1 |
| 153 |
raise DatabaseError(1, 2, 3) |
| 154 |
|
| 155 |
with pytest.raises(DatabaseError): |
| 156 |
raises_with_backend(mock_backend, max_retries=3) |
| 157 |
|
| 158 |
assert calls[0] == 3 |
| 159 |
assert mock_backend.on_backend_retryable_error.call_count == 3 |
| 160 |
for exc in hook_calls: |
| 161 |
assert isinstance(exc, DatabaseError) |
| 162 |
|
| 163 |
def test_retry_helper_without_hook(self): |
| 164 |
from celery.backends.database import DatabaseError |
| 165 |
|
| 166 |
calls = [0] |
| 167 |
|
| 168 |
mock_backend = Mock(spec=[]) |
| 169 |
|
| 170 |
@retry |
| 171 |
def raises_with_backend(backend): |
| 172 |
calls[0] += 1 |
| 173 |
raise DatabaseError(1, 2, 3) |
| 174 |
|
| 175 |
with pytest.raises(DatabaseError): |
| 176 |
raises_with_backend(mock_backend, max_retries=3) |
| 177 |
|
| 178 |
assert calls[0] == 3 |
| 179 |
|
| 180 |
def test_retry_helper_hook_failure_continues(self): |
| 181 |
from celery.backends.database import DatabaseError |
| 182 |
|
| 183 |
calls = [0] |
| 184 |
|
| 185 |
mock_backend = Mock() |
| 186 |
mock_backend.on_backend_retryable_error = Mock(side_effect=RuntimeError("hook failed")) |
| 187 |
|
| 188 |
@retry |
| 189 |
def raises_with_backend(backend): |
| 190 |
calls[0] += 1 |
| 191 |
raise DatabaseError(1, 2, 3) |
| 192 |
|
| 193 |
with pytest.raises(DatabaseError): |
| 194 |
raises_with_backend(mock_backend, max_retries=3) |
| 195 |
|
| 196 |
assert calls[0] == 3 |
| 197 |
assert mock_backend.on_backend_retryable_error.call_count == 3 |
| 198 |
|
| 199 |
def test_missing_dburi_raises_ImproperlyConfigured(self): |
| 200 |
self.app.conf.database_url = None |
| 201 |
with pytest.raises(ImproperlyConfigured): |
| 202 |
DatabaseBackend(app=self.app) |
| 203 |
|
| 204 |
def test_engine_options_include_pool_health_defaults(self): |
| 205 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 206 |
assert tb.engine_options["pool_pre_ping"] is True |
| 207 |
assert tb.engine_options["pool_recycle"] == 3600 |
| 208 |
|
| 209 |
def test_engine_options_explicit_values_override_defaults(self): |
| 210 |
self.app.conf.database_engine_options = {"pool_pre_ping": False} |
| 211 |
tb = DatabaseBackend( |
| 212 |
self.uri, |
| 213 |
app=self.app, |
| 214 |
engine_options={"pool_recycle": 15}, |
| 215 |
) |
| 216 |
assert tb.engine_options["pool_pre_ping"] is False |
| 217 |
assert tb.engine_options["pool_recycle"] == 15 |
| 218 |
|
| 219 |
def test_exception_safe_to_retry(self): |
| 220 |
from celery.backends.database import DatabaseError, InvalidRequestError, StaleDataError |
| 221 |
|
| 222 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 223 |
assert tb.exception_safe_to_retry(DatabaseError("", "", Exception("db error"))) |
| 224 |
assert tb.exception_safe_to_retry(InvalidRequestError()) |
| 225 |
assert tb.exception_safe_to_retry(StaleDataError()) |
| 226 |
assert not tb.exception_safe_to_retry(RuntimeError("not retryable")) |
| 227 |
|
| 228 |
def test_exception_safe_to_retry_with_interface_error(self): |
| 229 |
from celery.backends.database import InterfaceError |
| 230 |
|
| 231 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 232 |
assert tb.exception_safe_to_retry(InterfaceError("", None, Exception("connection lost"))) |
| 233 |
|
| 234 |
def test_on_backend_retryable_error_invalidates_session(self): |
| 235 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 236 |
tb.session_manager.invalidate = Mock() |
| 237 |
|
| 238 |
tb.on_backend_retryable_error(RuntimeError("retryable")) |
| 239 |
tb.session_manager.invalidate.assert_called_once_with(tb.url) |
| 240 |
|
| 241 |
def test_on_backend_retryable_error_called_with_exception(self): |
| 242 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 243 |
tb.session_manager.invalidate = Mock() |
| 244 |
mock_exc = RuntimeError("connection lost") |
| 245 |
|
| 246 |
tb.on_backend_retryable_error(mock_exc) |
| 247 |
|
| 248 |
tb.session_manager.invalidate.assert_called_once_with(tb.url) |
| 249 |
|
| 250 |
def test_table_schema_config(self): |
| 251 |
self.app.conf.database_table_schemas = { |
| 252 |
'task': 'foo', |
| 253 |
'group': 'bar', |
| 254 |
} |
| 255 |
# disable table creation because schema foo and bar do not exist |
| 256 |
# and aren't created if they don't exist. |
| 257 |
self.app.conf.database_create_tables_at_setup = False |
| 258 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 259 |
assert tb.task_cls.__table__.schema == 'foo' |
| 260 |
assert tb.task_cls.__table__.c.id.default.schema == 'foo' |
| 261 |
assert tb.taskset_cls.__table__.schema == 'bar' |
| 262 |
assert tb.taskset_cls.__table__.c.id.default.schema == 'bar' |
| 263 |
|
| 264 |
def test_table_name_config(self): |
| 265 |
self.app.conf.database_table_names = { |
| 266 |
'task': 'foo', |
| 267 |
'group': 'bar', |
| 268 |
} |
| 269 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 270 |
assert tb.task_cls.__table__.name == 'foo' |
| 271 |
assert tb.taskset_cls.__table__.name == 'bar' |
| 272 |
|
| 273 |
def test_table_creation_at_setup_config(self): |
| 274 |
from sqlalchemy import inspect |
| 275 |
self.app.conf.database_create_tables_at_setup = True |
| 276 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 277 |
engine = tb.session_manager.get_engine(tb.url) |
| 278 |
inspect(engine).has_table("celery_taskmeta") |
| 279 |
inspect(engine).has_table("celery_tasksetmeta") |
| 280 |
|
| 281 |
def test_missing_task_id_is_PENDING(self): |
| 282 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 283 |
assert tb.get_state('xxx-does-not-exist') == states.PENDING |
| 284 |
|
| 285 |
def test_missing_task_meta_is_dict_with_pending(self): |
| 286 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 287 |
meta = tb.get_task_meta('xxx-does-not-exist-at-all') |
| 288 |
assert meta['status'] == states.PENDING |
| 289 |
assert meta['task_id'] == 'xxx-does-not-exist-at-all' |
| 290 |
assert meta['result'] is None |
| 291 |
assert meta['traceback'] is None |
| 292 |
|
| 293 |
def test_mark_as_done(self): |
| 294 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 295 |
|
| 296 |
tid = uuid() |
| 297 |
|
| 298 |
assert tb.get_state(tid) == states.PENDING |
| 299 |
assert tb.get_result(tid) is None |
| 300 |
|
| 301 |
tb.mark_as_done(tid, 42) |
| 302 |
assert tb.get_state(tid) == states.SUCCESS |
| 303 |
assert tb.get_result(tid) == 42 |
| 304 |
|
| 305 |
def test_is_pickled(self): |
| 306 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 307 |
|
| 308 |
tid2 = uuid() |
| 309 |
result = {'foo': 'baz', 'bar': SomeClass(12345)} |
| 310 |
tb.mark_as_done(tid2, result) |
| 311 |
# is serialized properly. |
| 312 |
rindb = tb.get_result(tid2) |
| 313 |
assert rindb.get('foo') == 'baz' |
| 314 |
assert rindb.get('bar').data == 12345 |
| 315 |
|
| 316 |
def test_mark_as_started(self): |
| 317 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 318 |
tid = uuid() |
| 319 |
tb.mark_as_started(tid) |
| 320 |
assert tb.get_state(tid) == states.STARTED |
| 321 |
|
| 322 |
def test_mark_as_revoked(self): |
| 323 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 324 |
tid = uuid() |
| 325 |
tb.mark_as_revoked(tid) |
| 326 |
assert tb.get_state(tid) == states.REVOKED |
| 327 |
|
| 328 |
def test_mark_as_retry(self): |
| 329 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 330 |
tid = uuid() |
| 331 |
try: |
| 332 |
raise KeyError('foo') |
| 333 |
except KeyError as exception: |
| 334 |
import traceback |
| 335 |
trace = '\n'.join(traceback.format_stack()) |
| 336 |
tb.mark_as_retry(tid, exception, traceback=trace) |
| 337 |
assert tb.get_state(tid) == states.RETRY |
| 338 |
assert isinstance(tb.get_result(tid), KeyError) |
| 339 |
assert tb.get_traceback(tid) == trace |
| 340 |
|
| 341 |
def test_mark_as_failure(self): |
| 342 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 343 |
|
| 344 |
tid3 = uuid() |
| 345 |
try: |
| 346 |
raise KeyError('foo') |
| 347 |
except KeyError as exception: |
| 348 |
import traceback |
| 349 |
trace = '\n'.join(traceback.format_stack()) |
| 350 |
tb.mark_as_failure(tid3, exception, traceback=trace) |
| 351 |
assert tb.get_state(tid3) == states.FAILURE |
| 352 |
assert isinstance(tb.get_result(tid3), KeyError) |
| 353 |
assert tb.get_traceback(tid3) == trace |
| 354 |
|
| 355 |
def test_forget(self): |
| 356 |
tb = DatabaseBackend(self.uri, backend='memory://', app=self.app) |
| 357 |
tid = uuid() |
| 358 |
tb.mark_as_done(tid, {'foo': 'bar'}) |
| 359 |
tb.mark_as_done(tid, {'foo': 'bar'}) |
| 360 |
x = self.app.AsyncResult(tid, backend=tb) |
| 361 |
x.forget() |
| 362 |
assert x.result is None |
| 363 |
|
| 364 |
def test_process_cleanup(self): |
| 365 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 366 |
tb.process_cleanup() |
| 367 |
|
| 368 |
@pytest.mark.usefixtures('depends_on_current_app') |
| 369 |
def test_reduce(self): |
| 370 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 371 |
assert loads(dumps(tb)) |
| 372 |
|
| 373 |
def test_save__restore__delete_group(self): |
| 374 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 375 |
|
| 376 |
tid = uuid() |
| 377 |
res = {'something': 'special'} |
| 378 |
assert tb.save_group(tid, res) == res |
| 379 |
|
| 380 |
res2 = tb.restore_group(tid) |
| 381 |
assert res2 == res |
| 382 |
|
| 383 |
tb.delete_group(tid) |
| 384 |
assert tb.restore_group(tid) is None |
| 385 |
|
| 386 |
assert tb.restore_group('xxx-nonexisting-id') is None |
| 387 |
|
| 388 |
def test_cleanup(self): |
| 389 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 390 |
for i in range(10): |
| 391 |
tb.mark_as_done(uuid(), 42) |
| 392 |
tb.save_group(uuid(), {'foo': 'bar'}) |
| 393 |
s = tb.ResultSession() |
| 394 |
for t in s.query(Task).all(): |
| 395 |
t.date_done = datetime.now() - tb.expires * 2 |
| 396 |
for t in s.query(TaskSet).all(): |
| 397 |
t.date_done = datetime.now() - tb.expires * 2 |
| 398 |
s.commit() |
| 399 |
s.close() |
| 400 |
|
| 401 |
tb.cleanup() |
| 402 |
|
| 403 |
def test_Task__repr__(self): |
| 404 |
assert 'foo' in repr(Task('foo')) |
| 405 |
|
| 406 |
def test_TaskSet__repr__(self): |
| 407 |
assert 'foo', repr(TaskSet('foo' in None)) |
| 408 |
|
| 409 |
|
| 410 |
@skip.if_pypy |
| 411 |
class test_DatabaseBackend_result_extended(): |
| 412 |
def setup_method(self): |
| 413 |
self.uri = 'sqlite:///' + DB_PATH |
| 414 |
self.app.conf.result_serializer = 'pickle' |
| 415 |
self.app.conf.result_extended = True |
| 416 |
|
| 417 |
@pytest.mark.parametrize( |
| 418 |
'result_serializer, args, kwargs', |
| 419 |
[ |
| 420 |
('pickle', (SomeClass(1), SomeClass(2)), {'foo': SomeClass(123)}), |
| 421 |
('json', ['a', 'b'], {'foo': 'bar'}), |
| 422 |
], |
| 423 |
ids=['using pickle', 'using json'] |
| 424 |
) |
| 425 |
def test_store_result(self, result_serializer, args, kwargs): |
| 426 |
self.app.conf.result_serializer = result_serializer |
| 427 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 428 |
tid = uuid() |
| 429 |
|
| 430 |
request = Context(args=args, kwargs=kwargs, |
| 431 |
task='mytask', retries=2, |
| 432 |
hostname='celery@worker_1', |
| 433 |
delivery_info={'routing_key': 'celery'}) |
| 434 |
|
| 435 |
tb.store_result(tid, {'fizz': 'buzz'}, states.SUCCESS, request=request) |
| 436 |
meta = tb.get_task_meta(tid) |
| 437 |
|
| 438 |
assert meta['result'] == {'fizz': 'buzz'} |
| 439 |
assert meta['args'] == args |
| 440 |
assert meta['kwargs'] == kwargs |
| 441 |
assert meta['queue'] == 'celery' |
| 442 |
assert meta['name'] == 'mytask' |
| 443 |
assert meta['retries'] == 2 |
| 444 |
assert meta['worker'] == "celery@worker_1" |
| 445 |
|
| 446 |
@pytest.mark.parametrize( |
| 447 |
'result_serializer, args, kwargs', |
| 448 |
[ |
| 449 |
('pickle', (SomeClass(1), SomeClass(2)), {'foo': SomeClass(123)}), |
| 450 |
('json', ['a', 'b'], {'foo': 'bar'}), |
| 451 |
], |
| 452 |
ids=['using pickle', 'using json'] |
| 453 |
) |
| 454 |
def test_store_none_result(self, result_serializer, args, kwargs): |
| 455 |
self.app.conf.result_serializer = result_serializer |
| 456 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 457 |
tid = uuid() |
| 458 |
|
| 459 |
request = Context(args=args, kwargs=kwargs, |
| 460 |
task='mytask', retries=2, |
| 461 |
hostname='celery@worker_1', |
| 462 |
delivery_info={'routing_key': 'celery'}) |
| 463 |
|
| 464 |
tb.store_result(tid, None, states.SUCCESS, request=request) |
| 465 |
meta = tb.get_task_meta(tid) |
| 466 |
|
| 467 |
assert meta['result'] is None |
| 468 |
assert meta['args'] == args |
| 469 |
assert meta['kwargs'] == kwargs |
| 470 |
assert meta['queue'] == 'celery' |
| 471 |
assert meta['name'] == 'mytask' |
| 472 |
assert meta['retries'] == 2 |
| 473 |
assert meta['worker'] == "celery@worker_1" |
| 474 |
|
| 475 |
@pytest.mark.parametrize( |
| 476 |
'result_serializer, args, kwargs', |
| 477 |
[ |
| 478 |
('pickle', (SomeClass(1), SomeClass(2)), |
| 479 |
{'foo': SomeClass(123)}), |
| 480 |
('json', ['a', 'b'], {'foo': 'bar'}), |
| 481 |
], |
| 482 |
ids=['using pickle', 'using json'] |
| 483 |
) |
| 484 |
def test_get_result_meta(self, result_serializer, args, kwargs): |
| 485 |
self.app.conf.result_serializer = result_serializer |
| 486 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 487 |
|
| 488 |
request = Context(args=args, kwargs=kwargs, |
| 489 |
task='mytask', retries=2, |
| 490 |
hostname='celery@worker_1', |
| 491 |
delivery_info={'routing_key': 'celery'}) |
| 492 |
|
| 493 |
meta = tb._get_result_meta(result={'fizz': 'buzz'}, |
| 494 |
state=states.SUCCESS, traceback=None, |
| 495 |
request=request, format_date=False, |
| 496 |
encode=True) |
| 497 |
|
| 498 |
assert meta['result'] == {'fizz': 'buzz'} |
| 499 |
assert tb.decode(meta['args']) == args |
| 500 |
assert tb.decode(meta['kwargs']) == kwargs |
| 501 |
assert meta['queue'] == 'celery' |
| 502 |
assert meta['name'] == 'mytask' |
| 503 |
assert meta['retries'] == 2 |
| 504 |
assert meta['worker'] == "celery@worker_1" |
| 505 |
|
| 506 |
@pytest.mark.parametrize( |
| 507 |
'result_serializer, args, kwargs', |
| 508 |
[ |
| 509 |
('pickle', (SomeClass(1), SomeClass(2)), |
| 510 |
{'foo': SomeClass(123)}), |
| 511 |
('json', ['a', 'b'], {'foo': 'bar'}), |
| 512 |
], |
| 513 |
ids=['using pickle', 'using json'] |
| 514 |
) |
| 515 |
def test_get_result_meta_with_none(self, result_serializer, args, kwargs): |
| 516 |
self.app.conf.result_serializer = result_serializer |
| 517 |
tb = DatabaseBackend(self.uri, app=self.app) |
| 518 |
|
| 519 |
request = Context(args=args, kwargs=kwargs, |
| 520 |
task='mytask', retries=2, |
| 521 |
hostname='celery@worker_1', |
| 522 |
delivery_info={'routing_key': 'celery'}) |
| 523 |
|
| 524 |
meta = tb._get_result_meta(result=None, |
| 525 |
state=states.SUCCESS, traceback=None, |
| 526 |
request=request, format_date=False, |
| 527 |
encode=True) |
| 528 |
|
| 529 |
assert meta['result'] is None |
| 530 |
assert tb.decode(meta['args']) == args |
| 531 |
assert tb.decode(meta['kwargs']) == kwargs |
| 532 |
assert meta['queue'] == 'celery' |
| 533 |
assert meta['name'] == 'mytask' |
| 534 |
assert meta['retries'] == 2 |
| 535 |
assert meta['worker'] == "celery@worker_1" |
| 536 |
|
| 537 |
|
| 538 |
class test_SessionManager: |
| 539 |
|
| 540 |
def test_after_fork(self): |
| 541 |
s = SessionManager() |
| 542 |
assert not s.forked |
| 543 |
s._after_fork() |
| 544 |
assert s.forked |
| 545 |
|
| 546 |
@patch('celery.backends.database.session.create_engine') |
| 547 |
def test_get_engine_forked(self, create_engine): |
| 548 |
s = SessionManager() |
| 549 |
s._after_fork() |
| 550 |
engine = s.get_engine('dburi', foo=1) |
| 551 |
create_engine.assert_called_with('dburi', foo=1) |
| 552 |
assert engine is create_engine() |
| 553 |
engine2 = s.get_engine('dburi', foo=1) |
| 554 |
assert engine2 is engine |
| 555 |
|
| 556 |
@patch('celery.backends.database.session.create_engine') |
| 557 |
def test_get_engine_kwargs(self, create_engine): |
| 558 |
s = SessionManager() |
| 559 |
engine = s.get_engine('dbur', foo=1, pool_size=5) |
| 560 |
assert engine is create_engine() |
| 561 |
engine2 = s.get_engine('dburi', foo=1) |
| 562 |
assert engine2 is engine |
| 563 |
|
| 564 |
def test_invalidate_disposes_cached_engine(self): |
| 565 |
s = SessionManager() |
| 566 |
engine = Mock() |
| 567 |
s._engines['dburi'] = engine |
| 568 |
s._sessions['dburi'] = Mock() |
| 569 |
|
| 570 |
s.invalidate('dburi') |
| 571 |
|
| 572 |
assert 'dburi' not in s._engines |
| 573 |
assert 'dburi' not in s._sessions |
| 574 |
engine.dispose.assert_called_once_with() |
| 575 |
|
| 576 |
def test_invalidate_nonexistent_dburi_is_noop(self): |
| 577 |
s = SessionManager() |
| 578 |
s.invalidate('nonexistent-dburi') |
| 579 |
assert 'nonexistent-dburi' not in s._engines |
| 580 |
assert 'nonexistent-dburi' not in s._sessions |
| 581 |
|
| 582 |
def test_invalidate_only_engine_cached(self): |
| 583 |
s = SessionManager() |
| 584 |
engine = Mock() |
| 585 |
s._engines['dburi'] = engine |
| 586 |
|
| 587 |
s.invalidate('dburi') |
| 588 |
|
| 589 |
assert 'dburi' not in s._engines |
| 590 |
engine.dispose.assert_called_once_with() |
| 591 |
|
| 592 |
@patch('celery.backends.database.session.sessionmaker') |
| 593 |
def test_create_session_forked(self, sessionmaker): |
| 594 |
s = SessionManager() |
| 595 |
s.get_engine = Mock(name='get_engine') |
| 596 |
s._after_fork() |
| 597 |
engine, session = s.create_session('dburi', short_lived_sessions=True) |
| 598 |
sessionmaker.assert_called_with(bind=s.get_engine()) |
| 599 |
assert session is sessionmaker() |
| 600 |
sessionmaker.return_value = Mock(name='new') |
| 601 |
engine, session2 = s.create_session('dburi', short_lived_sessions=True) |
| 602 |
sessionmaker.assert_called_with(bind=s.get_engine()) |
| 603 |
assert session2 is not session |
| 604 |
sessionmaker.return_value = Mock(name='new2') |
| 605 |
engine, session3 = s.create_session( |
| 606 |
'dburi', short_lived_sessions=False) |
| 607 |
sessionmaker.assert_called_with(bind=s.get_engine()) |
| 608 |
assert session3 is session2 |
| 609 |
|
| 610 |
def test_coverage_madness(self): |
| 611 |
prev, session.register_after_fork = ( |
| 612 |
session.register_after_fork, None, |
| 613 |
) |
| 614 |
try: |
| 615 |
SessionManager() |
| 616 |
finally: |
| 617 |
session.register_after_fork = prev |
| 618 |
|
| 619 |
@patch('celery.backends.database.session.create_engine') |
| 620 |
def test_prepare_models_terminates(self, create_engine): |
| 621 |
"""SessionManager.prepare_models has retry logic because the creation |
| 622 |
of database tables by multiple workers is racy. This test patches |
| 623 |
the used method to always raise, so we can verify that it does |
| 624 |
eventually terminate. |
| 625 |
""" |
| 626 |
from sqlalchemy.dialects.sqlite import dialect |
| 627 |
from sqlalchemy.exc import DatabaseError |
| 628 |
|
| 629 |
if hasattr(dialect, 'dbapi'): |
| 630 |
# Method name in SQLAlchemy < 2.0 |
| 631 |
sqlite = dialect.dbapi() |
| 632 |
else: |
| 633 |
# Newer method name in SQLAlchemy 2.0 |
| 634 |
sqlite = dialect.import_dbapi() |
| 635 |
manager = SessionManager() |
| 636 |
engine = manager.get_engine('dburi') |
| 637 |
|
| 638 |
def raise_err(bind): |
| 639 |
raise DatabaseError("", "", [], sqlite.DatabaseError) |
| 640 |
|
| 641 |
patch_create_all = patch.object( |
| 642 |
ResultModelBase.metadata, 'create_all', side_effect=raise_err) |
| 643 |
|
| 644 |
with pytest.raises(DatabaseError), patch_create_all as mock_create_all: |
| 645 |
manager.prepare_models(engine) |
| 646 |
|
| 647 |
assert mock_create_all.call_count == PREPARE_MODELS_MAX_RETRIES + 1 |
| 648 |
|
| 649 |
@patch('celery.backends.database.session.create_engine') |
| 650 |
def test_get_engine_filters_nullpool_unsupported_kwargs(self, mock_create_engine): |
| 651 |
""" |
| 652 |
Test that QueuePool-specific kwargs (like pool_size and max_overflow) |
| 653 |
are filtered out when creating an engine with NullPool. |
| 654 |
""" |
| 655 |
from celery.backends.database.session import NullPool |
| 656 |
|
| 657 |
s = SessionManager() |
| 658 |
s.forked = False # Ensure we're in the non-forked code path |
| 659 |
|
| 660 |
s.get_engine('dburi', echo_pool=True, pool_size=10, max_overflow=5) |
| 661 |
|
| 662 |
mock_create_engine.assert_called_once_with( |
| 663 |
'dburi', |
| 664 |
poolclass=NullPool, |
| 665 |
) |