[英]How can I mock a class method of a celery Task
Using python 2.7, celery 3.0.24 and mock 1.0.1. 使用python 2.7,celery 3.0.24和模拟1.0.1。 I have this:
我有这个:
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
how can I patch helper_method1
while testing either task? 测试两个任务时如何修补
helper_method1
?
I've tried something like: 我已经尝试过类似的东西:
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')
and the test is failing. 测试失败。 The original function is the one being called.
原始函数是被调用的函数。 And no, this question didn't help me.
不, 这个问题对我没有帮助。
(I don't have a celery instance up and running so it's difficult for me to test this) (我没有启动和运行芹菜实例,因此我很难对其进行测试)
The target function in your application code is a classmethod. 应用程序代码中的目标函数是类方法。 The function your test code is mocking is an instance method.
您的测试代码正在模拟的功能是一个实例方法。
Does changing the test_task1 like this help - 是否像这样帮助更改test_task1-
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')
You probably also need to change the assert_called_with so it is called from the class level instead of the instance level. 您可能还需要更改assert_ Called_with,以便从类级别而不是实例级别调用它。
change 更改
task.helper_method1.assert_called_with('blah')
to 至
FancyTask.helper_method1.assert_called_with('blah')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.