gpt4 book ai didi

python - 如何验证一个函数是否被 pytest 命中

转载 作者:行者123 更新时间:2023-12-04 16:45:24 31 4
gpt4 key购买 nike

我试过这个:

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() method :

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()

关于python - 如何验证一个函数是否被 pytest 命中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64407497/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com