| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from concurrent.futures import ThreadPoolExecutor |
| 4 |
from unittest.mock import Mock |
| 5 |
|
| 6 |
import pytest |
| 7 |
from pytest_celery import CeleryTestSetup, CeleryTestWorker, CeleryWorkerCluster |
| 8 |
|
| 9 |
from celery import Celery |
| 10 |
from celery.app.base import set_default_app |
| 11 |
from celery.signals import after_task_publish |
| 12 |
from t.integration.tasks import identity |
| 13 |
|
| 14 |
|
| 15 |
@pytest.fixture( |
| 16 |
params=[ |
| 17 |
# Single worker |
| 18 |
["celery_setup_worker"], |
| 19 |
# Workers cluster (same queue) |
| 20 |
["celery_setup_worker", "celery_alt_dev_worker"], |
| 21 |
] |
| 22 |
) |
| 23 |
def celery_worker_cluster(request: pytest.FixtureRequest) -> CeleryWorkerCluster: |
| 24 |
nodes: tuple[CeleryTestWorker] = [ |
| 25 |
request.getfixturevalue(worker) for worker in request.param |
| 26 |
] |
| 27 |
cluster = CeleryWorkerCluster(*nodes) |
| 28 |
yield cluster |
| 29 |
cluster.teardown() |
| 30 |
|
| 31 |
|
| 32 |
class test_thread_safety: |
| 33 |
@pytest.fixture |
| 34 |
def default_worker_app(self, default_worker_app: Celery) -> Celery: |
| 35 |
app = default_worker_app |
| 36 |
app.conf.broker_pool_limit = 42 |
| 37 |
return app |
| 38 |
|
| 39 |
@pytest.mark.parametrize( |
| 40 |
"threads_count", |
| 41 |
[ |
| 42 |
# Single |
| 43 |
1, |
| 44 |
# Multiple |
| 45 |
2, |
| 46 |
# Many |
| 47 |
42, |
| 48 |
], |
| 49 |
) |
| 50 |
def test_multithread_task_publish( |
| 51 |
self, |
| 52 |
celery_setup: CeleryTestSetup, |
| 53 |
threads_count: int, |
| 54 |
): |
| 55 |
signal_was_called = Mock() |
| 56 |
|
| 57 |
@after_task_publish.connect |
| 58 |
def after_task_publish_handler(*args, **kwargs): |
| 59 |
signal_was_called(True) |
| 60 |
|
| 61 |
def thread_worker(): |
| 62 |
set_default_app(celery_setup.app) |
| 63 |
identity.si("Published from thread").apply_async( |
| 64 |
queue=celery_setup.worker.worker_queue |
| 65 |
) |
| 66 |
|
| 67 |
executor = ThreadPoolExecutor(threads_count) |
| 68 |
|
| 69 |
with executor: |
| 70 |
for _ in range(threads_count): |
| 71 |
executor.submit(thread_worker) |
| 72 |
|
| 73 |
assert signal_was_called.call_count == threads_count |