Python接口测试之封装requests
首先安装requests库:
pip install requests
test_requests.py 首先在TestRequest类中封装get与post方法,
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或者get
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()