Python:模拟在 celery 任务中不起作用

标签 python django unit-testing mocking celery

<分区>

我想使用 python mock 库来测试我的 Django 应用程序发送电子邮件。

测试代码:

# tests.py
from django.test import TestCase

class MyTestCase(TestCase):

    @mock.patch('django.core.mail.mail_managers')
    def test_canceled_wo_claiming(self, mocked_mail_managers):
        client = Client()
        client.get('/')
        print(mocked_mail_managers.called)
        mocked_mail_managers.assert_called_with('Hi, managers!', 'Message Body')

第一个例子——没有任务

# views.py
from django.views.generic import View
from django.core.mail import mail_managers

class MyView(View):

    def get(self, request):
        mail_managers('Hi, managers!', 'Message Body')
        return HttpResponse('Hello!')

第二个例子 - 有任务

# views.py
from django.views.generic import View
from . import tasks

class MyView(View):
    def get(self, request):
        tasks.notify.apply_async()
        return HttpResponse('Hello!')


# tasks.py
from celery import shared_task
from django.core.mail import mail_managers

@shared_task
def notify():
    mail_managers('Hi, managers!', 'Message Body')

第一个例子正常,第二个例子失败,出现Not called异常。

我的设置:

# Celery
BROKEN_URL = 'memory://'
BROKER_BACKEND = 'memory'

CELERY_ALWAYS_EAGER = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
TEST_RUNNER = 'djcelery.contrib.test_runner.CeleryTestSuiteRunner'

是否可以执行这样的集成测试,或者解决此问题的唯一方法是将测试拆分为两个?

最佳答案

我发现了一个问题,它很愚蠢。 Described hereHere :

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined.

我需要改变:

@mock.patch('django.core.mail.mail_managers')

@mock.patch('path.to.tasks.mail_managers')

关于Python:模拟在 celery 任务中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30531637/

相关文章:

unit-testing - MOCKITO:它是什么以及它与 Junit 有何不同

python - 如何解释 Python commands.getstatusoutput() 中的状态代码

带有本地 smtp 的 Django 电子邮件后端

python - 登录网站后使用 PyCurl 获取请求

html - Zurb Foundation - 创建自定义表单但现在不会创建帖子

python - 在Django模型中,有没有办法通过非pk列从多个表中选择属性并点击数据库一次?

java - 编写 JUnit 时如何绕过 Runtime.getRuntime()?

reactjs - 在 Jest 中使用 Next.Js 测试 Api

python - 使用 groupbyvars 作为 cols/index 获取 Pandas.groupby.shift() 结果?

Python 2.7 和 OpenCV 使用 64 位和 32 位的不同结果,可能的错误?