Python接口測試之封裝requests

首先安裝requests庫:python

pip install requests

test_requests.py 首先在TestRequest類中封裝get與post方法,json

import requests
import json

class TestRequest():

    def __init__(self):

        self.headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"}

    def get(self, url, params):

        try:
            r = requests.get(url=url, params=params, headers=self.headers)
            response = json.loads(r.text)
            print("get請求結果爲:%s"%response)

        except BaseException as e:
            print("get請求錯誤,錯誤緣由:%s"%e)

    def post(self, url, params):

        data = json.dumps(params)
        try:
            r = requests.post(url=url, json=data, headers=self.headers)
            response = json.loads(r.text)
            print("post請求結果爲:%s" %response)

        except BaseException as e:
            print("post請求錯誤,錯誤緣由:%s" % e)

if __name__ == '__main__':
    a = TestRequest()

test_api.py 此文件用於調用前邊封裝的test_requests.py文件,判斷是get仍是post方法,而後這個方法在調用類的時候執行init方法,url是要請求的網址,prove是憑證好比session,cookie,token之類的,parameter是要發送的參數,methods是請求的方法,post或者getapi

from api.test_request import TestRequest

req = TestRequest()
class TestApi():

    def __init__(self, url, prove, parameter, methods):

        self.url = url
        self.prove = prove
        self.parameter = parameter
        self.methods = methods

    def test_api(self):
        """
        判斷請求是GET仍是POST
        :return: url請求結果
        """
        if self.methods == "GET":
            self.params = {"prove": self.prove, "parameter": self.parameter}
            response= req.get(self.url, self.params)

        elif self.methods == "POST":
            self.params = {"prove": self.prove, "parameter": self.parameter}
            response = req.post(self.url, self.params["parameter"])
        return response

    def get_json(self):

        json_data= self.test_api()
        return json_data
if __name__ == '__main__':
    a = TestApi("http://10.141.121.29:8083/login","",{"workAccount":"xinjian","password":"8153cb3aa56ee4196091913849f14136"},"POST")
    a.get_json()
相關文章
相關標籤/搜索