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.
Files changed (48) hide show
  1. framework/__init__.py +1 -0
  2. framework/assertion/__init__.py +3 -0
  3. framework/assertion/retry_assert.py +67 -0
  4. framework/assertion/webhook_assert.py +129 -0
  5. framework/client/__init__.py +3 -0
  6. framework/client/crrm_client.py +155 -0
  7. framework/client/http_client.py +340 -0
  8. framework/client/mq_client.py +178 -0
  9. framework/client/websocket_client.py +414 -0
  10. framework/conftest.py +526 -0
  11. framework/core/__init__.py +3 -0
  12. framework/core/base_class.py +871 -0
  13. framework/core/extract.py +185 -0
  14. framework/core/global_attribute.py +187 -0
  15. framework/core/hooks/__init__.py +3 -0
  16. framework/core/hooks/filters.py +217 -0
  17. framework/core/hooks/reporter.py +228 -0
  18. framework/core/hooks/session.py +345 -0
  19. framework/core/hooks/sorting.py +84 -0
  20. framework/core/models.py +82 -0
  21. framework/core/render_data.py +309 -0
  22. framework/core/validate.py +648 -0
  23. framework/db/__init__.py +3 -0
  24. framework/db/mysql_db.py +226 -0
  25. framework/db/redis_db.py +319 -0
  26. framework/exceptions.py +22 -0
  27. framework/exit_code.py +20 -0
  28. framework/gen/__init__.py +3 -0
  29. framework/gen/case_gen.py +1268 -0
  30. framework/gen/create_app.py +265 -0
  31. framework/report.py +111 -0
  32. framework/script.py +35 -0
  33. framework/settings.py +93 -0
  34. framework/utils/__init__.py +3 -0
  35. framework/utils/cognito_util.py +348 -0
  36. framework/utils/common.py +298 -0
  37. framework/utils/date_util.py +218 -0
  38. framework/utils/encrypt.py +448 -0
  39. framework/utils/lark_util.py +167 -0
  40. framework/utils/log_util.py +10 -0
  41. framework/utils/mock_util.py +236 -0
  42. framework/utils/yaml_util.py +169 -0
  43. framework/ws_server.py +167 -0
  44. pytest_api_framework_alpha-1.0.5.dist-info/METADATA +98 -0
  45. pytest_api_framework_alpha-1.0.5.dist-info/RECORD +48 -0
  46. pytest_api_framework_alpha-1.0.5.dist-info/WHEEL +5 -0
  47. pytest_api_framework_alpha-1.0.5.dist-info/licenses/LICENSE +21 -0
  48. pytest_api_framework_alpha-1.0.5.dist-info/top_level.txt +1 -0
