python - Python unittest.mock.patch 未按预期工作
问题描述
我正在尝试测试我创建的向用户发送欢迎电子邮件的功能。但是,要做到这一点,我必须模拟实际发送它的函数(在欢迎电子邮件函数中)。我有以下文件夹结构:
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内部被模拟。
解决方案
推荐阅读
- ios - 在 Spritekit 中创建暂停菜单
- networking - 如何将击键/交互式 gui 发送到另一台 Win10 机器?
- reactjs - 布局表反应原生
- python - 查找数组中最大负元素和最小正元素的索引
- sql-server - 如何使用存储过程或函数在 T-SQL 中返回两个表?
- spring - Salesforce 的 OAuth2RestTemplate 给出错误 - HTTP 400 错误请求
- mysql - MySQL中按日期和用户列的累积和分组
- python - “webdriver.Firefox”的返回值记录在哪里?(硒/网络驱动程序)
- php - 在 wordpress 中为 orderby 函数添加元数据
- javascript - Sequelize 原始查询格式日期时间