佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > Python中requests做接口測試的方法

Python中requests做接口測試的方法

熱門標簽:呼叫中心市場需求 銀行業(yè)務 檢查注冊表項 鐵路電話系統(tǒng) 網(wǎng)站文章發(fā)布 智能手機 美圖手機 服務器配置

一、介紹

Requests是一個很實用的Python HTTP客戶端庫,編寫爬蟲和測試服務器響應數(shù)據(jù)時經(jīng)常會用到,Requests是Python語言的第三方的庫,專門用于發(fā)送HTTP請求

二、前提

pip install requests

三、get的請求

3.1 GET無參請求

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

3.2 GET傳參

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

案例:測試聚合數(shù)據(jù)

代碼

import requests
class UseRequestClass():
    #get傳參的第一種方式
    def XWTTMethod(self):
        r = requests.get("http://v.juhe.cn/toutiao/index?type=guoneikey=4b72107de3a197b3bafd9adacf685790")
        print(r.text)
    #get傳參的第二種方式
    def XWTTMethod(self):
        params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
        r = requests.get("http://v.juhe.cn/toutiao/index",params=params)
        print(r.text)

四、post請求

類似python中的表單提交

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

案例:測試聚合數(shù)據(jù)

代碼

import requests
class UseRequestClass():
    def XWTTPostMethod(self):
        params = {"type":"guonei","key":"4b72107de3a197b3bafd9adacf685790"}
        r = requests.post("http://v.juhe.cn/toutiao/index",params=params)
        #print(r.status_code)
        return r.status_code

五、Requests響應

r.status_code        響應狀態(tài)碼
r.heards             響應頭
r.cookies            響應cookies
r.text               響應文本
r. encoding          當前編碼
r. content          以字節(jié)形式(二進制)返回

最常用的是根據(jù)響應狀態(tài)碼判斷接口是否連通,經(jīng)常用于做接口中斷言判斷

六、Request擴充

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+pytest+allure

7.1 流程如下

讀取文件中的數(shù)據(jù)

requests拿到數(shù)據(jù)請求接口返回狀態(tài)碼

通過斷言驗證返回狀態(tài)碼和200對比

生成allure的測試報告

7.2 模塊總覽

dataDemo(存放數(shù)據(jù))>> readDemo(讀取數(shù)據(jù))

useRequests(發(fā)送請求)>>testDemo(生成報告)

7.3 讀取csv文件流程

7.3.1 存儲數(shù)據(jù)(csv)

通過excel另存為csv即可。

7.3.2 讀取數(shù)據(jù)(readDemo)

代碼展示

import csv
class ReadCsv():
    def readCsv(self):
        item = []
        rr = csv.reader(open("../dataDemo/123.csv"))
        for csv_i in rr:
            item.append(csv_i)
        item =item [1:]
        return item

7.3.3 request請求接口返回狀態(tài)碼

代碼展示

import requests
from readDataDemo.readcsv import ReadCsv
r = ReadCsv()
ee = r.readCsv()
# print(ee)
class RequestCsv():
    def requestsCsv(self):
        item = []
        for csv_i in ee:
            if csv_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)
        return item

7.3.4 pytest斷言設置并結(jié)合allure生成測試報告

代碼展示

import pytest,os,allure
from userequests.userequestsDemo.requestscsv import RequestCsv
r = RequestCsv()
ee = r.requestsCsv()
print(ee)
class TestClass02():
    def test001(self):
        for code in ee:
            assert code == 200
if __name__ == '__main__':
    pytest.main(['--alluredir', 'report/result', 'test_02csv.py'])
    split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'
    os.system(split)

7.3.5 測試報告展示

7.4 讀取excle文件流程

7.4.1 存儲數(shù)據(jù)(xlsx)

7.4.2 讀取數(shù)據(jù)(readDemo)

from openpyxl import load_workbook
class Readxcel():
    def getTestExcel(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 = []  # 把所有行的數(shù)據(jù)放到列表中
        for i in range(2, sheet.max_row + 1):
            sub_data = {}  # 把每行的數(shù)據(jù)放到字典中
            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)  # 拼接每行單元格的數(shù)據(jù)
        return test_data
t = Readxcel()
f = t.getTestExcel()
print(f)

7.4.3 request請求接口返回狀態(tài)碼

import requests
from requestdemo.readexcel import Readxcel
class GetStatusCode():
    def getStatusCode(self):
        t = Readxcel()
        f = t.getTestExcel()
        item = []
        for excel_i in f:
            if excel_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)
        return item
print(GetStatusCode().getStatusCode())

7.4.4 pytest斷言設置并結(jié)合allure生成測試報告

import allure, pytest, os
from requestdemo.getStatusCode import GetStatusCode

get = GetStatusCode()
statusCodes = get.getStatusCode()

class TestReadExcel():
    def testReadExcel(self):
        for code in statusCodes:
            assert code == 200
if __name__ == "__main__":
    # 生成測試報告json
    pytest.main(["-s", "-q", '--alluredir', 'report/result', 'testreadexcel.py'])
    # 將測試報告轉(zhuǎn)為html格式
    split = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'
    os.system(split)

7.4.5:測試報告展示

到此這篇關(guān)于Python中requests做接口測試的方法的文章就介紹到這了,更多相關(guān)Python requests接口測試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • python接口,繼承,重載運算符詳解
  • python編寫接口測試文檔(以豆瓣搜索為例)
  • Python3接口性能測試實例代碼
  • 如何理解python接口自動化之logging日志模塊
  • Python接口自動化之接口依賴

標簽:河南 滄州 樂山 沈陽 紅河 長治 上海 新疆

巨人網(wǎng)絡通訊聲明:本文標題《Python中requests做接口測試的方法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    河曲县| 阳春市| 顺昌县| 嘉荫县| 灌南县| 泰顺县| 玉门市| 赫章县| 屏山县| 日照市| 洛浦县| 浠水县| 康保县| 通山县| 洪泽县| 义马市| 馆陶县| 建宁县| 梁河县| 体育| 昌乐县| 云林县| 陇南市| 邮箱| 垣曲县| 高雄县| 石嘴山市| 兴海县| 洱源县| 蕲春县| 灯塔市| 平陆县| 三原县| 米脂县| 盐源县| 鄂尔多斯市| 成武县| 长武县| 阜新| 房产| 莫力|