我正在尝试测试我创建的向用户发送欢迎电子邮件的功能。但是,为此,我必须模拟实际发送它的功能(在欢迎电子邮件功能内)。我具有以下文件夹结构:
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,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 中被模拟。