天天看點

python接口自動化測試之requests(獨立接口測試)

文章目錄

    • 1.環境安裝
    • 2.獨立接口測試腳本,腳本技術示範
    • 3.面向對象方式設計接口測試腳本(獨立接口)
    • 4.面向對象讀取csv檔案中的接口資料,進行測試(獨立接口)

1.環境安裝

安裝和導包

pip install requests
pip install csv
import requests
import csv
           

2.獨立接口測試腳本,腳本技術示範

1.發送請求擷取響應結果

url做打碼處理

1.定義接口請求位址

2.通過requests對象調用post方法發送請求,并接收響應

3.調試腳本,print響應結果

import requests

url = "http://1xxxxxxxx/xxxxx/login.do"
# 通過requests對象調用post方法發送請求,并接收響應
response = requests.post(url).text
print(response)
           
運作結果
傳回其他響應結果方法
#傳回字元串類型的文本内容
print(login_res.text)
 
#傳回字典類型的json格式内容(null傳回None)
print(login_res.json())
 
#傳回cookies資訊
print(login_res.cookies)
 
#傳回位元組流(破解)
print(login_res.content.decode('utf8'))
 
#傳回位元組流
print(login_res.content)
 
#傳回響應頭
print(login_res.headers)
 
#傳回狀态碼
print(login_res.status_code)
           

2.傳入接口測試資料

攜帶參數發送請求

1.定義字典類型進行接口參數的指派

2.将參數傳入到post方法中 response = requests.post(url, data=userinfo).text

import requests

url = "http://xxxxxxxx/jxxxxx/user/login.do"
# 定義字典類型進行接口參數的指派
userinfo = {"username": "xxx1",
             "password": "123456"}
response = requests.post(url, data=userinfo).text
print(response)
           
傳回結果

3.對響應結果進行校驗,得出測試結論

1.調用find方法,查找傳回的字元串中是否存在對應得資訊 msg = response.find(“預期結果”)

2.判斷語句得出相關得出測試結論 if msg >0: ----這個預期結果是存在的,print(“測試通過”) else:print(“測試失敗”)

url = "http://xxxxxxxx/user/login.do"
userinfo = {"username": "1",
             "password": "123456"}
response = requests.post(url, data=userinfo).text
print(response)
# 預期結果
msg = response.find("使用者名不存在")
if msg > 0:
    print("測試通過")

else:
    print("測試失敗")
           

傳回結果

上面的預期結果是使用者明不存在,實際結果和預期相符,是以測試通過

{"status":1,"msg":"使用者名不存在"}
測試通過
           

4.在檔案中傳入多組測試資料,進行資料驅動測試

1.準備測試資料的 csv檔案

建立一個excel表寫上要用到的測試資料,以csv(逗号分隔)類型儲存到項目中
python接口自動化測試之requests(獨立接口測試)

2.讀取csv檔案中的測試資料

2.1以隻讀的方式打開檔案
2.2 擷取檔案中的資料,要用for循環去周遊檔案中的每一列 循環結構,row[0]--------0是下标
table = csv.reader(file)
for row in table:
	print(row[0])
           
2.3把測試資料放入字典中 userinfo[“username”] = row[0]--------username是參數的名字,0代表下标,第一列就是0,第二列就是1…

讀取檔案的完整代碼示範

兩個小數點表示傳回上一級
url = "http:xxxxxxxxx/user/login.do"
file = open("../interface_Case/userinfo_data.csv", "r",)
table = csv.reader(file)
userinfo = {}
for row in table:
    # print(row)
    userinfo["username"] = row[0]
    userinfo["password"] = row[1]
    response = requests.post(url, data=userinfo).text
    print(userinfo)
           
運作結果
{'username': '小紅1', 'password': '123456'}
{'username': '張三', 'password': '123456'}
{'username': '小紅1', 'password': '111111'}
{'username': '', 'password': ''}
           

5.把檔案寫入測試報告中

