欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python編寫接口測試文檔(以豆瓣搜索為例)

 更新時間:2021年07月08日 15:57:10   作者:測試baby  
接口測試的方式有很多,比如可以用工具(jmeter,postman)之類,也可以自己寫代碼進行接口測試,這篇文章主要給大家介紹了關于python編寫接口測試文檔,本文以豆瓣搜索功能為例,需要的朋友可以參考下

前言

很多人會使用postman工具,或者熟悉python,但不一定會使用python來編寫測試用例腳本,postman里面可以完整的將python代碼復制出來。

(以下所有內(nèi)容以豆瓣網(wǎng)站搜索功能為例子)

一、postman接口用例轉換為python測試用例

打開postman,點擊右側的</>圖標,頁面右邊會顯示腳本,頂部修改導出的語言,這邊我使用的是Python-Reqyests

復制腳本,在PyCharm中打開即可,在導入使用之前如果沒有reuqests庫,可能會報錯,我們需要安裝reuqests庫。

cmd命令窗口輸入:pip install requests

導出后的腳本格式如下:

import requests

url = "<https://www.douban.com/search?">

payload={'q': '三體'}
files=[

]
headers = {
  'Cookie': 'bid=5bBvkukAbvY'
}

response = requests.request("POST", url, headers=headers, data=payload, files=files)

print(response.text)

二、轉換為pytest測試用例

1.下面就是轉成pytest的測試用例

import requests

class TestDouban:

    def test_douban(self):
        url = "<https://www.douban.com/search?">
        payload = {'q': '三體'}
        files = []
        headers = {
          'Cookie': 'bid=5bBvkukAbvY'
        }
        response = requests.request("POST", url, headers=headers, data=payload, files=files)
        print(response.text)

三、封裝POST和GET方法

在一個項目中,根路由的路徑是一樣的,只是不同功能對應的具體的接口不一致,且POST和GET是目前測試用例中比較通用的方法,所以可以將根路由、POST和GET方法封裝成一個通用的類,后面直接調用即可。

1.common.py—公共類封裝

import requests

class Common:
    def __init__(self):
        # 豆瓣根路由
        self.url_root = "<https://www.douban.com>"

    # get請求,uri是接口具體地址,params是get請求的參數(shù),如果沒有,默認為空
    def get(self, uri, params=''):
        # 拼湊訪問地址
        url = self.url_root + uri + params
        # 通過get請求訪問對應地址
        response = requests.get(url)
        # 返回request的response結果,類型為requests的Response類型
        return response

    # post請求,uri是接口具體地址,params是post請求的參數(shù),如果沒有,默認為空
    def post(self, uri, params=''):
        # 拼湊訪問地址
        url = self.url_root + uri
        # 有參數(shù),則訪問對應的url,并賦值給默認參數(shù)data
        if len(params) > 0:
            response = requests.post(url, data=params)
        # 無參數(shù),只需要訪問對應的url即可
        else:
            response = requests.post(url)
        # 返回request的response結果,類型為requests的Response類型
        return response

2.具體接口測試用例

import requests

from common.common import Common

class TestDouban:
    def setup(self):
        self.com = Common()

    def test_douban(self):
        uri = "/search?"
        payload = {'q': '三體'}
        response = self.com.post(uri, payload)
# 由于file不需要,就將file刪除了,至于hearder是否要添加可根據(jù)需求來定

執(zhí)行結果如下:

總結

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

相關文章

最新評論