0

I've read Testing with Celery but I'm still a bit confused. I want to test code that generates a Celery task by running the task manually and explicitly, something like:

def test_something(self):
    do_something_that_generates_a_celery_task()
    assert_state_before_task_runs()
    run_task()
    assert_state_after_task_runs()

I don't want to entirely mock up the creation of the task but at the same time I don't care about testing the task being picked up by a Celery worker. I'm assuming Celery works.

The actual context in which I'm trying to do this is a Django application where there's some code that takes too long to run in a request, so, it's delegated to background jobs.

Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622
  • you could mock: `do_something_that_generates_a_celery_task()` and add a `side_effect()` which calls the the function that the celery task would invoke. if the celery task is a function, then you can easily run outside of celery – Uku Loskit Nov 18 '18 at 11:32
  • @UkuLoskit: I don't want to want to mock it. I'm not sure I can mock it. It's a selenium script that interacts with the testing web server. – Pablo Fernandez Nov 18 '18 at 11:41
  • This is related but I haven't managed to get it to work yet: https://stackoverflow.com/questions/22233680/in-memory-broker-for-celery-unit-tests – Pablo Fernandez Nov 18 '18 at 12:26

1 Answers1

0

In test mode use CELERY_TASK_ALWAYS_EAGER = True. You can set this setting in your settings.py in django if you have followed the default guide for django-celery configuration.

2ps
  • 15,099
  • 2
  • 27
  • 47
  • That would have two issues: 1) the http request would fail if the task takes too long, which is possible as it's the reason I'm using celery for and 2) it wouldn't let me assert the state of the system before the task is being done; which I want to do to make sure the user experience is good when tasks are not being picked up quickly. – Pablo Fernandez Nov 19 '18 at 09:08