把每一組測試資料對應的測試結果寫入測試報告中

1.在項目所在檔案夾建立一個新得excel空檔案,并以csv(逗号分隔)類型儲存

r表示讀得方式打開,w表示寫得方式打開

2.向檔案裡寫入内容,如果要換行,在末尾加上換行符

file2.write("zhangsan" + "," + "123" + "," "使用者名不存在")
file2.write("zhangsan" + "," + "123" + "," "使用者名不存在" + "\n")
           

完整代碼示範

循環結束後需要調用close方法關閉打開的檔案,以免造成記憶體洩露

file1 = open("userinfo_data.csv", "r",)
file2 = open("userinforesult_data.csv", "w")
url = "http://192.168.37.133:8888/jwshoplogin/user/login.do"
table = csv.reader(file1)
userinfo = {}
for row in table:
    userinfo["username"] = row[0]
    userinfo["password"] = row[1]
    response = requests.post(url, data=userinfo).text
    print(response)

    r = response.find(row[2])
    if r > 0:
        print("接口測試通過")
        file2.write(row[0] + "," + row[1] + "," + row[2] + "," + "測試通過" + "\n")
    else:
        print("接口測試失敗")
        file2.write(row[0] + "," + row[1] + "," + row[2] + "," + "測試失敗" + "\n")
file2.close()
           
運作結果
{"status":0,"msg":"登入成功",}
接口測試通過
{"status":1,"msg":"使用者名不存在"}
接口測試通過
{"status":1,"msg":"密碼錯誤"}
接口測試通過
{"status":1,"msg":"使用者名不存在"}
接口測試通過
           

寫腳本程式進行多個版本的疊代,重新編寫腳本

1.導入類庫檔案

2.做好測試準備工作-------打開檔案,接口測試位址,檔案的讀取

3.接口測試的執行----------通過循環結構讀取一組資料進行一次測試,進行測試結果分析,将測試結論寫入測試報告中

3.面向對象方式設計接口測試腳本(獨立接口)

用面向對象的思路設計接口測試腳本,定義一個類,把請求參數和請求方法封裝到類裡面

1.把請求位址和接口參數放在初始化屬性裡面

2.把請求方法進行封裝

# 用面向對象的思想設計正常注冊接口測試
# 定義測試類
import requests


class Register_test():
    # 定義類屬性,一般是定義在類的初始化方法中
    def __init__(self):
        self.url = "http://xxxxxxxxx/user/register.do"
        self.userinfo = {}
        self.userinfo = {"username": "李明",
                        "password": "123456",
                        "email": "[email protected]",
                        "phone": "13311096380",
                        "question": "最喜歡的水果",
                        "answer": "蘋果"}

    def register(self):
        # 發送接口請求
        s = requests.session()
        response = s.post(self.url, data=self.userinfo).json()
        print(response)


if __name__ == '__main__':
    register_obj = Register_test()
    register_obj.register()
           

4.面向對象讀取csv檔案中的接口資料,進行測試(獨立接口)

用面向對象讀取csv檔案中相關的接口測試資料,進行接口測試;需要用到的庫,requests,csv

設計腳本思路方向

1.在所在項目建立一個excel檔案,把要測試的資料參數值放在裡面,以csv(逗号分隔)類型儲存

python接口自動化測試之requests(獨立接口測試)
python接口自動化測試之requests(獨立接口測試)

2.開始寫腳本,定義一個類,定義初始化方法,寫上url固定參數

class Check_test():
    def __init__(self):
        self.url = "http://xxxxxxx/user/check_vaild.do"
           

3.寫一個測試方法,把讀取csv檔案,發送請求方法寫進去

