pytest-api-framework-alpha 1.0.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- framework/__init__.py +1 -0
- framework/assertion/__init__.py +3 -0
- framework/assertion/retry_assert.py +67 -0
- framework/assertion/webhook_assert.py +129 -0
- framework/client/__init__.py +3 -0
- framework/client/crrm_client.py +155 -0
- framework/client/http_client.py +340 -0
- framework/client/mq_client.py +178 -0
- framework/client/websocket_client.py +414 -0
- framework/conftest.py +526 -0
- framework/core/__init__.py +3 -0
- framework/core/base_class.py +871 -0
- framework/core/extract.py +185 -0
- framework/core/global_attribute.py +187 -0
- framework/core/hooks/__init__.py +3 -0
- framework/core/hooks/filters.py +217 -0
- framework/core/hooks/reporter.py +228 -0
- framework/core/hooks/session.py +345 -0
- framework/core/hooks/sorting.py +84 -0
- framework/core/models.py +82 -0
- framework/core/render_data.py +309 -0
- framework/core/validate.py +648 -0
- framework/db/__init__.py +3 -0
- framework/db/mysql_db.py +226 -0
- framework/db/redis_db.py +319 -0
- framework/exceptions.py +22 -0
- framework/exit_code.py +20 -0
- framework/gen/__init__.py +3 -0
- framework/gen/case_gen.py +1268 -0
- framework/gen/create_app.py +265 -0
- framework/report.py +111 -0
- framework/script.py +35 -0
- framework/settings.py +93 -0
- framework/utils/__init__.py +3 -0
- framework/utils/cognito_util.py +348 -0
- framework/utils/common.py +298 -0
- framework/utils/date_util.py +218 -0
- framework/utils/encrypt.py +448 -0
- framework/utils/lark_util.py +167 -0
- framework/utils/log_util.py +10 -0
- framework/utils/mock_util.py +236 -0
- framework/utils/yaml_util.py +169 -0
- framework/ws_server.py +167 -0
- pytest_api_framework_alpha-1.0.5.dist-info/METADATA +98 -0
- pytest_api_framework_alpha-1.0.5.dist-info/RECORD +48 -0
- pytest_api_framework_alpha-1.0.5.dist-info/WHEEL +5 -0
- pytest_api_framework_alpha-1.0.5.dist-info/licenses/LICENSE +21 -0
- pytest_api_framework_alpha-1.0.5.dist-info/top_level.txt +1 -0
framework/conftest.py
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
"""
|
|
2
|
+
pytest 插件配置文件,定义测试框架的核心 conftest hook 和 fixture。
|
|
3
|
+
|
|
4
|
+
主要职责:
|
|
5
|
+
- 提供测试用例所需的 fixture(response, data, app, config, context, http)
|
|
6
|
+
- 实现 pytest 各阶段 hook,完成测试数据加载、参数化、用例排序、执行控制、报告生成等
|
|
7
|
+
"""
|
|
8
|
+
import re
|
|
9
|
+
import sys
|
|
10
|
+
import copy
|
|
11
|
+
import traceback
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from itertools import chain
|
|
14
|
+
from urllib.parse import urljoin
|
|
15
|
+
from collections import OrderedDict
|
|
16
|
+
from datetime import datetime, timedelta
|
|
17
|
+
|
|
18
|
+
import allure
|
|
19
|
+
import pytest
|
|
20
|
+
from box import Box
|
|
21
|
+
|
|
22
|
+
import framework.settings as settings
|
|
23
|
+
from framework.exit_code import ExitCode
|
|
24
|
+
from framework.core.hooks.sorting import sort
|
|
25
|
+
from framework.utils.log_util import logger
|
|
26
|
+
from framework.utils.yaml_util import YamlUtil
|
|
27
|
+
from framework.utils.yaml_util import CachedYamlLoader
|
|
28
|
+
from framework.core.global_attribute import CONTEXT, CONFIG, FRAMEWORK_CONTEXT, GlobalAttribute
|
|
29
|
+
from framework.core.hooks.session import all_app, login, run_handlers, get_app_handlers, get_login_instance, \
|
|
30
|
+
close_all_ws, set_token_expire_time
|
|
31
|
+
from framework.core.hooks.reporter import collect_stats, print_stats, send_notifications, sync_report, generate_report
|
|
32
|
+
from framework.core.hooks.filters import (
|
|
33
|
+
match_keyword, match_mark, subset_and_diff, disable_field, find_data_path_by_case,
|
|
34
|
+
inject_test_object_attrs, skip_if_previous_failed, deep_merge,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# 将所有配置的用例标签统一转为小写,便于后续匹配
|
|
38
|
+
MARK_LIST = [item.lower() for sublist in settings.MARK_LIST.values() for item in sublist]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@pytest.fixture(autouse=True)
|
|
42
|
+
def data():
|
|
43
|
+
"""测试数据 fixture,每个测试用例自动注入。
|
|
44
|
+
|
|
45
|
+
存储当前用例的完整测试数据字典,
|
|
46
|
+
包含请求参数、期望结果、标签等信息。
|
|
47
|
+
|
|
48
|
+
@return: dict,存储当前用例的测试数据
|
|
49
|
+
"""
|
|
50
|
+
yield dict()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def load_app_context(app: str) -> dict:
|
|
54
|
+
"""加载指定应用在当前环境下的上下文配置。
|
|
55
|
+
|
|
56
|
+
文件是 config/{app}/context.{env}.yaml —— 环境体现在文件名上,
|
|
57
|
+
文件内没有顶层环境层级。
|
|
58
|
+
|
|
59
|
+
@param app: 应用名
|
|
60
|
+
@return: 该应用在当前环境下的上下文配置字典
|
|
61
|
+
"""
|
|
62
|
+
file = f"config/{app}/context.{CONTEXT.env}.yaml"
|
|
63
|
+
assert (Path(settings.ROOT_DIR) / file).is_file(), \
|
|
64
|
+
f"{app} 缺少 {CONTEXT.env} 环境的 context 配置: {file}"
|
|
65
|
+
return YamlUtil(file).load_yml()
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def pytest_configure(config):
|
|
69
|
+
"""pytest 配置阶段 hook,初始化各应用的上下文和配置。
|
|
70
|
+
|
|
71
|
+
遍历所有注册的应用,加载其上下文配置(如域名、token 过期时间等)和
|
|
72
|
+
当前环境的中间件配置 database.{env}.yaml,分别存入 CONTEXT 和 CONFIG 全局对象中。
|
|
73
|
+
同时将用例目录加入 sys.path,确保测试模块可被正常导入。
|
|
74
|
+
|
|
75
|
+
@param config: pytest 配置对象
|
|
76
|
+
"""
|
|
77
|
+
for app in all_app:
|
|
78
|
+
# 加载每个应用的上下文配置(如域名、token 等)
|
|
79
|
+
app_context = GlobalAttribute()
|
|
80
|
+
app_context.set_from_dict(dic=load_app_context(app))
|
|
81
|
+
CONTEXT.set(key=app, value=app_context)
|
|
82
|
+
|
|
83
|
+
# 加载全局配置。中间件配置按环境拆成了 config/database.{env}.yaml,
|
|
84
|
+
# 环境已体现在文件名上,文件内部不再有顶层环境层级,所以 load_yml() 不传 key
|
|
85
|
+
app_config = GlobalAttribute()
|
|
86
|
+
app_config.set_from_dict(dic=YamlUtil(f"config/database.{CONTEXT.env}.yaml").load_yml())
|
|
87
|
+
CONFIG.set(key=app, value=app_config)
|
|
88
|
+
# 保存所有应用列表到全局上下文
|
|
89
|
+
CONTEXT.set(key="all_app", value=all_app)
|
|
90
|
+
# 将用例目录加入模块搜索路径
|
|
91
|
+
sys.path.append(settings.CASES_DIR)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def pytest_generate_tests(metafunc):
|
|
95
|
+
"""pytest 测试用例生成 hook,负责参数化测试数据。
|
|
96
|
+
|
|
97
|
+
根据关键字表达式(-k)、标签表达式(-m)、测试数据文件中的配置,动态生成参数化用例。
|
|
98
|
+
支持 scenario 模式(多条场景数据逐一参数化)和单条用例模式。
|
|
99
|
+
自动处理 URL 拼接、域名协议补充、标签校验等功能。
|
|
100
|
+
|
|
101
|
+
@param metafunc: pytest 的 metafunc 对象,包含测试函数的模块、类、函数等信息
|
|
102
|
+
"""
|
|
103
|
+
# 获取命令行参数中的关键字和标签过滤表达式
|
|
104
|
+
keyword_expr = metafunc.config.getoption("keyword")
|
|
105
|
+
mark_expr = metafunc.config.getoption("markexpr")
|
|
106
|
+
node_id = metafunc.definition.keywords.node.nodeid
|
|
107
|
+
|
|
108
|
+
# 如果有关键字过滤,但当前节点不匹配,则不生成测试
|
|
109
|
+
if not match_keyword(keyword_expr, node_id) and not mark_expr:
|
|
110
|
+
return
|
|
111
|
+
|
|
112
|
+
module_name = metafunc.module.__name__.split(".")[-1]
|
|
113
|
+
func_file_path = metafunc.module.__file__
|
|
114
|
+
func_name = metafunc.function.__name__
|
|
115
|
+
|
|
116
|
+
# test_setup 和 test_teardown 不参与参数化,它们是前后置钩子
|
|
117
|
+
if func_name in ("test_setup", "test_teardown"):
|
|
118
|
+
return
|
|
119
|
+
|
|
120
|
+
# 从用例文件路径推断归属的应用名(路径的第一个目录段)
|
|
121
|
+
app = Path(func_file_path).relative_to(settings.CASES_DIR).parts[0]
|
|
122
|
+
# 查找对应的测试数据文件路径
|
|
123
|
+
data_path = find_data_path_by_case(app, module_name)
|
|
124
|
+
if not data_path:
|
|
125
|
+
logger.warning(f"测试数据文件: {func_file_path} 不存在")
|
|
126
|
+
return
|
|
127
|
+
|
|
128
|
+
# 加载 YAML 测试数据(使用缓存加载器避免重复读取)
|
|
129
|
+
test_data = CachedYamlLoader(data_path).load_yml()
|
|
130
|
+
if not test_data:
|
|
131
|
+
logger.warning(f"测试数据文件: {func_file_path} 内容为空")
|
|
132
|
+
return
|
|
133
|
+
|
|
134
|
+
# 获取用例公共配置部分
|
|
135
|
+
case_common = test_data.get("case_common")
|
|
136
|
+
# 如果公共配置标记了忽略,则不生成用例
|
|
137
|
+
if case_common.get("ignore"):
|
|
138
|
+
return
|
|
139
|
+
|
|
140
|
+
# 获取当前函数的专用测试数据
|
|
141
|
+
case_data = test_data.get(func_name) or {}
|
|
142
|
+
if not case_data:
|
|
143
|
+
return
|
|
144
|
+
|
|
145
|
+
# --- 初始化 case_data ---
|
|
146
|
+
case_data.setdefault("request", {})
|
|
147
|
+
case_data["request"].setdefault("headers", {})
|
|
148
|
+
case_data.setdefault("module", case_common.get("module"))
|
|
149
|
+
case_data.setdefault("describe", case_common.get("describe"))
|
|
150
|
+
case_data["app"] = app
|
|
151
|
+
|
|
152
|
+
# --- base_json/base_params 合并 ---
|
|
153
|
+
base_data = case_common.get("base_json")
|
|
154
|
+
if base_data:
|
|
155
|
+
case_json = case_data["request"].get("json")
|
|
156
|
+
if isinstance(case_json, dict):
|
|
157
|
+
case_data["request"]["json"] = deep_merge(base_data, case_json)
|
|
158
|
+
else:
|
|
159
|
+
case_data["request"]["json"] = copy.deepcopy(base_data)
|
|
160
|
+
base_params = case_common.get("base_params")
|
|
161
|
+
if base_params:
|
|
162
|
+
case_params = case_data["request"].get("params")
|
|
163
|
+
if isinstance(case_params, dict):
|
|
164
|
+
case_data["request"]["params"] = deep_merge(base_params, case_params)
|
|
165
|
+
else:
|
|
166
|
+
case_data["request"]["params"] = copy.deepcopy(base_params)
|
|
167
|
+
|
|
168
|
+
# --- URL 处理 ---
|
|
169
|
+
# 根据是否有 message 字段判断是 HTTP 还是 WebSocket 请求
|
|
170
|
+
if case_data["request"].get("message") is None:
|
|
171
|
+
domain_key = "domain"
|
|
172
|
+
proto = "https"
|
|
173
|
+
else:
|
|
174
|
+
domain_key = "wss"
|
|
175
|
+
proto = "wss"
|
|
176
|
+
# 从上下文获取对应应用的域名
|
|
177
|
+
domain = CONTEXT.get(key=domain_key, app=app)
|
|
178
|
+
if not domain:
|
|
179
|
+
return
|
|
180
|
+
prefix = f"{proto}://"
|
|
181
|
+
# 若域名没有协议前缀则自动补充
|
|
182
|
+
domain = domain if domain.startswith(("http", "ws")) else f"{prefix}{domain}"
|
|
183
|
+
|
|
184
|
+
# 拼接完整 URL:若使用变量占位符则不拼接域名
|
|
185
|
+
raw_url = case_data["request"].get("url") or case_common.get("url") or ""
|
|
186
|
+
case_data["request"]["url"] = raw_url if raw_url.strip().startswith("${") else urljoin(domain, raw_url)
|
|
187
|
+
|
|
188
|
+
# 如果请求中没有指定 method 且非 WebSocket,则使用公共默认方法
|
|
189
|
+
if not case_data["request"].get("method") and case_data["request"].get("message") is None:
|
|
190
|
+
case_data["request"]["method"] = case_common.get("method", None)
|
|
191
|
+
|
|
192
|
+
# 检查是否缺少必填的 title 字段
|
|
193
|
+
if not case_data.get("title"):
|
|
194
|
+
logger.warning(f"{func_name} 缺少必要字段: title")
|
|
195
|
+
|
|
196
|
+
# --- 构建 marks(不污染 func_pytestmark)---
|
|
197
|
+
# 这些内置 mark 不需要添加到用例标签中
|
|
198
|
+
mark_skip = {"skip", "skipif", "xfail", "usefixtures", "filterwarnings",
|
|
199
|
+
"parametrize", "order", "timeout", "django_db", "asyncio"}
|
|
200
|
+
marks = [*case_common.get("marks", []), case_common.get("module", "")]
|
|
201
|
+
# 收集函数上和类级别上的自定义 mark
|
|
202
|
+
for m in chain(metafunc.definition.own_markers, getattr(metafunc.cls, "pytestmark", [])):
|
|
203
|
+
if m.name not in mark_skip and not m.args:
|
|
204
|
+
marks.append(m.name)
|
|
205
|
+
marks = [m.lower() for m in marks]
|
|
206
|
+
# 检查当前用例的标签是否在允许的标签列表中
|
|
207
|
+
is_subset, diff = subset_and_diff(set(marks), set(MARK_LIST))
|
|
208
|
+
|
|
209
|
+
# --- scenario 检查 ---
|
|
210
|
+
scenarios = case_common.get("scenarios")
|
|
211
|
+
if settings.ONLY_SUPPORT_SCENARIO and not scenarios:
|
|
212
|
+
logger.error("当前仅支持使用scenario的方式执行用例")
|
|
213
|
+
pytest.exit(ExitCode.NONSUPPORT_RUN_MODE)
|
|
214
|
+
|
|
215
|
+
# --- 统一处理 scenarios / 单条用例 ---
|
|
216
|
+
case_data_list = []
|
|
217
|
+
ids = []
|
|
218
|
+
schema_items = scenarios or [None]
|
|
219
|
+
|
|
220
|
+
for index, item in enumerate(schema_items):
|
|
221
|
+
scenario = item.get("scenario") if scenarios else None
|
|
222
|
+
# 跳过被标记忽略的 scenario,或在排除列表中的函数
|
|
223
|
+
if scenario and (scenario.get("ignore") or func_name in scenario.get("exclude", [])):
|
|
224
|
+
continue
|
|
225
|
+
|
|
226
|
+
# 确定用例级别(优先级),默认从配置中获取
|
|
227
|
+
level = (scenario.get("level") if scenario else None) or case_data.get("level") or settings.DEFAULT_CASE_LEVEL
|
|
228
|
+
level = level.lower()
|
|
229
|
+
case_data["level"] = level
|
|
230
|
+
new_marks = [*marks, level]
|
|
231
|
+
|
|
232
|
+
# 再次根据关键字和标签表达式过滤
|
|
233
|
+
if not match_keyword(keyword_expr, node_id) or not match_mark(mark_expr, new_marks):
|
|
234
|
+
continue
|
|
235
|
+
# 非规范标签警告(仅严格标签模式下告警并跳过)
|
|
236
|
+
if settings.STRICT_MARKS and not is_subset:
|
|
237
|
+
logger.warning(f"{node_id} 使用非规范的用例标签:{list(diff)}")
|
|
238
|
+
return
|
|
239
|
+
# 非规范级别警告(仅严格标签模式下告警并跳过)
|
|
240
|
+
if settings.STRICT_MARKS and level not in settings.CASE_LEVEL_LIST:
|
|
241
|
+
logger.warning(f"{node_id} 使用非规范的用例级别 {level}")
|
|
242
|
+
continue
|
|
243
|
+
|
|
244
|
+
try:
|
|
245
|
+
if scenarios:
|
|
246
|
+
# scenario 模式:深拷贝基础数据,再应用 scenario 的字段覆盖
|
|
247
|
+
dc = copy.deepcopy(case_data)
|
|
248
|
+
dc = disable_field(scenario["data"], dc)
|
|
249
|
+
dc["_scenario"] = scenario
|
|
250
|
+
else:
|
|
251
|
+
dc = case_data
|
|
252
|
+
dc["_scenario"] = {"data": {}}
|
|
253
|
+
dc["_marks"] = new_marks
|
|
254
|
+
# 设置是否忽略失败标志,用于控制同一类下后续用例的执行
|
|
255
|
+
dc.setdefault("_ignore_failed", case_common.get("ignore_failed", settings.GLOBAL_IGNORE_FAILED))
|
|
256
|
+
case_data_list.append(dc)
|
|
257
|
+
|
|
258
|
+
# 生成用例显示名称
|
|
259
|
+
label = f'{case_data.get("title")}'
|
|
260
|
+
label += f' - {scenario.get("describe") or ""}#{index + 1}' if scenarios else "#1"
|
|
261
|
+
ids.append(label)
|
|
262
|
+
except Exception as e:
|
|
263
|
+
logger.error(f"scenario参数化格式不正确:{e}")
|
|
264
|
+
traceback.print_exc()
|
|
265
|
+
pytest.exit(ExitCode.SCENARIO_FORMAT_ERROR)
|
|
266
|
+
|
|
267
|
+
# 将参数化数据注入到测试函数
|
|
268
|
+
if case_data_list:
|
|
269
|
+
metafunc.parametrize("data", case_data_list, ids=ids, scope="function")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def pytest_collection_modifyitems(items):
|
|
273
|
+
"""pytest 用例收集完成后的修改 hook。
|
|
274
|
+
|
|
275
|
+
对收集到的参数化用例进行排序(按配置的排序规则),
|
|
276
|
+
并将测试数据中定义的标签(marks)逐一添加到对应的用例对象上,
|
|
277
|
+
确保 Allure 报告和 pytest 输出中能正确显示标签信息。
|
|
278
|
+
|
|
279
|
+
@param items: pytest 收集到的测试用例列表,修改该列表会影响执行顺序
|
|
280
|
+
"""
|
|
281
|
+
# 过滤出有 callspec(参数化)的用例并进行排序
|
|
282
|
+
items[:] = sort([item for item in items if getattr(item, "callspec", None)])
|
|
283
|
+
for item in items:
|
|
284
|
+
# 从参数化数据中取出 marks 并添加到用例的标签列表中
|
|
285
|
+
data = item.callspec.params.get("data")
|
|
286
|
+
if isinstance(data, dict):
|
|
287
|
+
for mark in (data.get("_marks") or []):
|
|
288
|
+
item.add_marker(mark)
|
|
289
|
+
logger.info(getattr(item, "nodeid"))
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def pytest_collection_finish(session):
|
|
293
|
+
"""pytest 用例收集完成后的最终处理 hook。
|
|
294
|
+
|
|
295
|
+
过滤掉 test_setup/test_teardown 等辅助方法(它们通过 pytest_runtest_setup/teardown 自动执行)。
|
|
296
|
+
对 scenario 参数化用例按模块+类分组,再按 scenario 索引重新排序,
|
|
297
|
+
并标记每组中的第一个(需要执行 setup)和最后一个元素(需要执行 teardown)。
|
|
298
|
+
|
|
299
|
+
@param session: pytest 会话对象,包含所有已收集的测试用例
|
|
300
|
+
"""
|
|
301
|
+
if not session.items:
|
|
302
|
+
pytest.exit("未收集到用例")
|
|
303
|
+
|
|
304
|
+
# 移除辅助方法 test_setup 和 test_teardown(它们通过 pytest_runtest_setup/teardown 执行)
|
|
305
|
+
session.items = [i for i in session.items if i.name not in ("test_setup", "test_teardown")]
|
|
306
|
+
logger.info(f"共收集到 {len(session.items)} 个测试用例")
|
|
307
|
+
|
|
308
|
+
# 找出所有参数化后名称中包含 "#" 的用例,记录其索引
|
|
309
|
+
hash_items_with_index = [(idx, item) for idx, item in enumerate(session.items) if "#" in item.name]
|
|
310
|
+
|
|
311
|
+
# 按模块 + 测试类名分组
|
|
312
|
+
grouped_by_cls = {}
|
|
313
|
+
for idx, item in hash_items_with_index:
|
|
314
|
+
key = item.cls.__module__ + item.parent.name
|
|
315
|
+
grouped_by_cls.setdefault(key, []).append((idx, item))
|
|
316
|
+
|
|
317
|
+
# 按 scenario 索引号分组(从名称中的 #(\d+) 提取)
|
|
318
|
+
pattern = r"#(\d+)]"
|
|
319
|
+
for cls_key, group in grouped_by_cls.items():
|
|
320
|
+
group_values = [x[1] for x in group]
|
|
321
|
+
grouped_data = OrderedDict()
|
|
322
|
+
for item in group_values:
|
|
323
|
+
match_result = re.search(pattern, item.name)
|
|
324
|
+
if match_result:
|
|
325
|
+
grouped_data.setdefault(match_result.group(1), []).append(item)
|
|
326
|
+
|
|
327
|
+
# 标记每组第一个用例(需要执行 setup)和最后一个用例(需要执行 teardown)
|
|
328
|
+
for group2 in grouped_data.values():
|
|
329
|
+
group2[0].funcargs["first"] = True
|
|
330
|
+
group2[-1].funcargs["last"] = True
|
|
331
|
+
|
|
332
|
+
# 用排序后的值覆盖原始索引位置,保持执行顺序
|
|
333
|
+
sorted_values = list(chain.from_iterable(grouped_data.values()))
|
|
334
|
+
for (original_index, _), val in zip(group, sorted_values):
|
|
335
|
+
session.items[original_index] = val
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def pytest_runtestloop(session):
|
|
339
|
+
"""pytest 用例执行循环开始前的 hook。
|
|
340
|
+
|
|
341
|
+
在所有用例执行之前执行全局登录,获取 HTTP 会话并存到框架全局上下文中,
|
|
342
|
+
然后运行所有应用的前置处理器(如初始化数据、准备资源等)。
|
|
343
|
+
该 hook 在整个测试会话中只执行一次。
|
|
344
|
+
|
|
345
|
+
@param session: pytest 会话对象
|
|
346
|
+
"""
|
|
347
|
+
# 执行登录,获取 HTTP 会话并存到框架全局上下文中
|
|
348
|
+
FRAMEWORK_CONTEXT.set(key="http_session", value=login())
|
|
349
|
+
# 执行全局和应用级别的前置处理器(如数据准备、环境初始化等)
|
|
350
|
+
handlers = (
|
|
351
|
+
getattr(settings, "GLOBAL_START_HANDLER_CLASSES", [])
|
|
352
|
+
+ get_app_handlers("APP_START_HANDLER_CLASSES")
|
|
353
|
+
)
|
|
354
|
+
run_handlers(handlers)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def pytest_runtest_setup(item):
|
|
358
|
+
"""每个测试用例执行前的 setup hook。
|
|
359
|
+
|
|
360
|
+
为测试对象注入上下文、配置、HTTP 会话等属性,并在每组第一个用例前
|
|
361
|
+
执行 test_setup 方法(用户自定义的前置逻辑,如数据准备、参数校验等)。
|
|
362
|
+
如果 test_setup 执行失败,会将 setup_success 标志置为 False,
|
|
363
|
+
后续用例可根据该标志决定是否跳过。
|
|
364
|
+
|
|
365
|
+
@param item: pytest 测试用例项
|
|
366
|
+
"""
|
|
367
|
+
# subSuite 已经在 sorting.sort() 里以 allure.sub_suite marker 的形式打好了。
|
|
368
|
+
# 这里不能再用 allure.dynamic.sub_suite()——它是往结果上追加而不是覆盖,
|
|
369
|
+
# 会让同一条用例挂两个 subSuite,报告的 Suites 树上出现两个重复节点
|
|
370
|
+
|
|
371
|
+
# 只对每组第一个用例执行 setup 操作(避免重复初始化)
|
|
372
|
+
if not item.funcargs.get("first"):
|
|
373
|
+
return
|
|
374
|
+
|
|
375
|
+
inject_test_object_attrs(item)
|
|
376
|
+
# 执行用户自定义的前置方法 test_setup
|
|
377
|
+
test_before_scenario = getattr(item.instance, "test_setup", None)
|
|
378
|
+
if test_before_scenario:
|
|
379
|
+
try:
|
|
380
|
+
test_before_scenario()
|
|
381
|
+
item.funcargs["setup_success"] = True
|
|
382
|
+
except Exception as e:
|
|
383
|
+
item.funcargs["setup_success"] = False
|
|
384
|
+
traceback.print_exc()
|
|
385
|
+
logger.error(f"{item.name} test_setup方法执行异常: {e}")
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def pytest_runtest_call(item):
|
|
389
|
+
"""每个测试用例实际执行时的 hook。
|
|
390
|
+
|
|
391
|
+
将测试数据、配置、上下文、HTTP 会话等注入到 funcargs 和测试实例中,
|
|
392
|
+
确保测试方法可以直接通过 self 或参数访问。
|
|
393
|
+
处理前置失败时的用例跳过逻辑(ignore_failed 机制),
|
|
394
|
+
以及 token 过期后的自动重新登录。
|
|
395
|
+
|
|
396
|
+
@param item: pytest 测试用例项
|
|
397
|
+
"""
|
|
398
|
+
data = Box(item.funcargs.get("data"))
|
|
399
|
+
item.instance.data = data
|
|
400
|
+
inject_test_object_attrs(item)
|
|
401
|
+
|
|
402
|
+
# 如果设置了 ignore_failed=false,需要检查前一个同组用例的执行状态
|
|
403
|
+
if not data.get("_ignore_failed"):
|
|
404
|
+
skip_if_previous_failed(item)
|
|
405
|
+
|
|
406
|
+
# 检查 token 是否过期,过期则自动重新登录
|
|
407
|
+
app = data.get("app")
|
|
408
|
+
expire_time = FRAMEWORK_CONTEXT.get(app=app, key="expire_time")
|
|
409
|
+
if expire_time and datetime.now() >= expire_time:
|
|
410
|
+
http_session = FRAMEWORK_CONTEXT.get(key="http_session")
|
|
411
|
+
setattr(http_session, app, get_login_instance(app))
|
|
412
|
+
# 换了新的 login 实例,下次请求才会真正重新登录,这里先按配置估一个,
|
|
413
|
+
# 登录成功后会被响应里的 expires_in 覆盖
|
|
414
|
+
set_token_expire_time(app)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def pytest_runtest_teardown(item):
|
|
418
|
+
"""每个测试用例执行后的 teardown hook。
|
|
419
|
+
|
|
420
|
+
只在每组最后一个用例执行后调用 test_teardown 方法,
|
|
421
|
+
执行用户自定义的后置清理逻辑(如清理测试数据、断开连接等)。
|
|
422
|
+
前置注入上下文和配置确保 teardown 中可正常使用框架对象。
|
|
423
|
+
|
|
424
|
+
@param item: pytest 测试用例项
|
|
425
|
+
"""
|
|
426
|
+
# 只对每组最后一个用例执行 teardown
|
|
427
|
+
if not item.funcargs.get("last"):
|
|
428
|
+
return
|
|
429
|
+
inject_test_object_attrs(item)
|
|
430
|
+
item.instance.data = None
|
|
431
|
+
# 执行用户自定义的后置方法 test_teardown
|
|
432
|
+
test_after_scenario = getattr(item.instance, "test_teardown", None)
|
|
433
|
+
if test_after_scenario:
|
|
434
|
+
try:
|
|
435
|
+
test_after_scenario()
|
|
436
|
+
except Exception as e:
|
|
437
|
+
traceback.print_exc()
|
|
438
|
+
logger.error(f"{item.name} test_setup方法执行异常: {e}")
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
|
|
442
|
+
def pytest_runtest_makereport(item, call):
|
|
443
|
+
"""pytest 用例执行报告生成 hook。
|
|
444
|
+
|
|
445
|
+
在用例调用阶段(call)捕获跳过(skip)原因,并将用例执行状态(passed/failed/skipped)
|
|
446
|
+
保存到 item.status 和 item.skip_reason 上,供同场景下一个用例的依赖判断。
|
|
447
|
+
使用 hookwrapper 模式在原有报告生成逻辑之后执行。
|
|
448
|
+
|
|
449
|
+
@param item: pytest 测试用例项
|
|
450
|
+
@param call: pytest 调用阶段的 call 对象,包含异常信息等
|
|
451
|
+
"""
|
|
452
|
+
outcome = yield
|
|
453
|
+
report = outcome.get_result()
|
|
454
|
+
if report.when == "call":
|
|
455
|
+
longrepr = report.longrepr
|
|
456
|
+
# 从 longrepr 中提取跳过原因
|
|
457
|
+
if longrepr:
|
|
458
|
+
try:
|
|
459
|
+
if ":" in longrepr[2]:
|
|
460
|
+
key, reason = longrepr[2].split(":", 1)
|
|
461
|
+
else:
|
|
462
|
+
key, reason = longrepr[2], ""
|
|
463
|
+
if key == "Skipped":
|
|
464
|
+
item.skip_reason = reason
|
|
465
|
+
except Exception:
|
|
466
|
+
pass
|
|
467
|
+
# 保存用例执行结果状态
|
|
468
|
+
item.status = report.outcome
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def pytest_exception_interact(node, call, report):
|
|
472
|
+
"""pytest 异常交互 hook,用于在断言失败时记录错误日志。
|
|
473
|
+
|
|
474
|
+
当用例抛出 AssertionError 时,将失败信息写入日志以便排查。
|
|
475
|
+
|
|
476
|
+
@param node: 测试节点对象,包含 nodeid 等标识信息
|
|
477
|
+
@param call: pytest 的 call 对象,包含异常信息
|
|
478
|
+
@param report: pytest 报告对象
|
|
479
|
+
"""
|
|
480
|
+
if call.excinfo.type is AssertionError:
|
|
481
|
+
logger.error(f"{node.nodeid} failed: {call.excinfo.value}\n")
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def pytest_sessionfinish(session, exitstatus):
|
|
485
|
+
"""pytest 会话结束时调用的 hook。
|
|
486
|
+
|
|
487
|
+
执行应用级别和全局的后置处理器(如资源清理、数据恢复等),
|
|
488
|
+
收集测试统计信息(通过数、失败数、跳过数、总数、通过率),
|
|
489
|
+
发送通知(飞书、钉钉等)并将结果同步到报告系统。
|
|
490
|
+
|
|
491
|
+
@param session: pytest 会话对象
|
|
492
|
+
@param exitstatus: pytest 退出状态码
|
|
493
|
+
"""
|
|
494
|
+
# 关闭所有 WebSocket 连接
|
|
495
|
+
close_all_ws()
|
|
496
|
+
# 执行后置处理器(如资源清理)
|
|
497
|
+
handlers = (
|
|
498
|
+
get_app_handlers("APP_FINISH_HANDLER_CLASSES")
|
|
499
|
+
+ getattr(settings, "GLOBAL_FINISH_HANDLER_CLASSES", [])
|
|
500
|
+
)
|
|
501
|
+
run_handlers(handlers)
|
|
502
|
+
try:
|
|
503
|
+
# 收集测试统计(通过数、失败数、跳过数、总数、通过率)
|
|
504
|
+
reporter, passed, failed, skipped, total, pass_rate = collect_stats(session)
|
|
505
|
+
# 发送通知(如飞书、钉钉等)
|
|
506
|
+
send_notifications(passed, failed, skipped, total, pass_rate)
|
|
507
|
+
# 同步报告到数据库或报告平台
|
|
508
|
+
sync_report(passed, failed, skipped, total, pass_rate)
|
|
509
|
+
except Exception as e:
|
|
510
|
+
logger.error(f"发送报告失败:{e}")
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def pytest_terminal_summary(terminalreporter, exitstatus, config):
|
|
514
|
+
"""pytest 终端摘要输出 hook。
|
|
515
|
+
|
|
516
|
+
在终端打印测试统计摘要(通过数、失败数、跳过数、通过率等),
|
|
517
|
+
并生成 Allure HTML 报告(如果配置了 AUTO_OPEN_REPORT 则自动打开)。
|
|
518
|
+
|
|
519
|
+
@param terminalreporter: pytest 终端报告对象,包含汇总统计信息
|
|
520
|
+
@param exitstatus: pytest 退出状态码
|
|
521
|
+
@param config: pytest 配置对象
|
|
522
|
+
"""
|
|
523
|
+
# 打印测试统计信息到终端
|
|
524
|
+
print_stats(**CONTEXT.get(key="summary"))
|
|
525
|
+
# 生成 Allure 报告
|
|
526
|
+
generate_report()
|