| 1 |
import gc |
| 2 |
import importlib |
| 3 |
import itertools |
| 4 |
import os |
| 5 |
import ssl |
| 6 |
import sys |
| 7 |
import typing |
| 8 |
import uuid |
| 9 |
from copy import deepcopy |
| 10 |
from datetime import datetime, timedelta |
| 11 |
from datetime import timezone as datetime_timezone |
| 12 |
from logging import LogRecord |
| 13 |
from pickle import dumps, loads |
| 14 |
from typing import Optional |
| 15 |
from unittest.mock import ANY, DEFAULT, MagicMock, Mock, patch |
| 16 |
|
| 17 |
import pytest |
| 18 |
from kombu import Exchange, Queue |
| 19 |
from pydantic import BaseModel, ValidationInfo, model_validator |
| 20 |
from vine import promise |
| 21 |
|
| 22 |
from celery import Celery, _state |
| 23 |
from celery import app as _app |
| 24 |
from celery import current_app, shared_task |
| 25 |
from celery.app import base as _appbase |
| 26 |
from celery.app import defaults |
| 27 |
from celery.backends.base import Backend |
| 28 |
from celery.contrib.testing.mocks import ContextMock |
| 29 |
from celery.exceptions import ImproperlyConfigured |
| 30 |
from celery.loaders.base import unconfigured |
| 31 |
from celery.platforms import pyimplementation |
| 32 |
from celery.utils.collections import DictAttribute |
| 33 |
from celery.utils.objects import Bunch |
| 34 |
from celery.utils.serialization import pickle |
| 35 |
from celery.utils.time import LocalTimezone, localize, timezone, to_utc |
| 36 |
from t.unit import conftest |
| 37 |
|
| 38 |
if sys.version_info >= (3, 9): |
| 39 |
from zoneinfo import ZoneInfo |
| 40 |
else: |
| 41 |
from backports.zoneinfo import ZoneInfo |
| 42 |
|
| 43 |
THIS_IS_A_KEY = 'this is a value' |
| 44 |
|
| 45 |
|
| 46 |
class ObjectConfig: |
| 47 |
FOO = 1 |
| 48 |
BAR = 2 |
| 49 |
|
| 50 |
|
| 51 |
object_config = ObjectConfig() |
| 52 |
dict_config = {'FOO': 10, 'BAR': 20} |
| 53 |
|
| 54 |
|
| 55 |
class ObjectConfig2: |
| 56 |
LEAVE_FOR_WORK = True |
| 57 |
MOMENT_TO_STOP = True |
| 58 |
CALL_ME_BACK = 123456789 |
| 59 |
WANT_ME_TO = False |
| 60 |
UNDERSTAND_ME = True |
| 61 |
|
| 62 |
|
| 63 |
class test_module: |
| 64 |
|
| 65 |
def test_default_app(self): |
| 66 |
assert _app.default_app == _state.default_app |
| 67 |
|
| 68 |
def test_bugreport(self, app): |
| 69 |
assert _app.bugreport(app=app) |
| 70 |
|
| 71 |
|
| 72 |
class test_task_join_will_block: |
| 73 |
|
| 74 |
def test_task_join_will_block(self, patching): |
| 75 |
patching('celery._state._task_join_will_block', 0) |
| 76 |
assert _state._task_join_will_block == 0 |
| 77 |
_state._set_task_join_will_block(True) |
| 78 |
assert _state._task_join_will_block is True |
| 79 |
# fixture 'app' sets this, so need to use orig_ function |
| 80 |
# set there by that fixture. |
| 81 |
res = _state.orig_task_join_will_block() |
| 82 |
assert res is True |
| 83 |
|
| 84 |
|
| 85 |
class test_App: |
| 86 |
|
| 87 |
def setup_method(self): |
| 88 |
self.app.add_defaults(deepcopy(self.CELERY_TEST_CONFIG)) |
| 89 |
|
| 90 |
def test_now(self): |
| 91 |
timezone_setting_value = 'US/Eastern' |
| 92 |
tz_utc = timezone.get_timezone('UTC') |
| 93 |
tz_us_eastern = timezone.get_timezone(timezone_setting_value) |
| 94 |
|
| 95 |
now = to_utc(datetime.now(datetime_timezone.utc)) |
| 96 |
app_now = self.app.now() |
| 97 |
|
| 98 |
assert app_now.tzinfo is tz_utc |
| 99 |
assert app_now - now <= timedelta(seconds=1) |
| 100 |
|
| 101 |
# Check that timezone conversion is applied from configuration |
| 102 |
self.app.conf.enable_utc = False |
| 103 |
self.app.conf.timezone = timezone_setting_value |
| 104 |
# timezone is a cached property |
| 105 |
del self.app.timezone |
| 106 |
|
| 107 |
app_now = self.app.now() |
| 108 |
|
| 109 |
assert app_now.tzinfo == tz_us_eastern |
| 110 |
|
| 111 |
diff = to_utc(datetime.now(datetime_timezone.utc)) - localize(app_now, tz_utc) |
| 112 |
assert diff <= timedelta(seconds=1) |
| 113 |
|
| 114 |
# Verify that timezone setting overrides enable_utc=on setting |
| 115 |
self.app.conf.enable_utc = True |
| 116 |
del self.app.timezone |
| 117 |
app_now = self.app.now() |
| 118 |
assert self.app.timezone == tz_us_eastern |
| 119 |
assert app_now.tzinfo == tz_us_eastern |
| 120 |
|
| 121 |
@patch('celery.app.base.set_default_app') |
| 122 |
def test_set_default(self, set_default_app): |
| 123 |
self.app.set_default() |
| 124 |
set_default_app.assert_called_with(self.app) |
| 125 |
|
| 126 |
@patch('celery.security.setup_security') |
| 127 |
def test_setup_security(self, setup_security): |
| 128 |
self.app.setup_security( |
| 129 |
{'json'}, 'key', None, 'cert', 'store', 'digest', 'serializer') |
| 130 |
setup_security.assert_called_with( |
| 131 |
{'json'}, 'key', None, 'cert', 'store', 'digest', 'serializer', |
| 132 |
app=self.app) |
| 133 |
|
| 134 |
def test_task_autofinalize_disabled(self): |
| 135 |
with self.Celery('xyzibari', autofinalize=False) as app: |
| 136 |
@app.task |
| 137 |
def ttafd(): |
| 138 |
return 42 |
| 139 |
|
| 140 |
with pytest.raises(RuntimeError): |
| 141 |
ttafd() |
| 142 |
|
| 143 |
with self.Celery('xyzibari', autofinalize=False) as app: |
| 144 |
@app.task |
| 145 |
def ttafd2(): |
| 146 |
return 42 |
| 147 |
|
| 148 |
app.finalize() |
| 149 |
assert ttafd2() == 42 |
| 150 |
|
| 151 |
def test_registry_autofinalize_disabled(self): |
| 152 |
with self.Celery('xyzibari', autofinalize=False) as app: |
| 153 |
with pytest.raises(RuntimeError): |
| 154 |
app.tasks['celery.chain'] |
| 155 |
app.finalize() |
| 156 |
assert app.tasks['celery.chain'] |
| 157 |
|
| 158 |
def test_task(self): |
| 159 |
with self.Celery('foozibari') as app: |
| 160 |
|
| 161 |
def fun(): |
| 162 |
pass |
| 163 |
|
| 164 |
fun.__module__ = '__main__' |
| 165 |
task = app.task(fun) |
| 166 |
assert task.name == app.main + '.fun' |
| 167 |
|
| 168 |
def test_task_too_many_args(self): |
| 169 |
with pytest.raises(TypeError): |
| 170 |
self.app.task(Mock(name='fun'), True) |
| 171 |
with pytest.raises(TypeError): |
| 172 |
self.app.task(Mock(name='fun'), True, 1, 2) |
| 173 |
|
| 174 |
def test_with_config_source(self): |
| 175 |
with self.Celery(config_source=ObjectConfig) as app: |
| 176 |
assert app.conf.FOO == 1 |
| 177 |
assert app.conf.BAR == 2 |
| 178 |
|
| 179 |
@pytest.mark.usefixtures('depends_on_current_app') |
| 180 |
def test_task_windows_execv(self): |
| 181 |
prev, _appbase.USING_EXECV = _appbase.USING_EXECV, True |
| 182 |
try: |
| 183 |
@self.app.task(shared=False) |
| 184 |
def foo(): |
| 185 |
pass |
| 186 |
|
| 187 |
assert foo._get_current_object() # is proxy |
| 188 |
|
| 189 |
finally: |
| 190 |
_appbase.USING_EXECV = prev |
| 191 |
assert not _appbase.USING_EXECV |
| 192 |
|
| 193 |
def test_task_takes_no_args(self): |
| 194 |
with pytest.raises(TypeError): |
| 195 |
@self.app.task(1) |
| 196 |
def foo(): |
| 197 |
pass |
| 198 |
|
| 199 |
def test_add_defaults(self): |
| 200 |
assert not self.app.configured |
| 201 |
_conf = {'foo': 300} |
| 202 |
|
| 203 |
def conf(): |
| 204 |
return _conf |
| 205 |
|
| 206 |
self.app.add_defaults(conf) |
| 207 |
assert conf in self.app._pending_defaults |
| 208 |
assert not self.app.configured |
| 209 |
assert self.app.conf.foo == 300 |
| 210 |
assert self.app.configured |
| 211 |
assert not self.app._pending_defaults |
| 212 |
|
| 213 |
# defaults not pickled |
| 214 |
appr = loads(dumps(self.app)) |
| 215 |
with pytest.raises(AttributeError): |
| 216 |
appr.conf.foo |
| 217 |
|
| 218 |
# add more defaults after configured |
| 219 |
conf2 = {'foo': 'BAR'} |
| 220 |
self.app.add_defaults(conf2) |
| 221 |
assert self.app.conf.foo == 'BAR' |
| 222 |
|
| 223 |
assert _conf in self.app.conf.defaults |
| 224 |
assert conf2 in self.app.conf.defaults |
| 225 |
|
| 226 |
def test_connection_or_acquire(self): |
| 227 |
with self.app.connection_or_acquire(block=True): |
| 228 |
assert self.app.pool._dirty |
| 229 |
|
| 230 |
with self.app.connection_or_acquire(pool=False): |
| 231 |
assert not self.app.pool._dirty |
| 232 |
|
| 233 |
def test_using_v1_reduce(self): |
| 234 |
self.app._using_v1_reduce = True |
| 235 |
assert loads(dumps(self.app)) |
| 236 |
|
| 237 |
def test_autodiscover_tasks_force_fixup_fallback(self): |
| 238 |
self.app.loader.autodiscover_tasks = Mock() |
| 239 |
self.app.autodiscover_tasks([], force=True) |
| 240 |
self.app.loader.autodiscover_tasks.assert_called_with( |
| 241 |
[], 'tasks', |
| 242 |
) |
| 243 |
|
| 244 |
def test_autodiscover_tasks_force(self): |
| 245 |
self.app.loader.autodiscover_tasks = Mock() |
| 246 |
self.app.autodiscover_tasks(['proj.A', 'proj.B'], force=True) |
| 247 |
self.app.loader.autodiscover_tasks.assert_called_with( |
| 248 |
['proj.A', 'proj.B'], 'tasks', |
| 249 |
) |
| 250 |
self.app.loader.autodiscover_tasks = Mock() |
| 251 |
|
| 252 |
def lazy_list(): |
| 253 |
return ['proj.A', 'proj.B'] |
| 254 |
self.app.autodiscover_tasks( |
| 255 |
lazy_list, |
| 256 |
related_name='george', |
| 257 |
force=True, |
| 258 |
) |
| 259 |
self.app.loader.autodiscover_tasks.assert_called_with( |
| 260 |
['proj.A', 'proj.B'], 'george', |
| 261 |
) |
| 262 |
|
| 263 |
def test_autodiscover_tasks_lazy(self): |
| 264 |
with patch('celery.signals.import_modules') as import_modules: |
| 265 |
def lazy_list(): |
| 266 |
return [1, 2, 3] |
| 267 |
self.app.autodiscover_tasks(lazy_list) |
| 268 |
import_modules.connect.assert_called() |
| 269 |
prom = import_modules.connect.call_args[0][0] |
| 270 |
assert isinstance(prom, promise) |
| 271 |
assert prom.fun == self.app._autodiscover_tasks |
| 272 |
assert prom.args[0](), [1, 2 == 3] |
| 273 |
|
| 274 |
def test_autodiscover_tasks__no_packages(self): |
| 275 |
fixup1 = Mock(name='fixup') |
| 276 |
fixup2 = Mock(name='fixup') |
| 277 |
self.app._autodiscover_tasks_from_names = Mock(name='auto') |
| 278 |
self.app._fixups = [fixup1, fixup2] |
| 279 |
fixup1.autodiscover_tasks.return_value = ['A', 'B', 'C'] |
| 280 |
fixup2.autodiscover_tasks.return_value = ['D', 'E', 'F'] |
| 281 |
self.app.autodiscover_tasks(force=True) |
| 282 |
self.app._autodiscover_tasks_from_names.assert_called_with( |
| 283 |
['A', 'B', 'C', 'D', 'E', 'F'], related_name='tasks', |
| 284 |
) |
| 285 |
|
| 286 |
def test_with_broker(self, patching): |
| 287 |
patching.setenv('CELERY_BROKER_URL', '') |
| 288 |
with self.Celery(broker='foo://baribaz') as app: |
| 289 |
assert app.conf.broker_url == 'foo://baribaz' |
| 290 |
|
| 291 |
def test_pending_configuration_non_true__kwargs(self): |
| 292 |
with self.Celery(task_create_missing_queues=False) as app: |
| 293 |
assert app.conf.task_create_missing_queues is False |
| 294 |
|
| 295 |
def test_pending_configuration__kwargs(self): |
| 296 |
with self.Celery(foo='bar') as app: |
| 297 |
assert app.conf.foo == 'bar' |
| 298 |
|
| 299 |
def test_pending_configuration__setattr(self): |
| 300 |
with self.Celery(broker='foo://bar') as app: |
| 301 |
app.conf.task_default_delivery_mode = 44 |
| 302 |
app.conf.worker_agent = 'foo:Bar' |
| 303 |
assert not app.configured |
| 304 |
assert app.conf.worker_agent == 'foo:Bar' |
| 305 |
assert app.conf.broker_url == 'foo://bar' |
| 306 |
assert app._preconf['worker_agent'] == 'foo:Bar' |
| 307 |
|
| 308 |
assert app.configured |
| 309 |
reapp = pickle.loads(pickle.dumps(app)) |
| 310 |
assert reapp._preconf['worker_agent'] == 'foo:Bar' |
| 311 |
assert not reapp.configured |
| 312 |
assert reapp.conf.worker_agent == 'foo:Bar' |
| 313 |
assert reapp.configured |
| 314 |
assert reapp.conf.broker_url == 'foo://bar' |
| 315 |
assert reapp._preconf['worker_agent'] == 'foo:Bar' |
| 316 |
|
| 317 |
def test_pending_configuration__update(self): |
| 318 |
with self.Celery(broker='foo://bar') as app: |
| 319 |
app.conf.update( |
| 320 |
task_default_delivery_mode=44, |
| 321 |
worker_agent='foo:Bar', |
| 322 |
) |
| 323 |
assert not app.configured |
| 324 |
assert app.conf.worker_agent == 'foo:Bar' |
| 325 |
assert app.conf.broker_url == 'foo://bar' |
| 326 |
assert app._preconf['worker_agent'] == 'foo:Bar' |
| 327 |
|
| 328 |
def test_pending_configuration__compat_settings(self): |
| 329 |
with self.Celery(broker='foo://bar', backend='foo') as app: |
| 330 |
app.conf.update( |
| 331 |
CELERY_ALWAYS_EAGER=4, |
| 332 |
CELERY_DEFAULT_DELIVERY_MODE=63, |
| 333 |
CELERYD_AGENT='foo:Barz', |
| 334 |
) |
| 335 |
assert app.conf.task_always_eager == 4 |
| 336 |
assert app.conf.task_default_delivery_mode == 63 |
| 337 |
assert app.conf.worker_agent == 'foo:Barz' |
| 338 |
assert app.conf.broker_url == 'foo://bar' |
| 339 |
assert app.conf.result_backend == 'foo' |
| 340 |
|
| 341 |
def test_pending_configuration__compat_settings_mixing(self): |
| 342 |
with self.Celery(broker='foo://bar', backend='foo') as app: |
| 343 |
app.conf.update( |
| 344 |
CELERY_ALWAYS_EAGER=4, |
| 345 |
CELERY_DEFAULT_DELIVERY_MODE=63, |
| 346 |
CELERYD_AGENT='foo:Barz', |
| 347 |
worker_consumer='foo:Fooz', |
| 348 |
) |
| 349 |
with pytest.raises(ImproperlyConfigured): |
| 350 |
assert app.conf.task_always_eager == 4 |
| 351 |
|
| 352 |
def test_pending_configuration__django_settings(self): |
| 353 |
with self.Celery(broker='foo://bar', backend='foo') as app: |
| 354 |
app.config_from_object(DictAttribute(Bunch( |
| 355 |
CELERY_TASK_ALWAYS_EAGER=4, |
| 356 |
CELERY_TASK_DEFAULT_DELIVERY_MODE=63, |
| 357 |
CELERY_WORKER_AGENT='foo:Barz', |
| 358 |
CELERY_RESULT_SERIALIZER='pickle', |
| 359 |
)), namespace='CELERY') |
| 360 |
assert app.conf.result_serializer == 'pickle' |
| 361 |
assert app.conf.CELERY_RESULT_SERIALIZER == 'pickle' |
| 362 |
assert app.conf.task_always_eager == 4 |
| 363 |
assert app.conf.task_default_delivery_mode == 63 |
| 364 |
assert app.conf.worker_agent == 'foo:Barz' |
| 365 |
assert app.conf.broker_url == 'foo://bar' |
| 366 |
assert app.conf.result_backend == 'foo' |
| 367 |
|
| 368 |
def test_pending_configuration__compat_settings_mixing_new(self): |
| 369 |
with self.Celery(broker='foo://bar', backend='foo') as app: |
| 370 |
app.conf.update( |
| 371 |
task_always_eager=4, |
| 372 |
task_default_delivery_mode=63, |
| 373 |
worker_agent='foo:Barz', |
| 374 |
CELERYD_CONSUMER='foo:Fooz', |
| 375 |
CELERYD_AUTOSCALER='foo:Xuzzy', |
| 376 |
) |
| 377 |
with pytest.raises(ImproperlyConfigured): |
| 378 |
assert app.conf.worker_consumer == 'foo:Fooz' |
| 379 |
|
| 380 |
def test_pending_configuration__compat_settings_mixing_alt(self): |
| 381 |
with self.Celery(broker='foo://bar', backend='foo') as app: |
| 382 |
app.conf.update( |
| 383 |
task_always_eager=4, |
| 384 |
task_default_delivery_mode=63, |
| 385 |
worker_agent='foo:Barz', |
| 386 |
CELERYD_CONSUMER='foo:Fooz', |
| 387 |
worker_consumer='foo:Fooz', |
| 388 |
CELERYD_AUTOSCALER='foo:Xuzzy', |
| 389 |
worker_autoscaler='foo:Xuzzy' |
| 390 |
) |
| 391 |
|
| 392 |
def test_pending_configuration__setdefault(self): |
| 393 |
with self.Celery(broker='foo://bar') as app: |
| 394 |
assert not app.configured |
| 395 |
app.conf.setdefault('worker_agent', 'foo:Bar') |
| 396 |
assert not app.configured |
| 397 |
|
| 398 |
def test_pending_configuration__iter(self): |
| 399 |
with self.Celery(broker='foo://bar') as app: |
| 400 |
app.conf.worker_agent = 'foo:Bar' |
| 401 |
assert not app.configured |
| 402 |
assert list(app.conf.keys()) |
| 403 |
assert app.configured |
| 404 |
assert 'worker_agent' in app.conf |
| 405 |
assert dict(app.conf) |
| 406 |
|
| 407 |
def test_pending_configuration__raises_ImproperlyConfigured(self): |
| 408 |
with self.Celery(set_as_current=False) as app: |
| 409 |
app.conf.worker_agent = 'foo://bar' |
| 410 |
app.conf.task_default_delivery_mode = 44 |
| 411 |
app.conf.CELERY_ALWAYS_EAGER = 5 |
| 412 |
with pytest.raises(ImproperlyConfigured): |
| 413 |
app.finalize() |
| 414 |
|
| 415 |
with self.Celery() as app: |
| 416 |
assert not self.app.conf.task_always_eager |
| 417 |
|
| 418 |
def test_pending_configuration__ssl_settings(self): |
| 419 |
with self.Celery(broker='foo://bar', |
| 420 |
broker_use_ssl={ |
| 421 |
'ssl_cert_reqs': ssl.CERT_REQUIRED, |
| 422 |
'ssl_ca_certs': '/path/to/ca.crt', |
| 423 |
'ssl_certfile': '/path/to/client.crt', |
| 424 |
'ssl_keyfile': '/path/to/client.key'}, |
| 425 |
redis_backend_use_ssl={ |
| 426 |
'ssl_cert_reqs': ssl.CERT_REQUIRED, |
| 427 |
'ssl_ca_certs': '/path/to/ca.crt', |
| 428 |
'ssl_certfile': '/path/to/client.crt', |
| 429 |
'ssl_keyfile': '/path/to/client.key'}) as app: |
| 430 |
assert not app.configured |
| 431 |
assert app.conf.broker_url == 'foo://bar' |
| 432 |
assert app.conf.broker_use_ssl['ssl_certfile'] == \ |
| 433 |
'/path/to/client.crt' |
| 434 |
assert app.conf.broker_use_ssl['ssl_keyfile'] == \ |
| 435 |
'/path/to/client.key' |
| 436 |
assert app.conf.broker_use_ssl['ssl_ca_certs'] == \ |
| 437 |
'/path/to/ca.crt' |
| 438 |
assert app.conf.broker_use_ssl['ssl_cert_reqs'] == \ |
| 439 |
ssl.CERT_REQUIRED |
| 440 |
assert app.conf.redis_backend_use_ssl['ssl_certfile'] == \ |
| 441 |
'/path/to/client.crt' |
| 442 |
assert app.conf.redis_backend_use_ssl['ssl_keyfile'] == \ |
| 443 |
'/path/to/client.key' |
| 444 |
assert app.conf.redis_backend_use_ssl['ssl_ca_certs'] == \ |
| 445 |
'/path/to/ca.crt' |
| 446 |
assert app.conf.redis_backend_use_ssl['ssl_cert_reqs'] == \ |
| 447 |
ssl.CERT_REQUIRED |
| 448 |
|
| 449 |
def test_repr(self): |
| 450 |
assert repr(self.app) |
| 451 |
|
| 452 |
def test_custom_task_registry(self): |
| 453 |
with self.Celery(tasks=self.app.tasks) as app2: |
| 454 |
assert app2.tasks is self.app.tasks |
| 455 |
|
| 456 |
def test_include_argument(self): |
| 457 |
with self.Celery(include=('foo', 'bar.foo')) as app: |
| 458 |
assert app.conf.include, ('foo' == 'bar.foo') |
| 459 |
|
| 460 |
def test_set_as_current(self): |
| 461 |
current = _state._tls.current_app |
| 462 |
try: |
| 463 |
app = self.Celery(set_as_current=True) |
| 464 |
assert _state._tls.current_app is app |
| 465 |
finally: |
| 466 |
_state._tls.current_app = current |
| 467 |
|
| 468 |
def test_current_task(self): |
| 469 |
@self.app.task |
| 470 |
def foo(shared=False): |
| 471 |
pass |
| 472 |
|
| 473 |
_state._task_stack.push(foo) |
| 474 |
try: |
| 475 |
assert self.app.current_task.name == foo.name |
| 476 |
finally: |
| 477 |
_state._task_stack.pop() |
| 478 |
|
| 479 |
def test_task_not_shared(self): |
| 480 |
with patch('celery.app.base.connect_on_app_finalize') as sh: |
| 481 |
@self.app.task(shared=False) |
| 482 |
def foo(): |
| 483 |
pass |
| 484 |
sh.assert_not_called() |
| 485 |
|
| 486 |
def test_task_compat_with_filter(self): |
| 487 |
with self.Celery() as app: |
| 488 |
check = Mock() |
| 489 |
|
| 490 |
def filter(task): |
| 491 |
check(task) |
| 492 |
return task |
| 493 |
|
| 494 |
@app.task(filter=filter, shared=False) |
| 495 |
def foo(): |
| 496 |
pass |
| 497 |
check.assert_called_with(foo) |
| 498 |
|
| 499 |
def test_task_with_filter(self): |
| 500 |
with self.Celery() as app: |
| 501 |
check = Mock() |
| 502 |
|
| 503 |
def filter(task): |
| 504 |
check(task) |
| 505 |
return task |
| 506 |
|
| 507 |
assert not _appbase.USING_EXECV |
| 508 |
|
| 509 |
@app.task(filter=filter, shared=False) |
| 510 |
def foo(): |
| 511 |
pass |
| 512 |
check.assert_called_with(foo) |
| 513 |
|
| 514 |
def test_task_with_pydantic_with_no_args(self): |
| 515 |
"""Test a pydantic task with no arguments or return value.""" |
| 516 |
with self.Celery() as app: |
| 517 |
check = Mock() |
| 518 |
|
| 519 |
@app.task(pydantic=True) |
| 520 |
def foo(): |
| 521 |
check() |
| 522 |
|
| 523 |
assert foo() is None |
| 524 |
check.assert_called_once() |
| 525 |
|
| 526 |
def test_task_with_pydantic_with_arg_and_kwarg(self): |
| 527 |
"""Test a pydantic task with simple (non-pydantic) arg/kwarg and return value.""" |
| 528 |
with self.Celery() as app: |
| 529 |
check = Mock() |
| 530 |
|
| 531 |
@app.task(pydantic=True) |
| 532 |
def foo(arg: int, kwarg: bool = True) -> int: |
| 533 |
check(arg, kwarg=kwarg) |
| 534 |
return 1 |
| 535 |
|
| 536 |
assert foo(0) == 1 |
| 537 |
check.assert_called_once_with(0, kwarg=True) |
| 538 |
|
| 539 |
def test_task_with_pydantic_with_optional_args(self): |
| 540 |
"""Test pydantic task receiving and returning an optional argument.""" |
| 541 |
with self.Celery() as app: |
| 542 |
check = Mock() |
| 543 |
|
| 544 |
@app.task(pydantic=True) |
| 545 |
def foo(arg: Optional[int], kwarg: Optional[bool] = True) -> Optional[int]: |
| 546 |
check(arg, kwarg=kwarg) |
| 547 |
if isinstance(arg, int): |
| 548 |
return 1 |
| 549 |
return 2 |
| 550 |
|
| 551 |
assert foo(0) == 1 |
| 552 |
check.assert_called_once_with(0, kwarg=True) |
| 553 |
|
| 554 |
assert foo(None) == 2 |
| 555 |
check.assert_called_with(None, kwarg=True) |
| 556 |
|
| 557 |
@pytest.mark.skipif(sys.version_info < (3, 9), reason="Notation is only supported in Python 3.9 or newer.") |
| 558 |
def test_task_with_pydantic_with_dict_args(self): |
| 559 |
"""Test pydantic task receiving and returning a generic dict argument.""" |
| 560 |
with self.Celery() as app: |
| 561 |
check = Mock() |
| 562 |
|
| 563 |
@app.task(pydantic=True) |
| 564 |
def foo(arg: dict[str, str], kwarg: dict[str, str]) -> dict[str, str]: |
| 565 |
check(arg, kwarg=kwarg) |
| 566 |
return {'x': 'y'} |
| 567 |
|
| 568 |
assert foo({'a': 'b'}, kwarg={'c': 'd'}) == {'x': 'y'} |
| 569 |
check.assert_called_once_with({'a': 'b'}, kwarg={'c': 'd'}) |
| 570 |
|
| 571 |
@pytest.mark.skipif(sys.version_info < (3, 9), reason="Notation is only supported in Python 3.9 or newer.") |
| 572 |
def test_task_with_pydantic_with_list_args(self): |
| 573 |
"""Test pydantic task receiving and returning a generic dict argument.""" |
| 574 |
with self.Celery() as app: |
| 575 |
check = Mock() |
| 576 |
|
| 577 |
@app.task(pydantic=True) |
| 578 |
def foo(arg: list[str], kwarg: list[str] = True) -> list[str]: |
| 579 |
check(arg, kwarg=kwarg) |
| 580 |
return ['x'] |
| 581 |
|
| 582 |
assert foo(['a'], kwarg=['b']) == ['x'] |
| 583 |
check.assert_called_once_with(['a'], kwarg=['b']) |
| 584 |
|
| 585 |
def test_task_with_pydantic_with_pydantic_arg_and_default_kwarg(self): |
| 586 |
"""Test a pydantic task with pydantic arg/kwarg and return value.""" |
| 587 |
|
| 588 |
class ArgModel(BaseModel): |
| 589 |
arg_value: int |
| 590 |
|
| 591 |
class KwargModel(BaseModel): |
| 592 |
kwarg_value: int |
| 593 |
|
| 594 |
kwarg_default = KwargModel(kwarg_value=1) |
| 595 |
|
| 596 |
class ReturnModel(BaseModel): |
| 597 |
ret_value: int |
| 598 |
|
| 599 |
with self.Celery() as app: |
| 600 |
check = Mock() |
| 601 |
|
| 602 |
@app.task(pydantic=True) |
| 603 |
def foo(arg: ArgModel, kwarg: KwargModel = kwarg_default) -> ReturnModel: |
| 604 |
check(arg, kwarg=kwarg) |
| 605 |
return ReturnModel(ret_value=2) |
| 606 |
|
| 607 |
assert foo({'arg_value': 0}) == {'ret_value': 2} |
| 608 |
check.assert_called_once_with(ArgModel(arg_value=0), kwarg=kwarg_default) |
| 609 |
check.reset_mock() |
| 610 |
|
| 611 |
# Explicitly pass kwarg (but as argument) |
| 612 |
assert foo({'arg_value': 3}, {'kwarg_value': 4}) == {'ret_value': 2} |
| 613 |
check.assert_called_once_with(ArgModel(arg_value=3), kwarg=KwargModel(kwarg_value=4)) |
| 614 |
check.reset_mock() |
| 615 |
|
| 616 |
# Explicitly pass all arguments as kwarg |
| 617 |
assert foo(arg={'arg_value': 5}, kwarg={'kwarg_value': 6}) == {'ret_value': 2} |
| 618 |
check.assert_called_once_with(ArgModel(arg_value=5), kwarg=KwargModel(kwarg_value=6)) |
| 619 |
|
| 620 |
def test_task_with_pydantic_with_non_strict_validation(self): |
| 621 |
"""Test a pydantic task with where Pydantic has to apply non-strict validation.""" |
| 622 |
|
| 623 |
class Model(BaseModel): |
| 624 |
value: timedelta |
| 625 |
|
| 626 |
with self.Celery() as app: |
| 627 |
check = Mock() |
| 628 |
|
| 629 |
@app.task(pydantic=True) |
| 630 |
def foo(arg: Model) -> Model: |
| 631 |
check(arg) |
| 632 |
return Model(value=timedelta(days=arg.value.days * 2)) |
| 633 |
|
| 634 |
assert foo({'value': timedelta(days=1)}) == {'value': 'P2D'} |
| 635 |
check.assert_called_once_with(Model(value=timedelta(days=1))) |
| 636 |
check.reset_mock() |
| 637 |
|
| 638 |
# Pass a serialized value to the task |
| 639 |
assert foo({'value': 'P3D'}) == {'value': 'P6D'} |
| 640 |
check.assert_called_once_with(Model(value=timedelta(days=3))) |
| 641 |
|
| 642 |
def test_task_with_pydantic_with_optional_pydantic_args(self): |
| 643 |
"""Test pydantic task receiving and returning an optional argument.""" |
| 644 |
class ArgModel(BaseModel): |
| 645 |
arg_value: int |
| 646 |
|
| 647 |
class KwargModel(BaseModel): |
| 648 |
kwarg_value: int |
| 649 |
|
| 650 |
class ReturnModel(BaseModel): |
| 651 |
ret_value: int |
| 652 |
|
| 653 |
with self.Celery() as app: |
| 654 |
check = Mock() |
| 655 |
|
| 656 |
@app.task(pydantic=True) |
| 657 |
def foo(arg: Optional[ArgModel], kwarg: Optional[KwargModel] = None) -> Optional[ReturnModel]: |
| 658 |
check(arg, kwarg=kwarg) |
| 659 |
if isinstance(arg, ArgModel): |
| 660 |
return ReturnModel(ret_value=1) |
| 661 |
return None |
| 662 |
|
| 663 |
assert foo(None) is None |
| 664 |
check.assert_called_once_with(None, kwarg=None) |
| 665 |
|
| 666 |
assert foo({'arg_value': 1}, kwarg={'kwarg_value': 2}) == {'ret_value': 1} |
| 667 |
check.assert_called_with(ArgModel(arg_value=1), kwarg=KwargModel(kwarg_value=2)) |
| 668 |
|
| 669 |
@pytest.mark.skipif(sys.version_info < (3, 9), reason="Notation is only supported in Python 3.9 or newer.") |
| 670 |
def test_task_with_pydantic_with_generic_return_value(self): |
| 671 |
"""Test pydantic task receiving and returning an optional argument.""" |
| 672 |
class ReturnModel(BaseModel): |
| 673 |
ret_value: int |
| 674 |
|
| 675 |
with self.Celery() as app: |
| 676 |
check = Mock() |
| 677 |
|
| 678 |
@app.task(pydantic=True) |
| 679 |
def foo() -> dict[str, str]: |
| 680 |
check() |
| 681 |
return ReturnModel(ret_value=1) # type: ignore # whole point here is that this doesn't match |
| 682 |
|
| 683 |
assert foo() == ReturnModel(ret_value=1) |
| 684 |
check.assert_called_once_with() |
| 685 |
|
| 686 |
def test_task_with_pydantic_with_task_name_in_context(self): |
| 687 |
"""Test that the task name is passed to as additional context.""" |
| 688 |
|
| 689 |
class ArgModel(BaseModel): |
| 690 |
value: int |
| 691 |
|
| 692 |
@model_validator(mode='after') |
| 693 |
def validate_context(self, info: ValidationInfo): |
| 694 |
context = info.context |
| 695 |
assert context |
| 696 |
assert context.get('celery_task_name') == 't.unit.app.test_app.task' |
| 697 |
return self |
| 698 |
|
| 699 |
with self.Celery() as app: |
| 700 |
check = Mock() |
| 701 |
|
| 702 |
@app.task(pydantic=True) |
| 703 |
def task(arg: ArgModel): |
| 704 |
check(arg) |
| 705 |
return 1 |
| 706 |
|
| 707 |
assert task({'value': 1}) == 1 |
| 708 |
|
| 709 |
def test_task_with_pydantic_with_strict_validation(self): |
| 710 |
"""Test a pydantic task with/without strict model validation.""" |
| 711 |
|
| 712 |
class ArgModel(BaseModel): |
| 713 |
value: int |
| 714 |
|
| 715 |
with self.Celery() as app: |
| 716 |
check = Mock() |
| 717 |
|
| 718 |
@app.task(pydantic=True, pydantic_strict=True) |
| 719 |
def strict(arg: ArgModel): |
| 720 |
check(arg) |
| 721 |
|
| 722 |
@app.task(pydantic=True, pydantic_strict=False) |
| 723 |
def loose(arg: ArgModel): |
| 724 |
check(arg) |
| 725 |
|
| 726 |
# In Pydantic, passing an "exact int" as float works without strict validation |
| 727 |
assert loose({'value': 1.0}) is None |
| 728 |
check.assert_called_once_with(ArgModel(value=1)) |
| 729 |
check.reset_mock() |
| 730 |
|
| 731 |
# ... but a non-strict value will raise an exception |
| 732 |
with pytest.raises(ValueError): |
| 733 |
loose({'value': 1.1}) |
| 734 |
check.assert_not_called() |
| 735 |
|
| 736 |
# ... with strict validation, even an "exact int" will not work: |
| 737 |
with pytest.raises(ValueError): |
| 738 |
strict({'value': 1.0}) |
| 739 |
check.assert_not_called() |
| 740 |
|
| 741 |
def test_task_with_pydantic_with_extra_context(self): |
| 742 |
"""Test passing additional validation context to the model.""" |
| 743 |
|
| 744 |
class ArgModel(BaseModel): |
| 745 |
value: int |
| 746 |
|
| 747 |
@model_validator(mode='after') |
| 748 |
def validate_context(self, info: ValidationInfo): |
| 749 |
context = info.context |
| 750 |
assert context, context |
| 751 |
assert context.get('foo') == 'bar' |
| 752 |
return self |
| 753 |
|
| 754 |
with self.Celery() as app: |
| 755 |
check = Mock() |
| 756 |
|
| 757 |
@app.task(pydantic=True, pydantic_context={'foo': 'bar'}) |
| 758 |
def task(arg: ArgModel): |
| 759 |
check(arg.value) |
| 760 |
return 1 |
| 761 |
|
| 762 |
assert task({'value': 1}) == 1 |
| 763 |
check.assert_called_once_with(1) |
| 764 |
|
| 765 |
def test_task_with_pydantic_with_dump_kwargs(self): |
| 766 |
"""Test passing keyword arguments to model_dump().""" |
| 767 |
|
| 768 |
class ArgModel(BaseModel): |
| 769 |
value: int |
| 770 |
|
| 771 |
class RetModel(BaseModel): |
| 772 |
value: datetime |
| 773 |
unset_value: typing.Optional[int] = 99 # this would be in the output, if exclude_unset weren't True |
| 774 |
|
| 775 |
with self.Celery() as app: |
| 776 |
check = Mock() |
| 777 |
|
| 778 |
@app.task(pydantic=True, pydantic_dump_kwargs={'mode': 'python', 'exclude_unset': True}) |
| 779 |
def task(arg: ArgModel) -> RetModel: |
| 780 |
check(arg) |
| 781 |
return RetModel(value=datetime(2024, 5, 14, tzinfo=timezone.utc)) |
| 782 |
|
| 783 |
assert task({'value': 1}) == {'value': datetime(2024, 5, 14, tzinfo=timezone.utc)} |
| 784 |
check.assert_called_once_with(ArgModel(value=1)) |
| 785 |
|
| 786 |
def test_task_with_pydantic_with_pydantic_not_installed(self): |
| 787 |
"""Test configuring a task with Pydantic when pydantic is not installed.""" |
| 788 |
|
| 789 |
with self.Celery() as app: |
| 790 |
@app.task(pydantic=True) |
| 791 |
def task(): |
| 792 |
return |
| 793 |
|
| 794 |
# mock function will raise ModuleNotFoundError only if pydantic is imported |
| 795 |
def import_module(name, *args, **kwargs): |
| 796 |
if name == 'pydantic': |
| 797 |
raise ModuleNotFoundError('Module not found.') |
| 798 |
return DEFAULT |
| 799 |
|
| 800 |
msg = r'^You need to install pydantic to use pydantic model serialization\.$' |
| 801 |
with patch( |
| 802 |
'celery.app.base.importlib.import_module', |
| 803 |
side_effect=import_module, |
| 804 |
wraps=importlib.import_module |
| 805 |
): |
| 806 |
with pytest.raises(ImproperlyConfigured, match=msg): |
| 807 |
task() |
| 808 |
|
| 809 |
def test_task_sets_main_name_MP_MAIN_FILE(self): |
| 810 |
from celery.utils import imports as _imports |
| 811 |
_imports.MP_MAIN_FILE = __file__ |
| 812 |
try: |
| 813 |
with self.Celery('xuzzy') as app: |
| 814 |
|
| 815 |
@app.task |
| 816 |
def foo(): |
| 817 |
pass |
| 818 |
|
| 819 |
assert foo.name == 'xuzzy.foo' |
| 820 |
finally: |
| 821 |
_imports.MP_MAIN_FILE = None |
| 822 |
|
| 823 |
def test_can_get_type_hints_for_tasks(self): |
| 824 |
import typing |
| 825 |
|
| 826 |
with self.Celery() as app: |
| 827 |
@app.task |
| 828 |
def foo(parameter: int) -> None: |
| 829 |
pass |
| 830 |
|
| 831 |
assert typing.get_type_hints(foo) == { |
| 832 |
'parameter': int, 'return': type(None)} |
| 833 |
|
| 834 |
@pytest.mark.skipif(sys.version_info < (3, 14), reason="PEP 649 deferred annotations require Python 3.14+") |
| 835 |
def test_task_with_type_checking_annotation(self): |
| 836 |
# Regression test for https://github.com/celery/celery/discussions/10099 |
| 837 |
# On Python 3.14+, annotations are deferred (PEP 649). Registering a task |
| 838 |
# whose annotations reference TYPE_CHECKING-only types must not raise NameError. |
| 839 |
local = {} |
| 840 |
exec( |
| 841 |
'def foo(args: Sequence[str], x: int = 0): return args', |
| 842 |
{'app': None}, |
| 843 |
local, |
| 844 |
) |
| 845 |
raw_fun = local['foo'] |
| 846 |
|
| 847 |
with self.Celery() as app: |
| 848 |
task = app.task(raw_fun) |
| 849 |
result = task.apply(args=(['hello'],)) |
| 850 |
assert result.result == ['hello'] |
| 851 |
# Annotations should be stored as strings, not evaluated |
| 852 |
assert task.__annotations__['args'] == 'Sequence[str]' |
| 853 |
|
| 854 |
def test_annotate_decorator(self): |
| 855 |
from celery.app.task import Task |
| 856 |
|
| 857 |
class adX(Task): |
| 858 |
|
| 859 |
def run(self, y, z, x): |
| 860 |
return y, z, x |
| 861 |
|
| 862 |
check = Mock() |
| 863 |
|
| 864 |
def deco(fun): |
| 865 |
|
| 866 |
def _inner(*args, **kwargs): |
| 867 |
check(*args, **kwargs) |
| 868 |
return fun(*args, **kwargs) |
| 869 |
return _inner |
| 870 |
|
| 871 |
self.app.conf.task_annotations = { |
| 872 |
adX.name: {'@__call__': deco} |
| 873 |
} |
| 874 |
adX.bind(self.app) |
| 875 |
assert adX.app is self.app |
| 876 |
|
| 877 |
i = adX() |
| 878 |
i(2, 4, x=3) |
| 879 |
check.assert_called_with(i, 2, 4, x=3) |
| 880 |
|
| 881 |
i.annotate() |
| 882 |
i.annotate() |
| 883 |
|
| 884 |
def test_apply_async_adds_children(self): |
| 885 |
from celery._state import _task_stack |
| 886 |
|
| 887 |
@self.app.task(bind=True, shared=False) |
| 888 |
def a3cX1(self): |
| 889 |
pass |
| 890 |
|
| 891 |
@self.app.task(bind=True, shared=False) |
| 892 |
def a3cX2(self): |
| 893 |
pass |
| 894 |
|
| 895 |
_task_stack.push(a3cX1) |
| 896 |
try: |
| 897 |
a3cX1.push_request(called_directly=False) |
| 898 |
try: |
| 899 |
res = a3cX2.apply_async(add_to_parent=True) |
| 900 |
assert res in a3cX1.request.children |
| 901 |
finally: |
| 902 |
a3cX1.pop_request() |
| 903 |
finally: |
| 904 |
_task_stack.pop() |
| 905 |
|
| 906 |
def test_pickle_app(self): |
| 907 |
changes = {'THE_FOO_BAR': 'bars', |
| 908 |
'THE_MII_MAR': 'jars'} |
| 909 |
self.app.conf.update(changes) |
| 910 |
saved = pickle.dumps(self.app) |
| 911 |
assert len(saved) < 2048 |
| 912 |
restored = pickle.loads(saved) |
| 913 |
for key, value in changes.items(): |
| 914 |
assert restored.conf[key] == value |
| 915 |
|
| 916 |
@patch('celery.bin.celery.celery') |
| 917 |
def test_worker_main(self, mocked_celery): |
| 918 |
self.app.worker_main(argv=['worker', '--help']) |
| 919 |
|
| 920 |
mocked_celery.main.assert_called_with( |
| 921 |
args=['worker', '--help'], standalone_mode=False) |
| 922 |
|
| 923 |
def test_config_from_envvar(self, monkeypatch): |
| 924 |
monkeypatch.setenv("CELERYTEST_CONFIG_OBJECT", 't.unit.app.test_app') |
| 925 |
self.app.config_from_envvar('CELERYTEST_CONFIG_OBJECT') |
| 926 |
assert self.app.conf.THIS_IS_A_KEY == 'this is a value' |
| 927 |
|
| 928 |
def assert_config2(self): |
| 929 |
assert self.app.conf.LEAVE_FOR_WORK |
| 930 |
assert self.app.conf.MOMENT_TO_STOP |
| 931 |
assert self.app.conf.CALL_ME_BACK == 123456789 |
| 932 |
assert not self.app.conf.WANT_ME_TO |
| 933 |
assert self.app.conf.UNDERSTAND_ME |
| 934 |
|
| 935 |
def test_config_from_object__lazy(self): |
| 936 |
conf = ObjectConfig2() |
| 937 |
self.app.config_from_object(conf) |
| 938 |
assert self.app.loader._conf is unconfigured |
| 939 |
assert self.app._config_source is conf |
| 940 |
|
| 941 |
self.assert_config2() |
| 942 |
|
| 943 |
def test_config_from_object__force(self): |
| 944 |
self.app.config_from_object(ObjectConfig2(), force=True) |
| 945 |
assert self.app.loader._conf |
| 946 |
|
| 947 |
self.assert_config2() |
| 948 |
|
| 949 |
def test_config_from_object__compat(self): |
| 950 |
|
| 951 |
class Config: |
| 952 |
CELERY_ALWAYS_EAGER = 44 |
| 953 |
CELERY_DEFAULT_DELIVERY_MODE = 30 |
| 954 |
CELERY_TASK_PUBLISH_RETRY = False |
| 955 |
|
| 956 |
self.app.config_from_object(Config) |
| 957 |
assert self.app.conf.task_always_eager == 44 |
| 958 |
assert self.app.conf.CELERY_ALWAYS_EAGER == 44 |
| 959 |
assert not self.app.conf.task_publish_retry |
| 960 |
assert self.app.conf.task_default_routing_key == 'testcelery' |
| 961 |
|
| 962 |
def test_config_from_object__supports_old_names(self): |
| 963 |
|
| 964 |
class Config: |
| 965 |
task_always_eager = 45 |
| 966 |
task_default_delivery_mode = 301 |
| 967 |
|
| 968 |
self.app.config_from_object(Config()) |
| 969 |
assert self.app.conf.CELERY_ALWAYS_EAGER == 45 |
| 970 |
assert self.app.conf.task_always_eager == 45 |
| 971 |
assert self.app.conf.CELERY_DEFAULT_DELIVERY_MODE == 301 |
| 972 |
assert self.app.conf.task_default_delivery_mode == 301 |
| 973 |
assert self.app.conf.task_default_routing_key == 'testcelery' |
| 974 |
|
| 975 |
def test_config_from_object__namespace_uppercase(self): |
| 976 |
|
| 977 |
class Config: |
| 978 |
CELERY_TASK_ALWAYS_EAGER = 44 |
| 979 |
CELERY_TASK_DEFAULT_DELIVERY_MODE = 301 |
| 980 |
|
| 981 |
self.app.config_from_object(Config(), namespace='CELERY') |
| 982 |
assert self.app.conf.task_always_eager == 44 |
| 983 |
|
| 984 |
def test_config_from_object__namespace_lowercase(self): |
| 985 |
|
| 986 |
class Config: |
| 987 |
celery_task_always_eager = 44 |
| 988 |
celery_task_default_delivery_mode = 301 |
| 989 |
|
| 990 |
self.app.config_from_object(Config(), namespace='celery') |
| 991 |
assert self.app.conf.task_always_eager == 44 |
| 992 |
|
| 993 |
def test_config_from_object__mixing_new_and_old(self): |
| 994 |
|
| 995 |
class Config: |
| 996 |
task_always_eager = 44 |
| 997 |
worker_agent = 'foo:Agent' |
| 998 |
worker_consumer = 'foo:Consumer' |
| 999 |
beat_schedule = '/foo/schedule' |
| 1000 |
CELERY_DEFAULT_DELIVERY_MODE = 301 |
| 1001 |
|
| 1002 |
with pytest.raises(ImproperlyConfigured) as exc: |
| 1003 |
self.app.config_from_object(Config(), force=True) |
| 1004 |
assert exc.args[0].startswith('CELERY_DEFAULT_DELIVERY_MODE') |
| 1005 |
assert 'task_default_delivery_mode' in exc.args[0] |
| 1006 |
|
| 1007 |
def test_config_from_object__mixing_old_and_new(self): |
| 1008 |
|
| 1009 |
class Config: |
| 1010 |
CELERY_ALWAYS_EAGER = 46 |
| 1011 |
CELERYD_AGENT = 'foo:Agent' |
| 1012 |
CELERYD_CONSUMER = 'foo:Consumer' |
| 1013 |
CELERYBEAT_SCHEDULE = '/foo/schedule' |
| 1014 |
task_default_delivery_mode = 301 |
| 1015 |
|
| 1016 |
with pytest.raises(ImproperlyConfigured) as exc: |
| 1017 |
self.app.config_from_object(Config(), force=True) |
| 1018 |
assert exc.args[0].startswith('task_default_delivery_mode') |
| 1019 |
assert 'CELERY_DEFAULT_DELIVERY_MODE' in exc.args[0] |
| 1020 |
|
| 1021 |
def test_config_form_object__module_attr_does_not_exist(self): |
| 1022 |
module_name = __name__ |
| 1023 |
attr_name = 'bar' |
| 1024 |
# the module must exist, but it should not have the config attr |
| 1025 |
self.app.config_from_object(f'{module_name}.{attr_name}') |
| 1026 |
|
| 1027 |
with pytest.raises(ModuleNotFoundError) as exc: |
| 1028 |
assert self.app.conf.broker_url is None |
| 1029 |
|
| 1030 |
assert module_name in exc.value.args[0] |
| 1031 |
assert attr_name in exc.value.args[0] |
| 1032 |
|
| 1033 |
def test_config_from_cmdline(self): |
| 1034 |
cmdline = ['task_always_eager=no', |
| 1035 |
'result_backend=/dev/null', |
| 1036 |
'worker_prefetch_multiplier=368', |
| 1037 |
'.foobarstring=(string)300', |
| 1038 |
'.foobarint=(int)300', |
| 1039 |
'database_engine_options=(dict){"foo": "bar"}'] |
| 1040 |
self.app.config_from_cmdline(cmdline, namespace='worker') |
| 1041 |
assert not self.app.conf.task_always_eager |
| 1042 |
assert self.app.conf.result_backend == '/dev/null' |
| 1043 |
assert self.app.conf.worker_prefetch_multiplier == 368 |
| 1044 |
assert self.app.conf.worker_foobarstring == '300' |
| 1045 |
assert self.app.conf.worker_foobarint == 300 |
| 1046 |
assert self.app.conf.database_engine_options == {'foo': 'bar'} |
| 1047 |
|
| 1048 |
def test_setting__broker_transport_options(self): |
| 1049 |
|
| 1050 |
_args = {'foo': 'bar', 'spam': 'baz'} |
| 1051 |
|
| 1052 |
self.app.config_from_object(Bunch()) |
| 1053 |
assert self.app.conf.broker_transport_options == \ |
| 1054 |
{'polling_interval': 0.1} |
| 1055 |
|
| 1056 |
self.app.config_from_object(Bunch(broker_transport_options=_args)) |
| 1057 |
assert self.app.conf.broker_transport_options == _args |
| 1058 |
|
| 1059 |
def test_Windows_log_color_disabled(self): |
| 1060 |
self.app.IS_WINDOWS = True |
| 1061 |
assert not self.app.log.supports_color(True) |
| 1062 |
|
| 1063 |
def test_WorkController(self): |
| 1064 |
x = self.app.WorkController |
| 1065 |
assert x.app is self.app |
| 1066 |
|
| 1067 |
def test_Worker(self): |
| 1068 |
x = self.app.Worker |
| 1069 |
assert x.app is self.app |
| 1070 |
|
| 1071 |
@pytest.mark.usefixtures('depends_on_current_app') |
| 1072 |
def test_AsyncResult(self): |
| 1073 |
x = self.app.AsyncResult('1') |
| 1074 |
assert x.app is self.app |
| 1075 |
r = loads(dumps(x)) |
| 1076 |
# not set as current, so ends up as default app after reduce |
| 1077 |
assert r.app is current_app._get_current_object() |
| 1078 |
|
| 1079 |
def test_get_active_apps(self): |
| 1080 |
assert list(_state._get_active_apps()) |
| 1081 |
|
| 1082 |
app1 = self.Celery() |
| 1083 |
appid = id(app1) |
| 1084 |
assert app1 in _state._get_active_apps() |
| 1085 |
app1.close() |
| 1086 |
del (app1) |
| 1087 |
|
| 1088 |
gc.collect() |
| 1089 |
|
| 1090 |
# weakref removed from list when app goes out of scope. |
| 1091 |
with pytest.raises(StopIteration): |
| 1092 |
next(app for app in _state._get_active_apps() if id(app) == appid) |
| 1093 |
|
| 1094 |
def test_config_from_envvar_more(self, key='CELERY_HARNESS_CFG1'): |
| 1095 |
assert not self.app.config_from_envvar( |
| 1096 |
'HDSAJIHWIQHEWQU', force=True, silent=True) |
| 1097 |
with pytest.raises(ImproperlyConfigured): |
| 1098 |
self.app.config_from_envvar( |
| 1099 |
'HDSAJIHWIQHEWQU', force=True, silent=False, |
| 1100 |
) |
| 1101 |
os.environ[key] = __name__ + '.object_config' |
| 1102 |
assert self.app.config_from_envvar(key, force=True) |
| 1103 |
assert self.app.conf['FOO'] == 1 |
| 1104 |
assert self.app.conf['BAR'] == 2 |
| 1105 |
|
| 1106 |
os.environ[key] = 'unknown_asdwqe.asdwqewqe' |
| 1107 |
with pytest.raises(ImportError): |
| 1108 |
self.app.config_from_envvar(key, silent=False) |
| 1109 |
assert not self.app.config_from_envvar(key, force=True, silent=True) |
| 1110 |
|
| 1111 |
os.environ[key] = __name__ + '.dict_config' |
| 1112 |
assert self.app.config_from_envvar(key, force=True) |
| 1113 |
assert self.app.conf['FOO'] == 10 |
| 1114 |
assert self.app.conf['BAR'] == 20 |
| 1115 |
|
| 1116 |
@patch('celery.bin.celery.celery') |
| 1117 |
def test_start(self, mocked_celery): |
| 1118 |
self.app.start() |
| 1119 |
mocked_celery.main.assert_called() |
| 1120 |
|
| 1121 |
@pytest.mark.parametrize('url,expected_fields', [ |
| 1122 |
('pyamqp://', { |
| 1123 |
'hostname': 'localhost', |
| 1124 |
'userid': 'guest', |
| 1125 |
'password': 'guest', |
| 1126 |
'virtual_host': '/', |
| 1127 |
}), |
| 1128 |
('pyamqp://:1978/foo', { |
| 1129 |
'port': 1978, |
| 1130 |
'virtual_host': 'foo', |
| 1131 |
}), |
| 1132 |
('pyamqp:////value', { |
| 1133 |
'virtual_host': '/value', |
| 1134 |
}) |
| 1135 |
]) |
| 1136 |
def test_amqp_get_broker_info(self, url, expected_fields): |
| 1137 |
info = self.app.connection(url).info() |
| 1138 |
for key, expected_value in expected_fields.items(): |
| 1139 |
assert info[key] == expected_value |
| 1140 |
|
| 1141 |
def test_amqp_failover_strategy_selection(self): |
| 1142 |
# Test passing in a string and make sure the string |
| 1143 |
# gets there untouched |
| 1144 |
self.app.conf.broker_failover_strategy = 'foo-bar' |
| 1145 |
assert self.app.connection('amqp:////value') \ |
| 1146 |
.failover_strategy == 'foo-bar' |
| 1147 |
|
| 1148 |
# Try passing in None |
| 1149 |
self.app.conf.broker_failover_strategy = None |
| 1150 |
assert self.app.connection('amqp:////value') \ |
| 1151 |
.failover_strategy == itertools.cycle |
| 1152 |
|
| 1153 |
# Test passing in a method |
| 1154 |
def my_failover_strategy(it): |
| 1155 |
yield True |
| 1156 |
|
| 1157 |
self.app.conf.broker_failover_strategy = my_failover_strategy |
| 1158 |
assert self.app.connection('amqp:////value') \ |
| 1159 |
.failover_strategy == my_failover_strategy |
| 1160 |
|
| 1161 |
def test_after_fork(self): |
| 1162 |
self.app._pool = Mock() |
| 1163 |
self.app.on_after_fork = Mock(name='on_after_fork') |
| 1164 |
self.app._after_fork() |
| 1165 |
assert self.app._pool is None |
| 1166 |
self.app.on_after_fork.send.assert_called_with(sender=self.app) |
| 1167 |
self.app._after_fork() |
| 1168 |
|
| 1169 |
def test_global_after_fork(self): |
| 1170 |
self.app._after_fork = Mock(name='_after_fork') |
| 1171 |
_appbase._after_fork_cleanup_app(self.app) |
| 1172 |
self.app._after_fork.assert_called_with() |
| 1173 |
|
| 1174 |
@patch('celery.app.base.logger') |
| 1175 |
def test_after_fork_cleanup_app__raises(self, logger): |
| 1176 |
self.app._after_fork = Mock(name='_after_fork') |
| 1177 |
exc = self.app._after_fork.side_effect = KeyError() |
| 1178 |
_appbase._after_fork_cleanup_app(self.app) |
| 1179 |
logger.info.assert_called_with( |
| 1180 |
'after forker raised exception: %r', exc, exc_info=1) |
| 1181 |
|
| 1182 |
def test_ensure_after_fork__no_multiprocessing(self): |
| 1183 |
prev, _appbase.register_after_fork = ( |
| 1184 |
_appbase.register_after_fork, None) |
| 1185 |
try: |
| 1186 |
self.app._after_fork_registered = False |
| 1187 |
self.app._ensure_after_fork() |
| 1188 |
assert self.app._after_fork_registered |
| 1189 |
finally: |
| 1190 |
_appbase.register_after_fork = prev |
| 1191 |
|
| 1192 |
def test_canvas(self): |
| 1193 |
assert self.app._canvas.Signature |
| 1194 |
|
| 1195 |
def test_signature(self): |
| 1196 |
sig = self.app.signature('foo', (1, 2)) |
| 1197 |
assert sig.app is self.app |
| 1198 |
|
| 1199 |
def test_timezone_none_set(self): |
| 1200 |
self.app.conf.timezone = None |
| 1201 |
self.app.conf.enable_utc = True |
| 1202 |
assert self.app.timezone == timezone.utc |
| 1203 |
del self.app.timezone |
| 1204 |
self.app.conf.enable_utc = False |
| 1205 |
assert self.app.timezone == timezone.local |
| 1206 |
|
| 1207 |
def test_use_local_timezone(self): |
| 1208 |
self.app.conf.timezone = None |
| 1209 |
self.app.conf.enable_utc = False |
| 1210 |
|
| 1211 |
self._clear_timezone_cache() |
| 1212 |
try: |
| 1213 |
assert isinstance(self.app.timezone, ZoneInfo) |
| 1214 |
finally: |
| 1215 |
self._clear_timezone_cache() |
| 1216 |
|
| 1217 |
@patch("celery.utils.time.get_localzone") |
| 1218 |
def test_use_local_timezone_failure(self, mock_get_localzone): |
| 1219 |
mock_get_localzone.side_effect = Exception("Failed to get local timezone") |
| 1220 |
self.app.conf.timezone = None |
| 1221 |
self.app.conf.enable_utc = False |
| 1222 |
|
| 1223 |
self._clear_timezone_cache() |
| 1224 |
try: |
| 1225 |
assert isinstance(self.app.timezone, LocalTimezone) |
| 1226 |
finally: |
| 1227 |
self._clear_timezone_cache() |
| 1228 |
|
| 1229 |
def _clear_timezone_cache(self): |
| 1230 |
del self.app.timezone |
| 1231 |
del timezone.local |
| 1232 |
|
| 1233 |
def test_uses_utc_timezone(self): |
| 1234 |
self.app.conf.timezone = None |
| 1235 |
self.app.conf.enable_utc = True |
| 1236 |
assert self.app.uses_utc_timezone() is True |
| 1237 |
|
| 1238 |
self.app.conf.enable_utc = False |
| 1239 |
del self.app.timezone |
| 1240 |
assert self.app.uses_utc_timezone() is False |
| 1241 |
|
| 1242 |
self.app.conf.timezone = 'US/Eastern' |
| 1243 |
del self.app.timezone |
| 1244 |
assert self.app.uses_utc_timezone() is False |
| 1245 |
|
| 1246 |
self.app.conf.timezone = 'UTC' |
| 1247 |
del self.app.timezone |
| 1248 |
assert self.app.uses_utc_timezone() is True |
| 1249 |
|
| 1250 |
def test_compat_on_configure(self): |
| 1251 |
_on_configure = Mock(name='on_configure') |
| 1252 |
|
| 1253 |
class CompatApp(Celery): |
| 1254 |
|
| 1255 |
def on_configure(self, *args, **kwargs): |
| 1256 |
# on pypy3 if named on_configure the class function |
| 1257 |
# will be called, instead of the mock defined above, |
| 1258 |
# so we add the underscore. |
| 1259 |
_on_configure(*args, **kwargs) |
| 1260 |
|
| 1261 |
with CompatApp(set_as_current=False) as app: |
| 1262 |
app.loader = Mock() |
| 1263 |
app.loader.conf = {} |
| 1264 |
app._load_config() |
| 1265 |
_on_configure.assert_called_with() |
| 1266 |
|
| 1267 |
def test_add_periodic_task(self): |
| 1268 |
|
| 1269 |
@self.app.task |
| 1270 |
def add(x, y): |
| 1271 |
pass |
| 1272 |
assert not self.app.configured |
| 1273 |
self.app.add_periodic_task( |
| 1274 |
10, self.app.signature('add', (2, 2)), |
| 1275 |
name='add1', expires=3, |
| 1276 |
) |
| 1277 |
assert self.app._pending_periodic_tasks |
| 1278 |
assert not self.app.configured |
| 1279 |
|
| 1280 |
sig2 = add.s(4, 4) |
| 1281 |
assert self.app.configured |
| 1282 |
self.app.add_periodic_task(20, sig2, name='add2', expires=4) |
| 1283 |
assert 'add1' in self.app.conf.beat_schedule |
| 1284 |
assert 'add2' in self.app.conf.beat_schedule |
| 1285 |
|
| 1286 |
def test_add_periodic_task_expected_override(self): |
| 1287 |
|
| 1288 |
@self.app.task |
| 1289 |
def add(x, y): |
| 1290 |
pass |
| 1291 |
sig = add.s(2, 2) |
| 1292 |
self.app.add_periodic_task(10, sig, name='add1', expires=3) |
| 1293 |
self.app.add_periodic_task(20, sig, name='add1', expires=3) |
| 1294 |
assert 'add1' in self.app.conf.beat_schedule |
| 1295 |
assert len(self.app.conf.beat_schedule) == 1 |
| 1296 |
|
| 1297 |
def test_add_periodic_task_unexpected_override(self, caplog): |
| 1298 |
|
| 1299 |
@self.app.task |
| 1300 |
def add(x, y): |
| 1301 |
pass |
| 1302 |
sig = add.s(2, 2) |
| 1303 |
self.app.add_periodic_task(10, sig, expires=3) |
| 1304 |
self.app.add_periodic_task(20, sig, expires=3) |
| 1305 |
|
| 1306 |
assert len(self.app.conf.beat_schedule) == 1 |
| 1307 |
assert caplog.records[0].message == ( |
| 1308 |
"Periodic task key='t.unit.app.test_app.add(2, 2)' shadowed a" |
| 1309 |
" previous unnamed periodic task. Pass a name kwarg to" |
| 1310 |
" add_periodic_task to silence this warning." |
| 1311 |
) |
| 1312 |
|
| 1313 |
@pytest.mark.masked_modules('multiprocessing.util') |
| 1314 |
def test_pool_no_multiprocessing(self, mask_modules): |
| 1315 |
pool = self.app.pool |
| 1316 |
assert pool is self.app._pool |
| 1317 |
|
| 1318 |
def test_bugreport(self): |
| 1319 |
assert self.app.bugreport() |
| 1320 |
|
| 1321 |
@patch('celery.app.base.detect_quorum_queues', return_value=[False, ""]) |
| 1322 |
def test_send_task__connection_provided(self, detect_quorum_queues): |
| 1323 |
connection = Mock(name='connection') |
| 1324 |
router = Mock(name='router') |
| 1325 |
router.route.return_value = {} |
| 1326 |
self.app.amqp = Mock(name='amqp') |
| 1327 |
self.app.amqp.Producer.attach_mock(ContextMock(), 'return_value') |
| 1328 |
self.app.send_task('foo', (1, 2), connection=connection, router=router) |
| 1329 |
self.app.amqp.Producer.assert_called_with( |
| 1330 |
connection, auto_declare=False) |
| 1331 |
self.app.amqp.send_task_message.assert_called_with( |
| 1332 |
self.app.amqp.Producer(), 'foo', |
| 1333 |
self.app.amqp.create_task_message()) |
| 1334 |
|
| 1335 |
def test_send_task_sent_event(self): |
| 1336 |
|
| 1337 |
class Dispatcher: |
| 1338 |
sent = [] |
| 1339 |
|
| 1340 |
def publish(self, type, fields, *args, **kwargs): |
| 1341 |
self.sent.append((type, fields)) |
| 1342 |
|
| 1343 |
conn = self.app.connection() |
| 1344 |
chan = conn.channel() |
| 1345 |
try: |
| 1346 |
for e in ('foo_exchange', 'moo_exchange', 'bar_exchange'): |
| 1347 |
chan.exchange_declare(e, 'direct', durable=True) |
| 1348 |
chan.queue_declare(e, durable=True) |
| 1349 |
chan.queue_bind(e, e, e) |
| 1350 |
finally: |
| 1351 |
chan.close() |
| 1352 |
assert conn.transport_cls == 'memory' |
| 1353 |
|
| 1354 |
message = self.app.amqp.create_task_message( |
| 1355 |
'id', 'footask', (), {}, create_sent_event=True, |
| 1356 |
) |
| 1357 |
|
| 1358 |
prod = self.app.amqp.Producer(conn) |
| 1359 |
dispatcher = Dispatcher() |
| 1360 |
self.app.amqp.send_task_message( |
| 1361 |
prod, 'footask', message, |
| 1362 |
exchange='moo_exchange', routing_key='moo_exchange', |
| 1363 |
event_dispatcher=dispatcher, |
| 1364 |
) |
| 1365 |
assert dispatcher.sent |
| 1366 |
assert dispatcher.sent[0][0] == 'task-sent' |
| 1367 |
self.app.amqp.send_task_message( |
| 1368 |
prod, 'footask', message, event_dispatcher=dispatcher, |
| 1369 |
exchange='bar_exchange', routing_key='bar_exchange', |
| 1370 |
) |
| 1371 |
|
| 1372 |
def test_select_queues(self): |
| 1373 |
self.app.amqp = Mock(name='amqp') |
| 1374 |
self.app.select_queues({'foo', 'bar'}) |
| 1375 |
self.app.amqp.queues.select.assert_called_with({'foo', 'bar'}) |
| 1376 |
|
| 1377 |
def test_Beat(self): |
| 1378 |
from celery.apps.beat import Beat |
| 1379 |
beat = self.app.Beat() |
| 1380 |
assert isinstance(beat, Beat) |
| 1381 |
|
| 1382 |
def test_registry_cls(self): |
| 1383 |
|
| 1384 |
class TaskRegistry(self.app.registry_cls): |
| 1385 |
pass |
| 1386 |
|
| 1387 |
class CustomCelery(type(self.app)): |
| 1388 |
registry_cls = TaskRegistry |
| 1389 |
|
| 1390 |
app = CustomCelery(set_as_current=False) |
| 1391 |
assert isinstance(app.tasks, TaskRegistry) |
| 1392 |
|
| 1393 |
def test_oid(self): |
| 1394 |
# Test that oid is global value. |
| 1395 |
oid1 = self.app.oid |
| 1396 |
oid2 = self.app.oid |
| 1397 |
uuid.UUID(oid1) |
| 1398 |
uuid.UUID(oid2) |
| 1399 |
assert oid1 == oid2 |
| 1400 |
|
| 1401 |
def test_global_oid(self): |
| 1402 |
# Test that oid is global value also within threads |
| 1403 |
main_oid = self.app.oid |
| 1404 |
uuid.UUID(main_oid) |
| 1405 |
from concurrent.futures import ThreadPoolExecutor |
| 1406 |
with ThreadPoolExecutor(max_workers=1) as executor: |
| 1407 |
future = executor.submit(lambda: self.app.oid) |
| 1408 |
thread_oid = future.result() |
| 1409 |
uuid.UUID(thread_oid) |
| 1410 |
assert main_oid == thread_oid |
| 1411 |
|
| 1412 |
def test_thread_oid(self): |
| 1413 |
# Test that thread_oid is global value in single thread. |
| 1414 |
oid1 = self.app.thread_oid |
| 1415 |
oid2 = self.app.thread_oid |
| 1416 |
uuid.UUID(oid1) |
| 1417 |
uuid.UUID(oid2) |
| 1418 |
assert oid1 == oid2 |
| 1419 |
|
| 1420 |
def test_backend(self): |
| 1421 |
# Test that app.backend returns the same backend in single thread |
| 1422 |
backend1 = self.app.backend |
| 1423 |
backend2 = self.app.backend |
| 1424 |
assert isinstance(backend1, Backend) |
| 1425 |
assert isinstance(backend2, Backend) |
| 1426 |
assert backend1 is backend2 |
| 1427 |
|
| 1428 |
def test_thread_backend(self): |
| 1429 |
# Test that app.backend returns the new backend for each thread |
| 1430 |
main_backend = self.app.backend |
| 1431 |
from concurrent.futures import ThreadPoolExecutor |
| 1432 |
with ThreadPoolExecutor(max_workers=1) as executor: |
| 1433 |
future = executor.submit(lambda: self.app.backend) |
| 1434 |
thread_backend = future.result() |
| 1435 |
assert isinstance(main_backend, Backend) |
| 1436 |
assert isinstance(thread_backend, Backend) |
| 1437 |
assert main_backend is not thread_backend |
| 1438 |
|
| 1439 |
def test_thread_oid_is_local(self): |
| 1440 |
# Test that thread_oid is local to thread. |
| 1441 |
main_oid = self.app.thread_oid |
| 1442 |
uuid.UUID(main_oid) |
| 1443 |
from concurrent.futures import ThreadPoolExecutor |
| 1444 |
with ThreadPoolExecutor(max_workers=1) as executor: |
| 1445 |
future = executor.submit(lambda: self.app.thread_oid) |
| 1446 |
thread_oid = future.result() |
| 1447 |
uuid.UUID(thread_oid) |
| 1448 |
assert main_oid != thread_oid |
| 1449 |
|
| 1450 |
def test_thread_backend_thread_safe(self): |
| 1451 |
# Should share the backend object across threads |
| 1452 |
from concurrent.futures import ThreadPoolExecutor |
| 1453 |
|
| 1454 |
with self.Celery() as app: |
| 1455 |
app.conf.update(result_backend_thread_safe=True) |
| 1456 |
main_backend = app.backend |
| 1457 |
with ThreadPoolExecutor(max_workers=1) as executor: |
| 1458 |
future = executor.submit(lambda: app.backend) |
| 1459 |
|
| 1460 |
thread_backend = future.result() |
| 1461 |
assert isinstance(main_backend, Backend) |
| 1462 |
assert isinstance(thread_backend, Backend) |
| 1463 |
assert main_backend is thread_backend |
| 1464 |
|
| 1465 |
def test_send_task_expire_as_string(self): |
| 1466 |
try: |
| 1467 |
self.app.send_task( |
| 1468 |
'foo', (1, 2), |
| 1469 |
expires='2023-03-16T17:21:20.663973') |
| 1470 |
except TypeError as e: |
| 1471 |
pytest.fail(f'raise unexcepted error {e}') |
| 1472 |
|
| 1473 |
@patch('celery.app.base.detect_quorum_queues', return_value=[True, "testcelery"]) |
| 1474 |
def test_native_delayed_delivery_countdown(self, detect_quorum_queues): |
| 1475 |
self.app.amqp = MagicMock(name='amqp') |
| 1476 |
self.app.amqp.router.route.return_value = { |
| 1477 |
'queue': Queue( |
| 1478 |
'testcelery', |
| 1479 |
routing_key='testcelery', |
| 1480 |
exchange=Exchange('testcelery', type='topic') |
| 1481 |
) |
| 1482 |
} |
| 1483 |
|
| 1484 |
self.app.send_task('foo', (1, 2), countdown=30) |
| 1485 |
|
| 1486 |
exchange = Exchange( |
| 1487 |
'celery_delayed_27', |
| 1488 |
type='topic', |
| 1489 |
) |
| 1490 |
self.app.amqp.send_task_message.assert_called_once_with( |
| 1491 |
ANY, |
| 1492 |
ANY, |
| 1493 |
ANY, |
| 1494 |
exchange=exchange, |
| 1495 |
routing_key='0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.1.1.1.0.testcelery' |
| 1496 |
) |
| 1497 |
driver_type_stub = self.app.amqp.producer_pool.connections.connection.transport.driver_type |
| 1498 |
detect_quorum_queues.assert_called_once_with(self.app, driver_type_stub) |
| 1499 |
|
| 1500 |
@patch('celery.app.base.detect_quorum_queues', return_value=[True, "testcelery"]) |
| 1501 |
def test_native_delayed_delivery__no_queue_arg__no_eta(self, detect_quorum_queues): |
| 1502 |
self.app.amqp = MagicMock(name='amqp') |
| 1503 |
options = { |
| 1504 |
'routing_key': 'testcelery', |
| 1505 |
'exchange': 'testcelery', |
| 1506 |
'exchange_type': 'topic', |
| 1507 |
} |
| 1508 |
self.app.amqp.router.route.return_value = options |
| 1509 |
|
| 1510 |
self.app.send_task( |
| 1511 |
name='foo', |
| 1512 |
args=(1, 2), |
| 1513 |
) |
| 1514 |
self.app.amqp.send_task_message.assert_called_once_with( |
| 1515 |
ANY, |
| 1516 |
ANY, |
| 1517 |
ANY, |
| 1518 |
**options, |
| 1519 |
) |
| 1520 |
assert not detect_quorum_queues.called |
| 1521 |
|
| 1522 |
@patch('celery.app.base.detect_quorum_queues', return_value=[True, "testcelery"]) |
| 1523 |
def test_native_delayed_delivery__no_queue_arg__with_countdown(self, detect_quorum_queues): |
| 1524 |
self.app.amqp = MagicMock(name='amqp') |
| 1525 |
options = { |
| 1526 |
'routing_key': 'testcelery', |
| 1527 |
'exchange': 'testcelery', |
| 1528 |
'exchange_type': 'topic', |
| 1529 |
} |
| 1530 |
self.app.amqp.router.route.return_value = options |
| 1531 |
|
| 1532 |
self.app.send_task( |
| 1533 |
name='foo', |
| 1534 |
args=(1, 2), |
| 1535 |
countdown=30, |
| 1536 |
) |
| 1537 |
exchange = Exchange( |
| 1538 |
'celery_delayed_27', |
| 1539 |
type='topic', |
| 1540 |
) |
| 1541 |
self.app.amqp.send_task_message.assert_called_once_with( |
| 1542 |
ANY, |
| 1543 |
ANY, |
| 1544 |
ANY, |
| 1545 |
exchange=exchange, |
| 1546 |
routing_key='0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.1.1.1.0.testcelery', |
| 1547 |
exchange_type="topic", |
| 1548 |
) |
| 1549 |
driver_type_stub = self.app.amqp.producer_pool.connections.connection.transport.driver_type |
| 1550 |
detect_quorum_queues.assert_called_once_with(self.app, driver_type_stub) |
| 1551 |
|
| 1552 |
@patch('celery.app.base.detect_quorum_queues', return_value=[True, "testcelery"]) |
| 1553 |
def test_native_delayed_delivery_eta_datetime(self, detect_quorum_queues): |
| 1554 |
self.app.amqp = MagicMock(name='amqp') |
| 1555 |
self.app.amqp.router.route.return_value = { |
| 1556 |
'queue': Queue( |
| 1557 |
'testcelery', |
| 1558 |
routing_key='testcelery', |
| 1559 |
exchange=Exchange('testcelery', type='topic') |
| 1560 |
) |
| 1561 |
} |
| 1562 |
self.app.now = Mock(return_value=datetime(2024, 8, 24, tzinfo=datetime_timezone.utc)) |
| 1563 |
|
| 1564 |
self.app.send_task('foo', (1, 2), eta=datetime(2024, 8, 25)) |
| 1565 |
|
| 1566 |
exchange = Exchange( |
| 1567 |
'celery_delayed_27', |
| 1568 |
type='topic', |
| 1569 |
) |
| 1570 |
self.app.amqp.send_task_message.assert_called_once_with( |
| 1571 |
ANY, |
| 1572 |
ANY, |
| 1573 |
ANY, |
| 1574 |
exchange=exchange, |
| 1575 |
routing_key='0.0.0.0.0.0.0.0.0.0.0.1.0.1.0.1.0.0.0.1.1.0.0.0.0.0.0.0.testcelery' |
| 1576 |
) |
| 1577 |
|
| 1578 |
@patch('celery.app.base.detect_quorum_queues', return_value=[True, "testcelery"]) |
| 1579 |
def test_native_delayed_delivery_eta_str(self, detect_quorum_queues): |
| 1580 |
self.app.amqp = MagicMock(name='amqp') |
| 1581 |
self.app.amqp.router.route.return_value = { |
| 1582 |
'queue': Queue( |
| 1583 |
'testcelery', |
| 1584 |
routing_key='testcelery', |
| 1585 |
exchange=Exchange('testcelery', type='topic') |
| 1586 |
) |
| 1587 |
} |
| 1588 |
self.app.now = Mock(return_value=datetime(2024, 8, 24, tzinfo=datetime_timezone.utc)) |
| 1589 |
|
| 1590 |
self.app.send_task('foo', (1, 2), eta=datetime(2024, 8, 25).isoformat()) |
| 1591 |
|
| 1592 |
exchange = Exchange( |
| 1593 |
'celery_delayed_27', |
| 1594 |
type='topic', |
| 1595 |
) |
| 1596 |
self.app.amqp.send_task_message.assert_called_once_with( |
| 1597 |
ANY, |
| 1598 |
ANY, |
| 1599 |
ANY, |
| 1600 |
exchange=exchange, |
| 1601 |
routing_key='0.0.0.0.0.0.0.0.0.0.0.1.0.1.0.1.0.0.0.1.1.0.0.0.0.0.0.0.testcelery', |
| 1602 |
) |
| 1603 |
|
| 1604 |
@patch('celery.app.base.detect_quorum_queues', return_value=[True, "testcelery"]) |
| 1605 |
def test_native_delayed_delivery_no_eta_or_countdown(self, detect_quorum_queues): |
| 1606 |
self.app.amqp = MagicMock(name='amqp') |
| 1607 |
self.app.amqp.router.route.return_value = {'queue': Queue('testcelery', routing_key='testcelery')} |
| 1608 |
|
| 1609 |
self.app.send_task('foo', (1, 2), countdown=-10) |
| 1610 |
|
| 1611 |
self.app.amqp.send_task_message.assert_called_once_with( |
| 1612 |
ANY, |
| 1613 |
ANY, |
| 1614 |
ANY, |
| 1615 |
queue=Queue( |
| 1616 |
'testcelery', |
| 1617 |
routing_key='testcelery' |
| 1618 |
) |
| 1619 |
) |
| 1620 |
|
| 1621 |
@patch('celery.app.base.detect_quorum_queues', return_value=[True, "testcelery"]) |
| 1622 |
def test_native_delayed_delivery_countdown_in_the_past(self, detect_quorum_queues): |
| 1623 |
self.app.amqp = MagicMock(name='amqp') |
| 1624 |
self.app.amqp.router.route.return_value = { |
| 1625 |
'queue': Queue( |
| 1626 |
'testcelery', |
| 1627 |
routing_key='testcelery', |
| 1628 |
exchange=Exchange('testcelery', type='topic') |
| 1629 |
) |
| 1630 |
} |
| 1631 |
|
| 1632 |
self.app.send_task('foo', (1, 2)) |
| 1633 |
|
| 1634 |
self.app.amqp.send_task_message.assert_called_once_with( |
| 1635 |
ANY, |
| 1636 |
ANY, |
| 1637 |
ANY, |
| 1638 |
queue=Queue( |
| 1639 |
'testcelery', |
| 1640 |
routing_key='testcelery', |
| 1641 |
exchange=Exchange('testcelery', type='topic') |
| 1642 |
) |
| 1643 |
) |
| 1644 |
|
| 1645 |
@patch('celery.app.base.detect_quorum_queues', return_value=[True, "testcelery"]) |
| 1646 |
def test_native_delayed_delivery_eta_in_the_past(self, detect_quorum_queues): |
| 1647 |
self.app.amqp = MagicMock(name='amqp') |
| 1648 |
self.app.amqp.router.route.return_value = { |
| 1649 |
'queue': Queue( |
| 1650 |
'testcelery', |
| 1651 |
routing_key='testcelery', |
| 1652 |
exchange=Exchange('testcelery', type='topic') |
| 1653 |
) |
| 1654 |
} |
| 1655 |
self.app.now = Mock(return_value=datetime(2024, 8, 24, tzinfo=datetime_timezone.utc)) |
| 1656 |
|
| 1657 |
self.app.send_task('foo', (1, 2), eta=datetime(2024, 8, 23).isoformat()) |
| 1658 |
|
| 1659 |
self.app.amqp.send_task_message.assert_called_once_with( |
| 1660 |
ANY, |
| 1661 |
ANY, |
| 1662 |
ANY, |
| 1663 |
queue=Queue( |
| 1664 |
'testcelery', |
| 1665 |
routing_key='testcelery', |
| 1666 |
exchange=Exchange('testcelery', type='topic') |
| 1667 |
) |
| 1668 |
) |
| 1669 |
|
| 1670 |
@patch('celery.app.base.detect_quorum_queues', return_value=[True, "testcelery"]) |
| 1671 |
def test_native_delayed_delivery_direct_exchange(self, detect_quorum_queues, caplog): |
| 1672 |
self.app.amqp = MagicMock(name='amqp') |
| 1673 |
self.app.amqp.router.route.return_value = { |
| 1674 |
'queue': Queue( |
| 1675 |
'testcelery', |
| 1676 |
routing_key='testcelery', |
| 1677 |
exchange=Exchange('testcelery', type='direct') |
| 1678 |
) |
| 1679 |
} |
| 1680 |
|
| 1681 |
self.app.send_task('foo', (1, 2), countdown=10) |
| 1682 |
|
| 1683 |
self.app.amqp.send_task_message.assert_called_once_with( |
| 1684 |
ANY, |
| 1685 |
ANY, |
| 1686 |
ANY, |
| 1687 |
queue=Queue( |
| 1688 |
'testcelery', |
| 1689 |
routing_key='testcelery', |
| 1690 |
exchange=Exchange('testcelery', type='direct') |
| 1691 |
) |
| 1692 |
) |
| 1693 |
|
| 1694 |
assert len(caplog.records) == 1 |
| 1695 |
record: LogRecord = caplog.records[0] |
| 1696 |
assert record.levelname == "WARNING" |
| 1697 |
assert record.message == ( |
| 1698 |
"Direct exchanges are not supported with native delayed delivery.\n" |
| 1699 |
"testcelery is a direct exchange but should be a topic exchange or " |
| 1700 |
"a fanout exchange in order for native delayed delivery to work properly.\n" |
| 1701 |
"If quorum queues are used, this task may block the worker process until the ETA arrives." |
| 1702 |
) |
| 1703 |
|
| 1704 |
|
| 1705 |
class test_defaults: |
| 1706 |
|
| 1707 |
def test_strtobool(self): |
| 1708 |
for s in ('false', 'no', '0'): |
| 1709 |
assert not defaults.strtobool(s) |
| 1710 |
for s in ('true', 'yes', '1'): |
| 1711 |
assert defaults.strtobool(s) |
| 1712 |
with pytest.raises(TypeError): |
| 1713 |
defaults.strtobool('unsure') |
| 1714 |
|
| 1715 |
|
| 1716 |
class test_debugging_utils: |
| 1717 |
|
| 1718 |
def test_enable_disable_trace(self): |
| 1719 |
try: |
| 1720 |
_app.enable_trace() |
| 1721 |
assert _state.app_or_default == _state._app_or_default_trace |
| 1722 |
_app.disable_trace() |
| 1723 |
assert _state.app_or_default == _state._app_or_default |
| 1724 |
finally: |
| 1725 |
_app.disable_trace() |
| 1726 |
|
| 1727 |
|
| 1728 |
class test_pyimplementation: |
| 1729 |
|
| 1730 |
def test_platform_python_implementation(self): |
| 1731 |
with conftest.platform_pyimp(lambda: 'Xython'): |
| 1732 |
assert pyimplementation() == 'Xython' |
| 1733 |
|
| 1734 |
def test_platform_jython(self): |
| 1735 |
with conftest.platform_pyimp(): |
| 1736 |
with conftest.sys_platform('java 1.6.51'): |
| 1737 |
assert 'Jython' in pyimplementation() |
| 1738 |
|
| 1739 |
def test_platform_pypy(self): |
| 1740 |
with conftest.platform_pyimp(): |
| 1741 |
with conftest.sys_platform('darwin'): |
| 1742 |
with conftest.pypy_version((1, 4, 3)): |
| 1743 |
assert 'PyPy' in pyimplementation() |
| 1744 |
with conftest.pypy_version((1, 4, 3, 'a4')): |
| 1745 |
assert 'PyPy' in pyimplementation() |
| 1746 |
|
| 1747 |
def test_platform_fallback(self): |
| 1748 |
with conftest.platform_pyimp(): |
| 1749 |
with conftest.sys_platform('darwin'): |
| 1750 |
with conftest.pypy_version(): |
| 1751 |
assert 'CPython' == pyimplementation() |
| 1752 |
|
| 1753 |
|
| 1754 |
class test_shared_task: |
| 1755 |
|
| 1756 |
def test_registers_to_all_apps(self): |
| 1757 |
with self.Celery('xproj', set_as_current=True) as xproj: |
| 1758 |
xproj.finalize() |
| 1759 |
|
| 1760 |
@shared_task |
| 1761 |
def foo(): |
| 1762 |
return 42 |
| 1763 |
|
| 1764 |
@shared_task() |
| 1765 |
def bar(): |
| 1766 |
return 84 |
| 1767 |
|
| 1768 |
assert foo.app is xproj |
| 1769 |
assert bar.app is xproj |
| 1770 |
assert foo._get_current_object() |
| 1771 |
|
| 1772 |
with self.Celery('yproj', set_as_current=True) as yproj: |
| 1773 |
assert foo.app is yproj |
| 1774 |
assert bar.app is yproj |
| 1775 |
|
| 1776 |
@shared_task() |
| 1777 |
def baz(): |
| 1778 |
return 168 |
| 1779 |
|
| 1780 |
assert baz.app is yproj |