接口测试框架——第三篇:发送(requests)
把下面的代码放在requests_module.py文件中
# coding: utf-8
import requests
import logging
from requests.exceptions import *
class GetResponse():
def __init__(self, url, method='get'):
self.__url = url
self.__method = method.lower()
self.with_session = requests.session()
def get_response(self, session=False, *args, **kwargs): if self.__method == 'get' and session == False:
try:
__resp = requests.get(self.__url, *args, **kwargs)
except (MissingSchema, InvalidURL):
logging.error(u'请检查url:%s 是否正确' % self.__url)
except ConnectionError:
logging.error(u'网络连接失败或接口响应时间过长')
else:
return __resp
elif self.__method == 'get' and session == True:
try:
__resp = self.with_session.get(self.__url, *args, **kwargs)
except (MissingSchema, InvalidURL):
logging.error(u'请检查url:%s 是否正确' % self.__url)
except ConnectionError:
logging.error(u'网络连接失败或接口响应时间过长')
else:
return __resp
elif self.__method == 'post' and session == False:
try:
__resp = requests.post(self.__url, *args, **kwargs)
except (MissingSchema, InvalidURL):
logging.error(u'请检查url:%s 是否正确' % self.__url)
except ConnectionError:
logging.error(u'网络连接失败或接口响应时间过长')
else:
return __resp
elif self.__method == 'post' and session == True:
try:
__resp = self.with_session.post(self.__url, *args, **kwargs)
except (MissingSchema, InvalidURL):
logging.error(u'请检查url:%s 是否正确' % self.__url)
except ConnectionError:
logging.error(u'网络连接失败或接口响应时间过长')
else:
return __respclass AnalysisResponse(object):
"""
解析response:response为一大段字符串,该类将这个大串字符串中有用的内容提取出来
"""
def __init__(self, resp):
self.__resp = resp
@property
def Url(self):
__url = self.__resp.url
return __url
@property
def Status_code(self):
__status_code = self.__resp.status_code
return __status_code
@property
def Str_Content(self):
"""
返回string类型的content
"""
__str_content = self.__resp.content
return __str_content
@property
def Dic_Content(self):
"""
将response转换成字典后返回
"""
__dic_content = self.__resp.json()
return __dic_content
@property
def Headers(self):
__headers = self.__resp.headers
return __headers
@property
def Cookies(self):
__cookies = self.__resp.cookies
return __cookies
发送的方法了,我们看到它会根据你传入接口的http请求选择发送方式,并且判断了是否含有session,session可以省去你登录的时候再去校验cookies。是不是对__xx不太熟悉?你需要复习前面的内容了
微信公众号搜索“自动化测试实战”或扫描下方二维码添加关注~~~