本篇来介绍请求异常。requests库中有一个RequestException的父类,它下面有很多种不同的异常分类。为什么要考虑异常呢,因为很多开发都不考虑异常,特别是调用第三方API的时候,他们认为第三方服务是一直工作的。作为测试,更加需要考虑异常,测试接口,需要测试正常的工作,更新需要测试异常。找出在异常情况下接口或者程序的反应,这个才是测试工程师的最大价值。而不是永远考虑软件在做对的事情,而不去考虑异常,去测试软件在处理异常的能力。
1.我们来举例一个请求超时异常
import json
import requests
from requests import exceptions
URL = 'https://api.github.com'
def build_uri(endpoint):
return '/'.join([URL, endpoint])
def better_output(json_str):
return json.dumps(json.loads(json_str), indent=4)
def timeout_request():
try:
response = requests.get(build_uri('user/emails'),auth=('xxxxxx','password'),timeout=0.1)
except exceptions.Timeout as e:
print(str(e))
else:
print(response.text)
if __name__ == '__main__':
timeout_request()
2. 运行结果
HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: /user/emails
(Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x03170ED0>,
'Connection to api.github.com timed out. (connect timeout=0.1)'))
因为我们设置了请求时间不能超过0.1秒,这个github,在中国发生请求,0.1秒是不能完成的任务,所以会报超时的异常。你可以设置10秒试试。3.查看不同异常方法
鼠标移动到exceptions,按下ctrl,点击这个单词,就打开了exceptions类,包含这些异常。
HTTPError
ConnectionError
ProxyError
SSLError
Timeout
ConnectTimeout
ReadTimeout
URLRequired
TooManyRedirects
MissingSchema
InvalidSchema
InvalidURL
InvalidHeader
ChunkedEncodingError
ContentDecodingError
StreamConsumedError
RetryError
UnrewindableBodyError