python - 如何验证函数是否已被pytest命中
问题描述
我试过这个:
def test_send_confirm_hit(monkeypatch):
hit = False
def called():
global hit
hit = True
monkeypatch.setattr("web.email.send_confirm", called)
# ... some event that will cause web.email.send_confirm to be hit
assert hit # verify send_confirm was hit
尽管我宁愿不使用全局变量,但这似乎可行。做这个的最好方式是什么?
解决方案
如果您使用“正确”的模拟,它带有一个.assert_called()
方法:
import unittest.mock
def test_send_confirm_hit(monkeypatch):
mock_send_confirm = unittest.mock.Mock()
monkeypatch.setattr("web.email.send_confirm", mock_send_confirm)
# ... some event that will cause web.email.send_confirm to be hit
mock_send_confirm.assert_called()
推荐阅读
- vba - Excel VBA 命名和更改 Power Query 的来源
- r - 在 Rmarkdown 中的参考书目后添加图形和表格
- android - Fragment.onCreateView 中的 OutOfMemoryError
- python - 如果数据库中不存在,则将输入标签添加到文章并创建新的标签记录
- machine-learning - Keras:为什么'accuracy'比'val_acc'高?
- reactjs - 将 JSX 注入到 React Native 组件中
- laravel - 动态下拉laravel服务器错误
- java - 从 Linux EXTREME VPS 读取文件时找不到文件异常
- sql - 选择具有不同字段 SQL 的多个名称
- r - ggplot2 texashousing 数据平滑短期噪声