之前都是用jmeter进行接口测试然后进行持续性集成,之前也写过用jmeter来请求各种类型的接口,今天来学习下如何使用python+requests对各种接口发起请求并断言。
1.接口类型
测试项目的ip和端口如下:
host = "ip"
port = "8080"
1.1.get类型接口请求
def test_get_params(self):
"""
请求方式为get
"""
url = "http://" + self.host + ":" + self.port + "/pinter/com/getSku"
# 请求参数
params = {"id": 1}
#发起请求
res = requests.get(url=url, params=params)
print(res.text)
assert res.status_code == 200
1.2.post类型接口请求,参数为params
def test_post_params(self):
"""
请求方式为post,请求参数为params
"""
url = "http://" + self.host + ":" + self.port + "/pinter/com/login"
# 请求参数
params = {"userName": "admin", "password": "1234"}
res = requests.post(url=url, params=params)
print(res.text)
assert res.status_code == 200
1.3.post类型接口请求,参数为json
def test_post_json(self):
"""
请求方式为post,请求参数为json
:return:
"""
url = "http://" + self.host + ":" + self.port + "/pinter/com/register"
json = {"userName": "test", "password": "1234", "gender": 1, "phoneNum": "110", "email": "beihe@163.com",
"address": "Beijing"}
res = requests.post(url=url, json=json)
print(res.text)
assert res.status_code == 200
1.4.post类型接口请求,参数为k=json
def test_post_params_json(self):
"""
请求方式为post,请求参数为k=json
:return:
"""
url = "http://" + self.host + ":" + self.port + "/pinter/com/buy"
params = {"param": '{"skuId":123,"num":10}'}
res = requests.post(url=url, params=params)
print(res.text)
assert res.status_code == 200
2.上传
def test_upload(self):
url = "http://" + self.host + ":" + self.port + "/pinter/file/api/upload"
files={
'file':open(file=r'C:\Users\29442\Desktop\user.txt',mode='rb')
}
#发起接口调佣
res=requests.post(url=url,files=files)
print(res.text)
3.获取token
部分接口依赖登录接口中的token,可以将登录接口中的token提取出来,用global定义为全局变量,然后在其它接口的header中进行调用,如下图所示。
def test_login_token(self):
"""
测试登录,带token
"""
url = "http://" + self.host + ":" + self.port + "/pinter/bank/api/login2"
params = {"userName":"admin","password":"1234"}
res = requests.post(url=url, params=params)
text=json.loads(res.text)
print(text)
global token
token=text.get("data")
assert res.status_code == 200
def test_token(self):
"""
查询余额,带token
"""
headers={
"testfan-token":token
}
url = "http://" + self.host + ":" + self.port + "/pinter/bank/api/query2"
params = {"userName":"admin"}
res = requests.get(url=url, params=params,headers=headers)
print(res.text)
assert res.status_code == 200
4.自动获取cookie
部分接口依赖登录接口的cookie,在代码中如果我们使用固定的cookie,cookie失效之后又需要人为手动填充很不方便,requests给我们提供了一种方法可以自动获取cookie,可以用session获取到cookie之后再用session调用方法发起请求,如下图所示。
#通过session自动获取cookie
session = requests.session()
def test_login_cookie(self):
"""
测试登录,带Cookie
"""
url = "http://" + self.host + ":" + self.port + "/pinter/bank/api/login"
params = {"userName":"admin","password":"1234"}
res = self.session.post(url=url, params=params)
print(res.text)
assert res.status_code == 200
def test_cookie(self):
"""
查询余额,带Cookie
"""
url = "http://" + self.host + ":" + self.port + "/pinter/bank/api/query"
params = {"userName":"admin"}
res = self.session.get(url=url, params=params)
print(res.text)
assert res.status_code == 200