我想使用 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'
是否可以执行这样的集成测试,或者解决此问题的唯一方法是将测试拆分为两个?
我是一名优秀的程序员,十分优秀!