业务背景
有些业务在做接口自动化的时候,接口头须要传入 token 参数,那么如何做呢?下边是整顿的内容,当然也借鉴了网友的一些材料。
1、先封装对 json 格局的数据存储,次要是用来保留和读取获取到的 token 值
operation_json.py
#coding:utf-8
import json
class OperetionJson:
def __init__(self,file_path=None):
if file_path == None:
self.file_path = '../case/user.json' # 获取的 token 须要保留的中央
else:
self.file_path = file_path
self.data = self.read_data()
#读取 json 文件
def read_data(self):
with open(self.file_path, 'r', encoding='utf-8') as fp:
data1 = fp.read()
if len(data1) > 0:
data = json.loads(data1)
else:
data = {}
return data
#依据关键字获取数据
def get_data(self,id):
print(type(self.data))
return self.data[id]
#写 json
def write_data(self,data):
with open('../case/token.json','w') as fp:
fp.truncate() # 先清空之前的数据,再写入,这样每次登录的 token 都是不一样的
fp.write(json.dumps(data))
if __name__ == '__main__':
opjson = OperetionJson()
#print(opjson.get_data('shop'))
data = {
"user":"zhang",
"passwd":123456
}
opjson.write_data(data)
2、封装如何获取 token 脚本
get_token.py
import json
import requests
from common.operation_json import OperetionJson
class OperationHeader:
def __init__(self, response):
self.response = json.loads(response)
def get_response_token(self):
'''获取登录返回的 token'''
token = {"data":{"token":self.response['data']['token']}}
#token = {"token": self.response['data']['token']}
return token
# 把数据写入文件
def write_token(self):
op_json = OperetionJson()
op_json.write_data(self.get_response_token())
def get_response_msg(self):
reponse_msg = {"msg":self.response['msg']}
#print("reponse_msg:", reponse_msg)
return reponse_msg
if __name__ == '__main__':
# 一个登录接口数据,仅供参考
url = "http://192.168.1.117/api/user/login"
data = {
"username": "zhang",
"password": "123456",
"deviceId": 0
}
res = requests.post(url,data).json()
res1 = json.dumps(res)
print(type(res1))
op = OperationHeader(res1)
print(op.get_response_msg())
3、在用例治理里边进行调用
局部代码:test_interface.py
class Test_api(unittest.TestCase):
@classmethod
def setUpClass(cls):
# 登录获取 token
cls.s = requests.session() # 创立会话
url = "http://192.168.1.102/api/user/login"
headers = {"content-type":"application/json","Connection":"keep-alive"}
data = {"username":"zhang","password":"123456","deviceId":0}
res = requests.post(url=url, json=data, headers=headers).json()
res1 = json.dumps(res)
#print(type(res1))
op = OperationHeader(res1)
op.write_token()
writeexcel.copy_excel(testxlsx, reportxlsx) # 复制 xlsx