一、场景说明
在面试接口自动化时,经常会问,其他接口调用的前提条件是当前用户必须是登录状态,如何处理接口依赖?
在此之前我们介绍过session管理器保存会话状态。如果接口请求需要携带token,那么又如果处理呢?以下详细介绍。
未登录状态下,直接请求充值接口的异常场景:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import unittest
import requests
class testrecharge(unittest.testcase):
def setup( self ):
pass
def teardown( self ):
pass
def test_recharge( self ):
url = 'http://127.0.0.1:8888/recharge'
payload = {
"member_id" : 100004312 ,
"amount" : 80
}
res = requests.post(url,json = payload)
print (res.json())
if __name__ = = '__main__' :
unittest.main()
|
运行结果如下:
{'code': 1003, 'msg': '未授权或token已过期'}
二、token处理思路
在处理之前,token灵魂三连问:
- 如何获取token?
- 获取的token如何管理?
- 其他接口如何携带token?
思路如下:
1.抽取登录接口返回值中的token;
2.使用全局变量存储token。token可以存到yaml或者json或者ini的配置文件里,以下介绍将token作为类属性;
3.其他接口将token值放入请求头,发送请求;
三、jsonpath基本用法
我们需要从登录接口中提取出token,这里介绍jsonpath基本用法。
1、jsonpath介绍
jsonpath为json文档提供了解析能力,通过使用jsonpath,你可以方便的查找节点、获取想要的数据,jsonpath是json版的xpath。
2、jsonpath语法
jsonpath | 说明 |
---|---|
$
|
文档根元素 |
@
|
当前元素 |
. 或[]
|
匹配下级元素 |
..
|
递归匹配所有子元素 |
*
|
通配符,匹配下级元素 |
[]
|
下标运算符,根据索引获取元素,jsonpath索引从0开始 |
[,]
|
连接操作符,将多个结果拼接成数组返回,可以使用索引或别名 |
[start:end:step]
|
数据切片操作 |
?()
|
过滤表达式 |
这么多语法规范,大家会觉得一脸懵逼吧,细心的小伙伴会发现语法中 .. 表示递归匹配所有子元素,简单粗暴,用..获取所有匹配的子元素,通过索引拿到想要的值,以下以实战进行演练。
3、jsonpath源码
1
2
|
def jsonpath(obj, expr, result_type = 'value' , debug = 0 , use_eval = true):
"""traverse json object using jsonpath expr, returning values or paths"""
|
obj: 需要解析的对象,比如接口的返回值。
expr: 匹配的表达式。
4、jsonpath实战
以下编写代码进行演示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
from jsonpath import jsonpath
# json格式结果
res = {
"code" : 0 ,
"msg" : "ok" ,
"data" : {
"token_info" : {
"token_type" : "bearer" ,
"expires_in" : "2020-05-28 13:07:29" ,
"token" : "eyjhbgcioijiuzuxaij9.eyjtzw1izzjfawqiojewmda1mtmxnswizxhwijoxntkwnjqyndq5fq.s6a7pzlilf9tqpedau9wipgglgkgkeq6ebhq26l-eum5secb48dwalke7u16irzv3uzd5hidfbw41jmi9v0t_q"
}
}
}
# 获取res中的token
token = jsonpath(res, '$..token' )[ 0 ]
print (token)
|
响应结果为:
eyjhbgcioijiuzuxbij9.eyjtzw1izzjfawqiopewmda1mtmxnswizxhwijoxntkwnjqyndq5fq.s6a7pzlilf9tqpedau9wipgglgkgkeq6ebhq26l-eum5secb48swalke8u16irzv3uzd5hidfbw41jmi9v0t_q
四、token依赖实例
①在config/setting.py配置文件中,配置全局的域名或ip。
1
2
3
4
|
class devconfig():
# 项目的域名或ip
host = 'http://127.0.0.1:8888'
config = devconfig()
|
②在config/config.yaml文件中,存入登录账号。
config.yaml
1
2
3
|
user:
mobile_phone: '155********'
pwd: '12345678'
|
③在项目根目录下,新建文件夹middleware,文件夹下新建文件helper.py,用于处理token。
④首先编写登录接口,返回接口数据。
helper.py
1
2
3
4
5
6
7
8
9
|
from common.requests_handler import requestshandler
from config.setting import config
from common.yaml_handler import yaml_data
def login():
"""登录,接口返回token"""
req = requestshandler()
res = req.visit( 'post' , config.host + '/login' , json = yaml_data[ 'user' ])
return res
print (login())
|
运行结果如下:
{
'code': 0,
'msg': 'ok',
'data': {
'token_info': {
'token_type': 'bearer',
'expires_in': '2020-05-26 13:31:41',
'token': 'eyjhbgcioijiupuxmij9.eyjtzw1izxjfawqiojewmda1mtmxnswizxhwijoxntkwndcxmtaxfq.4qdndq-wyecvpv7yrnmlcx1zxpalb8vpohxhht5ofncjgn_ytaisyhmn7omzjmglz68sj_ufbch2nhiao2p_lg'
}
}
}
⑤接下来编写函数,获取登录接口返回值并提取token和token_type进行拼接 。这里要使用jsonpath模块提取返回的token和token_type。
helper.py
1
2
3
4
5
6
7
8
|
def save_token():
"""保存token信息"""
res = login()
token = jsonpath(res, '$..token' )[ 0 ]
token_type = jsonpath(res, '$..token_type' )[ 0 ]
token = " " .join([token_type, token])
return token
print (save_token())
|
运行结果如下:
1
|
bearer eyjhbgciojipzuxmij9.eyjtzw1izxjfawqiojewmda1mtmxnswizxhwijoxntkwn
|
⑥最后定义类,将token作为类属性,整体代码如下:
helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
from common.requests_handler import requestshandler
from config.setting import config
from common.yaml_handler import yaml_data
from jsonpath import jsonpath
def login():
"""登录,返回token信息"""
req = requestshandler()
res = req.visit( 'post' , config.host + '/login' , json = yaml_data[ 'user' ])
return res
def save_token():
"""保存token信息"""
res = login()
token = jsonpath(res, '$..token' )[ 0 ]
token_type = jsonpath(res, '$..token_type' )[ 0 ]
token = " " .join([token_type, token])
context.token = token
return token
class context:
"""将token作为类属性"""
token = ''
if __name__ = = '__main__' :
print (save_token())
|
运行结果如下:
bearer eyjhbgcioijiuzuxmij9.eyjtzw1izxjfawqiojewmda1mtmxnswizxhwijoxntkwndcz
⑦充值接口携带token请求。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import unittest
import requests
from middleware.helper import context, save_token
class testrecharge(unittest.testcase):
def setup( self ):
pass
def teardown( self ):
pass
def test_recharge( self ):
save_token()
token = context.token
url = 'http://127.0.0.1:88888/recharge'
payload = {
"member_id" : 100051315 ,
"amount" : 80
}
res = requests.post(url,json = payload)
print (res.json())
if __name__ = = '__main__' :
unittest.main()
|
运行结果为:
{
'code': 0,
'msg': 'ok',
'data': {
'leave_amount': 240.0,
'mobile_phone': '155********',
}
}
总结:
本文主要介绍如何提取token、将token作为类属性全局调用及充值接口如何携带token进行请求。
本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注服务器之家的更多内容!
原文链接:https://blog.csdn.net/ZangKang1/article/details/119838519