模拟补丁没有正确替换功能

Mock patch not replacing function correctly

我有一个 tastypie REST API 资源,假设称为 Resource,它在其 [=14= 中导入并使用来自 libs.utils 的名为 get_token 的函数] 方法。

所以为了测试这个资源,在我的测试中 class 我创建了一个如下所示的测试:

mock_get_token = Mock(return_value="something")

@patch("path.to.resource.get_token", mock_get_token)
def test_get_token(self):
    params = {"args": "args"}
    # following call should call the get_token function in the resource
    response = self.client.get("path/to/resource", params)
    # do things with the response and make sure I get right output

因此,当我 运行 自己进行测试时,@patch 会按预期正常工作,将函数替换为模拟函数。但是,运行在我们更大的应用程序测试套件中进行测试会导致补丁失败。

手动尝试用模拟函数替换函数之类的操作也有不成功的补丁。我想知道还有什么可能导致这个问题,我发现当测试本身或我们的测试套件的较小子集 运行 时补丁正常工作是非常奇怪的。

我们无法找出确切的解决方案,但解决方法是,由于 obj_get 方法中的大部分逻辑都由另一个函数 api_call() 处理,我们模拟了对api_call 函数。

所以这个问题似乎是一些导入问题,因为 api_call 没有导入任何地方。