Django Celery如何忽略任务?

时间:2013-11-03 18:38:51

标签: django celery

我想在Django中执行功能测试。

如何在测试期间忽略Celery任务?

class TestsFunctional(TestCase):

    def test_ignore_task(self):
        response = my_method()
        self.assertEqual(201, response)



def my_method():
    #just want to ignore tasks
    from celery import chain
    chain(tasks.long_task.s(), tasks.another_task.s()).apply_async()
    return 201


@task(default_retry_delay=10, max_retries=None)
def long_task():
    try:
        #infinite on localhost
    except socket.error:
        logger.warning("Service not reachable")
        long_task.retry()
    except Exception as e:
        logger.exception(e)

在我的settings.py

TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'

2 个答案:

答案 0 :(得分:1)

我写了一个装饰器,我添加到我想在单元测试中跳过的函数。

https://gist.github.com/kevinastone/7295567

你可以选择使用mock并模拟任务。

答案 1 :(得分:1)

要展开Kevin Stone's答案,您可以使用patch装饰器和MagicMock模仿测试的Celery部分,如下所示:

测试代码

from unittest.mock import MagicMock, patch

@patch('reference.to.your.long_task', new=MagicMock())
class TestsFunctional(TestCase):

  def test_ignore_task(self):
      response = my_method()
      self.assertEqual(201, response) 

申请代码

def my_method():
  from celery import chain
  chain(tasks.long_task.s(), tasks.another_task.s()).apply_async()
  return 201

@task(default_retry_delay=10, max_retries=None)
def long_task():
  # Long running process

(YMMV)