前言
關於token,如果不了解的,先去看Jmeter這篇文章
https://www.cnblogs.com/wwho/p/14154786.html
思路跟 jmeter 中一樣,在 python 中取 token 的值,可以通過 re 正則來取,也可以通過 json 解析來取。
一、提取token
1、json解析提取
# -*- coding:utf-8 -*-
import requests
host = ""
user = ""
pwd = ""
url = host + "/pub/api/v1/web/web_login"
body = {
"phone": user,
"pwd": pwd
}
r = requests.post(url=url, data=body).json() # .json() 就是 json 解析,把json格式轉為字典
token = r["data"]["token"] # 字典取值
print(token)
2、正則提取json
# -*- coding:utf-8 -*-
import requests, re
host = ""
user = ""
pwd = ""
url = host + "/pub/api/v1/web/web_login"
body = {
"phone": user,
"pwd": pwd
}
r = requests.post(url=url, data=body).text
print(r)
token = re.findall('"token":"(.+?)"', r)
token = token[0] # 正則取出來的值是 列表 類型,所以要進行列表取值
print(token)
二、結合框架使用 token
python里面有個全局變量global,但這個只是針對於在同一個.py里才有效,跨腳本就不起作用了。
整體的思路:
1、登錄后返回 token,把 token 寫入 yaml 文件中,yaml 文件放在公共模塊 commen 中
2、需要 token 的時候(一般是調用寫用例的時候),在初始化中讀取 yaml 文件中最新的 token 值
3、每個用例的 package 執行的時候去調用獲取 token
4、最后執行所有用例,生成報告,發送郵件等
所以先把讀寫 yaml 的方法封裝好
headle.py
# -*- coding:utf-8 -*-
import os, yaml
def write_yaml(token):
cur = os.path.dirname(os.path.realpath(__file__)) # 獲取當前路徑
yaml_path = os.path.join(cur, "token.yaml") # 獲取yaml文件的路徑
print(yaml_path)
t = {"token": token} # 寫入的內容
with open(yaml_path, 'w', encoding='utf-8') as f:
yaml.dump(t, stream=f, allow_unicode=True)
def get_yaml(yaml_file):
# yaml_file = "D:\\code\\api_test\\commen\\token.yaml"
f = open(yaml_file, 'r', encoding='utf-8')
cfg = f.read()
d = yaml.load(cfg, Loader=yaml.FullLoader)
"""
用load轉字典
yaml5.1版本后棄用了yaml.load(file)這個用法,因為覺得很不安全,5.1版本之后就修改了需要指定Loader,通過默認加載器(FullLoader)禁止執行任意函數
Loader=yaml.FullLoader 加上這行代碼,告警就沒了
"""
d = d["token"]
return d
if __name__ == '__main__':
r = write_yaml("token的值")
封裝接口的時候,把 token 設置成變量
user.py
# -*- coding:utf-8 -*-
import requests
def user_info(host, token):
url = host + '/pub/api/v1/web/user_info'
headers = {"token": token} # token 放在請求頭
r = requests.get(url=url, headers=headers)
return r
編寫用例的時候先獲取 yaml 文件中 token 的值
test_user_info.py
# -*- coding:utf-8 -*-
from interface.user import user_info
from commen.headle_token import *
import unittest, os
current_path = os.path.dirname(os.path.realpath(__file__)) # 獲取當前路徑
# 獲取 token 的路徑
token_path = os.path.join(current_path, "commen")
token_path = os.path.join(token_path, "token.yaml")
class TestUserInfo(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.token = get_yaml(token_path)
print("獲取token")
print(cls.token)
def test_user_info_success(self):
r = user_info("https://api.xdclass.net", self.token)
print(r.text)
if __name__ == '__main__':
unittest.main()
主程序
1、登錄返回token
2、token 寫入 yaml 文件
3、執行用例初始化的時候先獲取 token
4、執行用例生成報告
run_case_report.py
# -*- coding:utf-8 -*-
import unittest, os
from commen import HTMLTestRunner
from interface.login import login
from commen.headle_token import *
current_path = os.path.dirname(os.path.realpath(__file__))
case_path = os.path.join(current_path, "case")
report_path = os.path.join(current_path, "report")
report = os.path.join(report_path, "report.html")
def all_case():
discover = unittest.defaultTestLoader.discover(case_path,
pattern='test*.py')
print(discover)
return discover
def run_case_report():
fb = open(report, "wb")
runner = HTMLTestRunner.HTMLTestRunner(
stream=fb,
title="xx項目測試報告",
description="xx項目的測試報告"
)
runner.run(all_case())
fb.close()
if __name__ == '__main__':
# 調用登錄獲取token
token = login("host", "登錄的賬號", "密碼")
# 把token寫入 yaml 文件
write_yaml(token)
# 執行用例的時候會讀取 yaml 中的token,case文件下 test_user_info.py 的
run_case_report()