【问题标题】:PYTEST: Get different response with different arg passing in monkeypatch on same function/api callPYTEST:在同一函数/api调用中通过monkeypatch传递不同的参数获得不同的响应
【发布时间】:2021-10-06 06:04:20
【问题描述】:

我正在工作 pytest,我需要知道如何猴子具有 api 调用的函数并根据 for 循环中的一些不同输入获得不同的响应。

例如:

value_1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
value_2 = {'key11': 'value11', 'key22': 'value22' 'key33': 'value33'}

class MockResponse:

    @staticmethod
    def json():
        return load_data("total_res.json")

class GetEntities:
    

   def mock_res(*args, **kwargs):
      return MockResponse().json()

   monkeypatch.setattr(api_funct, "get_data", mock_res)
   
   #test-function which have api call.

例如:始终发送相同的 json 文件 total_res 但我需要根据我的不同输入获得不同的响应,例如 value_1 和 value_2。

基本上 mock_res 应该使用不同的 json 文件发送。

在下面尝试过 - 不起作用:

    class MockResponse:
    
        @staticmethod
        def json(data_entry = "total_res.json"):
            if data_entry == "total_res.json":
                return load_data("total_res.json")
            elif data_entry == "value_1":
                return value_1
            elif data_entry == "value_2":
                return value_2
            else:
                print("There is no such data!")
                return None
    
    class GetEntities:
        
    
       def mock_res(data_entry):
          return MockResponse().json(data_entry)
       data_entry = # Type of response to get

       monkeypatch.setattr(api_funct, "get_data", mock_res(data_entry))
       
       #test-function which have api call.

【问题讨论】:

  • unittest.mock.Mock 可以通过 side effect 做到这一点。
  • 您能否举例说明解决方案,请@KlausD。

标签: python python-3.x unit-testing pytest testcase


【解决方案1】:

json() 静态函数定义一个输入参数:

def json(data_entry = "total_res.json"):
        if data_entry == "total_res.json":
            return load_data("total_res.json")
        elif data_entry == "value_1":
            return value_1
        elif data_entry == "value_2":
            return value_2
        else:
            print("There is no such data!")
            return None

【讨论】:

  • 好的,但是我需要如何/在哪里传递 arug 类 MockResponse 和 monkeypatch.setattr(api_funct, "get_data", mock_res) json(input_date) 知道并决定返回文件... @ Behdad Abdollahi Moghadam
  • 你能解释一下monkeypatch对象在这段代码中的作用吗?你有它的代码吗?
  • 在 api_funct.py 文件中,get_data 函数有 externalapi 连接,根据有效负载发送不同的响应。虽然 pytest,我不需要等待很长时间才能得到响应,所以我喜欢使用 monkeypatch。但这里的问题是如何根据某些变量或输入获得不同的响应。我浏览了monkeypatch 文档,但找不到解决方案。 @Behdad Abdollahi Moghadam
猜你喜欢
  • 2015-11-29
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
相关资源
最近更新 更多