• python--requests接口测试


    介绍

    requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到,Requests是Python语言的第三方的库,专门用于发送HTTP请求

    需要下载: pip install requests

    get请求

    GET无参请求

    r  = requests.get('http://www.baidu.com')

    GET传参

    payload = {'key1': 'value1', 'key2': 'value2', 'key3': None}
    r = requests.get('http://www.baidu.com ', params=payload)

    1. 测试聚合数据中查询手机号归属地接口
    2. import requests
    3. class UseRequestClass():
    4. #get传参的第一种方式
    5. def XWTTMethod(self):
    6. r = requests.get("http://v.juhe.cn/toutiao/index?type=guonei&key=4b72107de3a197b3bafd9adacf685790")
    7. print(r.text,r.json(),r.status_code)
    8. #get传参的第二种方式
    9. def XWTTMethod(self):
    10. params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
    11. r = requests.get("http://v.juhe.cn/toutiao/index",params=params)
    12. print(r.text)

    post请求

     payload = {'key1': 'value1', 'key2': 'value2'}
     r = requests.post("http://httpbin.org/post", data=payload)

    1. 测试聚合数据中新闻头条接口
    2. import requests
    3. class UseRequestClass():
    4. def XWTTPostMethod(self):
    5. params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
    6. r = requests.post("http://v.juhe.cn/toutiao/index",data=params)
    7. #print(r.json())
    8. return r.json()

    Requests响应

    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)

     

    requests+unittest+HtmlTestRunner  /  requests+pytest+allure

     自动化接口测试流程

    首先在数据包中存储接口的测试数据比如csv文件,excel文件等,实现数据和代码逻辑的分离
    然后在读取数据的包中实现读取文件的获取数据的操作
    接着在测试用例包中导入读取数据模块,通过requests的get/post方法获取该接口的返回数据的信息在单元测试模块(unittest/pytest)中通过断言验证返回的值和预期结果是否一致
    最终结果打印在html类型的测试报告中

    读取csv文件流程

    存储数据(csv)

     

    读取数据(readDemo)

    1. import csv
    2. class ReadCsv():
    3. def read_csv(self):
    4. item = []
    5. c = csv.reader(open("../data/datacsv.csv"))
    6. for i in c:
    7. item.append(i)
    8. item = item[1::]
    9. return item

    在测试用例中执行requests请求,验证预期结果和实际结果

    1. import pytest,requests
    2. from readdata.readcsv import ReadCsv
    3. r = ReadCsv()
    4. readdataresult = r.read_csv()
    5. class TestCsv1():
    6. def test_001(self):
    7. for i in readdataresult:
    8. cs = eval(i[1])
    9. if i[2] == "get":
    10. resultdata = requests.get(url=i[0],params=cs)
    11. assert resultdata.json()["error_code"] == int(i[3])
    12. else:
    13. resultdata = requests.post(url=i[0], data=cs)
    14. assert resultdata.json()["error_code"] == int(i[3])
    15. if __name__ == '__main__':
    16. pytest.main(["testcsv_py.py","--html=./report1.html"])
    1. import unittest,requests
    2. from readdata.readcsv import ReadCsv
    3. r = ReadCsv()
    4. readdataresult = r.read_csv()
    5. class TestCsv(unittest.TestCase):
    6. def test_001(self):
    7. for i in readdataresult:
    8. cs = eval(i[1])
    9. if i[2] == "get":
    10. resultdata = requests.get(url=i[0],params=cs)
    11. self.assertEqual(resultdata.json()["error_code"],int(i[3]))
    12. else:
    13. resultdata = requests.post(url=i[0], data=cs)
    14. self.assertEqual(resultdata.json()["error_code"], int(i[3]))
    15. if __name__ == '__main__':
    16. unittest.main()

    生成测试报告

    1. import unittest
    2. from testcase.testcsv_unit import TestCsv
    3. from common.HTMLTestRunner import HTMLTestRunner
    4. class TestHtmlReportClass():
    5. #生成测试报告
    6. def export_testhtmlreport(self):
    7. # 创建测试套件
    8. suite= unittest.TestSuite()
    9. list_i=["test_001"]
    10. for i in list_i:
    11. suite.addTest(TestCsv(i)) #将测试用例添加到测试套件里
    12. with open("./report.html", "wb") as f:
    13. HTMLTestRunner(
    14. stream=f,
    15. title="自动化接口测试",
    16. description="HTML单元测试报告",
    17. verbosity=2
    18. ).run(suite)
    19. t = TestHtmlReportClass()
    20. t.export_testhtmlreport()

     

    读取excle文件流程

    存储数据(xlsx)

     

    读取数据(readDemo)

    1. from openpyxl import load_workbook
    2. class UseExcel():
    3. def get_TestExcel(self):
    4. # 打开表
    5. workbook = load_workbook('D:\install\python\python\Test_allure\DataDemo\test1.xlsx')
    6. # 定位表单
    7. sheet = workbook['Sheet1']
    8. print(sheet.max_row) #3 行
    9. print(sheet.max_column) #3 列
    10. test_data = []#把所有行的数据放到列表中
    11. for i in range(2,sheet.max_row+1):
    12. sub_data = {}#把每行的数据放到字典中
    13. for j in range(1,sheet.max_column+1):
    14. sub_data[sheet.cell(1,j).value] = sheet.cell(i,j).value
    15. test_data.append(sub_data)#拼接每行单元格的数据
    16. return test_data
    17. t = UseExcel()
    18. f = t.get_TestExcel()
    19. print(f)

    测试用例中发送请求,设置断言并生成测试报告中

    1. import requests,pytest,os,allure
    2. from readDemo.readexcel import UseExcel
    3. ue = UseExcel()
    4. data= ue.get_TestExcel()
    5. class TestExcelClass():
    6. def test001(self):
    7. for list_i in data:
    8. path = eval(list_i["parameter"])
    9. if list_i["method"] =="get":
    10. objects = requests.get(url=list_i["url"],params=path)
    11. assert objects.json()["error_code"] == int(list_i["assert"])
    12. else:
    13. objects = requests.post(url=list_i["url"],data=path)
    14. assert objects.json()["error_code"] == int(list_i["assert"])
    15. if __name__ == '__main__':
    16. # 生成测试报告json
    17. pytest.main(["-s", "-q", '--alluredir', 'report/result', 'request002.py'])
    18. # 将测试报告转为html格式
    19. split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'
    20. os.system('cd D:\install\python/python\Test_allure\Test/test\report')
    21. os.system(split)


    接口测试中接口的关联

     将变量设置为全局变量,在下一个接口中调用

    1. import requests,pytest
    2. class TestApiAutoClass():
    3. city = ''
    4. def test_method1(self): #查询手机号归属地
    5. result = requests.get("http://apis.juhe.cn/mobile/get",{"phone":"15937373171","key":"a10c1058f273546302fcd37121d6037a"})
    6. global city
    7. city = result.json()["result"]["city"]
    8. assert result.json()["error_code"] == 0
    9. def test_method2(self): #查询天气预报
    10. result = requests.get(url="http://apis.juhe.cn/simpleWeather/query",params={"city":city,"key":"d7d581f072ed2bb6aab6083848ddefed"})
    11. assert result.json()["error_code"] == 0
    12. print(result.json())
    13. if __name__ == '__main__':
    14. pytest.main(['-s',"testapiassociation.py"])

  • 相关阅读:
    认识 ArkTS 语法
    【开源】JAVA+Vue.js实现个人健康管理系统
    MyBatis的缓存,一级缓存,二级缓存
    拦 截 器
    Linux防火的常用命令
    Python Opencv实践 - 模板匹配(Template Matching)
    疯狂星期四,但是程序员
    使用注解开发,lombox P16,P17,P18
    【leetcode】有效的回文
    Linux 串口工具 cutecom
  • 原文地址:https://blog.csdn.net/m0_72596958/article/details/126550175