将环境数据与配置数据, 模型数据隔离开,同步修改了配套相关代码

This commit is contained in:
floraachy
2023-05-25 15:59:00 +08:00
parent c9595c8ca2
commit 9904ba8626
14 changed files with 159 additions and 196 deletions
+1 -1
View File
@@ -7,7 +7,7 @@
import json import json
import allure import allure
from config.global_vars import AllureAttachmentType from config.models import AllureAttachmentType
import os import os
+4 -9
View File
@@ -12,7 +12,6 @@ from common_utils.data_handle import json_extractor, re_extract
from loguru import logger from loguru import logger
from case_utils.request_data_handle import response_type from case_utils.request_data_handle import response_type
from common_utils.mysql_handle import MysqlServer from common_utils.mysql_handle import MysqlServer
from config.settings import db_info
def assert_response(response: Response, expected: dict) -> None: def assert_response(response: Response, expected: dict) -> None:
@@ -85,10 +84,10 @@ def assert_response(response: Response, expected: dict) -> None:
"=====================================================") "=====================================================")
def assert_sql(env, expected: dict): def assert_sql(db_info, expected: dict):
""" """
数据库断言 数据库断言
:param env: 当前所处环境 :param db_info: 数据库配置信息
:param expected: 预期结果,从excel中或者yaml读取、或者手动传入,格式如下: :param expected: 预期结果,从excel中或者yaml读取、或者手动传入,格式如下:
{ {
'eq': 'eq':
@@ -104,11 +103,7 @@ def assert_sql(env, expected: dict):
allure_step(step_title='判断是否存在数据库断言', allure_step(step_title='判断是否存在数据库断言',
content='当前用例无数据库断言') content='当前用例无数据库断言')
return return
try: if not db_info:
# 拿不到数据库配置,则不进行数据库断言
db = db_info["test" if env.lower() == "test" else "live"]
db_host = db["db_host"]
except KeyError:
logger.error("当前环境无数据库配置,跳过数据库断言!") logger.error("当前环境无数据库配置,跳过数据库断言!")
allure_step(step_title='判断是否存在数据库配置', allure_step(step_title='判断是否存在数据库配置',
content='当前环境无数据库配置,跳过数据库断言!}') content='当前环境无数据库配置,跳过数据库断言!}')
@@ -121,7 +116,7 @@ def assert_sql(env, expected: dict):
if _k == "sql": if _k == "sql":
try: try:
# 查询数据库,获取查询结果 # 查询数据库,获取查询结果
sql_result = MysqlServer(**db).query_one(_v) sql_result = MysqlServer(**db_info).query_one(_v)
logger.info(f'数据库响应断言 -|- SQL{_v} || 查询结果:{sql_result}') logger.info(f'数据库响应断言 -|- SQL{_v} || 查询结果:{sql_result}')
allure_step(step_title=f'数据库断言', allure_step(step_title=f'数据库断言',
content=f'SQL{_v} || 查询结果:{sql_result}') content=f'SQL{_v} || 查询结果:{sql_result}')
+2 -2
View File
@@ -7,10 +7,10 @@
# @Desc: 生成测试用例文件并返回用例数据 # @Desc: 生成测试用例文件并返回用例数据
import os import os
from config.project_path import CASE_TEMPLATE_DIR, DATA_DIR, AUTO_CASE_DIR from config.path_config import CASE_TEMPLATE_DIR, DATA_DIR, AUTO_CASE_DIR
from common_utils.excel_handle import ExcelHandle from common_utils.excel_handle import ExcelHandle
from common_utils.yaml_handle import YamlHandle from common_utils.yaml_handle import YamlHandle
from config.global_vars import CaseFileType from config.models import CaseFileType
from config.settings import CASE_FILE_TYPE from config.settings import CASE_FILE_TYPE
from string import Template from string import Template
from loguru import logger from loguru import logger
+1 -1
View File
@@ -29,7 +29,7 @@ def get_test_results_from_pytest_html_report(html_report_path):
"Python": "python_version", "Python": "python_version",
"开始时间": "start_time", "开始时间": "start_time",
"项目名称": "project_name", "项目名称": "project_name",
"项目环境": "project_env" "项目环境": "run_env"
} }
for key, value in enumerate(new_environment_info): for key, value in enumerate(new_environment_info):
if value in info_mapping: if value in info_mapping:
+2 -1
View File
@@ -131,6 +131,7 @@ class RequestPreDataHandle:
if self.request_data.get("assert_response", None): if self.request_data.get("assert_response", None):
self.request_data["assert_response"] = eval_data_process( self.request_data["assert_response"] = eval_data_process(
data_replace(content=self.request_data.get("assert_response", None), source=GLOBAL_VARS)) data_replace(content=self.request_data.get("assert_response", None), source=GLOBAL_VARS))
# 由于数据库断言里面的变量需要请求响应后进行提取,因此目前不进行处理
# ---------------------------------------- 进行请求,请求后的参数提取处理----------------------------------------# # ---------------------------------------- 进行请求,请求后的参数提取处理----------------------------------------#
@@ -148,7 +149,7 @@ class RequestHandle:
""" """
response = BaseRequest.send_request(self.case_data) response = BaseRequest.send_request(self.case_data)
self.case_data["extract"] = self.after_extract(response, self.case_data.get("extract", None)) self.case_data["extract"] = self.after_extract(response, self.case_data.get("extract", None))
# 从全局变量中获取最新值,替换数据库断言中的参数 # 处理数据库断言 - 从全局变量中获取最新值,替换数据库断言中的参数
if self.case_data.get('assert_sql', None): if self.case_data.get('assert_sql', None):
self.case_data["assert_sql"] = eval_data_process( self.case_data["assert_sql"] = eval_data_process(
data_replace(content=self.case_data["assert_sql"], source=GLOBAL_VARS)) data_replace(content=self.case_data["assert_sql"], source=GLOBAL_VARS))
+1 -1
View File
@@ -7,7 +7,7 @@
from loguru import logger from loguru import logger
from common_utils.yagmail_handle import YagEmailServe from common_utils.yagmail_handle import YagEmailServe
from config.global_vars import NotificationType from config.models import NotificationType
from config.settings import SEND_RESULT_TYPE, email, ding_talk, wechat, email_subject, email_content, ding_talk_title, \ from config.settings import SEND_RESULT_TYPE, email, ding_talk, wechat, email_subject, email_content, ding_talk_title, \
ding_talk_content, wechat_content ding_talk_content, wechat_content
from common_utils.dingding_handle import DingTalkBot from common_utils.dingding_handle import DingTalkBot
+6 -4
View File
@@ -6,20 +6,22 @@ from pytest_html import extras # 往pytest-html报告中填写额外的内容
from common_utils.func_handle import add_docstring from common_utils.func_handle import add_docstring
from case_utils.allure_handle import allure_title from case_utils.allure_handle import allure_title
import allure import allure
from config.settings import db_info
from config.global_vars import GLOBAL_VARS
# 用例数据 # 用例数据
cases = ${case_data} cases = ${case_data}
@allure.story(f'{cases["case_common"]["allure_story"]}') @allure.story(f'{cases["case_common"]["allure_story"]}')
@pytest.mark.${func_title} @pytest.mark.${func_title}
@pytest.mark.auto @pytest.mark.auto
@pytest.mark.parametrize("case", cases.get("case_info")) @pytest.mark.parametrize("case", cases.get("case_info"))
def ${func_title}_auto(case, extra, request): def ${func_title}_auto(case, extra):
logger.info("-----------------------------START-开始执行用例-----------------------------") logger.info("-----------------------------START-开始执行用例-----------------------------")
logger.debug(f"当前执行的用例数据:{case}") logger.debug(f"当前执行的用例数据:{case}")
try: try:
# 获取命令行参数,判断当前处于哪个环境
env = request.config.getoption("--env")
# 给当前测试方法添加文档注释 # 给当前测试方法添加文档注释
add_docstring(case.get("title", ""))(${func_title}_auto) add_docstring(case.get("title", ""))(${func_title}_auto)
# 添加用例标题作为allure中显示的用例标题 # 添加用例标题作为allure中显示的用例标题
@@ -36,7 +38,7 @@ def ${func_title}_auto(case, extra, request):
# 进行响应断言 # 进行响应断言
assert_response(response, case_data["assert_response"]) assert_response(response, case_data["assert_response"])
# 进行数据库断言 # 进行数据库断言
assert_sql(env, case_data["assert_sql"]) assert_sql(db_info[GLOBAL_VARS["env_key"]], case_data["assert_sql"])
else: else:
reason = f"标记了该用例为false,不执行\\n" reason = f"标记了该用例为false,不执行\\n"
logger.warning(f"{reason}") logger.warning(f"{reason}")
+30 -53
View File
@@ -1,60 +1,37 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# @Version: Python 3.9 # @Time : 2023/5/25 14:52
# @Time : 2023/1/31 14:31
# @Author : chenyinhua # @Author : chenyinhua
# @File : global_vars.py # @File : global_vars.py
# @Software: PyCharm # @Software: PyCharm
# @Desc: 全局变量 # @Desc:
# 定义一个全局变量,用于存储运行过程中相关数据
from enum import Enum, unique # python 3.x版本才能使用
# 定义一个全局变量,作用于接口关联数据存储
GLOBAL_VARS = {} GLOBAL_VARS = {}
ENV_VARS = {
"common": {
"report_title": "自动化测试报告",
"project_name": "GitLink 确实开源",
"tester": "陈银花",
"department": "开源中心"
},
"test": {
# 示例测试环境及示例测试账号
"host": "https://testforgeplus.trustie.net/",
"login": "auotest",
"password": "12345678",
"nickname": "AutoTest",
"user_id": "84954",
"project_id": "",
"project": ""
class CaseFileType(Enum): },
""" "live": {
用例数据可存储文件的类型枚举 "host": "https://www.gitlink.org.cn",
""" "login": "******",
YAML = 1 "password": "******",
EXCEL = 2 "nickname": "******",
ALL = 0 "user_id": "******",
"project_id": "",
"project": ""
class NotificationType(Enum): }
""" 自动化通知方式 """ }
DEFAULT = 0
DING_TALK = 1
WECHAT = 2
EMAIL = 3
ALL = 4
@unique # 枚举类装饰器,确保只有一个名称绑定到任何一个值。
class AllureAttachmentType(Enum):
"""
allure 报告的文件类型枚举
"""
TEXT = "txt"
CSV = "csv"
TSV = "tsv"
URI_LIST = "uri"
HTML = "html"
XML = "xml"
JSON = "json"
YAML = "yaml"
PCAP = "pcap"
PNG = "png"
JPG = "jpg"
SVG = "svg"
GIF = "gif"
BMP = "bmp"
TIFF = "tiff"
MP4 = "mp4"
OGG = "ogg"
WEBM = "webm"
PDF = "pdf"
+57
View File
@@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
# @Version: Python 3.9
# @Time : 2023/1/31 14:31
# @Author : chenyinhua
# @File : models.py
# @Software: PyCharm
# @Desc: 全局变量
from enum import Enum, unique # python 3.x版本才能使用
class CaseFileType(Enum):
"""
用例数据可存储文件的类型枚举
"""
YAML = 1
EXCEL = 2
ALL = 0
class NotificationType(Enum):
""" 自动化通知方式 """
DEFAULT = 0
DING_TALK = 1
WECHAT = 2
EMAIL = 3
ALL = 4
@unique # 枚举类装饰器,确保只有一个名称绑定到任何一个值。
class AllureAttachmentType(Enum):
"""
allure 报告的文件类型枚举
"""
TEXT = "txt"
CSV = "csv"
TSV = "tsv"
URI_LIST = "uri"
HTML = "html"
XML = "xml"
JSON = "json"
YAML = "yaml"
PCAP = "pcap"
PNG = "png"
JPG = "jpg"
SVG = "svg"
GIF = "gif"
BMP = "bmp"
TIFF = "tiff"
MP4 = "mp4"
OGG = "ogg"
WEBM = "webm"
PDF = "pdf"
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# @Time : 2023/5/16 11:12 # @Time : 2023/5/16 11:12
# @Author : chenyinhua # @Author : chenyinhua
# @File : project_path.py # @File : path_config.py
# @Software: PyCharm # @Software: PyCharm
# @Desc: # @Desc:
+23 -57
View File
@@ -13,43 +13,29 @@ CASE_FILE_TYPE = 1
# 0表示默认不发送任何通知, 1代表钉钉通知,2代表企业微信通知, 3代表邮件通知, 4代表所有途径都发送通知 # 0表示默认不发送任何通知, 1代表钉钉通知,2代表企业微信通知, 3代表邮件通知, 4代表所有途径都发送通知
SEND_RESULT_TYPE = 0 SEND_RESULT_TYPE = 0
# 测试报告的定制化信息展示
ENV_INFO = {
"report_title": "自动化测试报告",
"report_name": "autotestreport_",
"project_name": "GitLink 确实开源",
"tester": "陈银花",
"department": "开源中心"
}
# 指定日志收集级别 # 指定日志收集级别
LOG_LEVEL = "INFO" LOG_LEVEL = "INFO"
# ------------------------------------ 测试数据 ----------------------------------------------------# # ------------------------------------ 数据库相关配置 ----------------------------------------------------#
test = [ db_info = {
{ "test": {
# 示例测试环境及示例测试账号 "db_host": "xx.xx.xx.xx",
"host": "https://testforgeplus.trustie.net/", "db_port": 3306,
"login": "auotest", "db_user": "root",
"password": "12345678", "db_pwd": "**********",
"nickname": "AutoTest", "db_database": "test**********",
"user_id": "84954", "ssh": True,
"project_id": "", "ssh_host": "xx.xx.xx.xx",
"project": "" "ssh_port": 3306,
"ssh_user": "root",
"ssh_pwd": "**********"
},
"live": {
} }
]
live = [ }
{
"host": "https://www.gitlink.org.cn",
"login": "******",
"password": "******",
"nickname": "******",
"user_id": "******",
"project_id": "",
"project": ""
}
]
# ------------------------------------ 邮件配置信息 ----------------------------------------------------# # ------------------------------------ 邮件配置信息 ----------------------------------------------------#
@@ -62,7 +48,7 @@ email = {
} }
# ------------------------------------ 邮件通知内容 ----------------------------------------------------# # ------------------------------------ 邮件通知内容 ----------------------------------------------------#
email_subject = f"{ENV_INFO.get('project_name', None)} 接口自动化报告" email_subject = f"接口自动化报告"
email_content = """ email_content = """
各位同事, 大家好: 各位同事, 大家好:
@@ -70,7 +56,7 @@ email_content = """
--------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------
测试人:<strong> ${tester} </strong> 测试人:<strong> ${tester} </strong>
所属部门:<strong> ${department} </strong> 所属部门:<strong> ${department} </strong>
项目环境:<strong> ${project_env} </strong> 项目环境:<strong> ${run_env} </strong>
--------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------
执行结果如下: 执行结果如下:
&nbsp;&nbsp;用例运行总数:<strong> ${total} 个</strong> &nbsp;&nbsp;用例运行总数:<strong> ${total} 个</strong>
@@ -91,7 +77,7 @@ ding_talk = {
} }
# ------------------------------------ 钉钉通知内容 ----------------------------------------------------# # ------------------------------------ 钉钉通知内容 ----------------------------------------------------#
ding_talk_title = f"{ENV_INFO.get('project_name', None)} 接口自动化报告" ding_talk_title = f"接口自动化报告"
ding_talk_content = """ ding_talk_content = """
各位同事, 大家好: 各位同事, 大家好:
@@ -99,7 +85,7 @@ ding_talk_content = """
--------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------
#### 测试人: ${tester} #### 测试人: ${tester}
#### 所属部门: ${department} #### 所属部门: ${department}
#### 项目环境:${project_env} #### 项目环境: ${run_env}
--------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------
#### 执行结果如下: #### 执行结果如下:
- 用例运行总数: ${total} - 用例运行总数: ${total}
@@ -125,7 +111,7 @@ wechat_content = """
-------------------------------- --------------------------------
#### 测试人: ${tester} #### 测试人: ${tester}
#### 所属部门: ${department} #### 所属部门: ${department}
#### 项目环境:${project_env} #### 项目环境: ${run_env}
-------------------------------- --------------------------------
#### 执行结果如下: #### 执行结果如下:
- 用例运行总数: ${total} - 用例运行总数: ${total}
@@ -139,23 +125,3 @@ wechat_content = """
********************************** **********************************
附件为具体的测试报告,详细情况可下载附件查看, 非相关负责人员可忽略此消息。谢谢。 附件为具体的测试报告,详细情况可下载附件查看, 非相关负责人员可忽略此消息。谢谢。
""" """
# ------------------------------------ 数据库相关配置 ----------------------------------------------------#
db_info = {
"test": {
"db_host": "xx.xx.xx.xx",
"db_port": 3306,
"db_user": "root",
"db_pwd": "**********",
"db_database": "test**********",
"ssh": True,
"ssh_host": "xx.xx.xx.xx",
"ssh_port": 3306,
"ssh_user": "root",
"ssh_pwd": "**********"
},
"live": {
}
}
+6 -49
View File
@@ -7,54 +7,12 @@
# @Desc: 这是文件的描述信息 # @Desc: 这是文件的描述信息
import os.path import os.path
from config.global_vars import GLOBAL_VARS from config.global_vars import ENV_VARS, GLOBAL_VARS
from loguru import logger
import pytest import pytest
from py._xmlgen import html # 安装pytest-html,版本最好是2.1.1 from py._xmlgen import html # 安装pytest-html,版本最好是2.1.1
from time import strftime from time import strftime
from config.settings import test, live, ENV_INFO
# ------------------------------------- START: 配置运行环境 ---------------------------------------#
def pytest_addoption(parser):
"""
pytest_addoption 可以让用户注册一个自定义的命令行参数,方便用户将数据传递给 pytest;
这个 Hook 方法一般和 内置 fixture pytestconfig 配合使用,pytest_addoption 注册命令行参数,pytestconfig 通过配置对象读取参数的值;
:param parser:
:return:
"""
parser.addoption(
# action="store" 默认,只存储参数的值,可以存储任何类型的值,此时 default 也可以是任何类型的值,而且命令行参数多次使用也只能生效一个,最后一个值覆盖之前的值;
# action="append",将参数值存储为一个列表,用append模式将可以在pytest命令行方式执行测试用例的同时多次向程序内部传递自定义参数对应的参数值
"--env", action="store",
default="test",
choices=["test", "live"], # choices 只允许输入的值的范围
type=str,
help="将命令行参数--env添加到pytest配置对象中,通过--env设置当前运行的环境host"
)
@pytest.fixture(scope="session", autouse=True)
def get_config(request):
"""
从配置对象中读取自定义参数的值
"""
# 根据指定的环境,获取指定环境的域名以及用例数据文件类型
env = request.config.getoption("--env")
if env.lower() == "live":
config_data = live
else:
config_data = test
for item in config_data:
for k, v in item.items():
GLOBAL_VARS[k] = v
logger.debug(f"当前环境变量为:{GLOBAL_VARS}")
# ------------------------------------- END: 配置运行环境 ---------------------------------------#
# ------------------------------------- START: 报告处理 ---------------------------------------# # ------------------------------------- START: 报告处理 ---------------------------------------#
def pytest_collection_modifyitems(items): def pytest_collection_modifyitems(items):
"""# 测试用例执行收集完成时,将收集到的item的name和nodeid的中文显示在控制台上""" """# 测试用例执行收集完成时,将收集到的item的name和nodeid的中文显示在控制台上"""
@@ -79,7 +37,7 @@ def pytest_html_report_title(report):
""" """
修改报告标题 修改报告标题
""" """
report.title = ENV_INFO.get('report_title', "") report.title = f'{ENV_VARS["common"]["project_name"]} {ENV_VARS["common"]["report_title"]}'
def pytest_configure(config): def pytest_configure(config):
@@ -87,7 +45,7 @@ def pytest_configure(config):
# 在测试运行前,修改Environment部分信息,配置测试报告环境信息 # 在测试运行前,修改Environment部分信息,配置测试报告环境信息
""" """
# 给环境表 添加项目名称及开始时间 # 给环境表 添加项目名称及开始时间
config._metadata["项目名称"] = ENV_INFO.get('project_name', "") config._metadata["项目名称"] = ENV_VARS["common"]["project_name"]
config._metadata['开始时间'] = strftime('%Y-%m-%d %H:%M:%S') config._metadata['开始时间'] = strftime('%Y-%m-%d %H:%M:%S')
# 给环境表 移除packages 及plugins # 给环境表 移除packages 及plugins
config._metadata.pop("Packages") config._metadata.pop("Packages")
@@ -100,16 +58,15 @@ def pytest_sessionfinish(session, exitstatus):
在测试运行后,修改Environment部分信息 在测试运行后,修改Environment部分信息
""" """
# 给环境表 添加 项目环境 # 给环境表 添加 项目环境
env = session.config.getoption("--env") # 可以获取到命令行参数指定的环境 session.config._metadata['项目环境'] = GLOBAL_VARS.get("host", "")
session.config._metadata['项目环境'] = {GLOBAL_VARS.get("host", env)}
def pytest_html_results_summary(prefix, summary, postfix): def pytest_html_results_summary(prefix, summary, postfix):
""" """
修改Summary部分的信息 修改Summary部分的信息
""" """
prefix.extend([html.p(f'测试人员:{ENV_INFO.get("tester", "")}')]) prefix.extend([html.p(f'测试人员:{ENV_VARS["common"]["tester"]}')])
prefix.extend([html.p(f'所属部门: {ENV_INFO.get("department", "")}')]) prefix.extend([html.p(f'所属部门: {ENV_VARS["common"]["department"]}')])
def pytest_html_results_table_header(cells): def pytest_html_results_table_header(cells):
+20 -12
View File
@@ -18,12 +18,13 @@
import os import os
import shutil import shutil
import pytest import pytest
from config.project_path import REPORT_DIR, LOG_DIR, AUTO_CASE_DIR, CONF_DIR, LIB_DIR, ALLURE_RESULTS_DIR, \ from config.path_config import REPORT_DIR, LOG_DIR, AUTO_CASE_DIR, CONF_DIR, LIB_DIR, ALLURE_RESULTS_DIR, \
ALLURE_HTML_DIR ALLURE_HTML_DIR
from case_utils.case_handle import get_case_data from case_utils.case_handle import get_case_data
from loguru import logger from loguru import logger
import click import click
from config.settings import LOG_LEVEL, ENV_INFO from config.settings import LOG_LEVEL
from config.global_vars import GLOBAL_VARS, ENV_VARS
from datetime import datetime from datetime import datetime
from case_utils.platform_handle import PlatformHandle from case_utils.platform_handle import PlatformHandle
from case_utils.get_results_handle import get_test_results_from_pytest_html_report, \ from case_utils.get_results_handle import get_test_results_from_pytest_html_report, \
@@ -81,8 +82,10 @@ def run(env, m, report):
"--reruns=3", "--reruns-delay=2" "--reruns=3", "--reruns-delay=2"
""" """
arg_list = [] arg_list = []
if env.lower() == "live": # 根据指定的环境参数,将运行环境所需相关配置数据保存到GLOBAL_VARS
arg_list.append("--env=live") GLOBAL_VARS["env_key"] = env.lower()
for k, v in ENV_VARS[env.lower()].items():
GLOBAL_VARS[k] = v
# 执行指定测试用例 # 执行指定测试用例
if m is not None: if m is not None:
arg_list.append(f"-m {m}") arg_list.append(f"-m {m}")
@@ -105,27 +108,32 @@ def run(env, m, report):
os.popen(cmd).read() os.popen(cmd).read()
logger.debug("-------美化allure测试报告-------") logger.debug("-------美化allure测试报告-------")
AllureReportBeautiful(allure_html_path=ALLURE_HTML_DIR).set_windows_title( AllureReportBeautiful(allure_html_path=ALLURE_HTML_DIR).set_windows_title(
new_title=ENV_INFO["project_name"]) new_title=ENV_VARS["common"]["project_name"])
AllureReportBeautiful(allure_html_path=ALLURE_HTML_DIR).set_report_name(new_name=ENV_INFO["report_title"]) AllureReportBeautiful(allure_html_path=ALLURE_HTML_DIR).set_report_name(
new_name=ENV_VARS["common"]["report_title"])
logger.debug("-------allure测试报告生成完毕,开始发送测试报告-------") logger.debug("-------allure测试报告生成完毕,开始发送测试报告-------")
# 往allure测试报告中写入环境配置相关信息 # 往allure测试报告中写入环境配置相关信息
ENV_INFO["project_env"] = env env_info = ENV_VARS["common"]
AllureReportBeautiful(allure_html_path=ALLURE_HTML_DIR).set_report_env_on_html(env_info=ENV_INFO) env_info["run_env"] = GLOBAL_VARS.get("host", env)
AllureReportBeautiful(allure_html_path=ALLURE_HTML_DIR).set_report_env_on_html(
env_info=env_info)
# 从allure-html测试报告获取测试结果 # 从allure-html测试报告获取测试结果
results = get_test_results_from_from_allure_report(ALLURE_HTML_DIR) results = get_test_results_from_from_allure_report(ALLURE_HTML_DIR)
# 复制http_server.exe以及双击查看报告.bat文件到allure-html根目录下,用于支撑电脑在未安装allure服务的情况下打开allure-html报告 # 复制http_server.exe以及双击查看报告.bat文件到allure-html根目录下,用于支撑电脑在未安装allure服务的情况下打开allure-html报告
# 注意:ZIP文件的名称包含某些特殊字符,会导致无法使用.bat文件打开allure-html报告, 例如空格,/ 等 # 注意:ZIP文件的名称包含某些特殊字符,会导致无法使用.bat文件打开allure-html报告, 例如空格,/ 等
allure_config_path = os.path.join(CONF_DIR, "allure_config") allure_config_path = os.path.join(CONF_DIR, "allure_config")
copy_file(src_file_path=os.path.join(allure_config_path, [i for i in os.listdir(allure_config_path) if i.endswith(".exe")][0]), copy_file(src_file_path=os.path.join(allure_config_path,
[i for i in os.listdir(allure_config_path) if i.endswith(".exe")][0]),
dest_dir_path=ALLURE_HTML_DIR) dest_dir_path=ALLURE_HTML_DIR)
copy_file(src_file_path=os.path.join(allure_config_path, [i for i in os.listdir(allure_config_path) if i.endswith(".bat")][0]), copy_file(src_file_path=os.path.join(allure_config_path,
[i for i in os.listdir(allure_config_path) if i.endswith(".bat")][0]),
dest_dir_path=ALLURE_HTML_DIR) dest_dir_path=ALLURE_HTML_DIR)
# 压缩allure-html报告为一个压缩文件zip # 压缩allure-html报告为一个压缩文件zip
allure_zip_path = os.path.join(REPORT_DIR, f'{ENV_INFO["report_name"]}{str(current_time)}.zip') allure_zip_path = os.path.join(REPORT_DIR, f'autotest_{str(current_time)}.zip')
zip_file(in_path=ALLURE_HTML_DIR, out_path=allure_zip_path) zip_file(in_path=ALLURE_HTML_DIR, out_path=allure_zip_path)
send_result(results=results, attachment_path=allure_zip_path) send_result(results=results, attachment_path=allure_zip_path)
else: else:
report_path = os.path.join(REPORT_DIR, ENV_INFO["report_name"] + str(current_time) + ".html") report_path = os.path.join(REPORT_DIR, "autotest_" + str(current_time) + ".html")
pytest_html_config_path = os.path.join(CONF_DIR, "pytest_html_config") pytest_html_config_path = os.path.join(CONF_DIR, "pytest_html_config")
report_css = os.path.join(pytest_html_config_path, "pytest_html_report.css") report_css = os.path.join(pytest_html_config_path, "pytest_html_report.css")
arg_list.extend([f'--html={report_path}', f"--css={report_css}"]) arg_list.extend([f'--html={report_path}', f"--css={report_css}"])
@@ -10,7 +10,7 @@
import pytest import pytest
import os import os
from common_utils.yaml_handle import YamlHandle from common_utils.yaml_handle import YamlHandle
from config.project_path import DATA_DIR from config.path_config import DATA_DIR
from case_utils.assert_handle import assert_response, assert_sql from case_utils.assert_handle import assert_response, assert_sql
from loguru import logger from loguru import logger
from case_utils.request_data_handle import RequestPreDataHandle, RequestHandle from case_utils.request_data_handle import RequestPreDataHandle, RequestHandle
@@ -18,6 +18,8 @@ from pytest_html import extras # 往pytest-html报告中填写额外的内容
from common_utils.func_handle import add_docstring from common_utils.func_handle import add_docstring
from case_utils.allure_handle import allure_title from case_utils.allure_handle import allure_title
import allure import allure
from config.settings import db_info
from config.global_vars import GLOBAL_VARS
# 读取用例数据 # 读取用例数据
cases = YamlHandle(filename=os.path.join(DATA_DIR, "test_login_demo.yaml")).read_yaml cases = YamlHandle(filename=os.path.join(DATA_DIR, "test_login_demo.yaml")).read_yaml
@@ -26,12 +28,10 @@ cases = YamlHandle(filename=os.path.join(DATA_DIR, "test_login_demo.yaml")).read
@allure.story(f'{cases["case_common"]["allure_story"]}') @allure.story(f'{cases["case_common"]["allure_story"]}')
@pytest.mark.test_login_demo @pytest.mark.test_login_demo
@pytest.mark.parametrize("case", cases.get("case_info")) @pytest.mark.parametrize("case", cases.get("case_info"))
def test_login_demo(case, extra, request): def test_login_demo(case, extra):
logger.info("-----------------------------START-开始执行用例-----------------------------") logger.info("-----------------------------START-开始执行用例-----------------------------")
logger.debug(f"当前执行的用例数据:{case}") logger.debug(f"当前执行的用例数据:{case}")
try: try:
# 获取命令行参数,判断当前处于哪个环境
env = request.config.getoption("--env")
# 给当前测试方法添加文档注释 # 给当前测试方法添加文档注释
add_docstring(case.get("title", ""))(test_login_demo) add_docstring(case.get("title", ""))(test_login_demo)
# 添加用例标题作为allure中显示的用例标题 # 添加用例标题作为allure中显示的用例标题
@@ -48,7 +48,7 @@ def test_login_demo(case, extra, request):
# 进行响应断言 # 进行响应断言
assert_response(response, case_data["assert_response"]) assert_response(response, case_data["assert_response"])
# 进行数据库断言 # 进行数据库断言
assert_sql(env, case_data["assert_sql"]) assert_sql(db_info[GLOBAL_VARS["env_key"]], case_data["assert_sql"])
else: else:
reason = f"标记了该用例为false,不执行\\n" reason = f"标记了该用例为false,不执行\\n"
logger.warning(f"{reason}") logger.warning(f"{reason}")