How can I mock a class method of a celery Task
使用python 2.7,celery 3.0.24和模拟1.0.1。 我有这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | class FancyTask(celery.Task): @classmethod def helper_method1(cls, name): """do some remote request depending on name""" return 'foo' + name + 'bar' def __call__(self, *args, **kwargs): funcname = self.name.split()[-1] bigname = self.helper_method1(funcname) return bigname @celery.task(base=FancyTask) def task1(*args, **kwargs): pass @celery.task(base=FancyTask) def task2(*args, **kwargs): pass |
测试任一个任务时如何修补
我已经尝试过类似的方法:
1 2 3 4 5 6 7 8 9 | import mock from mymodule import tasks class TestTasks(unittest.TestCase): def test_task1(self): task = tasks.task1 task.helper_method1 = mock.MagickMock(return_value='42') res = task.delay('blah') task.helper_method1.assert_called_with('blah') |
测试失败。 原始函数是被调用的函数。 不,这个问题对我没有帮助。
(我没有启动并运行芹菜实例,因此我很难对其进行测试)
应用程序代码中的目标函数是类方法。 您的测试代码正在模拟的功能是一个实例方法。
是否像这样帮助更改test_task1-
1 2 3 4 5 | def test_task1(self): FancyTask.helper_method1 = mock.MagickMock(return_value='42') task = tasks.task1 res = task.delay('blah') task.helper_method1.assert_called_with('blah') |
您可能还需要更改assert_ Called_with,以便从类级别而不是实例级别调用它。
更改
1 | task.helper_method1.assert_called_with('blah') |
至
1 | FancyTask.helper_method1.assert_called_with('blah') |