How do I capture Celery tasks during unit testing?

南楼画角 提交于 2019-12-12 11:45:14

问题


How can I capture without running Celery tasks created during a unit test?

For example, I'd like to write a test which looks something like this:

def test_add_user_avatar():
    add_user_avatar(…)
    tasks = get_deferred_tasks(…)
    assert_equal(tasks[0], ResizeImageTask(…))

Specifically, I do not want to use ALWAYS_EAGER — some of my tasks are quite slow, and have their own set of tests cases. I specifically want to assert that the correct tasks are being created by my front-end code.


回答1:


My situation is similar and the strategy I'm working with is to mock out the calls to Celery tasks and then check the calls made to those mocks after the run. Could this work here?

from … import ResizeImageTask


class NonQueuedTestCase(…):

    def setUp(self):
        """
        Patch out ResizeImageTask's delay method
        """
        super(NonQueuedTestCase, self).setUp()
        self.patcher = patch.object(ResizeImageTask, 'delay', autospec=True)
        self.m_delay = self.patcher.start()

    def tearDown(self):
        self.patcher.stop()
        super(NonQueuedTestCase, self).tearDown()

    def test_add_user_avatar(self):
        # Make call to front-end code
        add_user_avatar(…)
        # Check delay call was made
        self.m_delay.assert_called_once_with(…)

You can run these tests without a backend up (in memory or otherwise), keep a clean break between the front-end code and task code, and can test multiple code paths that would normally queue up a long running task without it running.



来源:https://stackoverflow.com/questions/22314242/how-do-i-capture-celery-tasks-during-unit-testing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!