pytest-api-framework-alpha 1.0.5__tar.gz
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.
- pytest_api_framework_alpha-1.0.5/LICENSE +21 -0
- pytest_api_framework_alpha-1.0.5/PKG-INFO +98 -0
- pytest_api_framework_alpha-1.0.5/README.md +47 -0
- pytest_api_framework_alpha-1.0.5/framework/__init__.py +1 -0
- pytest_api_framework_alpha-1.0.5/framework/assertion/__init__.py +3 -0
- pytest_api_framework_alpha-1.0.5/framework/assertion/retry_assert.py +67 -0
- pytest_api_framework_alpha-1.0.5/framework/assertion/webhook_assert.py +129 -0
- pytest_api_framework_alpha-1.0.5/framework/client/__init__.py +3 -0
- pytest_api_framework_alpha-1.0.5/framework/client/crrm_client.py +155 -0
- pytest_api_framework_alpha-1.0.5/framework/client/http_client.py +340 -0
- pytest_api_framework_alpha-1.0.5/framework/client/mq_client.py +178 -0
- pytest_api_framework_alpha-1.0.5/framework/client/websocket_client.py +414 -0
- pytest_api_framework_alpha-1.0.5/framework/conftest.py +526 -0
- pytest_api_framework_alpha-1.0.5/framework/core/__init__.py +3 -0
- pytest_api_framework_alpha-1.0.5/framework/core/base_class.py +871 -0
- pytest_api_framework_alpha-1.0.5/framework/core/extract.py +185 -0
- pytest_api_framework_alpha-1.0.5/framework/core/global_attribute.py +187 -0
- pytest_api_framework_alpha-1.0.5/framework/core/hooks/__init__.py +3 -0
- pytest_api_framework_alpha-1.0.5/framework/core/hooks/filters.py +217 -0
- pytest_api_framework_alpha-1.0.5/framework/core/hooks/reporter.py +228 -0
- pytest_api_framework_alpha-1.0.5/framework/core/hooks/session.py +345 -0
- pytest_api_framework_alpha-1.0.5/framework/core/hooks/sorting.py +84 -0
- pytest_api_framework_alpha-1.0.5/framework/core/models.py +82 -0
- pytest_api_framework_alpha-1.0.5/framework/core/render_data.py +309 -0
- pytest_api_framework_alpha-1.0.5/framework/core/validate.py +648 -0
- pytest_api_framework_alpha-1.0.5/framework/db/__init__.py +3 -0
- pytest_api_framework_alpha-1.0.5/framework/db/mysql_db.py +226 -0
- pytest_api_framework_alpha-1.0.5/framework/db/redis_db.py +319 -0
- pytest_api_framework_alpha-1.0.5/framework/exceptions.py +22 -0
- pytest_api_framework_alpha-1.0.5/framework/exit_code.py +20 -0
- pytest_api_framework_alpha-1.0.5/framework/gen/__init__.py +3 -0
- pytest_api_framework_alpha-1.0.5/framework/gen/case_gen.py +1268 -0
- pytest_api_framework_alpha-1.0.5/framework/gen/create_app.py +265 -0
- pytest_api_framework_alpha-1.0.5/framework/report.py +111 -0
- pytest_api_framework_alpha-1.0.5/framework/script.py +35 -0
- pytest_api_framework_alpha-1.0.5/framework/settings.py +93 -0
- pytest_api_framework_alpha-1.0.5/framework/utils/__init__.py +3 -0
- pytest_api_framework_alpha-1.0.5/framework/utils/cognito_util.py +348 -0
- pytest_api_framework_alpha-1.0.5/framework/utils/common.py +298 -0
- pytest_api_framework_alpha-1.0.5/framework/utils/date_util.py +218 -0
- pytest_api_framework_alpha-1.0.5/framework/utils/encrypt.py +448 -0
- pytest_api_framework_alpha-1.0.5/framework/utils/lark_util.py +167 -0
- pytest_api_framework_alpha-1.0.5/framework/utils/log_util.py +10 -0
- pytest_api_framework_alpha-1.0.5/framework/utils/mock_util.py +236 -0
- pytest_api_framework_alpha-1.0.5/framework/utils/yaml_util.py +169 -0
- pytest_api_framework_alpha-1.0.5/framework/ws_server.py +167 -0
- pytest_api_framework_alpha-1.0.5/pytest_api_framework_alpha.egg-info/PKG-INFO +98 -0
- pytest_api_framework_alpha-1.0.5/pytest_api_framework_alpha.egg-info/SOURCES.txt +51 -0
- pytest_api_framework_alpha-1.0.5/pytest_api_framework_alpha.egg-info/dependency_links.txt +1 -0
- pytest_api_framework_alpha-1.0.5/pytest_api_framework_alpha.egg-info/requires.txt +24 -0
- pytest_api_framework_alpha-1.0.5/pytest_api_framework_alpha.egg-info/top_level.txt +1 -0
- pytest_api_framework_alpha-1.0.5/setup.cfg +4 -0
- pytest_api_framework_alpha-1.0.5/setup.py +57 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 alpha
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pytest-api-framework-alpha
|
|
3
|
+
Version: 1.0.5
|
|
4
|
+
Summary: 基于 pytest 的 API 自动化测试框架,YAML 驱动,集成 Allure 报告
|
|
5
|
+
Author: alpha
|
|
6
|
+
Author-email:
|
|
7
|
+
License: MIT
|
|
8
|
+
Classifier: Framework :: Pytest
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Topic :: Software Development :: Testing
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: allure-pytest==2.13.1
|
|
19
|
+
Requires-Dist: allure-python-commons==2.13.1
|
|
20
|
+
Requires-Dist: cn2an==0.5.19
|
|
21
|
+
Requires-Dist: DBUtils==3.1.0
|
|
22
|
+
Requires-Dist: Faker==40.23.0
|
|
23
|
+
Requires-Dist: jsonpath==0.82
|
|
24
|
+
Requires-Dist: pytest==7.2.2
|
|
25
|
+
Requires-Dist: PyYAML==6.0.1
|
|
26
|
+
Requires-Dist: python-box==7.2.0
|
|
27
|
+
Requires-Dist: pycryptodome==3.21.0
|
|
28
|
+
Requires-Dist: pycognito==2024.5.1
|
|
29
|
+
Requires-Dist: pyotp==2.9.0
|
|
30
|
+
Requires-Dist: PyMySQL==1.1.0
|
|
31
|
+
Requires-Dist: redis==3.5.3
|
|
32
|
+
Requires-Dist: requests==2.25.1
|
|
33
|
+
Requires-Dist: requests-toolbelt==1.0.0
|
|
34
|
+
Requires-Dist: retry==0.9.2
|
|
35
|
+
Requires-Dist: simplejson==3.20.1
|
|
36
|
+
Requires-Dist: websocket-client==1.9.0
|
|
37
|
+
Requires-Dist: python-dotenv==1.0.1
|
|
38
|
+
Requires-Dist: pytest-order==1.3.0
|
|
39
|
+
Requires-Dist: dill==0.3.8
|
|
40
|
+
Requires-Dist: pika==1.4.1
|
|
41
|
+
Requires-Dist: websockets==15.0
|
|
42
|
+
Dynamic: author
|
|
43
|
+
Dynamic: classifier
|
|
44
|
+
Dynamic: description
|
|
45
|
+
Dynamic: description-content-type
|
|
46
|
+
Dynamic: license
|
|
47
|
+
Dynamic: license-file
|
|
48
|
+
Dynamic: requires-dist
|
|
49
|
+
Dynamic: requires-python
|
|
50
|
+
Dynamic: summary
|
|
51
|
+
|
|
52
|
+
# pytest-api-framework-alpha
|
|
53
|
+
|
|
54
|
+
基于 pytest 的 API 自动化测试框架,用 YAML 描述测试数据,自动生成 Allure 报告。
|
|
55
|
+
|
|
56
|
+
## 安装
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install pytest-api-framework-alpha
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
要求 Python >= 3.6。
|
|
63
|
+
|
|
64
|
+
## 主要能力
|
|
65
|
+
|
|
66
|
+
- **YAML 驱动**:测试数据与用例代码分离,支持变量提取、引用与动态渲染
|
|
67
|
+
- **多协议客户端**:HTTP、WebSocket、消息队列(RabbitMQ)
|
|
68
|
+
- **数据层支持**:MySQL(连接池)、Redis
|
|
69
|
+
- **断言**:常规断言,以及面向异步场景的重试断言(`eventually`)和 Webhook 断言
|
|
70
|
+
- **鉴权**:内置 AWS Cognito 登录流程封装,支持 token 过期自动重新登录
|
|
71
|
+
- **报告**:集成 Allure,测试结束后可自动打开报告
|
|
72
|
+
- **脚手架**:一条命令生成新应用的配置、用例和测试数据目录结构
|
|
73
|
+
|
|
74
|
+
## 快速开始
|
|
75
|
+
|
|
76
|
+
生成一个新应用的目录骨架:
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
python -m framework.gen.create_app --app myapp --env dev
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
这会创建配置文件 `config/myapp/context.dev.yaml`,以及对应的用例和测试数据目录。
|
|
83
|
+
在配置文件里填入目标环境的域名和账号信息后即可开始编写用例。
|
|
84
|
+
|
|
85
|
+
## 配置
|
|
86
|
+
|
|
87
|
+
框架的行为开关集中在 `framework/settings.py`,包括 Allure 输出路径、用例级别定义、
|
|
88
|
+
异步断言超时、MySQL 连接池参数等。环境相关的域名、账号、数据库连接信息则放在
|
|
89
|
+
使用方项目的 `config/` 目录下,按环境分文件(`context.{env}.yaml`、`database.{env}.yaml`)。
|
|
90
|
+
|
|
91
|
+
## 基类
|
|
92
|
+
|
|
93
|
+
- `framework.core.base_class.BaseTestCase` —— pytest 用例基类
|
|
94
|
+
- `framework.script.BaseScript` —— 非 pytest 场景(独立脚本)的基类,子类实现 `run()` 方法
|
|
95
|
+
|
|
96
|
+
## License
|
|
97
|
+
|
|
98
|
+
见 LICENSE 文件。
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# pytest-api-framework-alpha
|
|
2
|
+
|
|
3
|
+
基于 pytest 的 API 自动化测试框架,用 YAML 描述测试数据,自动生成 Allure 报告。
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install pytest-api-framework-alpha
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
要求 Python >= 3.6。
|
|
12
|
+
|
|
13
|
+
## 主要能力
|
|
14
|
+
|
|
15
|
+
- **YAML 驱动**:测试数据与用例代码分离,支持变量提取、引用与动态渲染
|
|
16
|
+
- **多协议客户端**:HTTP、WebSocket、消息队列(RabbitMQ)
|
|
17
|
+
- **数据层支持**:MySQL(连接池)、Redis
|
|
18
|
+
- **断言**:常规断言,以及面向异步场景的重试断言(`eventually`)和 Webhook 断言
|
|
19
|
+
- **鉴权**:内置 AWS Cognito 登录流程封装,支持 token 过期自动重新登录
|
|
20
|
+
- **报告**:集成 Allure,测试结束后可自动打开报告
|
|
21
|
+
- **脚手架**:一条命令生成新应用的配置、用例和测试数据目录结构
|
|
22
|
+
|
|
23
|
+
## 快速开始
|
|
24
|
+
|
|
25
|
+
生成一个新应用的目录骨架:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
python -m framework.gen.create_app --app myapp --env dev
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
这会创建配置文件 `config/myapp/context.dev.yaml`,以及对应的用例和测试数据目录。
|
|
32
|
+
在配置文件里填入目标环境的域名和账号信息后即可开始编写用例。
|
|
33
|
+
|
|
34
|
+
## 配置
|
|
35
|
+
|
|
36
|
+
框架的行为开关集中在 `framework/settings.py`,包括 Allure 输出路径、用例级别定义、
|
|
37
|
+
异步断言超时、MySQL 连接池参数等。环境相关的域名、账号、数据库连接信息则放在
|
|
38
|
+
使用方项目的 `config/` 目录下,按环境分文件(`context.{env}.yaml`、`database.{env}.yaml`)。
|
|
39
|
+
|
|
40
|
+
## 基类
|
|
41
|
+
|
|
42
|
+
- `framework.core.base_class.BaseTestCase` —— pytest 用例基类
|
|
43
|
+
- `framework.script.BaseScript` —— 非 pytest 场景(独立脚本)的基类,子类实现 `run()` 方法
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
见 LICENSE 文件。
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""
|
|
2
|
+
重试断言模块,提供超时重试机制。在指定超时时间内不断重试断言函数,直到断言成功或超时。
|
|
3
|
+
适用于异步场景中需要等待一段时间才能断言通过的测试。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import time
|
|
7
|
+
from typing import Any, Callable
|
|
8
|
+
|
|
9
|
+
from framework.utils.log_util import logger
|
|
10
|
+
from framework.settings import ASYNC_ASSERT_TRIES, ASYNC_ASSERT_TIMEOUT
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def eventually(
|
|
14
|
+
assert_func: Callable[..., Any],
|
|
15
|
+
*args: Any,
|
|
16
|
+
timeout: int | float = ASYNC_ASSERT_TIMEOUT,
|
|
17
|
+
interval: int | float = ASYNC_ASSERT_TRIES,
|
|
18
|
+
desc: str | None = None,
|
|
19
|
+
**kwargs: Any,
|
|
20
|
+
) -> Any:
|
|
21
|
+
"""
|
|
22
|
+
在指定超时时间内不断重试断言函数,直到断言成功或超时。
|
|
23
|
+
|
|
24
|
+
适用于异步场景,例如等待数据库记录更新、消息队列消费等,需要等待一段时间才能断言通过的场景。
|
|
25
|
+
|
|
26
|
+
@param assert_func: 断言函数
|
|
27
|
+
@param args: 断言函数的位置参数
|
|
28
|
+
@param timeout: 整体超时时间(秒),默认从全局配置读取
|
|
29
|
+
@param interval: 每次重试的间隔时间(秒),默认从全局配置读取
|
|
30
|
+
@param desc: 超时后的错误描述,默认为 "异步断言失败"
|
|
31
|
+
@param kwargs: 断言函数的关键字参数
|
|
32
|
+
@return: 断言函数的返回值
|
|
33
|
+
@raises AssertionError: 超时后仍未断言成功时抛出
|
|
34
|
+
"""
|
|
35
|
+
start = time.time()
|
|
36
|
+
last_exception = None # 记录最后一次异常信息
|
|
37
|
+
attempt = 0 # 重试次数计数
|
|
38
|
+
|
|
39
|
+
while True:
|
|
40
|
+
elapsed = time.time() - start
|
|
41
|
+
if elapsed >= timeout:
|
|
42
|
+
break # 超时,退出循环
|
|
43
|
+
|
|
44
|
+
attempt += 1
|
|
45
|
+
try:
|
|
46
|
+
return assert_func(*args, **kwargs)
|
|
47
|
+
except AssertionError as e:
|
|
48
|
+
last_exception = e
|
|
49
|
+
logger.warning(
|
|
50
|
+
f"第 {attempt} 次断言失败 "
|
|
51
|
+
f"(已等待 {elapsed:.1f}s / {timeout}s): {e}"
|
|
52
|
+
)
|
|
53
|
+
except Exception as e:
|
|
54
|
+
last_exception = e
|
|
55
|
+
logger.warning(
|
|
56
|
+
f"第 {attempt} 次执行异常 "
|
|
57
|
+
f"(已等待 {elapsed:.1f}s / {timeout}s): {e}"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
time.sleep(interval) # 等待间隔后继续重试
|
|
61
|
+
|
|
62
|
+
error_msg = desc or "异步断言失败"
|
|
63
|
+
raise AssertionError(
|
|
64
|
+
f"{error_msg}\n"
|
|
65
|
+
f"重试次数: {attempt}\n"
|
|
66
|
+
f"最后异常: {last_exception}"
|
|
67
|
+
)
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Webhook 断言模块,提供针对 webhook 回调数据的断言校验功能。
|
|
3
|
+
支持链式调用,可通过表达式路径获取嵌套属性值并进行各种断言。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from box import Box, BoxList
|
|
9
|
+
from framework.utils.log_util import logger
|
|
10
|
+
from framework.utils.common import is_digit
|
|
11
|
+
from framework.core.validate import Validate
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class WebhookAssert(object):
|
|
15
|
+
"""Webhook 断言类,封装了对 webhook 回调数据的断言校验。"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, webhook_info: dict | list | Box | BoxList | None = None) -> None:
|
|
18
|
+
"""
|
|
19
|
+
初始化 Webhook 断言对象。
|
|
20
|
+
@param webhook_info: webhook 回调数据(dict / list / 其他格式)
|
|
21
|
+
"""
|
|
22
|
+
if isinstance(webhook_info, dict):
|
|
23
|
+
self.webhook = Box(webhook_info)
|
|
24
|
+
elif isinstance(webhook_info, list):
|
|
25
|
+
self.webhook = BoxList(webhook_info)
|
|
26
|
+
else:
|
|
27
|
+
self.webhook = webhook_info
|
|
28
|
+
|
|
29
|
+
def assert_equal(self, expression: str, expected_result: Any, desc: str | None = None) -> "WebhookAssert":
|
|
30
|
+
"""
|
|
31
|
+
校验 webhook 中指定路径的数据等于预期结果。
|
|
32
|
+
自动对数字字符串做 int/float 转换,避免 "100" != 100 问题。
|
|
33
|
+
@param expression: 数据路径表达式,如 "a.b[0].c"
|
|
34
|
+
@param expected_result: 预期结果
|
|
35
|
+
@param desc: 断言失败时的错误描述
|
|
36
|
+
@return: self,支持链式调用
|
|
37
|
+
"""
|
|
38
|
+
if not isinstance(self.webhook, (Box, BoxList)):
|
|
39
|
+
logger.warning(f"不支持非标准格式的webhook校验")
|
|
40
|
+
return self
|
|
41
|
+
|
|
42
|
+
practical_result = self.to_number(self.get_nested_value(self.webhook, expression))
|
|
43
|
+
expected = self.to_number(expected_result)
|
|
44
|
+
|
|
45
|
+
logger.info(
|
|
46
|
+
f"WEBHOOK断言: assert_equal {expression} → "
|
|
47
|
+
f"实际结果({practical_result}) == 预期结果({expected})"
|
|
48
|
+
)
|
|
49
|
+
assert practical_result == expected, (
|
|
50
|
+
f"{desc}," if desc else "" +
|
|
51
|
+
f"实际结果({practical_result}) != 预期结果({expected})"
|
|
52
|
+
)
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
def assert_is_null(self, expression: str, desc: str | None = None) -> "WebhookAssert":
|
|
56
|
+
"""
|
|
57
|
+
校验 webhook 中指定路径的数据为空(None / 空字符串 / 空列表 / 空字典等)。
|
|
58
|
+
@param expression: 数据路径表达式,如 "a.b[0].c"
|
|
59
|
+
@param desc: 断言失败时的错误描述
|
|
60
|
+
@return: self,支持链式调用
|
|
61
|
+
"""
|
|
62
|
+
if not isinstance(self.webhook, (Box, BoxList)):
|
|
63
|
+
logger.warning(f"不支持非标准格式的webhook校验")
|
|
64
|
+
return self
|
|
65
|
+
|
|
66
|
+
practical_result = self.get_nested_value(self.webhook, expression)
|
|
67
|
+
|
|
68
|
+
logger.info(
|
|
69
|
+
f"WEBHOOK断言: assert_is_null {expression} → "
|
|
70
|
+
f"实际结果({practical_result})"
|
|
71
|
+
)
|
|
72
|
+
assert self.is_empty(practical_result), (
|
|
73
|
+
f"{desc}," if desc else "" +
|
|
74
|
+
f"实际结果({practical_result}) 不是空值"
|
|
75
|
+
)
|
|
76
|
+
return self
|
|
77
|
+
|
|
78
|
+
def assert_not_null(self, expression: str, desc: str | None = None) -> "WebhookAssert":
|
|
79
|
+
"""
|
|
80
|
+
校验 webhook 中指定路径的数据不为空。
|
|
81
|
+
@param expression: 数据路径表达式,如 "a.b[0].c"
|
|
82
|
+
@param desc: 断言失败时的错误描述
|
|
83
|
+
@return: self,支持链式调用
|
|
84
|
+
"""
|
|
85
|
+
if not isinstance(self.webhook, (Box, BoxList)):
|
|
86
|
+
logger.warning(f"不支持非标准格式的webhook校验")
|
|
87
|
+
return self
|
|
88
|
+
|
|
89
|
+
practical_result = self.get_nested_value(self.webhook, expression)
|
|
90
|
+
|
|
91
|
+
logger.info(
|
|
92
|
+
f"WEBHOOK断言: assert_not_null {expression} → "
|
|
93
|
+
f"实际结果({practical_result})"
|
|
94
|
+
)
|
|
95
|
+
assert not self.is_empty(practical_result), (
|
|
96
|
+
f"{desc}," if desc else "" +
|
|
97
|
+
f"实际结果({practical_result}) 是空值"
|
|
98
|
+
)
|
|
99
|
+
return self
|
|
100
|
+
|
|
101
|
+
@staticmethod
|
|
102
|
+
def get_nested_value(obj: Any, attr_path: str) -> Any:
|
|
103
|
+
"""
|
|
104
|
+
通过字符串路径获取嵌套属性值,路径支持属性和索引组合,如 "a.b[0].c"。
|
|
105
|
+
@param obj: 要访问的根对象
|
|
106
|
+
@param attr_path: 属性路径字符串,例如 "data.user.name" 或 "items[0].id"
|
|
107
|
+
@return: 路径对应的属性值,若路径不存在则返回 None
|
|
108
|
+
"""
|
|
109
|
+
return Validate.get_nested_value(obj, attr_path)
|
|
110
|
+
|
|
111
|
+
@staticmethod
|
|
112
|
+
def is_empty(value: Any) -> bool:
|
|
113
|
+
"""
|
|
114
|
+
判断值是否为空。
|
|
115
|
+
@param value: 输入值
|
|
116
|
+
@return: True 表示空(None / "" / [] / {} / () / set())
|
|
117
|
+
"""
|
|
118
|
+
return value in (None, "", [], {}, ())
|
|
119
|
+
|
|
120
|
+
@staticmethod
|
|
121
|
+
def to_number(value: Any) -> Any:
|
|
122
|
+
"""
|
|
123
|
+
将数字字符串转为 int 或 float。
|
|
124
|
+
@param value: 输入值
|
|
125
|
+
@return: 如果输入是数字字符串则返回 int/float,否则原样返回
|
|
126
|
+
"""
|
|
127
|
+
if not isinstance(value, str) or not is_digit(value):
|
|
128
|
+
return value
|
|
129
|
+
return float(value) if "." in value or "e" in value.lower() else int(value)
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""crrm 客户端模块。
|
|
2
|
+
|
|
3
|
+
只用原生 requests 发请求,不走框架的 HttpClient:那套是给被测应用用的,
|
|
4
|
+
会套上应用自己的会话和 bearer,还会把用例的 self.response 顶掉。
|
|
5
|
+
crrm 是另一个服务,自己发自己的请求。
|
|
6
|
+
|
|
7
|
+
由 BaseTestCase.crrm() 构造,一般不用直接 new。
|
|
8
|
+
"""
|
|
9
|
+
from typing import Any
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from functools import lru_cache
|
|
12
|
+
from urllib.parse import urljoin
|
|
13
|
+
|
|
14
|
+
import allure
|
|
15
|
+
import requests
|
|
16
|
+
from box import Box
|
|
17
|
+
|
|
18
|
+
import framework.settings as settings
|
|
19
|
+
from framework.utils.log_util import logger
|
|
20
|
+
from framework.utils.yaml_util import YamlUtil
|
|
21
|
+
from framework.settings import CONSOLE_DETAILED_LOG
|
|
22
|
+
from framework.client.http_client import HttpClient, ResponseUtil
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@lru_cache(maxsize=None)
|
|
26
|
+
def crrm_config(env: str) -> Box:
|
|
27
|
+
"""读 config/crrm/context.{env}.yaml。
|
|
28
|
+
|
|
29
|
+
crrm 跟被测应用无关、只跟环境有关,所以配置单独放一份,不塞进
|
|
30
|
+
config/settings.py 的 env→value 字典里——那样同一个环境的信息会被
|
|
31
|
+
拆成好几个字典,加环境要改好几处。
|
|
32
|
+
|
|
33
|
+
按 env 缓存,一个环境只读一次盘。
|
|
34
|
+
|
|
35
|
+
@param env: 框架的环境名(dev/uat)
|
|
36
|
+
@return: Box,含 env(crrm 侧的环境别名)、gateway 等
|
|
37
|
+
"""
|
|
38
|
+
path = f"config/crrm/context.{env}.yaml"
|
|
39
|
+
assert (Path(settings.ROOT_DIR) / path).is_file(), f"crrm 配置文件不存在: {path}"
|
|
40
|
+
return Box(YamlUtil(path).load_yml())
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class CrrmClient(object):
|
|
44
|
+
"""带着 crrm token 的轻客户端,提供 get/post/put/delete/patch。
|
|
45
|
+
|
|
46
|
+
url 留空打 base_url,传相对路径则和 base_url 拼接,传完整地址则直接用:
|
|
47
|
+
|
|
48
|
+
client.get() # 打配置里的 gateway
|
|
49
|
+
client.post("/v2.0/xxx", json={}) # 拼接
|
|
50
|
+
client.get("https://other/z") # 直接用
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, token: str, user_id: Any, env: str, timeout: int = 30) -> None:
|
|
54
|
+
"""
|
|
55
|
+
:param token: crrm 换回来的 token,之后每个请求都带上
|
|
56
|
+
:param user_id: 用户。先当账号名去配置的 accounts 里换真实 id,
|
|
57
|
+
换不到就原样用(可以直接传真实 id)
|
|
58
|
+
:param env: 框架的环境名,用来从 config/crrm/context.{env}.yaml 取服务根地址
|
|
59
|
+
:param timeout: 请求超时(秒)
|
|
60
|
+
"""
|
|
61
|
+
self.token = token
|
|
62
|
+
self.env = env
|
|
63
|
+
conf = crrm_config(env)
|
|
64
|
+
# 账号名换成真实 id:用例里写 "qa_01" 比写 6414 可读,而且这个 id 每个
|
|
65
|
+
# 环境还不一样。accounts 里没有就原样用——传进来的本来就可能是真实 id
|
|
66
|
+
self.user_id = (conf.get("accounts") or {}).get(user_id, user_id)
|
|
67
|
+
self.base_url = conf.gateway
|
|
68
|
+
self.timeout = timeout
|
|
69
|
+
self.response: ResponseUtil | None = None
|
|
70
|
+
|
|
71
|
+
# 每个请求都带的默认头。X-User-Id 必须转成字符串——requests 不收
|
|
72
|
+
# int 类型的头值,直接抛 InvalidHeader
|
|
73
|
+
self.headers = {
|
|
74
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
75
|
+
"(KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
|
|
76
|
+
"Content-Type": "application/json",
|
|
77
|
+
"X-User-Id": str(self.user_id),
|
|
78
|
+
"Authorization": f"Bearer {self.token}",
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
def request(self, method: str, url: str = "", **kwargs: Any) -> ResponseUtil:
|
|
82
|
+
"""发请求,响应包成 ResponseUtil 返回(可以用 .jsonpath() 取值)。
|
|
83
|
+
|
|
84
|
+
url 留空打 base_url,传相对路径则和 base_url 拼接,传完整地址则直接用。
|
|
85
|
+
调用方自己传的 headers 会覆盖同名的默认头。
|
|
86
|
+
"""
|
|
87
|
+
# self.headers 在前、调用方的在后,同名以调用方为准
|
|
88
|
+
headers = {**self.headers, **kwargs.pop("headers", {})}
|
|
89
|
+
kwargs.setdefault("timeout", self.timeout)
|
|
90
|
+
full_url = urljoin(self.base_url, url)
|
|
91
|
+
|
|
92
|
+
# 请求/响应日志照 HttpClient.__send_request 的格式走,
|
|
93
|
+
# 这样 crrm 的请求在控制台和 allure 报告里和被测应用的长一个样
|
|
94
|
+
with allure.step("发送请求(crrm)"):
|
|
95
|
+
raw = requests.request(method, full_url, headers=headers, **kwargs)
|
|
96
|
+
|
|
97
|
+
with allure.step(f"请求url: {full_url}"):
|
|
98
|
+
logger.info(f"⮕ url: {full_url}")
|
|
99
|
+
|
|
100
|
+
with allure.step(f"请求method: {method}"):
|
|
101
|
+
logger.info(f"⮕ method: {method}")
|
|
102
|
+
|
|
103
|
+
with allure.step(f"请求headers: {HttpClient.json(headers)}"):
|
|
104
|
+
if CONSOLE_DETAILED_LOG:
|
|
105
|
+
logger.info(f"⮕ headers: {HttpClient.json(headers)}")
|
|
106
|
+
|
|
107
|
+
params = kwargs.get("params")
|
|
108
|
+
if params:
|
|
109
|
+
with allure.step(f"请求参数params: {HttpClient.json(params)}"):
|
|
110
|
+
logger.info(f"⮕ params: {HttpClient.json(params)}")
|
|
111
|
+
|
|
112
|
+
req_data = kwargs.get("data")
|
|
113
|
+
if req_data:
|
|
114
|
+
with allure.step(f"请求参数data: {req_data}"):
|
|
115
|
+
logger.info(f"⮕ data: {req_data}")
|
|
116
|
+
|
|
117
|
+
req_json = kwargs.get("json")
|
|
118
|
+
if req_json:
|
|
119
|
+
with allure.step(f"请求参数json: {HttpClient.json(req_json)}"):
|
|
120
|
+
logger.info(f"⮕ json: {HttpClient.json(req_json)}")
|
|
121
|
+
|
|
122
|
+
# 这一段统一用包装前的 raw:ResponseUtil.__getattr__ 会先去响应体 Box 里找,
|
|
123
|
+
# 响应 JSON 里要是有 url / headers 这类同名字段,取到的就是字段值而不是响应本身
|
|
124
|
+
with allure.step("响应结果(crrm)"):
|
|
125
|
+
with allure.step(f"响应http code: {raw.status_code}"):
|
|
126
|
+
logger.info(f"⬅ http code: {raw.status_code}")
|
|
127
|
+
|
|
128
|
+
with allure.step(f"响应headers: {HttpClient.json(dict(raw.headers))}"):
|
|
129
|
+
if CONSOLE_DETAILED_LOG:
|
|
130
|
+
logger.info(f"⬅ headers: {HttpClient.json(dict(raw.headers))}")
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
with allure.step(f"响应body: {HttpClient.json(raw.json())}"):
|
|
134
|
+
logger.info(f"⬅ body: {HttpClient.json(raw.json())}")
|
|
135
|
+
except Exception:
|
|
136
|
+
with allure.step(f"响应body: {raw.text}"):
|
|
137
|
+
logger.info(f"⬅ body: {raw.text}")
|
|
138
|
+
|
|
139
|
+
self.response = ResponseUtil(raw)
|
|
140
|
+
return self.response
|
|
141
|
+
|
|
142
|
+
def get(self, url: str = "", **kwargs: Any) -> ResponseUtil:
|
|
143
|
+
return self.request("get", url, **kwargs)
|
|
144
|
+
|
|
145
|
+
def post(self, url: str = "", **kwargs: Any) -> ResponseUtil:
|
|
146
|
+
return self.request("post", url, **kwargs)
|
|
147
|
+
|
|
148
|
+
def put(self, url: str = "", **kwargs: Any) -> ResponseUtil:
|
|
149
|
+
return self.request("put", url, **kwargs)
|
|
150
|
+
|
|
151
|
+
def delete(self, url: str = "", **kwargs: Any) -> ResponseUtil:
|
|
152
|
+
return self.request("delete", url, **kwargs)
|
|
153
|
+
|
|
154
|
+
def patch(self, url: str = "", **kwargs: Any) -> ResponseUtil:
|
|
155
|
+
return self.request("patch", url, **kwargs)
|