我正在尝试测试我创建的向用户发送欢迎电子邮件的功能。但是,要做到这一点,我必须模拟实际发送它的函数(在欢迎电子邮件函数中)。我有以下文件夹结构:
app/
__init__.py
mail.py
tests/
__init__.py
conftest.py
test_mail.py
这是我在mail.py中的代码
import flask_mail
mail = flask_mail.Mail()
def send_mail(subject, sender, recipients, text_body, html_body):
msg = flask_mail.Message(subject, sender=sender, recipients=recipients, body=text_body, html=html_body)
mail.send(msg)
def send_sign_up_mail(user):
subject = "Test subject"
sender = ("Test sender", "testsender@gmail.com")
recipients = [user.email]
text_body = "text body"
html_body = f"Test html body"
send_mail(subject, sender, recipients, text_body, html_body)
这是test_mail.py的代码,我正在尝试创建的测试:
from unittest import mock
from app.mail import send_sign_up_mail
@mock.patch('app.mail.send_mail')
def test_send_sign_up_mail(mock_send_mail, user):
send_sign_up_mail(user)
assert mock_send_mail.call_count == 1
参数user是我创建的一个夹具,它正在工作,所以不必担心。
使用pdb调试器,我检查了send_mail函数没有在send_sign_up_mail内部被模拟。