首页 > 解决方案 > 如何验证函数是否已被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

尽管我宁愿不使用全局变量,但这似乎可行。做这个的最好方式是什么?

标签: pythontestingpytestmonkeypatching

解决方案


如果您使用“正确”的模拟,它带有一个.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()

推荐阅读