我的功能如下:
#define P(X) {(LED##X##_PIN)}
ioport_pin_t *commands[LED_COUNT] = {
P(0), P(1), P(2),......}
#undefine P
我做了一个测试:
def request_API(request_url): #To test
fail_request = -1
response = requests.get(request_url)
if response.ok:
infos = json.loads(response.text)
if infos.has_key("movie"):
return infos["movie"]
if infos.has_key("tvseries"):
return infos["tvseries"]
print "Allocine API Request Error"
return fail_request
但我有一个错误:
def test_should_fail_to_request(self):
#GIVEN
response = json.dumps({"error":{"code":0,"$":"No result"}})
requests.get = mock.MagicMock(return_value=response)
#WHEN
response = my_mod.request_allocine_API("") #requests mocked so we don't need an URL
#THEN
self.assertEqual(response, -1, "There should be an error in the API")
我知道这是因为当我模拟request.get时,我返回一个JSON。我的问题是做到这一点的正确方法是什么。我是否要重新创建对象请求,或者有更简单的方法来执行此操作。
答案 0 :(得分:1)
您正在模拟requests.get
,它通常会返回一个Response
对象,而是返回一个纯字符串。尝试让它返回Response
对象:
from mock import patch
from requests import Response
def test_should_fail_to_request(self):
mock_response = Response()
mock_response.status_code = 404
mock_response.body = json.dumps({"error":{"code":0,"$":"No result"}})
with patch('requests.get', return_value=mock_response):
response = my_mod.request_allocine_API("")
self.assertEqual(response, -1, "There should be an error in the API")
答案 1 :(得分:1)