【发布时间】: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