【问题标题】:Pytest-mock not patching imported function in class modulePytest-mock 不修补类模块中的导入函数
【发布时间】:2021-06-07 13:12:49
【问题描述】:

pytest-mock 补丁无法按预期工作。我的代码:

utils.py:

def my_func():
    return 42

classes.py:

from utils import my_func

class MyClass:
    def class_method(self):
        return my_func()

test_classes.py:

import pytest
from classes import MyClass

def test_myclass(mocker):
    mocker.patch("utils.my_func", return_value=21)
    assert MyClass().class_method() == 21

这失败了,返回的是42而不是21

【问题讨论】:

    标签: pytest pytest-mock


    【解决方案1】:

    解决方案是在测试中更改补丁。而不是

    mocker.patch("utils.my_func", return_value=21)
    

    mocker.patch("classes.my_func", return_value=21)
    

    因为classes.py中的这一行:from .utils import my_func

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      相关资源
      最近更新 更多