@@ -0,0 +1,82 @@
1
+ """
2
+ 数据模型模块。
3
+
4
+ 定义测试框架中使用的数据类(dataclass),描述测试数据、场景、请求的结构。
5
+ 对应 YAML 测试数据的完整字段,同时包含框架运行时注入的内部字段(以 _ 开头)。
6
+ """
7
+ from __future__ import annotations
8
+ from dataclasses import dataclass
9
+
10
+ from box import Box
11
+
12
+
13
+ @dataclass
14
+ class Scenario:
15
+ """场景数据对象,对应 YAML 中 scenarios 下的单个 scenario 项。"""
16
+ describe: str # 场景描述
17
+ level: str # 场景级别
18
+ data: Box # 场景变量覆盖
19
+ expect: Box # 场景预期结果覆盖
20
+ ignore: bool # 是否忽略该场景
21
+ exclude: list[str] # 排除的 case 方法名列表
22
+
23
+
24
+ @dataclass
25
+ class RequestData:
26
+ """HTTP/WebSocket 请求数据,对应 YAML 中 request 下的字段。
27
+
28
+ HTTP 请求含 json/params/data;WebSocket 请求含 message。
29
+ """
30
+ url: str # 请求地址
31
+ method: str # 请求方法
32
+ headers: Box # 请求头
33
+ json: Box # JSON 请求体(HTTP)
34
+ params: Box # URL 查询参数(HTTP)
35
+ data: Box # 表单请求体(HTTP)
36
+ message: Box # 消息体(WebSocket)
37
+
38
+
39
+ @dataclass
40
+ class ValidateRule:
41
+ """单条断言规则。
42
+
43
+ YAML 格式: {"断言方式": "实际值表达式, 预期值"}
44
+ 无预期值: {"is_null": "$.data"}
45
+ 有预期值: {"eq": "$.code, 200"}
46
+ """
47
+ type: str # 断言方式(eq, contains, not_null 等)
48
+ expression: str # 实际值表达式
49
+ expected: str # 预期值
50
+
51
+
52
+ @dataclass
53
+ class ExtractRule:
54
+ """单条变量提取规则。
55
+
56
+ YAML 格式: {"变量名": "提取表达式"}
57
+ 支持 jsonpath($.)、正则(/pattern/)、box 属性 三种表达式。
58
+ """
59
+ name: str # 变量名
60
+ expression: str # 提取表达式
61
+
62
+
63
+ @dataclass
64
+ class CaseData:
65
+ """测试用例完整数据,对应 YAML 中单个 case 的结构。
66
+
67
+ 包含测试字段和框架运行时注入的内部字段(以 _ 开头)。
68
+ """
69
+ title: str # 用例标题
70
+ request: RequestData # 请求数据
71
+ level: str # 用例等级(p0/p1/p2)
72
+ validate: list[ValidateRule] # 断言规则列表
73
+ extract: list[ExtractRule] # 提取规则列表
74
+ module: str # 所属模块
75
+ describe: str # 描述
76
+ # ── 框架运行时注入的内部字段 ──
77
+ app: str # 所属应用(如 client_api)
78
+ _account: str # 账号名(如 client_api_v2)
79
+ _scenario: Scenario # 场景数据
80
+ _marks: list[str] # 标签列表
81
+ _ignore_failed: bool # 是否忽略前置失败
82
+ _is_multipart: bool # 是否为 multipart 上传请求
@@ -0,0 +1,309 @@
1
+ """
2
+ 数据渲染模块。
3
+
4
+ 负责将 YAML 测试数据中的占位符 ${...} 替换为实际值。
5
+ 支持从场景数据、全局上下文、函数调用三个来源取值。
6
+ 同时支持文件路径识别(用于 multipart 上传)和类型转换。
7
+ """
8
+ import os
9
+ import re
10
+ import ast
11
+ import importlib
12
+ from functools import lru_cache
13
+
14
+ import allure
15
+ from box import Box
16
+
17
+ from framework.utils.log_util import logger
18
+ from framework.core.global_attribute import CONTEXT
19
+ from framework.settings import FAKER_LANGUAGE, FILE_DIR
20
+ from framework.utils.common import SingletonFaker
21
+ from typing import Any
22
+
23
+ # 占位符匹配正则:${表达式} 或 ${表达式:类型}
24
+ _PLACEHOLDER_RE = re.compile(r"\$\{([\w.\[\]0-9]+(?:\([^)]*\))?)(?::(\w+))?\}")
25
+ # 宽松的占位符匹配,用于在替换前规范化 ${ ... } 内部的空格
26
+ _LOOSE_PLACEHOLDER_RE = re.compile(r"\$\{[^{}]*}")
27
+ # 文件扩展名匹配正则(用于 multipart 上传识别)
28
+ _FILE_EXT_RE = re.compile(
29
+ r'\.(txt|doc|docx|pdf|xls|xlsx|ppt|pptx|md|jpg|jpeg|png|gif|svg|webp|ico|mp4|avi|mov|wmv|flv|mkv|webm|mp3|exe)$',
30
+ re.IGNORECASE,
31
+ )
32
+ # 函数调用匹配正则:func_name(arg1, arg2, key=value)
33
+ _FUNC_RE = re.compile(r'(?P<func_name>.+)\((?P<args>.*)\)')
34
+ # 属性路径元素匹配正则:匹配 "name" 或 "[0]"
35
+ _PATH_ELEMENT_RE = re.compile(r'(\w+)|\[(\d+)]')
36
+ # 类型映射表:字符串类型名 -> Python 类型
37
+ _TYPE_MAP = {
38
+ "str": str, "string": str,
39
+ "int": int, "integer": int,
40
+ "float": float, "number": float,
41
+ "bool": bool, "boolean": bool,
42
+ "list": list,
43
+ "dict": dict,
44
+ }
45
+
46
+
47
+ @lru_cache(maxsize=1024)
48
+ def _parse_attr_path(attr_path: str) -> tuple[tuple[str, str], ...]:
49
+ """
50
+ 缓存属性路径解析结果,避免重复正则匹配。
51
+
52
+ :param attr_path: 属性路径字符串
53
+ :return: (attr, index) 元组的元组
54
+ """
55
+ return tuple(_PATH_ELEMENT_RE.findall(attr_path))
56
+
57
+
58
+ class RenderData(object):
59
+ """
60
+ 数据渲染器。
61
+
62
+ 将 YAML 测试数据中的占位符 ${...} 替换为实际值。
63
+ 支持三级变量查找:场景数据 -> 全局上下文(app前缀) -> 全局上下文。
64
+ 支持调用 utils.common 和 faker 中的函数。
65
+ 支持文件路径识别和类型转换。
66
+ """
67
+
68
+ _app_prefixes: tuple[str, ...] | None = None
69
+
70
+ def __init__(self, data: Any) -> None:
71
+ """
72
+ 初始化渲染器。
73
+
74
+ :param data: Box 类型测试数据,含 request、_scenario、app 等字段
75
+ """
76
+ self.data = data
77
+ self.request = data.get("request")
78
+ self.scenario = self._load_scenario(data)
79
+ self.context = CONTEXT
80
+ self.faker = SingletonFaker(locale=FAKER_LANGUAGE).faker
81
+ self._is_multipart = False
82
+
83
+ def render(self) -> Box:
84
+ """
85
+ 执行数据渲染,替换所有占位符。
86
+
87
+ 渲染顺序:场景数据 → URL → request 其他字段。
88
+ 渲染后标记是否为 multipart 请求。
89
+
90
+ :return: 渲染后的完整数据
91
+ """
92
+ with allure.step("渲染数据"):
93
+ self._replace(self.scenario)
94
+ self._render_url()
95
+ self._replace(self.request)
96
+ self.data["request"] = self.request
97
+ self.data["_is_multipart"] = self._is_multipart
98
+ # 将渲染后的 scenario 数据写回,_replace(self.scenario) 修改的是独立 Box 对象
99
+ if self.data.get("_scenario"):
100
+ self.data["_scenario"]["data"] = self.scenario
101
+ return Box(self.data)
102
+
103
+ def _render_url(self) -> None:
104
+ """
105
+ 渲染 URL 中的 {param} 占位符(非 ${...} 格式)。
106
+
107
+ 用于动态路径参数替换,如 /api/user/{userId}。
108
+ """
109
+ url = self.request.get("url")
110
+ if not url or "{" not in url:
111
+ return
112
+ self.request["url"] = self._substitute(self._normalize(url))
113
+
114
+ def _replace(self, data: Any) -> None:
115
+ """递归遍历 dict/list,替换 ${...} 占位符和文件路径。"""
116
+ if isinstance(data, dict):
117
+ for key, value in data.items():
118
+ data[key] = self._resolve_node(value, field_name=key)
119
+ elif isinstance(data, list):
120
+ for i, item in enumerate(data):
121
+ data[i] = self._resolve_node(item)
122
+
123
+ def _resolve_node(self, value: Any, field_name: str = None) -> Any:
124
+ """处理单个节点:递归嵌套结构,字符串则尝试替换。"""
125
+ if isinstance(value, (dict, list)):
126
+ self._replace(value)
127
+ return value
128
+ if isinstance(value, str) and value:
129
+ return self._resolve_string(self._normalize(value), field_name=field_name)
130
+ return value
131
+
132
+ def _resolve_string(self, value: str, field_name: str = None) -> Any:
133
+ """对字符串值进行占位符替换或文件路径识别。
134
+
135
+ 整串就是一个占位符时按原始类型返回(如 ${count:int} 得到 int);
136
+ 占位符只是串的一部分时(如 "Bearer ${token}")逐个替换后拼回字符串。
137
+ """
138
+ if "${" in value:
139
+ m = _PLACEHOLDER_RE.fullmatch(value)
140
+ if m:
141
+ return self._convert_type(self.get_attribute(m.group(1), field_name=field_name), m.group(2))
142
+ value = self._substitute(value, field_name=field_name)
143
+
144
+ if _FILE_EXT_RE.search(value) and not value.startswith(('http://', 'https://')):
145
+ self._is_multipart = True
146
+ return self._open_file(value)
147
+ return value
148
+
149
+ @staticmethod
150
+ def _normalize(value: str) -> str:
151
+ """只清掉 ${...} 内部的空格,占位符以外的文本原样保留。
152
+
153
+ 这样 "${ token }"、"${func(a, b)}" 仍能被识别,
154
+ 而 "Bearer ${token}"、"John Smith" 里的空格不会被误删。
155
+ """
156
+ if "${" not in value:
157
+ return value
158
+ return _LOOSE_PLACEHOLDER_RE.sub(lambda m: m.group(0).replace(" ", ""), value)
159
+
160
+ def _substitute(self, value: str, field_name: str = None) -> str:
161
+ """把字符串中所有 ${...} 占位符替换成对应的值,结果始终是字符串。
162
+
163
+ 取不到值的占位符原样保留(get_attribute 内部已经记了错误日志)。
164
+ """
165
+
166
+ def replacer(match):
167
+ result = self.get_attribute(match.group(1), field_name=field_name)
168
+ if result is None:
169
+ return match.group(0)
170
+ return str(self._convert_type(result, match.group(2)))
171
+
172
+ return _PLACEHOLDER_RE.sub(replacer, value)
173
+
174
+ def get_attribute(self, keyword: str, field_name: str = None) -> Any:
175
+ """分发:函数调用(以 ) 结尾)还是变量查找。"""
176
+ if not keyword.strip().endswith(")"):
177
+ return self._get_variable(keyword, field_name=field_name)
178
+ return self._get_function(keyword, field_name=field_name)
179
+
180
+ def _get_variable(self, expression: str, field_name: str = None) -> Any:
181
+ """三级查找:场景数据 → 全局上下文(app前缀) → 全局上下文。"""
182
+ # 如果 expression 已带 app 前缀则直接用,否则拼接 app
183
+ if expression.startswith(self._get_app_prefixes()):
184
+ key_with_app = expression
185
+ else:
186
+ app = self.data.get('app')
187
+ key_with_app = f"{app}.{expression}" if app else expression
188
+ value = (self._nested_get(self.scenario, expression)
189
+ or self._nested_get(self.context, key_with_app)
190
+ or self._nested_get(self.context, expression))
191
+ if value is None:
192
+ with allure.step(f"解析变量异常,context中不存在变量: {expression}"):
193
+ logger.error(f"解析变量异常,context中不存在变量: {expression}")
194
+ return None
195
+ prefix = f"{field_name} → {expression}" if field_name else expression
196
+ with allure.step(f"解析变量: {prefix} = {value}"):
197
+ logger.info(f"解析变量: {prefix} = {value} ({type(value).__name__})")
198
+ return value
199
+
200
+ def _get_function(self, keyword: str, field_name: str = None) -> Any:
201
+ """从 utils.common 或 faker 中调用函数。"""
202
+ m = _FUNC_RE.match(keyword)
203
+ func_name = m.group("func_name")
204
+ args_str = m.group("args")
205
+ pos_args, kw_args = self._parse_args(args_str)
206
+
207
+ utils_module = importlib.import_module("utils.common")
208
+ func = getattr(utils_module, func_name, None) or getattr(self.faker, func_name, None)
209
+ if func is None:
210
+ with allure.step(f"解析变量异常,函数不存在: {keyword}"):
211
+ logger.error(f"解析变量异常,函数不存在: {keyword}")
212
+ return None
213
+ value = func(*pos_args, **kw_args)
214
+ prefix = f"{field_name} → {keyword}" if field_name else keyword
215
+ with allure.step(f"解析变量: {prefix} = {value}"):
216
+ logger.info(f"解析变量: {prefix} = {value} ({type(value).__name__})")
217
+ return value
218
+
219
+ @staticmethod
220
+ def _parse_args(args_str: str) -> tuple[list[Any], dict[str, Any]]:
221
+ """安全解析函数参数,返回 (pos_args, kw_args)。"""
222
+ if not args_str.strip():
223
+ return [], {}
224
+ try:
225
+ # 用 AST 解析参数列表,支持字符串、数字、关键字参数
226
+ tree = ast.parse(f"f({args_str})", mode='eval')
227
+ call = tree.body
228
+ pos_args = [ast.literal_eval(a) for a in call.args]
229
+ kw_args = {kw.arg: ast.literal_eval(kw.value) for kw in call.keywords}
230
+ return pos_args, kw_args
231
+ except Exception:
232
+ # AST 解析降级:按逗号拆分后单个求值
233
+ pos_args = [ast.literal_eval(a.strip()) for a in args_str.split(",")]
234
+ return pos_args, {}
235
+
236
+ @staticmethod
237
+ def _nested_get(obj: Any, attr_path: str) -> Any:
238
+ """通过 'a.b[0].c' 路径获取嵌套属性值。"""
239
+ try:
240
+ for attr, index in _parse_attr_path(attr_path):
241
+ if attr:
242
+ obj = getattr(obj, attr)
243
+ if index:
244
+ obj = obj[int(index)]
245
+ return obj
246
+ except Exception:
247
+ return None
248
+
249
+ @staticmethod
250
+ def _open_file(filepath: str) -> tuple[str, Any, str]:
251
+ """
252
+ 打开文件,用于 multipart 上传。
253
+
254
+ :param filepath: 相对于 FILE_DIR 的文件路径
255
+ :return: (文件名, 文件对象, MIME 类型)
256
+ :raises FileNotFoundError: 文件不存在
257
+ """
258
+ full_path = os.path.join(FILE_DIR, filepath)
259
+ if not os.path.isfile(full_path):
260
+ raise FileNotFoundError(f"File not found: {full_path}")
261
+ f = open(full_path, "rb")
262
+ return os.path.basename(filepath), f, "application/octet-stream"
263
+
264
+ @staticmethod
265
+ def _convert_type(value: Any, type_name: str | None) -> Any:
266
+ """
267
+ 将值转换为指定类型。
268
+
269
+ :param value: 原始值
270
+ :param type_name: 目标类型名称(如 "int"、"str"、"bool")
271
+ :return: 转换后的值,转换失败返回原始值
272
+ """
273
+ if type_name is None or value is None:
274
+ return value
275
+ convert = _TYPE_MAP.get(type_name.lower())
276
+ if convert is None:
277
+ logger.warning(f"未知的类型标注: {type_name}, 返回原始值")
278
+ return value
279
+ try:
280
+ return convert(value)
281
+ except (ValueError, TypeError):
282
+ logger.warning(f"类型转换失败: {value}:{type(value).__name__} -> {type_name}")
283
+ return value
284
+
285
+ @staticmethod
286
+ def _load_scenario(data):
287
+ """
288
+ 从测试数据中加载场景数据。
289
+
290
+ :param data: 原始测试数据
291
+ :return: 场景数据 Box 对象,不存在则返回空 Box
292
+ """
293
+ try:
294
+ return Box(data.get("_scenario").get("data") or {})
295
+ except AttributeError:
296
+ return {}
297
+
298
+ @classmethod
299
+ def _get_app_prefixes(cls):
300
+ """
301
+ 获取所有已注册的 app 前缀列表。
302
+
303
+ 用于判断变量 expression 是否已包含 app 前缀。
304
+
305
+ :return: app 前缀元组,如 ("camp_admin.", "psp_api.")
306
+ """
307
+ if cls._app_prefixes is None:
308
+ cls._app_prefixes = tuple(f"{app}." for app in CONTEXT.all_app)
309
+ return cls._app_prefixes