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
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""
|
|
2
|
+
变量提取模块。
|
|
3
|
+
|
|
4
|
+
从 HTTP/WebSocket 响应中按指定规则提取字段值,并写入全局上下文 CONTEXT,
|
|
5
|
+
供后续测试步骤引用。支持三种提取方式:
|
|
6
|
+
- JSONPath 表达式($.xxx.xxx)
|
|
7
|
+
- 正则表达式(/pattern/)
|
|
8
|
+
- Box 属性路径(data.items[0].id)
|
|
9
|
+
"""
|
|
10
|
+
import re
|
|
11
|
+
from json import JSONDecodeError
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import allure
|
|
15
|
+
from box import Box, BoxList
|
|
16
|
+
from jsonpath import jsonpath
|
|
17
|
+
|
|
18
|
+
from framework.utils.common import is_digit
|
|
19
|
+
from framework.utils.log_util import logger
|
|
20
|
+
from framework.core.global_attribute import CONTEXT
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Extract(object):
|
|
24
|
+
"""
|
|
25
|
+
响应变量提取器。
|
|
26
|
+
|
|
27
|
+
根据 expressions 配置从响应中提取字段值,通过上下文管理变量生命周期。
|
|
28
|
+
支持 jsonpath、正则、box 属性链三种提取方式。
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
# 用于解析 box 属性路径的正则:匹配 "name" 或 "[0]" 片段
|
|
32
|
+
_PATH_RE = re.compile(r'(\w+)|\[(\d+)]')
|
|
33
|
+
|
|
34
|
+
def __init__(self, response: Any, app: str) -> None:
|
|
35
|
+
"""
|
|
36
|
+
初始化提取器。
|
|
37
|
+
|
|
38
|
+
:param response: ResponseUtil 对象(含 .text / .json() 方法)
|
|
39
|
+
:param app: 当前 case 所属应用名称,用于上下文写入
|
|
40
|
+
"""
|
|
41
|
+
self.raw_body = response.text
|
|
42
|
+
try:
|
|
43
|
+
body = response.json()
|
|
44
|
+
except JSONDecodeError:
|
|
45
|
+
body = self.raw_body
|
|
46
|
+
# 统一转为 Box 或 BoxList 以便属性路径访问
|
|
47
|
+
if isinstance(body, dict):
|
|
48
|
+
self.response = Box(body)
|
|
49
|
+
elif isinstance(body, list):
|
|
50
|
+
self.response = BoxList(body)
|
|
51
|
+
else:
|
|
52
|
+
self.response = body
|
|
53
|
+
self.app = app
|
|
54
|
+
self.context = CONTEXT
|
|
55
|
+
|
|
56
|
+
def _parse_app_key(self, key: str) -> tuple[str | None, str]:
|
|
57
|
+
"""
|
|
58
|
+
解析 key 是否带 app 前缀。
|
|
59
|
+
|
|
60
|
+
如 "camp_admin.token" 将返回 ("camp_admin", "token")。
|
|
61
|
+
未匹配则返回 (None, 原key)。
|
|
62
|
+
|
|
63
|
+
:param key: 变量键名,可带 app 前缀
|
|
64
|
+
:return: (app, key) 元组
|
|
65
|
+
"""
|
|
66
|
+
for app in getattr(self.context, 'all_app', []):
|
|
67
|
+
if key.startswith(f"{app}."):
|
|
68
|
+
return key.split(".", 1)
|
|
69
|
+
return None, key
|
|
70
|
+
|
|
71
|
+
def extracts(self, expressions: list[dict[str, str]]) -> None:
|
|
72
|
+
"""
|
|
73
|
+
批量提取变量。
|
|
74
|
+
|
|
75
|
+
根据表达式前缀自动选择提取方式:
|
|
76
|
+
- $. → jsonpath
|
|
77
|
+
- /.../ → 正则
|
|
78
|
+
- 其他 → box 属性路径
|
|
79
|
+
|
|
80
|
+
:param expressions: 提取表达式列表,如 [{"token": "$.data.token"}]
|
|
81
|
+
"""
|
|
82
|
+
for item in expressions:
|
|
83
|
+
key = next(iter(item)).strip()
|
|
84
|
+
expression = item.get(key).strip()
|
|
85
|
+
try:
|
|
86
|
+
if expression.lower().startswith("$."):
|
|
87
|
+
self.extract_by_jsonpath(key, expression)
|
|
88
|
+
elif expression.startswith("/") and expression.endswith("/"):
|
|
89
|
+
self.extract_by_regex(key, expression[1:-1])
|
|
90
|
+
else:
|
|
91
|
+
self.extract_by_box(key, expression)
|
|
92
|
+
except Exception as e:
|
|
93
|
+
with allure.step(f"提取字段{key}失败: {e}"):
|
|
94
|
+
logger.error(f"提取字段{key}失败: {e}")
|
|
95
|
+
# pytest.fail(f"提取字段{key}失败: {e}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def extract(self, key: str, expression: str) -> None:
|
|
99
|
+
"""
|
|
100
|
+
单条变量提取(便捷接口)。
|
|
101
|
+
|
|
102
|
+
:param key: 变量名
|
|
103
|
+
:param expression: 提取表达式
|
|
104
|
+
:return: extracts 方法返回值
|
|
105
|
+
"""
|
|
106
|
+
return self.extracts([{key.strip(): expression.strip()}])
|
|
107
|
+
|
|
108
|
+
def extract_by_jsonpath(self, key: str, expression: str) -> None:
|
|
109
|
+
"""
|
|
110
|
+
通过 JSONPath 表达式提取值。
|
|
111
|
+
|
|
112
|
+
:param key: 变量名
|
|
113
|
+
:param expression: JSONPath 表达式,如 "$.data.token"
|
|
114
|
+
"""
|
|
115
|
+
app, key = self._parse_app_key(key)
|
|
116
|
+
app = app or self.app
|
|
117
|
+
result = jsonpath(self.response, expression)
|
|
118
|
+
if result is False:
|
|
119
|
+
raise Exception(f"jsonpath未匹配到结果: {expression}")
|
|
120
|
+
try:
|
|
121
|
+
extract_value = result[0]
|
|
122
|
+
except (IndexError, TypeError) as e:
|
|
123
|
+
raise Exception(f"jsonpath结果异常: {result}, 表达式: {expression}")
|
|
124
|
+
|
|
125
|
+
self.context.set(key=key, value=extract_value, app=app)
|
|
126
|
+
with allure.step(f"提取字段: {key} = {extract_value}"):
|
|
127
|
+
logger.info(f"提取字段: {key} = {extract_value} ({type(extract_value).__name__})")
|
|
128
|
+
|
|
129
|
+
def extract_by_regex(self, key: str, reg_expression: str) -> None:
|
|
130
|
+
"""
|
|
131
|
+
通过正则表达式提取值。
|
|
132
|
+
|
|
133
|
+
:param key: 变量名
|
|
134
|
+
:param reg_expression: 正则表达式(不含定界符)
|
|
135
|
+
"""
|
|
136
|
+
app, key = self._parse_app_key(key)
|
|
137
|
+
app = app or self.app
|
|
138
|
+
match = re.search(reg_expression, self.raw_body, flags=re.S)
|
|
139
|
+
if match is None:
|
|
140
|
+
raise Exception(f"正则未匹配到结果: /{reg_expression}/")
|
|
141
|
+
extract_value = match.group()
|
|
142
|
+
# 如果提取结果是数字字符串,自动转为 int/float
|
|
143
|
+
if is_digit(extract_value):
|
|
144
|
+
extract_value = float(extract_value) if '.' in extract_value else int(extract_value)
|
|
145
|
+
self.context.set(key=key, value=extract_value, app=app)
|
|
146
|
+
with allure.step(f"提取字段: {key} = {extract_value}"):
|
|
147
|
+
logger.info(f"提取字段: {key} = {extract_value} ({type(extract_value).__name__})")
|
|
148
|
+
|
|
149
|
+
def extract_by_box(self, key: str, expression: str) -> None:
|
|
150
|
+
"""
|
|
151
|
+
通过 Box 属性路径提取值。
|
|
152
|
+
|
|
153
|
+
:param key: 变量名
|
|
154
|
+
:param expression: 属性路径,如 "data.items[0].id"
|
|
155
|
+
"""
|
|
156
|
+
app, key = self._parse_app_key(key)
|
|
157
|
+
app = app or self.app
|
|
158
|
+
extract_value = self.get_nested_value(self.response, expression)
|
|
159
|
+
if extract_value is None:
|
|
160
|
+
raise ValueError(f"box属性路径未匹配到结果: {expression}")
|
|
161
|
+
self.context.set(key=key, value=extract_value, app=app)
|
|
162
|
+
with allure.step(f"提取字段: {key} = {extract_value}"):
|
|
163
|
+
logger.info(f"提取字段: {key} = {extract_value} ({type(extract_value).__name__})")
|
|
164
|
+
|
|
165
|
+
@classmethod
|
|
166
|
+
def get_nested_value(cls, obj: Any, attr_path: str) -> Any:
|
|
167
|
+
"""
|
|
168
|
+
按属性路径从对象中逐层取值。
|
|
169
|
+
|
|
170
|
+
例如 get_nested_value(obj, "data.items[0].id") 等价于 obj.data.items[0].id。
|
|
171
|
+
|
|
172
|
+
:param obj: 起始对象
|
|
173
|
+
:param attr_path: 属性路径字符串
|
|
174
|
+
:return: 取值结果,任意节点不存在则返回 None
|
|
175
|
+
"""
|
|
176
|
+
path_elements = cls._PATH_RE.findall(attr_path)
|
|
177
|
+
try:
|
|
178
|
+
for attr, index in path_elements:
|
|
179
|
+
if attr:
|
|
180
|
+
obj = getattr(obj, attr)
|
|
181
|
+
if index:
|
|
182
|
+
obj = obj[int(index)]
|
|
183
|
+
return obj
|
|
184
|
+
except Exception:
|
|
185
|
+
return None
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""
|
|
2
|
+
全局属性管理模块。
|
|
3
|
+
|
|
4
|
+
提供链式属性读写能力,支持通过 "app.key" 点分路径读写嵌套属性。
|
|
5
|
+
包含三个全局单例对象:
|
|
6
|
+
- CONTEXT: 存储测试过程中的临时变量
|
|
7
|
+
- CONFIG: 存储全局配置
|
|
8
|
+
- FRAMEWORK_CONTEXT: 存储框架内部状态(数据库连接、MQ 连接、HTTP 客户端等)
|
|
9
|
+
"""
|
|
10
|
+
from box import Box, BoxList
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def singleton(cls: type) -> Callable[[Any, Any], Any]:
|
|
15
|
+
"""
|
|
16
|
+
单例模式装饰器。
|
|
17
|
+
|
|
18
|
+
保证一个类在整个进程生命周期中只有唯一实例。
|
|
19
|
+
|
|
20
|
+
:param cls: 被装饰的类
|
|
21
|
+
:return: 返回实例化函数
|
|
22
|
+
"""
|
|
23
|
+
instances = {}
|
|
24
|
+
|
|
25
|
+
def get_instance(*args, **kwargs):
|
|
26
|
+
if cls not in instances:
|
|
27
|
+
instances[cls] = cls(*args, **kwargs)
|
|
28
|
+
return instances[cls]
|
|
29
|
+
|
|
30
|
+
return get_instance
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class GlobalAttribute(object):
|
|
34
|
+
"""
|
|
35
|
+
全局属性对象,支持点分路径链式读写。
|
|
36
|
+
|
|
37
|
+
当设置属性时,dict 自动转为 Box,list 自动转为 BoxList。
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __setattr__(self, key: str, value: Any) -> None:
|
|
41
|
+
"""
|
|
42
|
+
重写属性设置方法,自动将 dict/list 转为 Box/BoxList。
|
|
43
|
+
|
|
44
|
+
:param key: 属性名
|
|
45
|
+
:param value: 属性值
|
|
46
|
+
"""
|
|
47
|
+
super().__setattr__(
|
|
48
|
+
key,
|
|
49
|
+
Box(value) if isinstance(value, dict) else BoxList(value) if isinstance(value, list) else value
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
def __str__(self) -> str:
|
|
53
|
+
"""
|
|
54
|
+
返回格式化的 JSON 字符串表示。
|
|
55
|
+
"""
|
|
56
|
+
return Box(self.__to_dict()).to_json(indent=2)
|
|
57
|
+
|
|
58
|
+
def __list_to_dict(self, data: list[Any]) -> list[Any]:
|
|
59
|
+
"""
|
|
60
|
+
递归将列表中嵌套的 GlobalAttribute 转为普通 dict。
|
|
61
|
+
|
|
62
|
+
:param data: 原始列表
|
|
63
|
+
:return: 转换后的列表
|
|
64
|
+
"""
|
|
65
|
+
result = []
|
|
66
|
+
for item in data:
|
|
67
|
+
if isinstance(item, GlobalAttribute):
|
|
68
|
+
result.append(item.__to_dict())
|
|
69
|
+
elif isinstance(item, list):
|
|
70
|
+
result.append(self.__list_to_dict(item))
|
|
71
|
+
else:
|
|
72
|
+
result.append(item)
|
|
73
|
+
return result
|
|
74
|
+
|
|
75
|
+
def __to_dict(self) -> dict[str, Any]:
|
|
76
|
+
"""
|
|
77
|
+
递归将 GlobalAttribute 及其嵌套属性转为普通 dict。
|
|
78
|
+
|
|
79
|
+
:return: 普通 dict 对象
|
|
80
|
+
"""
|
|
81
|
+
result = {}
|
|
82
|
+
for key, value in self.__dict__.items():
|
|
83
|
+
if isinstance(value, GlobalAttribute):
|
|
84
|
+
result[key] = value.__to_dict()
|
|
85
|
+
elif isinstance(value, list):
|
|
86
|
+
result[key] = self.__list_to_dict(value)
|
|
87
|
+
else:
|
|
88
|
+
result[key] = value
|
|
89
|
+
return result
|
|
90
|
+
|
|
91
|
+
def get(self, key: str, app: str | None = None, default: Any = None) -> Any:
|
|
92
|
+
"""
|
|
93
|
+
获取属性值,支持按 app 作用域隔离。
|
|
94
|
+
|
|
95
|
+
:param key: 属性名
|
|
96
|
+
:param app: 应用名称(可选),提供时以 "app.key" 形式查找
|
|
97
|
+
:param default: 未找到时的默认值
|
|
98
|
+
:return: 属性值或 default
|
|
99
|
+
"""
|
|
100
|
+
key_chain = f"{app}.{key}" if app else key
|
|
101
|
+
return self.__get_by_chain(key_chain) or default
|
|
102
|
+
|
|
103
|
+
def set(self, key: str, value: Any, app: str | None = None) -> None:
|
|
104
|
+
"""
|
|
105
|
+
设置属性值,支持按 app 作用域隔离。
|
|
106
|
+
|
|
107
|
+
:param key: 属性名
|
|
108
|
+
:param value: 属性值
|
|
109
|
+
:param app: 应用名称(可选),提供时以 "app.key" 形式写入
|
|
110
|
+
"""
|
|
111
|
+
key_chain = f"{app}.{key}" if app else key
|
|
112
|
+
self.__set_by_chain(key_chain, value)
|
|
113
|
+
|
|
114
|
+
def __get_by_chain(self, key_chain: str) -> Any:
|
|
115
|
+
"""
|
|
116
|
+
链式格式的 key 进行 get。
|
|
117
|
+
|
|
118
|
+
:param key_chain: 链式 key,例如 "app.module.key"
|
|
119
|
+
:return: 属性值,找不到返回 None
|
|
120
|
+
"""
|
|
121
|
+
keys = key_chain.split(".") if "." in key_chain else [key_chain]
|
|
122
|
+
obj = self
|
|
123
|
+
for key in keys:
|
|
124
|
+
obj = getattr(obj, key, None)
|
|
125
|
+
if obj is None:
|
|
126
|
+
return None
|
|
127
|
+
return obj
|
|
128
|
+
|
|
129
|
+
def __set_by_chain(self, key_chain: str, value: Any) -> None:
|
|
130
|
+
"""
|
|
131
|
+
链式格式的 key 进行 set。
|
|
132
|
+
|
|
133
|
+
:param key_chain: 链式 key,例如 "app.module.key"
|
|
134
|
+
:param value: 要设置的值
|
|
135
|
+
"""
|
|
136
|
+
keys = key_chain.split(".") if "." in key_chain else [key_chain]
|
|
137
|
+
current = self
|
|
138
|
+
# 逐层创建中间节点(如不存在则自动创建 Box)
|
|
139
|
+
for key in keys[:-1]:
|
|
140
|
+
if not hasattr(current, key):
|
|
141
|
+
setattr(current, key, Box())
|
|
142
|
+
current = getattr(current, key)
|
|
143
|
+
setattr(current, keys[-1], value)
|
|
144
|
+
|
|
145
|
+
def set_from_dict(self, dic: dict[str, Any], app: str | None = None) -> None:
|
|
146
|
+
"""
|
|
147
|
+
从字典批量设置属性。
|
|
148
|
+
|
|
149
|
+
:param dic: 键值对字典
|
|
150
|
+
:param app: 应用名称(可选),统一作用域
|
|
151
|
+
"""
|
|
152
|
+
for k, v in dic.items():
|
|
153
|
+
self.set(k, v, app)
|
|
154
|
+
|
|
155
|
+
def delete(self, key: str) -> None:
|
|
156
|
+
"""
|
|
157
|
+
删除指定属性。
|
|
158
|
+
|
|
159
|
+
:param key: 属性名
|
|
160
|
+
"""
|
|
161
|
+
delattr(self, key)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@singleton
|
|
165
|
+
class Context(GlobalAttribute):
|
|
166
|
+
"""全局上下文,用于存储测试过程的临时变量。"""
|
|
167
|
+
...
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@singleton
|
|
171
|
+
class Config(GlobalAttribute):
|
|
172
|
+
"""全局配置对象,用于存储应用配置信息。"""
|
|
173
|
+
...
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@singleton
|
|
177
|
+
class FrameworkContext(GlobalAttribute):
|
|
178
|
+
"""框架上下文,用于存储框架内部状态(数据库连接、MQ 连接、HTTP 客户端等)。"""
|
|
179
|
+
...
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# 创建管理变量的全局对象,用于存储临时变量
|
|
183
|
+
CONTEXT = Context()
|
|
184
|
+
# 创建配置内容管理的全局对象
|
|
185
|
+
CONFIG = Config()
|
|
186
|
+
|
|
187
|
+
FRAMEWORK_CONTEXT = FrameworkContext()
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""
|
|
2
|
+
过滤模块 — 提供关键字表达式匹配、标记匹配、字段禁用以及数据文件路径查找功能。
|
|
3
|
+
用于 pytest hook 中对测试用例进行筛选和前置数据处理。
|
|
4
|
+
"""
|
|
5
|
+
import re
|
|
6
|
+
import copy
|
|
7
|
+
from typing import Any
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
from box import Box
|
|
12
|
+
|
|
13
|
+
import framework.settings as settings
|
|
14
|
+
from framework.utils.log_util import logger
|
|
15
|
+
from framework.core.global_attribute import CONTEXT
|
|
16
|
+
from framework.assertion.retry_assert import eventually
|
|
17
|
+
|
|
18
|
+
# 前置失败跳过机制:合法的 skip 原因集合
|
|
19
|
+
_VALID_SKIP_REASONS = frozenset({
|
|
20
|
+
"上一条用例已跳过",
|
|
21
|
+
"上一条用例执行失败",
|
|
22
|
+
"test_setup 执行异常",
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
# 解析 nodeid 中的类前缀和 scenario 索引号,格式: path::ClassName[params#index]
|
|
26
|
+
_NODEID_PATTERN = re.compile(r"^(?P<prefix>.*)::[^:\[\]]+\[.*#(?P<index>\d+)\]$")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def match_keyword(keyword_expr: str, target_str: str) -> bool:
|
|
30
|
+
"""
|
|
31
|
+
使用关键字表达式匹配目标字符串,支持 and/or/not 及括号组合的布尔表达式。
|
|
32
|
+
|
|
33
|
+
@param keyword_expr: 关键字表达式,如 "foo and (bar or baz)"
|
|
34
|
+
@param target_str: 待匹配的目标字符串
|
|
35
|
+
@return: 匹配成功返回 True,否则返回 False;表达式为空时返回 True
|
|
36
|
+
"""
|
|
37
|
+
if not keyword_expr.strip():
|
|
38
|
+
return True
|
|
39
|
+
keyword_expr = keyword_expr.strip().lower()
|
|
40
|
+
target_str = target_str.lower()
|
|
41
|
+
words = re.findall(r"[^\s()]+", keyword_expr)
|
|
42
|
+
if len(words) == 1:
|
|
43
|
+
return words[0] in target_str
|
|
44
|
+
tokens = re.findall(r"\(|\)|and|or|not|[^\s()]+", keyword_expr)
|
|
45
|
+
expr_list = [
|
|
46
|
+
t if t in {"and", "or", "not", "(", ")"} else str(t in target_str)
|
|
47
|
+
for t in tokens
|
|
48
|
+
]
|
|
49
|
+
try:
|
|
50
|
+
return eval(" ".join(expr_list))
|
|
51
|
+
except Exception as e:
|
|
52
|
+
logger.error(f"表达式解析错误: {e}, 表达式: {' '.join(expr_list)}")
|
|
53
|
+
return False
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def match_mark(keyword_expr: str, target_list: list[str]) -> bool:
|
|
57
|
+
"""
|
|
58
|
+
使用关键字表达式匹配目标字符串列表,支持 and/or/not 及括号组合的布尔表达式。
|
|
59
|
+
|
|
60
|
+
@param keyword_expr: 关键字表达式,如 "smoke and not slow"
|
|
61
|
+
@param target_list: 待匹配的字符串列表
|
|
62
|
+
@return: 匹配成功返回 True,否则返回 False;表达式为空时返回 True
|
|
63
|
+
"""
|
|
64
|
+
if not keyword_expr.strip():
|
|
65
|
+
return True
|
|
66
|
+
keyword_expr = keyword_expr.strip().lower()
|
|
67
|
+
target_list = [s.lower() for s in target_list]
|
|
68
|
+
tokens = re.findall(r"\(|\)|and|or|not|[^\s()]+", keyword_expr)
|
|
69
|
+
expr_list = [
|
|
70
|
+
t if t in {"and", "or", "not", "(", ")"} else str(t in target_list)
|
|
71
|
+
for t in tokens
|
|
72
|
+
]
|
|
73
|
+
try:
|
|
74
|
+
return eval(" ".join(expr_list))
|
|
75
|
+
except Exception as e:
|
|
76
|
+
logger.error(f"表达式解析错误: {e}, 表达式: {' '.join(expr_list)}")
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def subset_and_diff(small: set, big: set) -> tuple[bool, set]:
|
|
81
|
+
"""
|
|
82
|
+
判断 small 是否为 big 的子集,并返回差集。
|
|
83
|
+
|
|
84
|
+
@param small: 较小的集合
|
|
85
|
+
@param big: 较大的集合
|
|
86
|
+
@return: (is_subset, difference) — 是否为子集以及 small 比 big 多出的元素
|
|
87
|
+
"""
|
|
88
|
+
return small.issubset(big), small - big
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def disable_field(scenario: dict, data: Any) -> Any:
|
|
92
|
+
"""
|
|
93
|
+
根据场景配置中标记为 "disable" 的字段名,递归地从 data 中删除对应占位符的字段。
|
|
94
|
+
|
|
95
|
+
遍历 data 中的所有层级,若字段的字符串值等于 "${field_name}" 且 field_name
|
|
96
|
+
在 scenario 中被标记为 "disable",则删除该字段。
|
|
97
|
+
|
|
98
|
+
@param scenario: 场景配置字典,值为 "disable" 表示该字段需被禁用
|
|
99
|
+
@param data: 待处理的数据对象(dict 或 list 嵌套结构)
|
|
100
|
+
@return: 处理后的数据对象
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
def _clean(obj):
|
|
104
|
+
# 递归清理 dict 或 list 中符合禁用条件的字段
|
|
105
|
+
if isinstance(obj, dict):
|
|
106
|
+
keys_to_delete = []
|
|
107
|
+
for k, v in obj.items():
|
|
108
|
+
if isinstance(v, (dict, list)):
|
|
109
|
+
# 嵌套结构,递归处理
|
|
110
|
+
_clean(v)
|
|
111
|
+
elif isinstance(v, str):
|
|
112
|
+
# 检查字符串值是否为 "${field_name}" 形式且 field_name 被标记为 disable
|
|
113
|
+
for ak, av in scenario.items():
|
|
114
|
+
if av == "disable" and v == f"${{{ak}}}":
|
|
115
|
+
keys_to_delete.append(k)
|
|
116
|
+
break
|
|
117
|
+
# 删除收集到的要删除的键
|
|
118
|
+
for k in keys_to_delete:
|
|
119
|
+
del obj[k]
|
|
120
|
+
elif isinstance(obj, list):
|
|
121
|
+
for item in obj:
|
|
122
|
+
if isinstance(item, (dict, list)):
|
|
123
|
+
_clean(item)
|
|
124
|
+
|
|
125
|
+
if not scenario:
|
|
126
|
+
return data
|
|
127
|
+
_clean(data)
|
|
128
|
+
return data
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def find_data_path_by_case(app: str, case_file_name: str) -> Path | None:
|
|
132
|
+
"""
|
|
133
|
+
根据应用名和用例文件名,在数据目录下查找对应的 YAML 数据文件。
|
|
134
|
+
|
|
135
|
+
在 {DATA_DIR}/{app}/ 目录下递归搜索以 case_file_name 开头、.y 后缀的文件
|
|
136
|
+
(同时匹配 .yaml 和 .yml)。
|
|
137
|
+
|
|
138
|
+
@param app: 应用名称
|
|
139
|
+
@param case_file_name: 用例文件名(不含后缀)
|
|
140
|
+
@return: 匹配到的 Path 对象,未找到则返回 None
|
|
141
|
+
"""
|
|
142
|
+
# 在 data 目录下递归搜索 yaml 文件
|
|
143
|
+
return next(Path(settings.DATA_DIR, app).rglob(f"{case_file_name}.y*"), None)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def inject_test_object_attrs(item: Any) -> None:
|
|
147
|
+
"""将测试数据、配置、上下文、HTTP 会话等注入到测试实例中。
|
|
148
|
+
|
|
149
|
+
@param item: pytest 测试用例项
|
|
150
|
+
"""
|
|
151
|
+
data = item.callspec.params.get("data")
|
|
152
|
+
app = data.get("app")
|
|
153
|
+
item.instance.app = app
|
|
154
|
+
item.instance.retry_assert = eventually
|
|
155
|
+
item.instance.scenario = Box(data.get("_scenario"))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def skip_if_previous_failed(item: Any) -> None:
|
|
159
|
+
"""当 ignore_failed=false 时,检查前置用例状态并决定是否跳过当前用例。"""
|
|
160
|
+
if item.funcargs.get("setup_success") is False:
|
|
161
|
+
pytest.skip("test_setup 执行异常")
|
|
162
|
+
|
|
163
|
+
current_match = _NODEID_PATTERN.match(item.nodeid)
|
|
164
|
+
if not current_match:
|
|
165
|
+
return
|
|
166
|
+
|
|
167
|
+
index = item.session.items.index(item)
|
|
168
|
+
if index == 0:
|
|
169
|
+
return
|
|
170
|
+
prev_item = item.session.items[index - 1]
|
|
171
|
+
prev_match = _NODEID_PATTERN.match(prev_item.nodeid)
|
|
172
|
+
if not prev_match:
|
|
173
|
+
return
|
|
174
|
+
|
|
175
|
+
if current_match.group("prefix") != prev_match.group("prefix"):
|
|
176
|
+
return
|
|
177
|
+
if current_match.group("index") != prev_match.group("index"):
|
|
178
|
+
return
|
|
179
|
+
|
|
180
|
+
prev_status = getattr(prev_item, "status", None)
|
|
181
|
+
if prev_status == "skipped":
|
|
182
|
+
skip_reason = (getattr(prev_item, "skip_reason", None) or "").strip()
|
|
183
|
+
if skip_reason in _VALID_SKIP_REASONS:
|
|
184
|
+
pytest.skip("上一条用例已跳过")
|
|
185
|
+
elif prev_status == "failed":
|
|
186
|
+
pytest.skip("上一条用例执行失败")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def deep_merge(base, override):
|
|
190
|
+
"""Deep merge override into base, returning a new dict.
|
|
191
|
+
|
|
192
|
+
Dot-path keys (e.g. "buyerInfo.firstName") are expanded into nested dicts.
|
|
193
|
+
"__missing__" values delete the key from base.
|
|
194
|
+
Dict values trigger recursive merge; all others override.
|
|
195
|
+
"""
|
|
196
|
+
if not isinstance(override, dict) or not isinstance(base, dict):
|
|
197
|
+
return override
|
|
198
|
+
result = copy.deepcopy(base)
|
|
199
|
+
for k, v in override.items():
|
|
200
|
+
if "." in k:
|
|
201
|
+
parts = k.split(".")
|
|
202
|
+
target = result
|
|
203
|
+
for part in parts[:-1]:
|
|
204
|
+
if part not in target or not isinstance(target[part], dict):
|
|
205
|
+
target[part] = {}
|
|
206
|
+
target = target[part]
|
|
207
|
+
leaf = parts[-1]
|
|
208
|
+
else:
|
|
209
|
+
target = result
|
|
210
|
+
leaf = k
|
|
211
|
+
if v == settings.DEL_FLAG:
|
|
212
|
+
target.pop(leaf, None)
|
|
213
|
+
elif isinstance(v, dict) and leaf in target and isinstance(target.get(leaf), dict):
|
|
214
|
+
target[leaf] = deep_merge(target[leaf], v)
|
|
215
|
+
else:
|
|
216
|
+
target[leaf] = copy.deepcopy(v)
|
|
217
|
+
return result
|