使用this answer作为模型,我正在测试以下实例化类(EmailMultiAlternatives
)的方法:
admintools / emailer.py
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
def send_email(template_path, context, subject_line, from_email, to=[], cc=[], bcc=DEFAULT_BCC_EMAILS):
msg_html = render_to_string(template_path, context)
msg_plain = strip_tags(msg_html)
email = EmailMultiAlternatives(subject_line, msg_plain, from_email, to, cc=cc, bcc=bcc)
email.attach_alternative(msg_html, "text/html")
email.send()
使用 test.py :
from unittest.mock import patch
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.test import TestCase
from admintools.emailer import send_email
class EmailerTestCase(TestCase):
@patch('django.core.mail.EmailMultiAlternatives')
def test_send_email(self, mockEmailMultiAlternatives):
context = {}
template_path = "emails/closings/seller_pre_close_update_prompt.html"
msg_plain = render_to_string(template_path, context)
to = ['']
cc = ['']
send_email(template_path, {}, 'subject', "from", to, cc=cc)
mockEmailMultiAlternatives.assert_called()
即使在测试运行期间成功创建了AssertionError: Expected 'EmailMultiAlternatives' to have been called.
(在实例化返回email
之后立即由print(email)
验证),我仍然收到<django.core.mail.message.EmailMultiAlternatives object at 0x7fbf4bb4b590>
。
即使实例化EmailMultiAlternatives
,是什么导致断言失败?
答案 0 :(得分:1)
由于admintools.emailer
如何导入EmailMultiAlternatives
,因此您需要模拟admintools.email.EmailMultiAlternatives
。
@patch('admintools.emailer.EmailMultiAlternatives')
def test_send_email(self, mockEmailMultiAlternatives):
send_email
通过模块全局名称而不是django.core.mail
属性调用函数。