1

我的代码的以下部分应该在 HTTP 请求期间进行异常处理。

应用程序.py

class Get:
    def __init__(self, url):
        self.url = url
    def get(self):
        waitingFactor = 1
        for i in range(0,5):   #retries if a timeout error occurs
            waitingFactor = waitingFactor*1.5
            response = requests.get(url)
            try:
                response.raise_for_status()
            except requests.exceptions.Timeout:
                #status code 408
                print("Timeout Error ocurred, program waits and retries again")
                sleep(0.5*waitingFactor)
                continue
            except requests.exceptions.TooManyRedirects:
                #status code 301
                print("Too many redirects")
                raise SystemExit()
            except requests.exceptions.HTTPError as e:
                #overally status codes 400,500, ...
                print("HTTP error, status code is "+ str(response.status_code)+
                    "\nMessage from Server: "+response.content.decode("utf-8") )
                raise SystemExit()
            except requests.exceptions.RequestException as e:
                print(e)
                raise SystemExit()
            break
        print(response)

url  =  "sample url"
getObject = Get(url)

为了模拟不同的异常,我提出了以下函数,它会生成带有所需状态代码的假 HTTP 响应。然后,在类内部,request.get 方法被替换为假的 http 响应,我们可以测试不同状态码的异常处理是如何工作的。

测试.py

def getFakeHTTPResponse(statusCode, text):
    response = requests.models.Response()
    response.status_code = statusCode
    response._content = text.encode("utf-8")
    response.encoding = "utf-8"
    return response

class TestRequest(unittest.TestCase):

    @patch("app.requests.get", return_value=getFakeHTTPResponse(400,"A fake message from server"))
    def testRequest(self, mock1):
        print("hi")
        app.getObject.get()

if __name__ == '__main__':
    unittest.main()

给定状态代码:400,我在终端中正确收到以下 HTTP 错误,这意味着我的代码运行良好:

HTTP error, status code is 400
Message from Server: Any Message

我的问题是,代码不会对其他情况进行异常处理(例如,重定向过多、超时等)。例如,如果我使用状态码:301 做出虚假的 http 响应,我希望获得太多重定向的异常处理消息。但这根本不会发生。你的建议是什么?

4

0 回答 0