| 1 |
from contextlib import contextmanager |
| 2 |
from unittest.mock import MagicMock, Mock, patch |
| 3 |
|
| 4 |
import pytest |
| 5 |
|
| 6 |
from celery.concurrency.thread import TaskPool as ThreadTaskPool |
| 7 |
from celery.fixups.django import DjangoFixup, DjangoWorkerFixup, FixupWarning, _maybe_close_fd, fixup |
| 8 |
from t.unit import conftest |
| 9 |
|
| 10 |
|
| 11 |
class FixupCase: |
| 12 |
Fixup = None |
| 13 |
|
| 14 |
@contextmanager |
| 15 |
def fixup_context(self, app, **kwargs): |
| 16 |
with patch('celery.fixups.django.DjangoWorkerFixup.validate_models'): |
| 17 |
with patch('celery.fixups.django.symbol_by_name') as symbyname: |
| 18 |
with patch('celery.fixups.django.import_module') as impmod: |
| 19 |
worker = Mock() |
| 20 |
worker.pool_cls = Mock(__module__='celery.concurrency.prefork') |
| 21 |
f = self.Fixup(app, **kwargs) |
| 22 |
f.worker = worker |
| 23 |
yield f, impmod, symbyname |
| 24 |
|
| 25 |
|
| 26 |
class test_DjangoFixup(FixupCase): |
| 27 |
Fixup = DjangoFixup |
| 28 |
|
| 29 |
def test_setting_default_app(self): |
| 30 |
from celery import _state |
| 31 |
prev, _state.default_app = _state.default_app, None |
| 32 |
try: |
| 33 |
app = Mock(name='app') |
| 34 |
DjangoFixup(app) |
| 35 |
app.set_default.assert_called_with() |
| 36 |
finally: |
| 37 |
_state.default_app = prev |
| 38 |
|
| 39 |
@patch('celery.fixups.django.DjangoWorkerFixup') |
| 40 |
def test_worker_fixup_property(self, DjangoWorkerFixup): |
| 41 |
f = DjangoFixup(self.app) |
| 42 |
f._worker_fixup = None |
| 43 |
assert f.worker_fixup is DjangoWorkerFixup() |
| 44 |
assert f.worker_fixup is DjangoWorkerFixup() |
| 45 |
|
| 46 |
def test_on_import_modules(self): |
| 47 |
f = DjangoFixup(self.app) |
| 48 |
f.worker_fixup = Mock(name='worker_fixup') |
| 49 |
f.on_import_modules() |
| 50 |
f.worker_fixup.validate_models.assert_called_with() |
| 51 |
|
| 52 |
def test_autodiscover_tasks(self, patching): |
| 53 |
patching.modules('django.apps') |
| 54 |
from django.apps import apps |
| 55 |
f = DjangoFixup(self.app) |
| 56 |
configs = [Mock(name='c1'), Mock(name='c2')] |
| 57 |
apps.get_app_configs.return_value = configs |
| 58 |
assert f.autodiscover_tasks() == [c.name for c in configs] |
| 59 |
|
| 60 |
@pytest.mark.masked_modules('django') |
| 61 |
def test_fixup_no_django(self, patching, mask_modules): |
| 62 |
with patch('celery.fixups.django.DjangoFixup') as Fixup: |
| 63 |
patching.setenv('DJANGO_SETTINGS_MODULE', '') |
| 64 |
fixup(self.app) |
| 65 |
Fixup.assert_not_called() |
| 66 |
|
| 67 |
patching.setenv('DJANGO_SETTINGS_MODULE', 'settings') |
| 68 |
with pytest.warns(FixupWarning): |
| 69 |
fixup(self.app) |
| 70 |
Fixup.assert_not_called() |
| 71 |
|
| 72 |
def test_fixup(self, patching): |
| 73 |
with patch('celery.fixups.django.DjangoFixup') as Fixup: |
| 74 |
patching.setenv('DJANGO_SETTINGS_MODULE', '') |
| 75 |
fixup(self.app) |
| 76 |
Fixup.assert_not_called() |
| 77 |
|
| 78 |
patching.setenv('DJANGO_SETTINGS_MODULE', 'settings') |
| 79 |
with conftest.module_exists('django'): |
| 80 |
import django |
| 81 |
django.VERSION = (1, 11, 1) |
| 82 |
fixup(self.app) |
| 83 |
Fixup.assert_called() |
| 84 |
|
| 85 |
def test_maybe_close_fd(self): |
| 86 |
with patch('os.close'): |
| 87 |
_maybe_close_fd(Mock()) |
| 88 |
_maybe_close_fd(object()) |
| 89 |
|
| 90 |
def test_init(self): |
| 91 |
with self.fixup_context(self.app) as (f, importmod, sym): |
| 92 |
assert f |
| 93 |
|
| 94 |
@pytest.mark.patched_module( |
| 95 |
'django', |
| 96 |
'django.db', |
| 97 |
'django.db.transaction', |
| 98 |
) |
| 99 |
def test_install(self, patching, module): |
| 100 |
self.app.loader = Mock() |
| 101 |
self.cw = patching('os.getcwd') |
| 102 |
self.p = patching('sys.path') |
| 103 |
self.sigs = patching('celery.fixups.django.signals') |
| 104 |
with self.fixup_context(self.app) as (f, _, _): |
| 105 |
self.cw.return_value = '/opt/vandelay' |
| 106 |
f.install() |
| 107 |
self.sigs.worker_init.connect.assert_called_with(f.on_worker_init) |
| 108 |
assert self.app.loader.now == f.now |
| 109 |
|
| 110 |
# Specialized DjangoTask class is used |
| 111 |
assert self.app.task_cls == 'celery.contrib.django.task:DjangoTask' |
| 112 |
from celery.contrib.django.task import DjangoTask |
| 113 |
assert issubclass(f.app.Task, DjangoTask) |
| 114 |
assert hasattr(f.app.Task, 'delay_on_commit') |
| 115 |
assert hasattr(f.app.Task, 'apply_async_on_commit') |
| 116 |
|
| 117 |
self.p.insert.assert_called_with(0, '/opt/vandelay') |
| 118 |
|
| 119 |
def test_install_custom_user_task(self, patching): |
| 120 |
patching('celery.fixups.django.signals') |
| 121 |
|
| 122 |
self.app.task_cls = 'myapp.celery.tasks:Task' |
| 123 |
self.app._custom_task_cls_used = True |
| 124 |
|
| 125 |
with self.fixup_context(self.app) as (f, _, _): |
| 126 |
f.install() |
| 127 |
# Specialized DjangoTask class is NOT used, |
| 128 |
# The one from the user's class is |
| 129 |
assert self.app.task_cls == 'myapp.celery.tasks:Task' |
| 130 |
|
| 131 |
def test_install_custom_user_task_as_class_attribute(self, patching): |
| 132 |
patching('celery.fixups.django.signals') |
| 133 |
|
| 134 |
from celery.app import Celery |
| 135 |
|
| 136 |
class MyCeleryApp(Celery): |
| 137 |
task_cls = 'myapp.celery.tasks:Task' |
| 138 |
|
| 139 |
app = MyCeleryApp('mytestapp') |
| 140 |
|
| 141 |
with self.fixup_context(app) as (f, _, _): |
| 142 |
f.install() |
| 143 |
# Specialized DjangoTask class is NOT used, |
| 144 |
# The one from the user's class is |
| 145 |
assert app.task_cls == 'myapp.celery.tasks:Task' |
| 146 |
|
| 147 |
def test_now(self): |
| 148 |
with self.fixup_context(self.app) as (f, _, _): |
| 149 |
assert f.now(utc=True) |
| 150 |
f._now.assert_not_called() |
| 151 |
assert f.now(utc=False) |
| 152 |
f._now.assert_called() |
| 153 |
|
| 154 |
def test_on_worker_init(self): |
| 155 |
with self.fixup_context(self.app) as (f, _, _): |
| 156 |
with patch('celery.fixups.django.DjangoWorkerFixup') as DWF: |
| 157 |
mock_worker = Mock(name="worker") |
| 158 |
f.on_worker_init(sender=mock_worker) |
| 159 |
assert DWF.return_value.worker == mock_worker |
| 160 |
|
| 161 |
DWF.assert_called_with(f.app) |
| 162 |
DWF.return_value.install.assert_called_with() |
| 163 |
assert f._worker_fixup is DWF.return_value |
| 164 |
|
| 165 |
def test_on_worker_init_warns_without_sender(self): |
| 166 |
with self.fixup_context(self.app) as (f, _, _): |
| 167 |
with patch("celery.fixups.django.DjangoWorkerFixup"): |
| 168 |
with pytest.warns(FixupWarning, match="called without a sender"): |
| 169 |
f.on_worker_init(sender=None) |
| 170 |
|
| 171 |
|
| 172 |
class InterfaceError(Exception): |
| 173 |
pass |
| 174 |
|
| 175 |
|
| 176 |
class test_DjangoWorkerFixup(FixupCase): |
| 177 |
Fixup = DjangoWorkerFixup |
| 178 |
|
| 179 |
def test_init(self): |
| 180 |
with self.fixup_context(self.app) as (f, importmod, sym): |
| 181 |
assert f |
| 182 |
|
| 183 |
def test_install(self): |
| 184 |
self.app.conf = {'CELERY_DB_REUSE_MAX': None} |
| 185 |
self.app.loader = Mock() |
| 186 |
with self.fixup_context(self.app) as (f, _, _): |
| 187 |
with patch('celery.fixups.django.signals') as sigs: |
| 188 |
f.install() |
| 189 |
sigs.beat_embedded_init.connect.assert_called_with( |
| 190 |
f.close_database, |
| 191 |
) |
| 192 |
sigs.task_prerun.connect.assert_called_with(f.on_task_prerun) |
| 193 |
sigs.task_postrun.connect.assert_called_with(f.on_task_postrun) |
| 194 |
sigs.worker_process_init.connect.assert_called_with( |
| 195 |
f.on_worker_process_init, |
| 196 |
) |
| 197 |
|
| 198 |
def test_on_worker_process_init(self, patching): |
| 199 |
with self.fixup_context(self.app) as (f, _, _): |
| 200 |
with patch('celery.fixups.django._maybe_close_fd', side_effect=InterfaceError) as mcf: |
| 201 |
_all = f._db.connections.all = Mock() |
| 202 |
conns = _all.return_value = [ |
| 203 |
Mock(), MagicMock(), |
| 204 |
] |
| 205 |
conns[0].connection = None |
| 206 |
with patch.object(f, 'close_cache'): |
| 207 |
with patch.object(f, '_close_database'): |
| 208 |
f.interface_errors = (InterfaceError, ) |
| 209 |
f.on_worker_process_init() |
| 210 |
mcf.assert_called_with(conns[1].connection) |
| 211 |
f.close_cache.assert_called_with() |
| 212 |
f._close_database.assert_called_with() |
| 213 |
|
| 214 |
f.validate_models = Mock(name='validate_models') |
| 215 |
patching.setenv('FORKED_BY_MULTIPROCESSING', '1') |
| 216 |
f.on_worker_process_init() |
| 217 |
f.validate_models.assert_called_with() |
| 218 |
|
| 219 |
def test_on_task_prerun(self): |
| 220 |
task = Mock() |
| 221 |
with self.fixup_context(self.app) as (f, _, _): |
| 222 |
task.request.is_eager = False |
| 223 |
with patch.object(f, 'close_database'): |
| 224 |
f.on_task_prerun(task) |
| 225 |
f.close_database.assert_called_with() |
| 226 |
|
| 227 |
task.request.is_eager = True |
| 228 |
with patch.object(f, 'close_database'): |
| 229 |
f.on_task_prerun(task) |
| 230 |
f.close_database.assert_not_called() |
| 231 |
|
| 232 |
def test_on_task_postrun(self): |
| 233 |
task = Mock() |
| 234 |
with self.fixup_context(self.app) as (f, _, _): |
| 235 |
with patch.object(f, 'close_cache'): |
| 236 |
task.request.is_eager = False |
| 237 |
with patch.object(f, 'close_database'): |
| 238 |
f.on_task_postrun(task) |
| 239 |
f.close_database.assert_called() |
| 240 |
f.close_cache.assert_called() |
| 241 |
|
| 242 |
# when a task is eager, don't close connections |
| 243 |
with patch.object(f, 'close_cache'): |
| 244 |
task.request.is_eager = True |
| 245 |
with patch.object(f, 'close_database'): |
| 246 |
f.on_task_postrun(task) |
| 247 |
f.close_database.assert_not_called() |
| 248 |
f.close_cache.assert_not_called() |
| 249 |
|
| 250 |
def test_close_database(self): |
| 251 |
with self.fixup_context(self.app) as (f, _, _): |
| 252 |
with patch.object(f, '_close_database') as _close: |
| 253 |
f.db_reuse_max = None |
| 254 |
f.close_database() |
| 255 |
_close.assert_called_with() |
| 256 |
_close.reset_mock() |
| 257 |
|
| 258 |
f.db_reuse_max = 10 |
| 259 |
f._db_recycles = 3 |
| 260 |
f.close_database() |
| 261 |
_close.assert_not_called() |
| 262 |
assert f._db_recycles == 4 |
| 263 |
_close.reset_mock() |
| 264 |
|
| 265 |
f._db_recycles = 20 |
| 266 |
f.close_database() |
| 267 |
_close.assert_called_with() |
| 268 |
assert f._db_recycles == 1 |
| 269 |
|
| 270 |
def test__close_database(self): |
| 271 |
with self.fixup_context(self.app) as (f, _, _): |
| 272 |
conns = [Mock(), Mock(), Mock()] |
| 273 |
conns[1].close.side_effect = KeyError('already closed') |
| 274 |
f.DatabaseError = KeyError |
| 275 |
f.interface_errors = () |
| 276 |
|
| 277 |
f._db.connections = Mock() # ConnectionHandler |
| 278 |
f._db.connections.all.side_effect = lambda initialized_only: conns |
| 279 |
|
| 280 |
f._close_database() |
| 281 |
conns[0].close.assert_called_with() |
| 282 |
conns[1].close.assert_called_with() |
| 283 |
conns[2].close.assert_called_with() |
| 284 |
|
| 285 |
conns[1].close.side_effect = KeyError( |
| 286 |
'omg') |
| 287 |
with pytest.raises(KeyError): |
| 288 |
f._close_database() |
| 289 |
|
| 290 |
def test__close_database_django_pre_41(self): |
| 291 |
"""Test that Django < 4.1 (without initialized_only parameter) is handled.""" |
| 292 |
with self.fixup_context(self.app) as (f, _, _): |
| 293 |
conns = [Mock(), Mock()] |
| 294 |
f.DatabaseError = KeyError |
| 295 |
f.interface_errors = () |
| 296 |
|
| 297 |
# Mock Django < 4.1 behavior: connections.all() doesn't accept initialized_only |
| 298 |
f._db.connections = Mock() |
| 299 |
|
| 300 |
def all_without_initialized_only(**kwargs): |
| 301 |
if 'initialized_only' in kwargs: |
| 302 |
raise TypeError("all() got an unexpected keyword argument 'initialized_only'") |
| 303 |
return conns |
| 304 |
|
| 305 |
f._db.connections.all = Mock(side_effect=all_without_initialized_only) |
| 306 |
|
| 307 |
# Should fall back to calling all() without initialized_only |
| 308 |
f._close_database() |
| 309 |
|
| 310 |
# Verify it was called twice: first with initialized_only (raises), then without |
| 311 |
assert f._db.connections.all.call_count == 2 |
| 312 |
# First call with initialized_only=True |
| 313 |
f._db.connections.all.assert_any_call(initialized_only=True) |
| 314 |
# Second call without arguments (fallback) |
| 315 |
f._db.connections.all.assert_any_call() |
| 316 |
|
| 317 |
# Verify connections were closed |
| 318 |
conns[0].close.assert_called_with() |
| 319 |
conns[1].close.assert_called_with() |
| 320 |
|
| 321 |
def test_close_database_always_closes_connections(self): |
| 322 |
with self.fixup_context(self.app) as (f, _, _): |
| 323 |
conn = Mock() |
| 324 |
f._db.connections.all = Mock(return_value=[conn]) |
| 325 |
f.close_database() |
| 326 |
conn.close.assert_called_once_with() |
| 327 |
# close_if_unusable_or_obsolete is not safe to call in all conditions, so avoid using |
| 328 |
# it to optimize connection handling. |
| 329 |
conn.close_if_unusable_or_obsolete.assert_not_called() |
| 330 |
|
| 331 |
def test_close_database_skip_conn_pool(self): |
| 332 |
class Connection: |
| 333 |
"""Mock connection without `close_pool` method.""" |
| 334 |
alias = 'default' |
| 335 |
|
| 336 |
def close(self): |
| 337 |
pass |
| 338 |
|
| 339 |
with self.fixup_context(self.app) as (f, _, _): |
| 340 |
conn = Mock(spec=Connection) |
| 341 |
f._db.connections.all = Mock(return_value=[conn]) |
| 342 |
f.close_database() |
| 343 |
assert not hasattr(conn, "close_pool") |
| 344 |
conn.close.assert_called_once_with() |
| 345 |
|
| 346 |
def test_close_database_suppresses_close_pool_keyerror(self): |
| 347 |
with self.fixup_context(self.app) as (f, _, _): |
| 348 |
conn = Mock() |
| 349 |
conn.close_pool = Mock(side_effect=KeyError("pool already closed")) |
| 350 |
f._db.connections.all = Mock(return_value=[conn]) |
| 351 |
f.close_database() # should not raise |
| 352 |
conn.close.assert_called_once_with() |
| 353 |
conn.close_pool.assert_called_once_with() |
| 354 |
|
| 355 |
def test_close_database_conn_pool_based_on_settings(self): |
| 356 |
class DJSettings: |
| 357 |
DATABASES = {} |
| 358 |
|
| 359 |
with self.fixup_context(self.app) as (f, _, _): |
| 360 |
conn = Mock() |
| 361 |
conn.alias = "default" |
| 362 |
conn.close_pool = Mock() |
| 363 |
f._db.connections.all = Mock(return_value=[conn]) |
| 364 |
f._settings = DJSettings |
| 365 |
|
| 366 |
f._settings.DATABASES["default"] = {"OPTIONS": {}} |
| 367 |
f.close_database() |
| 368 |
conn.close.assert_called_once_with() |
| 369 |
conn.close_pool.assert_not_called() |
| 370 |
|
| 371 |
conn.reset_mock() |
| 372 |
f._settings.DATABASES["default"] = {"OPTIONS": {"pool": True}} |
| 373 |
f.close_database() |
| 374 |
conn.close.assert_called_once_with() |
| 375 |
conn.close_pool.assert_called_once_with() |
| 376 |
|
| 377 |
conn.reset_mock() |
| 378 |
f._settings.DATABASES["default"] = {"OPTIONS": {"pool": False}} |
| 379 |
f.close_database() |
| 380 |
conn.close.assert_called_once_with() |
| 381 |
conn.close_pool.assert_not_called() |
| 382 |
|
| 383 |
def test_close_database_conn_pool_thread_pool(self): |
| 384 |
class DJSettings: |
| 385 |
DATABASES = {} |
| 386 |
|
| 387 |
with self.fixup_context(self.app) as (f, _, _): |
| 388 |
conn = Mock() |
| 389 |
conn.alias = "default" |
| 390 |
conn.close_pool = Mock() |
| 391 |
f._db.connections.all = Mock(return_value=[conn]) |
| 392 |
f._settings = DJSettings |
| 393 |
|
| 394 |
f._settings.DATABASES["default"] = {"OPTIONS": {"pool": True}} |
| 395 |
f.close_database() |
| 396 |
conn.close.assert_called_once_with() |
| 397 |
conn.close_pool.assert_called_once_with() |
| 398 |
|
| 399 |
conn.reset_mock() |
| 400 |
f.worker.pool_cls = ThreadTaskPool |
| 401 |
assert "prefork" not in ThreadTaskPool.__module__ |
| 402 |
f.close_database() |
| 403 |
conn.close.assert_called_once_with() |
| 404 |
conn.close_pool.assert_not_called() |
| 405 |
|
| 406 |
def test_close_cache_raises_error(self): |
| 407 |
with self.fixup_context(self.app) as (f, _, _): |
| 408 |
f._cache.close_caches.side_effect = AttributeError |
| 409 |
f.close_cache() |
| 410 |
|
| 411 |
def test_close_cache(self): |
| 412 |
with self.fixup_context(self.app) as (f, _, _): |
| 413 |
f.close_cache() |
| 414 |
f._cache.close_caches.assert_called_with() |
| 415 |
|
| 416 |
@pytest.mark.patched_module('django', 'django.db', 'django.core', |
| 417 |
'django.core.cache', 'django.conf', |
| 418 |
'django.db.utils') |
| 419 |
def test_validate_models(self, patching, module): |
| 420 |
f = self.Fixup(self.app) |
| 421 |
f.django_setup = Mock(name='django.setup') |
| 422 |
patching.modules('django.core.checks') |
| 423 |
from django.core.checks import run_checks |
| 424 |
|
| 425 |
f.validate_models() |
| 426 |
f.django_setup.assert_called_with() |
| 427 |
run_checks.assert_called_with() |
| 428 |
|
| 429 |
# test --skip-checks flag |
| 430 |
f.django_setup.reset_mock() |
| 431 |
run_checks.reset_mock() |
| 432 |
|
| 433 |
patching.setenv('CELERY_SKIP_CHECKS', 'true') |
| 434 |
f.validate_models() |
| 435 |
f.django_setup.assert_called_with() |
| 436 |
run_checks.assert_not_called() |
| 437 |
|
| 438 |
def test_django_setup(self, patching): |
| 439 |
patching('celery.fixups.django.symbol_by_name') |
| 440 |
patching('celery.fixups.django.import_module') |
| 441 |
django, = patching.modules('django') |
| 442 |
f = self.Fixup(self.app) |
| 443 |
f.django_setup() |
| 444 |
django.setup.assert_called_with() |
| 445 |
|
| 446 |
def test__is_prefork(self): |
| 447 |
with self.fixup_context(self.app) as (f, _, _): |
| 448 |
f.worker.pool_cls = Mock(__module__='celery.concurrency.prefork') |
| 449 |
assert f._is_prefork() |
| 450 |
|
| 451 |
f.worker.pool_cls = "prefork" |
| 452 |
assert f._is_prefork() |
| 453 |
|
| 454 |
f.worker.pool_cls = Mock(__module__='celery.concurrency.thread') |
| 455 |
assert not f._is_prefork() |
| 456 |
|
| 457 |
f.worker = None |
| 458 |
assert not f._is_prefork() |
| 459 |
|
| 460 |
def test_no_recursive_worker_instantiation(self, patching): |
| 461 |
"""Regression test: DjangoWorkerFixup must not create a WorkController in __init__. |
| 462 |
|
| 463 |
Historically, DjangoWorkerFixup.__init__ instantiated a WorkController when |
| 464 |
called with worker=None, which could cause recursive instantiation when |
| 465 |
invoked from worker lifecycle signals. |
| 466 |
|
| 467 |
This test verifies the fixed behavior: |
| 468 |
- DjangoWorkerFixup(app, worker=None) must not create a WorkController |
| 469 |
- It should instead leave self.worker unset and rely on on_worker_init |
| 470 |
to attach the actual worker instance later |
| 471 |
""" |
| 472 |
from celery.worker import WorkController |
| 473 |
|
| 474 |
patching('celery.fixups.django.symbol_by_name') |
| 475 |
patching('celery.fixups.django.import_module') |
| 476 |
patching.modules('django', 'django.db', 'django.core.checks') |
| 477 |
|
| 478 |
# Track WorkController instantiations |
| 479 |
instantiation_count = {'count': 0} |
| 480 |
original_init = WorkController.__init__ |
| 481 |
|
| 482 |
def tracking_init(self_worker, *args, **kwargs): |
| 483 |
instantiation_count['count'] += 1 |
| 484 |
return original_init(self_worker, *args, **kwargs) |
| 485 |
|
| 486 |
with patch.object(WorkController, '__init__', tracking_init): |
| 487 |
# Creating DjangoWorkerFixup without a worker argument |
| 488 |
# should NOT create a WorkController instance |
| 489 |
DjangoWorkerFixup(self.app) |
| 490 |
|
| 491 |
# EXPECTED: 0 WorkController instances created |
| 492 |
assert instantiation_count['count'] == 0, ( |
| 493 |
f"DjangoWorkerFixup(app) should NOT create a WorkController, " |
| 494 |
f"but {instantiation_count['count']} instance(s) were created. " |
| 495 |
f"This is the root cause of the recursion bug." |
| 496 |
) |