我的芹菜任务有一个基类,实现了on_failure
方法。
在我的测试中,我修补了任务调用的方法之一,以引发异常,但永远不会调用on_faliure
。
基础课程
class BaseTask(celery.Task):
abstract = True
def on_failure(self, exc, task_id, args, kwargs, einfo):
print("error")
任务
@celery.task(bind=True, base=BaseTask)
def multiple(self, a, b):
logic.method(a, b)
测试
@patch('tasks.logic.method')
def test_something(self, mock):
# arrange
mock.side_effect = NotImplementedError
# act
with self.assertRaises(NotImplementedError):
multiple(1, 2)
当运行芹菜并引发异常时,一切正常。
CELERY_ALWAYS_EAGER
已激活。
如何让on_faliure
运行?
答案 0 :(得分:1)
从discussion on a issue in celery GitHub:on_failure
开始的测试已“已在芹菜级别完成(验证是否调用了on_failure)” 和“编写了一个测试以进行测试不管您的on_failure做什么”。。您可以在on_failure
方法内定义一个函数并对其进行测试,或者像类方法一样调用on_failure
:
import TestCase
from billiard.einfo import ExceptionInfo
class TestTask(TestCase):
def test_on_failure(self):
"Testing on failure method"
exc = Exception("Test")
task_id = "test_task_id"
args = ["argument 1"]
kwargs = {"key": "value"}
einfo = ExceptionInfo
# call on_failure method
multiple.on_failure(exc, task_id, args, kwargs, einfo)
# assert something appened
ExceptionInfo
与celery
使用的对象类型相同; multiple
是您在问题中定义的任务。
希望这会有所帮助