前提:pip install requests
get的请求:r = requests.get('http://www.baidu.com', params=payload)
post请求:r =requests.post("http://httpbin.org/post", data=payload)
Requests响应:
r.status_code 响应状态码r.heards 响应头r.cookies 响应cookiesr.text 响应文本r. encoding 当前编码r. content 以字节形式(二进制)返回
最常用的是根据响应状态码判断接口是否连通,经常用于做接口中断言判断
requests+pytest+allure
流程如下
读取文件中的数据requests拿到数据请求接口返回状态码通过断言验证返回状态码和200对比生成allure的测试报告
模块总览:
dataDemo(存放数据)>> readDemo(读取数据)
useRequests(发送请求)>>testDemo(生成报告)
1.读取csv文件流程:通过excel另存为csv即可
2.读取数据(readDemo):
importcsvclassReadCsv():defreadCsv(self):item=[]rr=csv.reader(open("../dataDemo/123.csv"))forcsv_iinrr:item.append(csv_i)item=item[1:]returnitem
3.request请求接口返回状态码
importrequestsfromreadDataDemo.readcsvimportReadCsvr=ReadCsv()ee=r.readCsv()# print(ee)classRequestCsv():defrequestsCsv(self):item=[]forcsv_iinee:ifcsv_i[2]=="get":rr=requests.get(csv_i[0],params=csv_i[1])item.append(rr.status_code)else:rr=requests.post(csv_i[0],data=csv_i[1])item.append(rr.status_code)returnitem
pytest断言设置并结合allure生成测试报告
importpytest,os,allurefromuserequests.userequestsDemo.requestscsvimportRequestCsvr=RequestCsv()ee=r.requestsCsv()print(ee)classTestClass02():deftest001(self):forcodeinee:assertcode==200if__name__=='__main__':pytest.main(['--alluredir','report/result','test_02csv.py'])split='allure '+'generate '+'./report/result '+'-o '+'./report/html '+'--clean'os.system(split)
读取excle文件流程
1 存储数据(xlsx)
2 读取数据(readDemo)
安装openpyxl:pip install openpyxl
fromopenpyxlimportload_workbookclassReadxcel():defgetTestExcel(self):# 打开表workbook=load_workbook("G:\python\pythonProject\pytest05a\\requestdemo\\a.xlsx")# 定位表单sheet=workbook['Sheet1']print(sheet.max_row)# 3 行print(sheet.max_column)# 3 列test_data=[]# 把所有行的数据放到列表中foriinrange(2,sheet.max_row+1):sub_data={}# 把每行的数据放到字典中forjinrange(1,sheet.max_column+1):sub_data[sheet.cell(1,j).value]=sheet.cell(i,j).value test_data.append(sub_data)# 拼接每行单元格的数据returntest_datat=Readxcel()f=t.getTestExcel()print(f)
3 request请求接口返回状态码
importrequestsfromrequestdemo.readexcelimportReadxcelclassGetStatusCode():defgetStatusCode(self):t=Readxcel()f=t.getTestExcel()item=[]forexcel_iinf:ifexcel_i["method"]=="get":rr=requests.get(excel_i["url"],params=excel_i["params"])item.append(rr.status_code)else:rr=requests.post(excel_i["url"],data=excel_i["params"])item.append(rr.status_code)returnitemprint(GetStatusCode().getStatusCode())
4 pytest断言设置并结合allure生成测试报告
importallure,pytest,osfromrequestdemo.getStatusCodeimportGetStatusCodeget=GetStatusCode()statusCodes=get.getStatusCode()classTestReadExcel():deftestReadExcel(self):forcodeinstatusCodes:assertcode==200if__name__=="__main__":# 生成测试报告jsonpytest.main(["-s","-q",'--alluredir','report/result','testreadexcel.py'])# 将测试报告转为html格式split='allure '+'generate '+'./report/result '+'-o '+'./report/html '+'--clean'os.system(split)