我需要在单元测试中模拟以下方法。
def get_app_info(role):
conn = http.client.HTTPSConnection(url)
conn.request(
method="GET",url="/v1/profile",headers={
"appName": app["name"],"appRole": role
}
)
response = conn.getresponse()
res_data = json.load(response)
conn.close()
return res_data
我尝试修补@patch('http.client.HTTPSConnection')
,因此请求在嘲笑,但由于以下错误而在json.load
失败。
提高TypeError(f'JSON对象必须为str,字节或字节数组,' TypeError:JSON对象必须是str,bytes或bytearray,而不是 魔术模拟
我尝试如下模拟
def mocked_response(*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
return MockResponse(
{
"url": "/test/home
},200)
class MyGreatClassTestCase(unittest.TestCase):
@patch('http.client.HTTPSConnection')
@patch('http.client.HTTPResponse')
def test_retrive_token(self,mock_con,mock_resp,side_effect = mocked_response):
json_data = common.retrieve_access_token("sometoken")
print(json_data)
任何输入均受到高度赞赏。