我在一个名为libs的文件夹(部分代码)中有一个如下类:
import requests
import json
import logging
class IdefixAPI:
def get_events(self, create_from, create_to):
"""récupération des events pour une période passée en paramètre"""
url = "".join([self.api_base_url,
self.monitoring_api_url,
self.monitor_event_search])
try:
response = self.session.get(
url,
data={"CreateFrom": create_from,
"CreateTo": create_to})
return response
except requests.exceptions.RequestException as e:
logging.exception(e)
raise
我在libs文件夹之外的名为tests的文件夹中有一个单元测试,如下所示:
class Test_Idefix(unittest.TestCase):
def mocked_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
def status_code():
return self.status_code
if 'Search' in args[0]:
return MockResponse({"key1": "value1"}, 200)
elif args[0] == 'http://someotherurl.com/anothertest.json':
return MockResponse({"key2": "value2"}, 200)
return MockResponse({"None": "None"}, 404)
@mock.patch('libs.Idefix.requests', side_effet=mocked_requests_get)
def test_get_events(self, mock_get):
instance = libs.Idefix.IdefixAPI(username=idefix_user, password=decode(
key=key, password=idefix_pass))
instance.login()
json_data = instance.get_events("a", "b").json()
self.assertEqual(json_data, {'None': 'None'})
如果我运行单元测试,则会收到以下assertionError:
AssertionError: <MagicMock name='requests.session().get().json()'id='4544441256'> != {'None': 'None'}
我该如何模拟IdefixAPI类的请求会话获取? 在我的MockResponse中,我模拟了一个MockResponse。但是似乎json_data变量只是一个模拟对象