我目前正在使用Pytest,我需要了解如何使用monkeypatch特性来模拟包含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.
为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