问题:在多接口测试中,存在接口token等参数需要关联的情况,为了避免无法进行关联或者错误关联及写很多冗余代码的情况。采用session的方式进行接口关联
作用:requests库的session会话对象可以跨请求保持某些参数,Requests中的Session会话管理的作用就是自动的记录cookie和session的登录状态
使用正则表达式通过session关联
class TestApi:
csrf_token = ''
access_token = ''
session = requests.session() # 确保是同一个session回话
def test_phpwind(self):
url = 'http://aaa/phpwind/'
res = TestApi.session.request(method="get",url=url)
# print(res.text)
# 因为token是在文本中,通过正则表达式的方式获取token
res_token = re.search('name="csrf_token" value="(.*?)"',res.text)
TestApi.csrf_token = res_token.group(1)
print(TestApi.csrf_token)
def test_phpwind_login(self):
url = 'http://aaa/phpwind/index.php?m=u&c=login&a=dorun'
header = {
"Accept":"application/json, text/javascript, /; q=0.01",
"X-Requested-With":"XMLHttpRequest"
}
data = {
"username":"baili",
"password":"baili123",
"csrf_token":TestApi.csrf_token,
"backurl":"http://aaa/phpwind/",
"invite":""
}
res = TestApi.session.request(method="post",url=url, data=data, headers=header)
print(res.json())
使用jsonpath通过session关联,跟上面共有一个session
def test_get_token(self):
url = 'https://api.weixin.qq.com/cgi-bin/token'
params ={
"grant_type":"client_credential",
"appid":"wx74a8627810cfa308",
"secret":"e40a02f9d79a8097df497e6aaf93ab80"
}
res = TestApi.session.request(method="get",url=url,params=params)
print(res.json())
access_token= jsonpath.jsonpath(res.json(),'$.access_token')
TestApi.access_token = access_token[0]
print(access_token[0])
def test__edit_flag(self):
url = 'https://api.weixin.qq.com/cgi-bin/tags/update'
params = {
"access_token":TestApi.access_token
}
json = {"tag" : {"id":134,"name":"广东人"}}
res = TestApi.session.request(method="post", url=url, params=params, json=json)
print(res.json())
从上面代码可以看出:
1. 在类下面建立了一个session = requests.session()请求,然后所有方法通过TestApi.session.request()的方式调用同一个session
2. 将需要关联的token先access_token = ''后,之后直接将接口中获取到的token通过TestApi.access_token = access_token[0]的方式赋值给到access_token,这样之后的接口需要使用时直接调用即可