如何使用requests库进行接口测试?
答:
如果有接口文档,先分析接口文档.
如果无接口文档,就先抓取接口并分析接口,设计测试用例,设计断言,编写代码,执行测试,生成测试报告。
#安装requests库
pip install requests
#导入requests模块
import requests
class RequestsMethod:
"""
创建RequestsMethod类
"""
def __init__(self):
"""
再初始化方法中定义url
"""
self.base_url = "http://120.79.30.173:8090/WoniuSales" # url地址
def login_api(self):
"""
登录接口
:return: 返回login_api对象
"""
login_uri = "/user/login" # 定义uri路径
login_data = "username=admin&password=xxxxx&verifycode=0000" # 登录需要提交的数据
custom_header = {"Content-Type": "application/x-www-form-urlencoded"} # 自定义请求头
reponse = requests.request(method='POST', url=self.base_url + login_uri, data=login_data,headers=custom_header) # 响应体
print(reponse.status_code) # 打印状态码
print(reponse.text)
print(reponse.content)
return reponse
def get_cookie(self):
"""
获取cookie
:return: 返回用户登录后的cookie
"""
res = self.login_api()
return res.cookies
def add_member(self):
"""
添加会员
:return:
"""
add_member_uri = "/customer/add" #会员添加的接口
add_member_params = {'customername': "", 'customerphone': 7778888901, 'childsex': "女",
'childdate': "2020-02-05", 'creditkids': 0, 'creditcloth': 0}
reponse = requests.request(method="POST", url=self.base_url + add_member_uri, data=add_member_params,
cookies=self.get_cookie())
print(reponse.status_code)
print(reponse.text)
def requests_upload(self):
"""
批次管理的文件上传函数
:return: upload_uri 是文件上传的接口地址
"""
upload_uri = '/goods/upload' #文件上传的接口
file_data = {"batchname": (None, "GB20200735"), # batchname是批次字段,GB20200735是选择的批次编号
"batchfile": ("anyname", open('../../data/testbatch.xls', 'rb')) #batchfile是文件接收流的字段
}
res = requests.request(method='POST', url=self.base_url + upload_uri, files=file_data,
cookies=self.get_cookie())
print(res.text)
if __name__ == '__main__':
mytest = RequestsMethod()
# mytest.login_api() #登录测试
# mytest.add_member() #添加会员数据测试
mytest.requests_upload() #批次管理模块上传数据测试