requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到,Requests是Python语言的第三方的库,专门用于发送HTTP请求
需要下载: pip install requests
r = requests.get('http://www.baidu.com')
payload = {'key1': 'value1', 'key2': 'value2', 'key3': None}
r = requests.get('http://www.baidu.com ', params=payload)
- 测试聚合数据中查询手机号归属地接口
- import requests
- class UseRequestClass():
- #get传参的第一种方式
- def XWTTMethod(self):
- r = requests.get("http://v.juhe.cn/toutiao/index?type=guonei&key=4b72107de3a197b3bafd9adacf685790")
- print(r.text,r.json(),r.status_code)
- #get传参的第二种方式
- def XWTTMethod(self):
- params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
- r = requests.get("http://v.juhe.cn/toutiao/index",params=params)
- print(r.text)
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
- 测试聚合数据中新闻头条接口
- import requests
- class UseRequestClass():
- def XWTTPostMethod(self):
- params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
- r = requests.post("http://v.juhe.cn/toutiao/index",data=params)
- #print(r.json())
- return r.json()
r.status_code 响应状态码
r.heards 响应头
r.cookies 响应cookies
r.text 响应文本
r.json() 响应的字典类型数据
r. encoding 当前编码
r. content 以字节形式(二进制)返回
扩充
1:添加等待时间
requests.get(url,timeout=1) #超过等待时间则报错
2:添加请求头信息
requests.get(url,headers=headers) #设置请求头
3:添加文件
requests.post(url, files=files) #添加文件
文件传输
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
首先在数据包中存储接口的测试数据比如csv文件,excel文件等,实现数据和代码逻辑的分离
然后在读取数据的包中实现读取文件的获取数据的操作
接着在测试用例包中导入读取数据模块,通过requests的get/post方法获取该接口的返回数据的信息在单元测试模块(unittest/pytest)中通过断言验证返回的值和预期结果是否一致
最终结果打印在html类型的测试报告中
存储数据(csv)
读取数据(readDemo)
- import csv
- class ReadCsv():
- def read_csv(self):
- item = []
- c = csv.reader(open("../data/datacsv.csv"))
- for i in c:
- item.append(i)
- item = item[1::]
- return item
在测试用例中执行requests请求,验证预期结果和实际结果
- import pytest,requests
- from readdata.readcsv import ReadCsv
- r = ReadCsv()
- readdataresult = r.read_csv()
- class TestCsv1():
- def test_001(self):
- for i in readdataresult:
- cs = eval(i[1])
- if i[2] == "get":
- resultdata = requests.get(url=i[0],params=cs)
- assert resultdata.json()["error_code"] == int(i[3])
- else:
- resultdata = requests.post(url=i[0], data=cs)
- assert resultdata.json()["error_code"] == int(i[3])
-
- if __name__ == '__main__':
- pytest.main(["testcsv_py.py","--html=./report1.html"])
- import unittest,requests
- from readdata.readcsv import ReadCsv
- r = ReadCsv()
- readdataresult = r.read_csv()
- class TestCsv(unittest.TestCase):
- def test_001(self):
- for i in readdataresult:
- cs = eval(i[1])
- if i[2] == "get":
- resultdata = requests.get(url=i[0],params=cs)
- self.assertEqual(resultdata.json()["error_code"],int(i[3]))
- else:
- resultdata = requests.post(url=i[0], data=cs)
- self.assertEqual(resultdata.json()["error_code"], int(i[3]))
- if __name__ == '__main__':
- unittest.main()
生成测试报告
- import unittest
- from testcase.testcsv_unit import TestCsv
- from common.HTMLTestRunner import HTMLTestRunner
- class TestHtmlReportClass():
- #生成测试报告
- def export_testhtmlreport(self):
- # 创建测试套件
- suite= unittest.TestSuite()
- list_i=["test_001"]
- for i in list_i:
- suite.addTest(TestCsv(i)) #将测试用例添加到测试套件里
- with open("./report.html", "wb") as f:
- HTMLTestRunner(
- stream=f,
- title="自动化接口测试",
- description="HTML单元测试报告",
- verbosity=2
- ).run(suite)
- t = TestHtmlReportClass()
- t.export_testhtmlreport()
存储数据(xlsx)
读取数据(readDemo)
- from openpyxl import load_workbook
- class UseExcel():
- def get_TestExcel(self):
- # 打开表
- workbook = load_workbook('D:\install\python\python\Test_allure\DataDemo\test1.xlsx')
- # 定位表单
- sheet = workbook['Sheet1']
- print(sheet.max_row) #3 行
- print(sheet.max_column) #3 列
- test_data = []#把所有行的数据放到列表中
- for i in range(2,sheet.max_row+1):
- sub_data = {}#把每行的数据放到字典中
- for j in range(1,sheet.max_column+1):
- sub_data[sheet.cell(1,j).value] = sheet.cell(i,j).value
- test_data.append(sub_data)#拼接每行单元格的数据
- return test_data
- t = UseExcel()
- f = t.get_TestExcel()
- print(f)
测试用例中发送请求,设置断言并生成测试报告中
- import requests,pytest,os,allure
- from readDemo.readexcel import UseExcel
- ue = UseExcel()
- data= ue.get_TestExcel()
- class TestExcelClass():
- def test001(self):
- for list_i in data:
- path = eval(list_i["parameter"])
- if list_i["method"] =="get":
- objects = requests.get(url=list_i["url"],params=path)
- assert objects.json()["error_code"] == int(list_i["assert"])
- else:
- objects = requests.post(url=list_i["url"],data=path)
- assert objects.json()["error_code"] == int(list_i["assert"])
- if __name__ == '__main__':
- # 生成测试报告json
- pytest.main(["-s", "-q", '--alluredir', 'report/result', 'request002.py'])
- # 将测试报告转为html格式
- split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'
- os.system('cd D:\install\python/python\Test_allure\Test/test\report')
- os.system(split)
将变量设置为全局变量,在下一个接口中调用
- import requests,pytest
- class TestApiAutoClass():
- city = ''
- def test_method1(self): #查询手机号归属地
- result = requests.get("http://apis.juhe.cn/mobile/get",{"phone":"15937373171","key":"a10c1058f273546302fcd37121d6037a"})
- global city
- city = result.json()["result"]["city"]
- assert result.json()["error_code"] == 0
- def test_method2(self): #查询天气预报
- result = requests.get(url="http://apis.juhe.cn/simpleWeather/query",params={"city":city,"key":"d7d581f072ed2bb6aab6083848ddefed"})
- assert result.json()["error_code"] == 0
- print(result.json())
- if __name__ == '__main__':
- pytest.main(['-s',"testapiassociation.py"])