Commit bbcb0877 by crob

源码

parent dcefbb83
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: __init__.py
# Author: lao_zhao
# Datetime: 2024/9/4 14:01
# Description:
#
# ---------------------------------------------------------------------------
import logging
import os
import time
"""
pytest输出报告的插件:pytest-html. pip install pytest-html.
命令:pytest 用例层 -vv --html=报告存名称 --self-contained-html
报告输出是可能有用例会断言失败,断言失败的用例可以进行失败重跑。失败重跑的插件为:pytest-rerunfailures. pip install pytest-rerunfailures
pytest 用例层 -vv --html=报告存名称 --self-contained-html --reruns 失败重跑的次数 --reruns-delay 每次失败重跑的间隔时间
"""
"""
allure生成报告:
pip install allure-pytest
1: 生成测试结果的json文件。 pytest 用例层 --alluredir=存放json文件的目录 --clean-alluredir
2: 根据第一步的json文件生成报告
allure serve 第一步生成json文件的存放目录
allure generate 第一步生成json文件的存放目录 -o 静态报告保存的路径
3: 打开allure生成的静态报告:allure open 静态报告保存的路径
"""
def log(name="张三"):
# 创建Logger对象
logger = logging.getLogger(name)
# 设置日志的级别
logger.level = logging.INFO
# 2024-09-04-14-09-10.log
log_name = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())+".log"
log_dir = os.path.join(os.path.join(os.path.dirname(__file__), "report"), "log")
log_path = os.path.join(log_dir, log_name)
# 设置写入日志的文件
handle = logging.FileHandler(log_path, mode="a", encoding="utf-8")
# 设置日志的显示格式
formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s -- %(name)s')
# 设置日志文件中的日志格式
handle.setFormatter(formatter)
# 给Logger对象添加文件
logger.addHandler(handle)
# 将Logger对象返回
return logger
# 先执行函数,获取函数的返回值,以后之间使用函数的返回值写入日志
log = log()
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: __init__.py
# Author: lao_zhao
# Datetime: 2024/9/4 14:01
# Description:
#
# ---------------------------------------------------------------------------
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: db.py
# Author: lao_zhao
# Datetime: 2024/9/4 14:35
# Description:
#
# ---------------------------------------------------------------------------
import pymysql
from apiAutoTest_v3 import log
from apiAutoTest_v3.common.read_project_ini import ReadProjectIni
class DB:
def __init__(self):
"""链接数据库,获取链接对象和游标对象"""
# 链接数据库,数据库的连续配置信息存放在项目的配置文件中的,需要使用ReadProjectIni类对象调用get_sql_connect_msg方法
pro_ini = ReadProjectIni()
self.conn = pymysql.connect(
host=pro_ini.get_sql_connect_msg("host"),
port=int(pro_ini.get_sql_connect_msg("port")),
user=pro_ini.get_sql_connect_msg("user"),
password=pro_ini.get_sql_connect_msg("password"),
database=pro_ini.get_sql_connect_msg("database"),
charset="utf8"
)
self.cursor = self.conn.cursor()
def close(self):
self.cursor.close()
self.conn.close()
def select(self, sql, n=0):
"""执行查询的sql语句,并返回查询的结果"""
if isinstance(sql, str):
if sql.strip().lower().startswith("select"):
try:
self.cursor.execute(sql)
except Exception as e:
log.error(f"执行select方法时,产生错误,错误为:{e},sql语句为:{sql}")
raise e
else:
select_result = self.cursor.fetchall()
if isinstance(n, int) and select_result:
try:
return select_result[n][0]
except Exception as e:
log.error(f"执行select方法时,获取查询结果失败,传入的n为:{n}")
raise e
else:
log.error(f"执行select方法时,sql语句不是查询的sql语句,sql语句为:{sql}")
raise ValueError("sql语句错误")
else:
log.error(f"执行select方法时,sql语句错误,sql语句为:{sql}")
raise ValueError("sql语句错误")
def delete(self, sql):
"""执行删除的SQL语句"""
if isinstance(sql, str):
if sql.strip().lower().startswith("delete"):
try:
self.cursor.execute(sql)
self.conn.commit()
except Exception as e:
log.error(f"执行delete方法时,产生错误,sql语句为:{sql}, 错误为:{e}")
raise e
else:
log.error(f"执行delete方法时,sql语句错误,sql语句为:{sql}")
raise ValueError("sql语句错误")
else:
log.error(f"执行delete方法时,sql语句错误,sql语句为:{sql}")
raise ValueError("sql语句错误")
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: read_excel.py
# Author: lao_zhao
# Datetime: 2024/9/4 14:53
# Description:
#
# ---------------------------------------------------------------------------
import openpyxl
from apiAutoTest_v3 import log
from apiAutoTest_v3.common.read_json import read_json
from apiAutoTest_v3.common.read_project_ini import ReadProjectIni
from apiAutoTest_v3.common.read_user_ini import ReadUserIni
from apiAutoTest_v3.data_config.settings import *
# read_excel.py文件的功能:就是获取每个用户的测试数据,并将测试数据存放在一个二维列表中
class ReadExcel:
def __init__(self, user_dir_name):
"""获取所有json文件的路径,并读取json文件,再获取excel文件的路径,加载excel的工作簿,并获取工作表的名称,再获取工作表"""
# 被测系统的域名存放在项目的ini配置文件中,所有需要ReadProjectIni对象,调用get_host方法获取被测系统的域名
self.pro_ini = ReadProjectIni()
# 先读取每个用户的配置文件的对象。ReadUserIni对象。因为每个用户的数据存放的文件信息放在每个用户的ini配置文件中。
user_ini = ReadUserIni(user_dir_name)
# 根据ReadUserIni对象获取每个用户的数据文件路径
case_data_path = user_ini.get_file_path(FILE_CASE)
expect_data_path = user_ini.get_file_path(FILE_EXPECT)
sql_data_path = user_ini.get_file_path(FILE_SQL)
excel_path = user_ini.get_file_path(FILE_EXCEL)
table_name = user_ini.get_table_name(TABLE_kEY)
self.case_data_dict = read_json(case_data_path)
self.expect_data_dict = read_json(expect_data_path)
self.sql_data_dict = read_json(sql_data_path)
try:
wb = openpyxl.load_workbook(excel_path)
self.ws = wb[table_name]
except Exception as e:
log.error(f"加载excel的工作簿或获取excel的工作表时产生错误,错误为:{e}, excel的路径为:{excel_path}, 工作表的名称为:{table_name}")
raise e
def __get_cell_value(self, column, row):
"""根据列号和行号获取指定单元格数据"""
try:
cell_value = self.ws[column+str(row)].value
except Exception as e:
log.error(f"获取指定单元格数据,出错,错误为:{e}, 传入的列号:{column}和行号:{row}")
raise e
else:
if cell_value is None:
return None
elif cell_value.strip():
return cell_value.strip()
def module_name(self, row):
"""根据行号,获取模块名称"""
return self.__get_cell_value(MODULE, row)
def api_name(self, row):
"""根据行号,获取接口名称"""
return self.__get_cell_value(API, row)
def case_url(self, row):
"""根据行号,获取用例的url"""
path = self.__get_cell_value(URL, row)
if path:
# 被测系统的域名存放在项目的ini配置文件中,所有需要ReadProjectIni对象,调用get_host方法获取被测系统的域名
return self.pro_ini.get_host(HOST_KEY) + path
def case_req_method(self, row):
"""根据行号,获取用例的请求方法"""
return self.__get_cell_value(REQ_METHOD, row)
def case_mime(self, row):
"""根据行号,获取用例请求的媒体类型"""
mime = self.__get_cell_value(MIME, row)
if mime:
return mime.lower()
def case_data(self, row):
"""根据行号,获取用例数据"""
case_data_key = self.__get_cell_value(CASE_DATA, row)
if case_data_key:
module_name = self.module_name(row)
api_name = self.api_name(row)
return self.case_data_dict[module_name][api_name][case_data_key]
def expect_data(self, row):
"""根据行号,获取期望数据"""
expect_data_key = self.__get_cell_value(EXPECT_DATA, row)
if expect_data_key:
module_name = self.module_name(row)
api_name = self.api_name(row)
return self.expect_data_dict[module_name][api_name][expect_data_key]
def sql_data(self, row):
"""根据行号,获取sql语句"""
sql_data_key = self.__get_cell_value(SQL_DATA, row)
if sql_data_key:
module_name = self.module_name(row)
api_name = self.api_name(row)
return self.sql_data_dict[module_name][api_name][sql_data_key]
def sql_type(self, row):
"""根据行号,获取sql语句的类型"""
value = self.__get_cell_value(SQL_TYPE, row)
if value:
return value.lower()
def update_key(self, row):
"""根号行号,获取更新的key"""
return self.__get_cell_value(UPDATE_KEY, row)
def case_title(self, row):
"""根据行号,获取用例的标题"""
return self.__get_cell_value(TITLE, row)
def case_level(self, row):
"""根号行号,获取用例的等级"""
return self.__get_cell_value(LEVEL, row)
def get_data(self):
"""获取所有的测试数据,并存放在一个二维列表中"""
list_data = []
for row in range(2, self.ws.max_row+1):
module_name = self.module_name(row)
api_name = self.api_name(row)
title = self.case_title(row)
level = self.case_level(row)
url = self.case_url(row)
method = self.case_req_method(row)
mime = self.case_mime(row)
case_data = self.case_data(row)
expect_data = self.expect_data(row)
sql_type = self.sql_type(row)
sql_data = self.sql_data(row)
update_key = self.update_key(row)
if url is not None and method is not None and expect_data is not None:
list_data.append([module_name, api_name, level, title, url, method, mime, case_data, expect_data, sql_type, sql_data, update_key])
else:
return list_data
if __name__ == '__main__':
excel = ReadExcel("lao_zhang")
print(excel.get_data())
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: read_json.py
# Author: lao_zhao
# Datetime: 2024/9/4 14:31
# Description:
#
# ---------------------------------------------------------------------------
import json
from apiAutoTest_v3 import log
def read_json(file_path):
"""读取json文件,将json文件的数据序列化为python对象再返回"""
if isinstance(file_path, str):
try:
with open(file_path, mode="r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
log.error(f"读取json文件失败,传入的文件路径:{file_path}-可能文件路径不存在,也有可能文件的数据格式有错误,错误为:{e}")
raise e
else:
log.error(f"执行read_json失败,传入的文件路径:{file_path}-不为字符串")
raise ValueError("传入的文件路径必须为字符串")
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: read_project_ini.py
# Author: lao_zhao
# Datetime: 2024/9/6 17:03
# Description:
#
# ---------------------------------------------------------------------------
import configparser
import os
from apiAutoTest_v3 import log
class ReadProjectIni:
def __init__(self):
"""获取ini文件的路径,并读取ini"""
self.data_config = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data_config")
# 获取项目配置ini文件的路径
ini_path = os.path.join(self.data_config, "project_config.ini")
self.conf = configparser.ConfigParser()
self.conf.read(ini_path, encoding="utf-8")
def get_host(self, key):
"""根据key获取host节点下key对应被测系统的域名"""
try:
return self.conf.get("host", key)
except Exception as e:
log.error(f"方法get_host执行失败,形参key传参为:{key},错误为:{e}")
raise e
def get_sql_connect_msg(self, key):
"""根据key获取sql节点下key对应的数据库链接信息"""
try:
return self.conf.get("sql", key)
except Exception as e:
log.error(f"方法get_sql_connect_msg执行失败,形参key传参为:{key},错误为:{e}")
raise e
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: read_ini.py
# Author: lao_zhao
# Datetime: 2024/9/4 14:17
# Description:
#
# ---------------------------------------------------------------------------
import configparser
import os
from apiAutoTest_v3 import log
class ReadUserIni:
def __init__(self, user_dir_name):
"""获取ini文件的路径,并读取ini"""
# 获取数据配置层的目录路径
data_config = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data_config")
# 获取存放用户数据的目录路径
self.user_dir = os.path.join(data_config, user_dir_name)
# 拼接用户的ini文件路径
ini_path = os.path.join(self.user_dir, "config.ini")
self.conf = configparser.ConfigParser()
self.conf.read(ini_path, encoding="utf-8")
def get_file_path(self, key):
"""根据key获取file节点下key对应文件的路径"""
try:
log.info(f"执行方法get_file_path为:根据key获取file节点下key对应文件的路径,形参key的传参为{key},")
file_name = self.conf.get("file", key)
except Exception as e:
log.error(f"方法get_file_path执行失败,形参key传参为:{key},错误为:{e}")
raise e
else:
return os.path.join(self.user_dir, file_name)
def get_table_name(self, key):
"""根据key获取table节点下key对应的工作表名"""
try:
return self.conf.get("table", key)
except Exception as e:
log.error(f"方法get_table_name执行失败,形参key传参为:{key},错误为:{e}")
raise e
if __name__ == '__main__':
ini = ReadUserIni("demo")
# D:\Project\PythonDoc\test62\test62\apiAutoTest_v3\data_config\demo\apiAutoTest.xlsx
# D:\Project\PythonDoc\test62\test62\apiAutoTest_v3\data_config\demo\apiAutoTest.xlsx
print(ini.get_file_path("excel"))
\ No newline at end of file
{
"认证接口":{
"登录系统":{
"LoginSuccess": {"username": "admin","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsNone": {"username": "","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsSpecialChar": {"username": "#!$!@#!@#","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsLong": {"username": "adminadminadminadminadminadminadminadminadmin","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsShort": {"username": "a","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsError": {"username": "adminxyz","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorPasswordIsNone": {"username": "admin","password": ""},
"LoginErrorPasswordIsSpecialChar": {"username": "admin","password": "#!$!@#!@#"},
"LoginErrorPasswordIsLong": {"username": "admin","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jznbF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jznbF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jznbF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jznbF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn"},
"LoginErrorPasswordIsShort": {"username": "admin","password": "123456"},
"LoginErrorPasswordIsError": {"username": "admin","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ"}
}
},
"维度管理": {
"添加维度": {
"AddDemSuccess": {"code": "requestsAddDem","description": "requestsAddDem","isDefault": 1,"name": "requests添加的维度"}
},
"根据维度编码获取维度信息": {
"GetDemMessageSuccess": {"code": "requestsAddDem"}
},
"根据维度编码删除维度": {
"DeleteDemSuccess": {"ids": "需要更新"}
},
"更新维度": {
"UpdateDemSuccess": {
"code": "requestsAddDem",
"description": "requestsAddDem",
"isDefault": 0,
"name": "requestsAddDem"
}
}
},
"组织管理": {
"添加组织": {
"AddOrgSuccess": {
"code": "testAddOrg",
"demId": "需要更新",
"exceedLimitNum": 0,
"grade": "",
"limitNum": 0,
"name": "测试添加的组织",
"nowNum": 0,
"orderNo": 0,
"parentId": "0"
}
},
"用户加入组织": {
"OrgAddUserSuccess": {"orgCode": "testAddOrg", "accounts": "admin,guest"}
},
"保存组织参数": {
"SaveOrgparamsSuccess": {
"query": {"orgCode": "testAddOrg"},
"body": [{"alias": "hxxmts", "value": "项目中没有关系户"}]
}
},
"删除组织": {
"DeleteOrgSuccess": "testAddOrg"
}
}
}
[file]
# 配置数据配置层中文件的名称
excel=apiAutoTest.xlsx
case=case_data.json
expect=expect_data.json
sql=sql_data.json
[table]
# 配置工作表名称
table_name=BPM
{
"认证接口":{
"登录系统":{
"LoginSuccess": {"username":"超级管理员","account":"admin","userId":"1","expiration":86400,"loginStatus":true},
"LoginErrorUsernameIsNone": {"message":"账号或密码错误"},
"LoginErrorUsernameIsSpecialChar": {"message":"账号或密码错误"},
"LoginErrorUsernameIsLong": {"message":"账号或密码错误"},
"LoginErrorUsernameIsShort": {"message":"账号或密码错误"},
"LoginErrorUsernameIsError": {"message":"账号或密码错误"},
"LoginErrorPasswordIsNone":{"message":"账号或密码错误"},
"LoginErrorPasswordIsSpecialChar": {"message":"账号或密码错误"},
"LoginErrorPasswordIsLong": {"message":"账号或密码错误"},
"LoginErrorPasswordIsShort": {"message":"账号或密码错误"},
"LoginErrorPasswordIsError":{"message":"账号或密码错误"}
},
"刷新token": {
"RefreshSuccess": {"message": "刷新token成功"}
}
},
"维度管理": {
"添加维度": {
"AddDemSuccess": {"message": "添加维度成功"}
},
"根据维度编码获取维度信息": {
"GetDemMessageSuccess": {"isDelete": "0"}
},
"根据维度编码删除维度": {
"DeleteDemSuccess": {"message": "删除维度成功!"}
},
"更新维度": {
"UpdateDemSuccess": {"message": "更新维度成功"}
}
},
"组织管理": {
"添加组织": {
"AddOrgSuccess": {"message": "添加组织成功"}
},
"用户加入组织": {
"OrgAddUserSuccess": {"message":"加入成功"}
},
"保存组织参数": {
"SaveOrgparamsSuccess": {"message":"保存组织参数成功!"}
},
"删除组织": {
"DeleteOrgSuccess": {"message":"删除组织成功!"}
}
}
}
{
"维度管理": {
"添加维度": {
"AddDemSuccess": {"delete": "dELETE FROM uc_demension WHERE `CODE_`=\"requestsAddDem\";"}
},
"根据维度编码删除维度": {
"DeleteDemSuccess": {"select": "select ID_ from uc_demension where CODE_=\"requestsAddDem\";"}
}
},
"组织管理": {
"添加组织": {
"AddOrgSuccess": {
"select": "select ID_ from uc_demension where CODE_=\"requestsAddDem\"; ",
"delete": "delete from uc_org where CODE_=\"testAddOrg\";"
}
}
}
}
[file]
# 配置数据配置层中文件的名称
excel=老张的用例管理文件.xlsx
case=老张的用例数据文件.json
expect=老张的期望数据文件.json
sql=老张的sql语句文件.json
[table]
# 配置工作表名称
table_name=登录和添加维度的用例
{
{
"维度管理": {
"添加维度": {
"AddDemSuccess": "dELETE FROM uc_demension WHERE `CODE_`=\"requestsAddDem\";"
},
"根据维度编码删除维度": {
"DeleteDemSuccess": "select ID_ from uc_demension where CODE_=\"requestsAddDem\";"
}
}
}
{
{
"认证接口":{
"登录系统":{
"LoginSuccess": {"username":"超级管理员","account":"admin","userId":"1","expiration":86400,"loginStatus":true},
"LoginErrorUsernameIsNone": {"message":"账号或密码错误"},
"LoginErrorUsernameIsSpecialChar": {"message":"账号或密码错误"},
"LoginErrorUsernameIsLong": {"message":"账号或密码错误"},
"LoginErrorUsernameIsShort": {"message":"账号或密码错误"},
"LoginErrorUsernameIsError": {"message":"账号或密码错误"},
"LoginErrorPasswordIsNone":{"message":"账号或密码错误"},
"LoginErrorPasswordIsSpecialChar": {"message":"账号或密码错误"},
"LoginErrorPasswordIsLong": {"message":"账号或密码错误"},
"LoginErrorPasswordIsShort": {"message":"账号或密码错误"},
"LoginErrorPasswordIsError":{"message":"账号或密码错误"}
},
"刷新token": {
"RefreshSuccess": {"message": "刷新token成功"}
}
},
"维度管理": {
"添加维度": {
"AddDemSuccess": {"message": "添加维度成功"}
},
"根据维度编码获取维度信息": {
"GetDemMessageSuccess": {"isDelete": "0"}
},
"根据维度编码删除维度": {
"DeleteDemSuccess": {"message": "删除维度成功!"}
}
}
}
{
{
"认证接口":{
"登录系统":{
"LoginSuccess": {"username": "admin","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsNone": {"username": "","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsSpecialChar": {"username": "#!$!@#!@#","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsLong": {"username": "adminadminadminadminadminadminadminadminadmin","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsShort": {"username": "a","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorUsernameIsError": {"username": "adminxyz","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="},
"LoginErrorPasswordIsNone": {"username": "admin","password": ""},
"LoginErrorPasswordIsSpecialChar": {"username": "admin","password": "#!$!@#!@#"},
"LoginErrorPasswordIsLong": {"username": "admin","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jznbF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jznbF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jznbF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jznbF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn"},
"LoginErrorPasswordIsShort": {"username": "admin","password": "123456"},
"LoginErrorPasswordIsError": {"username": "admin","password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQqmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerVlYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ"}
}
},
"维度管理": {
"添加维度": {
"AddDemSuccess": {"code": "requestsAddDem","description": "requestsAddDem","isDefault": 1,"name": "requests添加的维度"}
},
"根据维度编码获取维度信息": {
"GetDemMessageSuccess": {"code": "requestsAddDem"}
},
"根据维度编码删除维度": {
"DeleteDemSuccess": {"ids": "需要更新"}
}
}
}
[host]
# 配置被测系统的域名
bpm_host=http://36.139.193.99:8088
[sql]
host=36.139.193.99
port=3306
user=root
password=Rhrc@2024
database=eip8
[report]
log=log
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: settings.py
# Author: lao_zhao
# Datetime: 2024/9/4 16:03
# Description:
#
# ---------------------------------------------------------------------------
# excel的列号---------------------------------------------------------------------------
NUMBER = "A"
MODULE = "B"
API = "C"
TITLE = "D"
LEVEL = "E"
URL = "F"
REQ_METHOD = "G"
MIME = "H"
CASE_DATA = "I"
EXPECT_DATA = "J"
SQL_TYPE = "K"
SQL_DATA = "L"
UPDATE_KEY = "M"
# ini文件中file节点的key---------------------------------------------------------------------------
FILE_EXCEL = "excel"
FILE_CASE = "case"
FILE_EXPECT = "expect"
FILE_SQL = "sql"
# ini文件中host节点的key---------------------------------------------------------------------------
HOST_KEY = "bpm_host"
# ini文件中table节点的key---------------------------------------------------------------------------
TABLE_kEY = "table_name"
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: __init__.py
# Author: lao_zhao
# Datetime: 2024/9/4 14:01
# Description:
#
# ---------------------------------------------------------------------------
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: request_method.py
# Author: lao_zhao
# Datetime: 2024/9/4 15:35
# Description:
#
# ---------------------------------------------------------------------------
import requests
from apiAutoTest_v3.common.read_project_ini import ReadProjectIni
class RequestMethod:
def __init__(self):
"""关联登录成功的token"""
# 被测系统的域名存放在项目的ini配置文件中,所有需要ReadProjectIni对象,调用get_host方法获取被测系统的域名
login_url = ReadProjectIni().get_host("bpm_host") + "/auth"
login_data = {"username": "admin", "password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQ"
"qmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerV"
"lYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="}
self.bpm_session = requests.sessions.Session()
res = self.bpm_session.post(url=login_url, json=login_data)
token = res.json().get("token")
self.bpm_session.headers["Authorization"] = f"Bearer {token}"
def request_all(self, req_method, req_url, req_mime, case_data):
"""
封装公共的请求方法
:param req_method:请求方法
:param req_url:请求的url
:param req_mime:媒体类型
:param case_data:用例数据
:return:Response type
"""
if req_mime == "application/json" or req_mime == "json":
return self.bpm_session.request(method=req_method, url=req_url, json=case_data)
elif req_mime == "application/x-www-form-urlencoded" or req_mime == "form":
# 除了上传文件和json类型在请求体中传参以外,其他类型的数据全部使用data关键字传参。
return self.bpm_session.request(method=req_method, url=req_url, data=case_data)
elif req_mime == "multipart/form-data" or req_mime == "form-data":
return self.bpm_session.request(method=req_method, url=req_url, files=case_data)
elif req_mime == "query" or req_mime == "params":
return self.bpm_session.request(method=req_method, url=req_url, params=case_data)
elif req_mime is None:
return self.bpm_session.request(method=req_method, url=req_url)
# 判断媒体类型是否为query|json或者为json|query, 表示请求体和地址栏同时传参
elif req_mime == "query|json" or req_mime == "json|query":
# requests是支持地址栏和请求体同时传参的。地址栏使用params传参,请求体根据不同的媒体类型选择不同的关键字传参。
return self.bpm_session.request(method=req_method, url=req_url, params=case_data["query"], json=case_data["body"])
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: __init__.py
# Author: lao_zhao
# Datetime: 2024/9/6 17:25
# Description:
#
# ---------------------------------------------------------------------------
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: __init__.py
# Author: lao_zhao
# Datetime: 2024/9/4 14:01
# Description:
#
# ---------------------------------------------------------------------------
# user_data_dir_name就是用户存放数据的目录名称
# user_data_dir_name = "demo"
# namespace也是用户存放数据的目录名称
namespace = "demo"
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: conftest.py
# Author: lao_zhao
# Datetime: 2024/9/4 15:43
# Description:
#
# ---------------------------------------------------------------------------
import pytest
from apiAutoTest_v3.common.db import DB
from apiAutoTest_v3.request_method.request_method import RequestMethod
# DB自定义固件
@pytest.fixture(scope="session")
def fix_db():
db = DB()
yield db
db.close()
# RequestMethod自定义固件
@pytest.fixture(scope="session")
def fix_req():
req = RequestMethod()
yield req
[pytest]
; ;开启日志
; log_cli=true
; ;设置日志的级别,如果不设置级别的话,可以设置为NOTSET,如果要设置级别,级别可以有debug,info,warning,error,致命
; log_level=NOTSET
; ;设置日志显示的信息格式
; log_format=%(levelname)s--%(asctime)s--%(message)s
; ;设置日志中时间显示的格式
; log_date_format=%Y-%m-%d %H:%M:%S
; ;每个py文件运行的时候追加的命令
; ;addopts=-vs
; ;设置日志保存的文件
; log_file=../report/log/bpm_test.log
;设置日志保存在文件中的级别
log_file_level=error
;设置日志在文件中的信息格式
log_file_format=%(levelname)s--%(asctime)s--%(message)s
;设置文件日志中时间显示的格式
log_file_date_format=%Y-%m-%d %H:%M:%S
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: test_bpm.py
# Author: lao_zhao
# Datetime: 2024/9/4 15:46
# Description:
#
# ---------------------------------------------------------------------------
import pytest
import allure
from apiAutoTest_v3 import log
from apiAutoTest_v3.common.read_excel import ReadExcel
from apiAutoTest_v3.test_case.test_demo import namespace
# 创建ReadExcel对象,便于获取用户的测试数据,所有创建ReadExcel对象时需要传入用户存放数据的目录名称
excel = ReadExcel(namespace)
class TestBPM:
@allure.epic("BPM项目-Demo")
# @allure.feature("模块名称")
# @allure.story("接口名称")
# @allure.title("用例标题")
# @allure.severity("用例等级")
@pytest.mark.parametrize("module_name, api_name, level, title, url, method, mime, case_data, expect_data, sql_type, sql_data, update_key", excel.get_data())
def test_bpm(self, fix_db, fix_req, module_name, api_name, level, title, url, method, mime, case_data, expect_data, sql_type, sql_data, update_key):
allure.dynamic.feature(module_name)
allure.dynamic.story(api_name)
allure.dynamic.title(title)
allure.dynamic.severity(level)
# 判断sql语句的类型是否为delete
if sql_type == "delete":
# 使用DB类对象调用delete方法执行删除的sql语句,DB类对象===fix_db自定义固件
fix_db.delete(sql_data['delete'])
# 判断sql语句类型是否为select
elif sql_type == "select":
# 使用DB类对象调用select方法执行查询的sql语句, 并获取查询结果,DB类对象===fix_db自定义固件
select_result = fix_db.select(sql_data['select'])
# 将查询结果更新到用例数据中
case_data[update_key] = select_result
# 判断sql语句的类型是否为select|delete 或者为 delete|select
elif sql_type == "select|delete" or sql_type == "delete|select":
# 使用DB类对象调用delete方法执行删除的sql语句,DB类对象===fix_db自定义固件
fix_db.delete(sql_data['delete'])
# 使用DB类对象调用select方法执行查询的sql语句, 并获取查询结果,DB类对象===fix_db自定义固件
select_result = fix_db.select(sql_data['select'])
# 将查询结果更新到用例数据中
case_data[update_key] = select_result
# 使用RequestMethod类对象发送请求
res = fix_req.request_all(req_method=method, req_url=url, req_mime=mime, case_data=case_data)
# 断言
try:
for key in expect_data.keys():
assert expect_data[key] == res.json().get(key)
except AssertionError:
log.error(f"断言失败,接口url为:{url}, 用例数据:{case_data}, 期望数据:{expect_data}, 服务器返回数据:{res.text}")
raise AssertionError("断言失败")
else:
log.info(f"断言成功,接口url为:{url}, 用例数据:{case_data}, 期望数据:{expect_data}, 服务器返回数据:{res.text}")
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: __init__.py
# Author: lao_zhao
# Datetime: 2024/9/6 17:30
# Description:
#
# ---------------------------------------------------------------------------
namespace = "lao_zhang"
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: conftest.py
# Author: lao_zhao
# Datetime: 2024/9/4 15:43
# Description:
#
# ---------------------------------------------------------------------------
import pytest
from apiAutoTest_v3.common.db import DB
from apiAutoTest_v3.request_method.request_method import RequestMethod
# DB自定义固件
@pytest.fixture(scope="session")
def fix_db():
db = DB()
yield db
db.close()
# RequestMethod自定义固件
@pytest.fixture(scope="session")
def fix_req():
req = RequestMethod()
yield req
[pytest]
; ;开启日志
; log_cli=true
; ;设置日志的级别,如果不设置级别的话,可以设置为NOTSET,如果要设置级别,级别可以有debug,info,warning,error,致命
; log_level=NOTSET
; ;设置日志显示的信息格式
; log_format=%(levelname)s--%(asctime)s--%(message)s
; ;设置日志中时间显示的格式
; log_date_format=%Y-%m-%d %H:%M:%S
; ;每个py文件运行的时候追加的命令
; ;addopts=-vs
; ;设置日志保存的文件
; log_file=../report/log/bpm_test.log
;设置日志保存在文件中的级别
log_file_level=error
;设置日志在文件中的信息格式
log_file_format=%(levelname)s--%(asctime)s--%(message)s
;设置文件日志中时间显示的格式
log_file_date_format=%Y-%m-%d %H:%M:%S
\ No newline at end of file
# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName: test62
# FileName: test_bpm.py
# Author: lao_zhao
# Datetime: 2024/9/4 15:46
# Description:
#
# ---------------------------------------------------------------------------
import pytest
import allure
from apiAutoTest_v3 import log
from apiAutoTest_v3.common.read_excel import ReadExcel
from apiAutoTest_v3.test_case.test_zhang import namespace
# 创建ReadExcel对象,便于获取用户的测试数据,所有创建ReadExcel对象时需要传入用户存放数据的目录名称
excel = ReadExcel(namespace)
class TestBPM:
@allure.epic("BPM项目-Demo")
# @allure.feature("模块名称")
# @allure.story("接口名称")
# @allure.title("用例标题")
# @allure.severity("用例等级")
@pytest.mark.parametrize("module_name, api_name, level, title, url, method, mime, case_data, expect_data, sql_type, sql_data, update_key", excel.get_data())
def test_bpm(self, fix_db, fix_req, module_name, api_name, level, title, url, method, mime, case_data, expect_data, sql_type, sql_data, update_key):
allure.dynamic.feature(module_name)
allure.dynamic.story(api_name)
allure.dynamic.title(title)
allure.dynamic.severity(level)
# 判断sql语句的类型是否为delete
if sql_type == "delete":
# 使用DB类对象调用delete方法执行删除的sql语句,DB类对象===fix_db自定义固件
fix_db.delete(sql_data['delete'])
# 判断sql语句类型是否为select
elif sql_type == "select":
# 使用DB类对象调用select方法执行查询的sql语句, 并获取查询结果,DB类对象===fix_db自定义固件
select_result = fix_db.select(sql_data['select'])
# 将查询结果更新到用例数据中
case_data[update_key] = select_result
# 判断sql语句的类型是否为select|delete 或者为 delete|select
elif sql_type == "select|delete" or sql_type == "delete|select":
# 使用DB类对象调用delete方法执行删除的sql语句,DB类对象===fix_db自定义固件
fix_db.delete(sql_data['delete'])
# 使用DB类对象调用select方法执行查询的sql语句, 并获取查询结果,DB类对象===fix_db自定义固件
select_result = fix_db.select(sql_data['select'])
# 将查询结果更新到用例数据中
case_data[update_key] = select_result
# 使用RequestMethod类对象发送请求
res = fix_req.request_all(req_method=method, req_url=url, req_mime=mime, case_data=case_data)
# 断言
try:
for key in expect_data.keys():
assert expect_data[key] == res.json().get(key)
except AssertionError:
log.error(f"断言失败,接口url为:{url}, 用例数据:{case_data}, 期望数据:{expect_data}, 服务器返回数据:{res.text}")
raise AssertionError("断言失败")
else:
log.info(f"断言成功,接口url为:{url}, 用例数据:{case_data}, 期望数据:{expect_data}, 服务器返回数据:{res.text}")
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment