【问题标题】:Mock patch not replacing function correctly模拟补丁无法正确替换功能
【发布时间】:2016-11-15 07:49:24
【问题描述】:

我有一个美味的 REST API 资源,假设称为 Resource,它在其 obj_get 方法中从 libs.utils 导入并使用一个名为 get_token 的函数。

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

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 可以正常工作并按预期工作,将函数替换为模拟函数。但是,在我们更大的应用程序测试套件中运行测试会导致补丁失败。

手动尝试将函数替换为模拟函数之类的操作也有一个不成功的补丁。我想知道还有什么可能导致该问题,并且我非常好奇补丁在单独运行测试或与我们的测试套件的较小子集运行时能够正常工作。

【问题讨论】:

    标签: python django unit-testing mocking django-testing


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 2011-08-19
      • 2023-03-24
      • 1970-01-01
      • 2012-04-15
      • 2020-11-26
      相关资源
      最近更新 更多