def checktest(self):
        # 從csv檔案中擷取測試資料
        checkinfo = {}
        file = open("../interface_data/check_test_data.csv", "r")
        table = csv.reader(file)
        for row in table:
            checkinfo["str"] = row[0]
            checkinfo["type"] = row[1]
            # 如果不卻動讀取資料是否正确,可以列印列印一下
            print(row[0])
            # 這裡用requests對象調用session的方法去擷取請求的一個對象,
            # 然後指派給一個變量,然後用這個對象再去調用post方法
            s = requests.session()
            # 把結果儲存下來放在響應裡面去
            response = s.post(self.url,data=checkinfo).json()
            print(response)
           

完整代碼示範

import csv

import requests


class Check_test():
    def __init__(self):
        self.url = "http://1xxxxxxx/user/check_vaild.do"

    def checktest(self):
        # 從csv檔案中擷取測試資料
        checkinfo = {}
        file = open("../interface_data/check_test_data.csv", "r")
        table = csv.reader(file)
        for row in table:
            checkinfo["str"] = row[0]
            checkinfo["type"] = row[1]
            print(row[0])
            # 這裡用requests對象調用session的方法去擷取請求的一個對象,
            # 然後指派給一個變量,然後用這個對象再去調用post方法
            s = requests.session()
            # 把結果儲存下來放在響應裡面去
            response = s.post(self.url,data=checkinfo).json()
            print(response)


if __name__ == '__main__':
    checkobj = Check_test()
    checkobj.checktest()
           

4.預期結果比對,寫入測試報告

4.1 在項目所在位置新建立一個空檔案,或者直接寫上路徑,沒有檔案會自動建立新的檔案
# 所在檔案沒有這個check_result.csv的話會自動建立一個新的檔案夾
file2 = open("../interface_data/check_result.csv", "w")
           
4.2 用接收響應結果的對象調用find()方法,傳入測試資料預期結果列;然後加上if,else條件判斷,實際結果和預期結果進行比對,把實際結果寫入測試報告
r = response.find(row[2])
            if r > 0:
                file2.write(row[0] + "," + row[1] + "," + row[2] + "," + "測試通過" + "\n")
            else:
                file2.write(row[0] + "," + row[1] + "," + row[2] + "," + "測試失敗" + "\n")
           

完整代碼示範

import csv

import requests


class Check_test():
    def __init__(self):
        self.url = "http://xxxxxxx/user/check_vaild.do"

    def checktest(self):
        # 從csv檔案中擷取測試資料
        checkinfo = {}
        file1 = open("../interface_data/check_test_data.csv", "r")
        file2 = open("../interface_data/check_result.csv", "w")
        table = csv.reader(file1)
        for row in table:
            checkinfo["str"] = row[0]
            checkinfo["type"] = row[1]
            print(row[0])
            # 這裡用requests對象調用session的方法去擷取請求的一個對象,
            # 然後指派給一個變量,然後用這個對象再去調用post方法
            s = requests.session()
            # 把結果儲存下來放在響應裡面去
            response = s.post(self.url, data=checkinfo).text
            r = response.find(row[2])
            if r > 0:
                file2.write(row[0] + "," + row[1] + "," + row[2] + "," + "測試通過" + "\n")
            else:
                file2.write(row[0] + "," + row[1] + "," + row[2] + "," + "測試失敗" + "\n")
        file2.close()

if __name__ == '__main__':
    checkobj = Check_test()
    checkobj.checktest()
           

測試報告結果

python接口自動化測試之requests(獨立接口測試)

面向對象的設計思路總結:

1.一個接口測試腳本對應一個類檔案;

2.接口請求位址作為屬性;

3.接口的測試資料如果時固定的,也可以放在屬性中定義

4.測試方法中:發送請求,擷取響應,對響應的結果進行比對

5.在main方法中進行類的執行個體化,類的執行個體化過程:

對象名 = 類名()

對象名.測試方法()

接口測試工作中容易出現的問題:接口文檔沒有了解清楚,出現了解上錯誤,導緻發現了不時bug的bug,需要快速進行确認,并學習;得盡快對相關的測試資料進行修複:接口說明,測試資料