| 1 |
.. _testing: |
| 2 |
|
| 3 |
================================================================ |
| 4 |
Testing with Celery |
| 5 |
================================================================ |
| 6 |
|
| 7 |
Testing with Celery is divided into two parts: |
| 8 |
|
| 9 |
* Unit & Integration: Using ``celery.contrib.pytest``. |
| 10 |
* Smoke / Production: Using :pypi:`pytest-celery <pytest-celery>` >= 1.0.0 |
| 11 |
|
| 12 |
Installing the pytest-celery plugin will install the ``celery.contrib.pytest`` infrastructure as well, |
| 13 |
alongside the pytest plugin infrastructure. The difference is how you use it. |
| 14 |
|
| 15 |
.. warning:: |
| 16 |
|
| 17 |
Both APIs are NOT compatible with each other. The pytest-celery plugin is Docker based |
| 18 |
and the ``celery.contrib.pytest`` is mock based. |
| 19 |
|
| 20 |
To use the ``celery.contrib.pytest`` infrastructure, follow the instructions below. |
| 21 |
|
| 22 |
The pytest-celery plugin has its `own documentation <https://pytest-celery.readthedocs.io/>`_. |
| 23 |
|
| 24 |
Tasks and unit tests |
| 25 |
==================== |
| 26 |
|
| 27 |
To test task behavior in unit tests the preferred method is mocking. |
| 28 |
|
| 29 |
.. admonition:: Eager mode |
| 30 |
|
| 31 |
The eager mode enabled by the :setting:`task_always_eager` setting |
| 32 |
is by definition not suitable for unit tests. |
| 33 |
|
| 34 |
When testing with eager mode you are only testing an emulation |
| 35 |
of what happens in a worker, and there are many discrepancies |
| 36 |
between the emulation and what happens in reality. |
| 37 |
|
| 38 |
Note that eagerly executed tasks don't write results to backend by default. |
| 39 |
If you want to enable this functionality, have a look at :setting:`task_store_eager_result`. |
| 40 |
|
| 41 |
A Celery task is much like a web view, in that it should only |
| 42 |
define how to perform the action in the context of being called as a task. |
| 43 |
|
| 44 |
This means optimally tasks only handle things like serialization, message headers, |
| 45 |
retries, and so on, with the actual logic implemented elsewhere. |
| 46 |
|
| 47 |
Say we had a task like this: |
| 48 |
|
| 49 |
.. code-block:: python |
| 50 |
|
| 51 |
from .models import Product |
| 52 |
|
| 53 |
|
| 54 |
@app.task(bind=True) |
| 55 |
def send_order(self, product_pk, quantity, price): |
| 56 |
price = Decimal(price) # json serializes this to string. |
| 57 |
|
| 58 |
# models are passed by id, not serialized. |
| 59 |
product = Product.objects.get(product_pk) |
| 60 |
|
| 61 |
try: |
| 62 |
product.order(quantity, price) |
| 63 |
except OperationalError as exc: |
| 64 |
raise self.retry(exc=exc) |
| 65 |
|
| 66 |
|
| 67 |
``Note``: A task being `bound <https://docs.celeryq.dev/en/latest/userguide/tasks.html#bound-tasks>`_ means the first |
| 68 |
argument to the task will always be the task instance (self). which means you do get a self argument as the |
| 69 |
first argument and can use the Task class methods and attributes. |
| 70 |
|
| 71 |
You could write unit tests for this task, using mocking like |
| 72 |
in this example: |
| 73 |
|
| 74 |
.. code-block:: python |
| 75 |
|
| 76 |
from pytest import raises |
| 77 |
|
| 78 |
from celery.exceptions import Retry |
| 79 |
|
| 80 |
# for python 2: use mock.patch from `pip install mock`. |
| 81 |
from unittest.mock import patch |
| 82 |
|
| 83 |
from proj.models import Product |
| 84 |
from proj.tasks import send_order |
| 85 |
|
| 86 |
class test_send_order: |
| 87 |
|
| 88 |
@patch('proj.tasks.Product.order') # < patching Product in module above |
| 89 |
def test_success(self, product_order): |
| 90 |
product = Product.objects.create( |
| 91 |
name='Foo', |
| 92 |
) |
| 93 |
send_order(product.pk, 3, Decimal(30.3)) |
| 94 |
product_order.assert_called_with(3, Decimal(30.3)) |
| 95 |
|
| 96 |
@patch('proj.tasks.Product.order') |
| 97 |
@patch('proj.tasks.send_order.retry') |
| 98 |
def test_failure(self, send_order_retry, product_order): |
| 99 |
product = Product.objects.create( |
| 100 |
name='Foo', |
| 101 |
) |
| 102 |
|
| 103 |
# Set a side effect on the patched methods |
| 104 |
# so that they raise the errors we want. |
| 105 |
send_order_retry.side_effect = Retry() |
| 106 |
product_order.side_effect = OperationalError() |
| 107 |
|
| 108 |
with raises(Retry): |
| 109 |
send_order(product.pk, 3, Decimal(30.6)) |
| 110 |
|
| 111 |
.. _pytest_plugin: |
| 112 |
|
| 113 |
pytest |
| 114 |
====== |
| 115 |
|
| 116 |
.. versionadded:: 4.0 |
| 117 |
|
| 118 |
Celery also makes a :pypi:`pytest` plugin available that adds fixtures that you can |
| 119 |
use in your integration (or unit) test suites. |
| 120 |
|
| 121 |
Enabling |
| 122 |
-------- |
| 123 |
|
| 124 |
Celery initially ships the plugin in a disabled state. To enable it, you can either: |
| 125 |
|
| 126 |
* ``pip install celery[pytest]`` |
| 127 |
* or add an environment variable ``PYTEST_PLUGINS=celery.contrib.pytest`` |
| 128 |
* or add ``pytest_plugins = ("celery.contrib.pytest", )`` to your root conftest.py |
| 129 |
|
| 130 |
|
| 131 |
Marks |
| 132 |
----- |
| 133 |
|
| 134 |
``celery`` - Set test app configuration. |
| 135 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 136 |
|
| 137 |
The ``celery`` mark enables you to override the configuration |
| 138 |
used for a single test case: |
| 139 |
|
| 140 |
.. code-block:: python |
| 141 |
|
| 142 |
@pytest.mark.celery(result_backend='redis://') |
| 143 |
def test_something(): |
| 144 |
... |
| 145 |
|
| 146 |
|
| 147 |
or for all the test cases in a class: |
| 148 |
|
| 149 |
.. code-block:: python |
| 150 |
|
| 151 |
@pytest.mark.celery(result_backend='redis://') |
| 152 |
class test_something: |
| 153 |
|
| 154 |
def test_one(self): |
| 155 |
... |
| 156 |
|
| 157 |
def test_two(self): |
| 158 |
... |
| 159 |
|
| 160 |
Fixtures |
| 161 |
-------- |
| 162 |
|
| 163 |
Function scope |
| 164 |
^^^^^^^^^^^^^^ |
| 165 |
|
| 166 |
``celery_app`` - Celery app used for testing. |
| 167 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 168 |
|
| 169 |
This fixture returns a Celery app you can use for testing. |
| 170 |
|
| 171 |
Example: |
| 172 |
|
| 173 |
.. code-block:: python |
| 174 |
|
| 175 |
def test_create_task(celery_app, celery_worker): |
| 176 |
@celery_app.task |
| 177 |
def mul(x, y): |
| 178 |
return x * y |
| 179 |
|
| 180 |
celery_worker.reload() |
| 181 |
assert mul.delay(4, 4).get(timeout=10) == 16 |
| 182 |
|
| 183 |
``celery_worker`` - Embed live worker. |
| 184 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 185 |
|
| 186 |
This fixture starts a Celery worker instance that you can use |
| 187 |
for integration tests. The worker will be started in a *separate thread* |
| 188 |
and will be shutdown as soon as the test returns. |
| 189 |
|
| 190 |
By default the fixture will wait up to 10 seconds for the worker to complete |
| 191 |
outstanding tasks and will raise an exception if the time limit is exceeded. |
| 192 |
The timeout can be customized by setting the ``shutdown_timeout`` key in the |
| 193 |
dictionary returned by the :func:`celery_worker_parameters` fixture. |
| 194 |
|
| 195 |
Example: |
| 196 |
|
| 197 |
.. code-block:: python |
| 198 |
|
| 199 |
# Put this in your conftest.py |
| 200 |
@pytest.fixture(scope='session') |
| 201 |
def celery_config(): |
| 202 |
return { |
| 203 |
'broker_url': 'amqp://', |
| 204 |
'result_backend': 'redis://' |
| 205 |
} |
| 206 |
|
| 207 |
def test_add(celery_worker): |
| 208 |
mytask.delay() |
| 209 |
|
| 210 |
|
| 211 |
# If you wish to override some setting in one test cases |
| 212 |
# only - you can use the ``celery`` mark: |
| 213 |
@pytest.mark.celery(result_backend='rpc') |
| 214 |
def test_other(celery_worker): |
| 215 |
... |
| 216 |
|
| 217 |
Heartbeats are disabled by default which means that the test worker doesn't |
| 218 |
send events for ``worker-online``, ``worker-offline`` and ``worker-heartbeat``. |
| 219 |
To enable heartbeats modify the :func:`celery_worker_parameters` fixture: |
| 220 |
|
| 221 |
.. code-block:: python |
| 222 |
|
| 223 |
# Put this in your conftest.py |
| 224 |
@pytest.fixture(scope="session") |
| 225 |
def celery_worker_parameters(): |
| 226 |
return {"without_heartbeat": False} |
| 227 |
... |
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
Session scope |
| 232 |
^^^^^^^^^^^^^ |
| 233 |
|
| 234 |
``celery_config`` - Override to setup Celery test app configuration. |
| 235 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 236 |
You can redefine this fixture to configure the test Celery app. |
| 237 |
|
| 238 |
The config returned by your fixture will then be used |
| 239 |
to configure the :func:`celery_app`, and :func:`celery_session_app` fixtures. |
| 240 |
|
| 241 |
Example: |
| 242 |
|
| 243 |
.. code-block:: python |
| 244 |
|
| 245 |
@pytest.fixture(scope='session') |
| 246 |
def celery_config(): |
| 247 |
return { |
| 248 |
'broker_url': 'amqp://', |
| 249 |
'result_backend': 'rpc', |
| 250 |
} |
| 251 |
|
| 252 |
|
| 253 |
``celery_parameters`` - Override to setup Celery test app parameters. |
| 254 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 255 |
|
| 256 |
You can redefine this fixture to change the ``__init__`` parameters of test |
| 257 |
Celery app. In contrast to :func:`celery_config`, these are directly passed to |
| 258 |
when instantiating :class:`~celery.Celery`. |
| 259 |
|
| 260 |
The config returned by your fixture will then be used |
| 261 |
to configure the :func:`celery_app`, and :func:`celery_session_app` fixtures. |
| 262 |
|
| 263 |
Example: |
| 264 |
|
| 265 |
.. code-block:: python |
| 266 |
|
| 267 |
@pytest.fixture(scope='session') |
| 268 |
def celery_parameters(): |
| 269 |
return { |
| 270 |
'task_cls': my.package.MyCustomTaskClass, |
| 271 |
'strict_typing': False, |
| 272 |
} |
| 273 |
|
| 274 |
``celery_worker_parameters`` - Override to setup Celery worker parameters. |
| 275 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 276 |
|
| 277 |
You can redefine this fixture to change the ``__init__`` parameters of test |
| 278 |
Celery workers. These are directly passed to |
| 279 |
:class:`~celery.worker.WorkController` when it is instantiated. |
| 280 |
|
| 281 |
The config returned by your fixture will then be used |
| 282 |
to configure the :func:`celery_worker`, and :func:`celery_session_worker` |
| 283 |
fixtures. |
| 284 |
|
| 285 |
Example: |
| 286 |
|
| 287 |
.. code-block:: python |
| 288 |
|
| 289 |
@pytest.fixture(scope='session') |
| 290 |
def celery_worker_parameters(): |
| 291 |
return { |
| 292 |
'queues': ('high-prio', 'low-prio'), |
| 293 |
'exclude_queues': ('celery'), |
| 294 |
} |
| 295 |
|
| 296 |
|
| 297 |
``celery_enable_logging`` - Override to enable logging in embedded workers. |
| 298 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 299 |
|
| 300 |
This is a fixture you can override to enable logging in embedded workers. |
| 301 |
|
| 302 |
Example: |
| 303 |
|
| 304 |
.. code-block:: python |
| 305 |
|
| 306 |
@pytest.fixture(scope='session') |
| 307 |
def celery_enable_logging(): |
| 308 |
return True |
| 309 |
|
| 310 |
``celery_includes`` - Add additional imports for embedded workers. |
| 311 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 312 |
You can override fixture to include modules when an embedded worker starts. |
| 313 |
|
| 314 |
You can have this return a list of module names to import, |
| 315 |
which can be task modules, modules registering signals, and so on. |
| 316 |
|
| 317 |
Example: |
| 318 |
|
| 319 |
.. code-block:: python |
| 320 |
|
| 321 |
@pytest.fixture(scope='session') |
| 322 |
def celery_includes(): |
| 323 |
return [ |
| 324 |
'proj.tests.tasks', |
| 325 |
'proj.tests.celery_signal_handlers', |
| 326 |
] |
| 327 |
|
| 328 |
``celery_worker_pool`` - Override the pool used for embedded workers. |
| 329 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 330 |
You can override fixture to configure the execution pool used for embedded |
| 331 |
workers. |
| 332 |
|
| 333 |
Example: |
| 334 |
|
| 335 |
.. code-block:: python |
| 336 |
|
| 337 |
@pytest.fixture(scope='session') |
| 338 |
def celery_worker_pool(): |
| 339 |
return 'prefork' |
| 340 |
|
| 341 |
.. warning:: |
| 342 |
|
| 343 |
You cannot use the gevent/eventlet pools, that is unless your whole test |
| 344 |
suite is running with the monkeypatches enabled. |
| 345 |
|
| 346 |
``celery_session_worker`` - Embedded worker that lives throughout the session. |
| 347 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 348 |
|
| 349 |
This fixture starts a worker that lives throughout the testing session |
| 350 |
(it won't be started/stopped for every test). |
| 351 |
|
| 352 |
Example: |
| 353 |
|
| 354 |
.. code-block:: python |
| 355 |
|
| 356 |
# Add this to your conftest.py |
| 357 |
@pytest.fixture(scope='session') |
| 358 |
def celery_config(): |
| 359 |
return { |
| 360 |
'broker_url': 'amqp://', |
| 361 |
'result_backend': 'rpc', |
| 362 |
} |
| 363 |
|
| 364 |
# Do this in your tests. |
| 365 |
def test_add_task(celery_session_worker): |
| 366 |
assert add.delay(2, 2).get() == 4 |
| 367 |
|
| 368 |
.. warning:: |
| 369 |
|
| 370 |
It's probably a bad idea to mix session and ephemeral workers... |
| 371 |
|
| 372 |
``celery_session_app`` - Celery app used for testing (session scope). |
| 373 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 374 |
|
| 375 |
This can be used by other session scoped fixtures when they need to refer |
| 376 |
to a Celery app instance. |
| 377 |
|
| 378 |
``use_celery_app_trap`` - Raise exception on falling back to default app. |
| 379 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 380 |
|
| 381 |
This is a fixture you can override in your ``conftest.py``, to enable the "app trap": |
| 382 |
if something tries to access the default or current_app, an exception |
| 383 |
is raised. |
| 384 |
|
| 385 |
Example: |
| 386 |
|
| 387 |
.. code-block:: python |
| 388 |
|
| 389 |
@pytest.fixture(scope='session') |
| 390 |
def use_celery_app_trap(): |
| 391 |
return True |
| 392 |
|
| 393 |
|
| 394 |
If a test wants to access the default app, you would have to mark it using |
| 395 |
the ``depends_on_current_app`` fixture: |
| 396 |
|
| 397 |
.. code-block:: python |
| 398 |
|
| 399 |
@pytest.mark.usefixtures('depends_on_current_app') |
| 400 |
def test_something(): |
| 401 |
something() |