You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pytest与mocker模拟函数时出现补丁错误的问题排查

解决pytest-mock模拟validate_email_exists的问题

问题原因拆解

  • 第一个报错是patch路径写错了:library.brouhaha.general完全不存在,bourhaha.py是单个模块文件,不是包结构,没法通过它访问同级的general模块。
  • 第二个测试失败的核心是mock的目标不对:如果你的bourhaha.py里是这么导入的——from library.general import validate_email_exists,那create_username调用的其实是bourhaha模块自己命名空间里的validate_email_exists引用,不是原general模块里的函数。你patch原模块的函数,根本影响不到已经导入到bourhaha里的这个引用。

正确的mock方式

你需要patch的是bourhaha模块中已经导入的那个validate_email_exists对象,路径写成library.bourhaha.validate_email_exists就行。

测试代码示例

def test_create_username(mocker):
    # 模拟函数返回你需要的值,比如False
    mock_validate = mocker.patch("library.bourhaha.validate_email_exists")
    mock_validate.return_value = False

    # 导入并调用被测试函数
    from library.bourhaha import create_username
    username = create_username("test@example.com")
    
    # 做断言
    assert username == "你预期的用户名结果"
    # 验证mock被正确调用
    mock_validate.assert_called_once_with("test@example.com")

核心逻辑

pytest-mock的patch是基于模块命名空间生效的:当你把一个函数从模块A导入到模块B,模块B里就会生成一个该函数的本地引用。被测试代码调用的是这个本地引用,所以必须patch这个本地引用所在的路径,而不是原函数的路径。

内容的提问来源于stack exchange,提问作者Danny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 14:50:01