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,167 @@
1
+ """
2
+ 飞书(Lark)消息通知工具模块
3
+
4
+ 提供通过飞书 Webhook 发送消息通知的功能,包括:
5
+ - 文本消息发送
6
+ - Markdown 卡片消息发送
7
+ - 自动化测试结果报告
8
+ - 测试结果图表数据发送
9
+ """
10
+
11
+ import base64
12
+ import hmac
13
+ import hashlib
14
+ import time
15
+ from datetime import datetime
16
+
17
+ import json
18
+ import requests
19
+
20
+
21
+ class LarkUtil:
22
+ """飞书机器人消息通知工具类"""
23
+
24
+ def __init__(self, webhook: dict):
25
+ """
26
+ 初始化飞书机器人
27
+
28
+ @param webhook: Webhook 配置字典,包含以下键:
29
+ - url: Webhook 地址
30
+ - secret: 签名密钥(可选)
31
+ - open_ids: 需要 @ 的用户 open_id 列表(可选)
32
+ """
33
+ self.webhook = webhook
34
+ self.url = self.webhook.get("url")
35
+ self.secret = self.webhook.get("secret")
36
+ self.at_ids = self.webhook.get("open_ids") or None
37
+ self.headers = {"Content-Type": "application/json"}
38
+
39
+ @staticmethod
40
+ def gen_sign(timestamp: int, secret: str) -> str:
41
+ """
42
+ 生成 HMAC-SHA256 签名(用于飞书 Webhook 安全验证)
43
+
44
+ @param timestamp: 当前时间戳(秒级)
45
+ @param secret: 签名密钥
46
+ @return: Base64 编码的签名字符串
47
+ """
48
+ # 拼接 timestamp 和 secret
49
+ string_to_sign = '{}\n{}'.format(timestamp, secret)
50
+ hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
51
+ # 对结果进行 Base64 处理
52
+ sign = base64.b64encode(hmac_code).decode('utf-8')
53
+ return sign
54
+
55
+ def send_text(self, text: str, at_ids: list[str] | None = None) -> None:
56
+ """
57
+ 发送飞书文本消息
58
+
59
+ @param text: 消息文本内容
60
+ @param at_ids: 需要 @ 的用户 open_id 列表(可选)
61
+ @return: requests.Response 对象
62
+ """
63
+ data = {
64
+ "msg_type": "text",
65
+ "content": {"text": text},
66
+ }
67
+ if at_ids:
68
+ data["at"] = {"open_ids": at_ids}
69
+ if self.secret:
70
+ # 有 secret 时需生成签名并带上时间戳
71
+ timestamp = str(int(time.time()))
72
+ data["sign"] = LarkUtil.gen_sign(timestamp, self.secret)
73
+ data["timestamp"] = timestamp
74
+
75
+ return requests.post(self.url, data=json.dumps(data), headers=self.headers)
76
+
77
+ def send_markdown(self, title: str, markdown_text: str, at_ids: list[str] = None):
78
+ """
79
+ 发送飞书 Markdown 卡片消息
80
+
81
+ @param title: 卡片标题
82
+ @param markdown_text: Markdown 格式的消息内容
83
+ @param at_ids: 需要 @ 的用户 open_id 列表(可选)
84
+ @return: requests.Response 对象
85
+ """
86
+
87
+ data = {
88
+ "msg_type": "interactive",
89
+ "card": {
90
+ "header": {
91
+ "template": "blue",
92
+ "title": {"tag": "plain_text", "content": title}
93
+ },
94
+ "elements": [
95
+ {
96
+ "tag": "markdown",
97
+ "content": markdown_text
98
+ }
99
+ ]
100
+ }
101
+ }
102
+ if at_ids:
103
+ data["at"] = {"open_ids": at_ids}
104
+ if self.secret:
105
+ # 有 secret 时需生成签名并带上时间戳
106
+ timestamp = str(int(time.time()))
107
+ data["sign"] = LarkUtil.gen_sign(timestamp, self.secret)
108
+ data["timestamp"] = timestamp
109
+ return requests.post(self.url, headers=self.headers, data=json.dumps(data))
110
+
111
+ def send_test_report(self, total: int, passed: int, failed: int, skipped: int, env: str, job_name: str,
112
+ command: str, report_url: str = None):
113
+ """
114
+ 发送自动化测试结果报告(Markdown 卡片消息)
115
+
116
+ @param total: 用例总数
117
+ @param passed: 通过用例数
118
+ @param failed: 失败用例数
119
+ @param skipped: 跳过用例数
120
+ @param env: 执行环境
121
+ @param job_name: 任务名称(用于标题)
122
+ @param command: 执行命令/标签
123
+ @param report_url: 测试报告链接(可选)
124
+ @return: requests.Response 对象
125
+ """
126
+ try:
127
+ # 计算通过率 = 通过数 / (总数 - 跳过数) * 100
128
+ pass_rate = round(passed / (total - skipped) * 100, 2)
129
+ except ZeroDivisionError:
130
+ # 避免除零错误
131
+ pass_rate = 0
132
+ markdown = f"""**执行环境:** {env}
133
+ **执行标签:** {command}
134
+ **执行完成时间:** {datetime.now().strftime("%Y-%m-%d %X")}
135
+ **执行用例总数:** {total}
136
+ **通过用例数:** {passed}
137
+ **失败用例数:** {failed}
138
+ **跳过用例数:** {skipped}
139
+ **用例通过率:** {pass_rate}%
140
+ """
141
+ if report_url:
142
+ markdown += f"\n**测试报告:** [点击查看测试报告]({report_url})"
143
+ title = f"【自动化测试结果】-{job_name} " if job_name else "【自动化测试结果】"
144
+ return self.send_markdown(title, markdown)
145
+
146
+ def send_test_chart(self, total: int, passed: int, failed: int, skipped: int, job_name: str, env: str):
147
+ """
148
+ 发送测试结果图表数据(JSON 格式 POST 请求)
149
+
150
+ @param total: 用例总数
151
+ @param passed: 通过用例数
152
+ @param failed: 失败用例数
153
+ @param skipped: 跳过用例数
154
+ @param job_name: 任务名称
155
+ @param env: 执行环境
156
+ @return: requests.Response 对象
157
+ """
158
+
159
+ return requests.post(self.url, headers=self.headers,
160
+ json={
161
+ "job": job_name,
162
+ "total": total,
163
+ "passed": passed,
164
+ "failed": failed,
165
+ "skiped": skipped,
166
+ "env": env
167
+ })
@@ -0,0 +1,10 @@
1
+ """
2
+ 日志工具模块
3
+
4
+ 提供项目日志记录器实例,供其他模块导入使用。
5
+ """
6
+
7
+ import logging
8
+
9
+ logger = logging.getLogger(__name__)
10
+ """项目日志记录器实例,基于当前模块名获取 logger"""
@@ -0,0 +1,236 @@
1
+ """
2
+ Mock 模拟接口工具模块
3
+
4
+ 提供调用模拟服务接口的功能,包括:
5
+ - KYT 风控模拟(设置/获取)
6
+ - MQ 消息模拟
7
+ - 环境配置管理
8
+ """
9
+
10
+ import requests
11
+ from enum import Enum, unique
12
+ from typing import Dict
13
+
14
+ from framework.settings import AVAILABLE_ENVS, ENV_CONFIG
15
+ from typing import Any
16
+ from framework.utils.log_util import logger
17
+
18
+ @unique
19
+ class PaymentType(Enum):
20
+ """支付类型枚举"""
21
+ DEPOSIT = 0 # 入金
22
+ WALLET_SCANNING = 1 # 出金
23
+ CHECKOUT = 2 # 结账
24
+
25
+
26
+ @unique
27
+ class RiskLevel(Enum):
28
+ """风险等级枚举"""
29
+ DISABLE_MOCK = 0 # 禁用模拟
30
+ LOW = 1 # 低风险
31
+ MEDIUM_LOW = 2 # 中低风险
32
+ MEDIUM_HIGH = 3 # 中高风险
33
+ HIGH = 4 # 高风险
34
+ SEVERE = 5 # 严重风险
35
+ PENDING_KYT = 6 # 待 KYT 审核
36
+
37
+
38
+ @unique
39
+ class IsDelayed(Enum):
40
+ """是否延迟枚举"""
41
+ NO_DELAY = 0 # 不延迟
42
+ DELAY = 1 # 延迟
43
+
44
+
45
+ def get_environment_config(env: str) -> Dict:
46
+ """
47
+ 获取指定环境的完整配置
48
+
49
+ @param env: 环境名称(如 "dev", "test" 等)
50
+ @return: 对应环境的配置字典
51
+ @raises ValueError: 当环境名称不存在时抛出
52
+ """
53
+ if env not in AVAILABLE_ENVS:
54
+ raise ValueError(f"不支持的环境: {env},可用环境: {AVAILABLE_ENVS}")
55
+ return ENV_CONFIG[env]
56
+
57
+
58
+ def get_full_api_url(env: str, method: str) -> str:
59
+ """
60
+ 拼接完整的 API URL
61
+
62
+ @param env: 环境名称
63
+ @param method: 接口配置键名
64
+ @return: 完整的 URL 字符串
65
+ """
66
+ config = get_environment_config(env)
67
+ return f"{config['base_url']}{config[method]}"
68
+
69
+
70
+ def set_customized_kytmock(env: str, request_id: str, payment_type: PaymentType,
71
+ risk_level: RiskLevel, is_delayed: IsDelayed = IsDelayed.NO_DELAY):
72
+ """
73
+ 设置自定义 KYT 模拟(调用模拟服务接口)
74
+
75
+ @param env: 环境名称(如 "dev", "test")
76
+ @param request_id: 请求 ID
77
+ @param payment_type: 支付类型枚举
78
+ @param risk_level: 风险等级枚举
79
+ @param is_delayed: 是否延迟枚举,默认不延迟
80
+ @return: 接口响应的 JSON 字典,失败则返回 None
81
+ @raises ValueError: 参数校验失败时抛出
82
+ """
83
+ # 获取环境配置
84
+ env_config = get_environment_config(env)
85
+ method = "set_mock"
86
+ url = get_full_api_url(env, method)
87
+
88
+ # 参数验证
89
+ if not isinstance(request_id, str) or not request_id:
90
+ raise ValueError("request_id必须是非空字符串")
91
+
92
+ # 检查各枚举参数类型是否正确
93
+ for param, name in [
94
+ (payment_type, "payment_type"),
95
+ (risk_level, "risk_level"),
96
+ (is_delayed, "is_delayed")
97
+ ]:
98
+ if not isinstance(param, (PaymentType, RiskLevel, IsDelayed)):
99
+ raise ValueError(f"{name}必须是对应的枚举类型")
100
+
101
+ # 构建请求参数,取枚举对应的 value
102
+ payload = {
103
+ "request_id": request_id,
104
+ "payment_type": payment_type.value,
105
+ "risk_level": risk_level.value,
106
+ "is_delayed": is_delayed.value
107
+ }
108
+
109
+ try:
110
+ # 使用环境配置中的超时时间发送 POST 请求
111
+ response = requests.post(
112
+ url,
113
+ json=payload,
114
+ timeout=env_config["timeout"]
115
+ )
116
+ response.raise_for_status() # 非 2xx 状态码抛出异常
117
+
118
+ return response.json()
119
+ except requests.exceptions.HTTPError as e:
120
+ logger.error(f"HTTP错误 [{env}]: {e}")
121
+ except requests.exceptions.RequestException as e:
122
+ logger.error(f"请求异常 [{env}]: {e}")
123
+ except ValueError:
124
+ logger.error(f"响应解析失败 [{env}]")
125
+
126
+ return None
127
+
128
+
129
+ def get_customized_kytmock(env: str, request_id: str) -> dict[str, Any] | None:
130
+ """
131
+ 查询自定义 KYT 模拟结果
132
+
133
+ @param env: 环境名称
134
+ @param request_id: 请求 ID
135
+ @return: 查询结果的 JSON 字典,失败则返回 None
136
+ @raises ValueError: 参数校验失败时抛出
137
+ """
138
+ # 获取环境配置
139
+ env_config = get_environment_config(env)
140
+
141
+ # 参数验证
142
+ if not isinstance(request_id, str) or not request_id:
143
+ raise ValueError("request_id必须是非空字符串")
144
+ method = f"get_mock"
145
+ url = f"{get_full_api_url(env, method)}{request_id}" # 拼接完整查询 URL
146
+ try:
147
+ response = requests.get(url)
148
+ return response.json()
149
+ except requests.exceptions.HTTPError as e:
150
+ logger.error(f"HTTP错误 [{env}]: {e}")
151
+ except requests.exceptions.RequestException as e:
152
+ logger.error(f"请求异常 [{env}]: {e}")
153
+ except ValueError:
154
+ logger.error(f"响应解析失败 [{env}]")
155
+
156
+ return None
157
+
158
+
159
+ def mock_mq(env: str, target_exchange: str, exchange_type: str, message: str, routing_key: str) -> None:
160
+ """
161
+ 模拟 MQ 消息发送
162
+
163
+ @param env: 环境名称
164
+ @param target_exchange: 目标交换机名称
165
+ @param exchange_type: 交换机类型(如 fanout, direct, topic)
166
+ @param message: 消息内容(JSON 字符串)
167
+ @param routing_key: 路由键
168
+ @return: 接口响应的 JSON 字典,失败则返回 None
169
+ @raises ValueError: 参数校验失败时抛出
170
+ """
171
+ # 获取环境配置
172
+ env_config = get_environment_config(env)
173
+ method = "mock_mq"
174
+ url = get_full_api_url(env, method)
175
+ # 参数验证
176
+ if not isinstance(target_exchange, str) or not target_exchange:
177
+ raise ValueError("target_exchange必须是非空字符串")
178
+ if not isinstance(exchange_type, str) or not exchange_type:
179
+ raise ValueError("exchange_type 必须是非空字符串")
180
+ if not isinstance(message, str) or not message:
181
+ raise ValueError("message 必须是非空字符串")
182
+ # 构建请求参数
183
+ payload = {
184
+ "targetExchange": target_exchange,
185
+ "targetExchangeType": exchange_type,
186
+ "message": message,
187
+ "targetRoutingKey": routing_key
188
+ }
189
+
190
+ try:
191
+ # 使用环境配置中的超时时间发送 POST 请求
192
+ response = requests.post(
193
+ url,
194
+ json=payload,
195
+ timeout=env_config["timeout"]
196
+ )
197
+ response.raise_for_status() # 非 2xx 状态码抛出异常
198
+
199
+ return response.json()
200
+ except requests.exceptions.HTTPError as e:
201
+ logger.error(f"HTTP错误 [{env}]: {e}")
202
+ except requests.exceptions.RequestException as e:
203
+ logger.error(f"请求异常 [{env}]: {e}")
204
+ except ValueError:
205
+ logger.error(f"响应解析失败 [{env}]")
206
+
207
+ return None
208
+
209
+
210
+ if __name__ == "__main__":
211
+ # # 1. 调用测试环境的入金接口
212
+ # test_deposit = set_customized_kytmock(
213
+ # env="dev",
214
+ # request_id="A0101585",
215
+ # payment_type=PaymentType.DEPOSIT,
216
+ # risk_level=RiskLevel.LOW
217
+ # )
218
+ # logger.error(f"测试环境入金响应: {test_deposit}")
219
+ #
220
+ # # 2. 调用测试环境的出金接口
221
+ # dev_withdrawal = set_customized_kytmock(
222
+ # env="dev",
223
+ # request_id="0xf3C3e95597544cD0525393CE49B685994b8e50A7",
224
+ # payment_type=PaymentType.WITHDRAWAL,
225
+ # risk_level=RiskLevel.LOW
226
+ # )
227
+ # logger.error(f"开发环境出金响应: {dev_withdrawal}")
228
+
229
+ # get_content = get_customized_kytmock("dev","A0101585")
230
+ # logger.error(f"查询结果:{get_content}")
231
+ exchange_name = "camp.gateway.backbone.mock.ex.order-status"
232
+ exchange_type = "fanout"
233
+ message = "{ \"avgFillPrice\": 440.23, \"filled\": 11.0000000000000000, \"orderId\": 409, \"remaining\": 0.0000000000000000, \"status\": \"Filled\" }"
234
+ result = mock_mq("dev", exchange_name, exchange_type, message)
235
+ logger.error(result)
236
+
@@ -0,0 +1,169 @@
1
+ """
2
+ YAML 配置文件工具模块
3
+
4
+ 提供 YAML 文件的加载和缓存功能,包括:
5
+ - 自定义 YAML 加载器(保留原始字符串格式,避免日期和特殊数字被自动转换)
6
+ - 基本的 YAML 文件加载(YamlUtil)
7
+ - 带缓存机制的 YAML 文件加载(CachedYamlLoader),文件未改动时使用 JSON 缓存加速
8
+ """
9
+
10
+ import os
11
+ import json
12
+ import datetime
13
+ import hashlib
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ import yaml
18
+ from box import Box
19
+
20
+ from framework.settings import ROOT_DIR, YML_CACHE_DIR
21
+
22
+
23
+ class _DateAwareEncoder(json.JSONEncoder):
24
+ """
25
+ 自定义 JSON 编码器:自动将 date/datetime 类型转为 ISO 格式字符串
26
+ """
27
+ def default(self, o: Any) -> Any:
28
+ if isinstance(o, (datetime.date, datetime.datetime)):
29
+ return o.isoformat()
30
+ return super().default(o)
31
+
32
+
33
+ class _SafeStringLoader(yaml.SafeLoader):
34
+ """
35
+ 安全 YAML 加载器:不自动识别日期和 0x/0o/0b 格式数字,保持原始字符串格式
36
+
37
+ 通过移除默认的隐式类型解析器来实现字符串原样保留
38
+ """
39
+ pass
40
+
41
+
42
+ # 移除 timestamp 解析器,避免 '2019-10-04' 这类值被自动转成 date 对象
43
+ # yaml_implicit_resolvers keyed by first character, not tag — filter digit entries
44
+ for _ch in '0123456789':
45
+ _resolvers = _SafeStringLoader.yaml_implicit_resolvers.get(_ch, [])
46
+ _SafeStringLoader.yaml_implicit_resolvers[_ch] = [
47
+ (tag, regex) for tag, regex in _resolvers
48
+ if 'timestamp' not in tag
49
+ ]
50
+
51
+ # 移除 int 类型中的 hex/octal/binary 隐式解析器,避免 '0x...' 等被转成数字类型
52
+ _int_resolvers = _SafeStringLoader.yaml_implicit_resolvers.get('tag:yaml.org,2002:int', [])
53
+ _SafeStringLoader.yaml_implicit_resolvers['tag:yaml.org,2002:int'] = [
54
+ (regex, priority) for regex, priority in _int_resolvers
55
+ if not any(prefix in regex for prefix in ('0x', '0X', '0o', '0O', '0b', '0B'))
56
+ ]
57
+
58
+
59
+ class YamlUtil(object):
60
+ """YAML 文件加载工具类"""
61
+
62
+ def __init__(self, file_path):
63
+ """
64
+ @param file_path: YAML 文件路径(相对于 ROOT_DIR)
65
+ """
66
+ self.file_path = file_path
67
+
68
+ def load_yml(self, key: str | None = None, is_box: bool = False) -> Any:
69
+ """
70
+ 加载 YAML 文件内容
71
+
72
+ @param key: 若指定,仅获取 YAML 中该 key 对应的值
73
+ @param is_box: 若为 True,将结果转为 Box 对象(支持属性访问)
74
+ @return: 解析后的字典 / Box 对象 / 指定 key 的值
75
+ """
76
+ with open(os.path.join(ROOT_DIR, self.file_path), mode="r", encoding="utf-8") as f:
77
+ result = yaml.load(stream=f, Loader=_SafeStringLoader) or dict()
78
+ if key:
79
+ result = result.get(key)
80
+ if is_box:
81
+ result = Box(result) if isinstance(result, dict) else result
82
+ return result
83
+
84
+
85
+ class CachedYamlLoader(object):
86
+ """
87
+ YAML 加载器(带缓存机制)
88
+
89
+ - 文件未改动时直接读取 JSON 缓存,提升加载速度
90
+ - 文件修改时间或大小变化后自动重新解析 YAML 并更新缓存
91
+ - 缓存文件以文件路径哈希 + 内容特征哈希命名
92
+ """
93
+
94
+ def __init__(self, file_path):
95
+ """
96
+ @param file_path: YAML 文件路径(相对于 ROOT_DIR)
97
+ """
98
+ self.file_path = os.path.join(ROOT_DIR, file_path)
99
+ self.cache_dir = YML_CACHE_DIR
100
+ os.makedirs(self.cache_dir, exist_ok=True)
101
+
102
+ def _get_cache_file(self) -> Path:
103
+ """
104
+ 根据文件修改时间 + 文件大小生成唯一的缓存文件名
105
+
106
+ 使用两次 MD5 哈希:文件路径哈希 + (文件路径+修改时间+文件大小)哈希
107
+ @return: 缓存文件的绝对路径
108
+ """
109
+ stat = os.stat(self.file_path)
110
+ key = f"{self.file_path}-{stat.st_mtime}-{stat.st_size}"
111
+ hash_key = hashlib.md5(key.encode()).hexdigest() # 内容特征哈希
112
+ hash_path = hashlib.md5(self.file_path.encode()).hexdigest() # 路径哈希
113
+ return os.path.join(self.cache_dir, f"{hash_path}_{hash_key}.json")
114
+
115
+ def load_yml(self, key: str | None = None, is_box: bool = False) -> Any:
116
+ """
117
+ 加载 YAML 文件(优先使用缓存)
118
+
119
+ @param key: 若指定,仅获取 YAML 中该 key 对应的值
120
+ @param is_box: 若为 True,将结果转为 Box 对象
121
+ @return: dict / Box / 指定 key 的值
122
+ """
123
+ cache_file = self._get_cache_file()
124
+
125
+ if os.path.exists(cache_file):
126
+ # 缓存存在,直接读取
127
+ try:
128
+ with open(cache_file, "r", encoding="utf-8") as f:
129
+ result = json.load(f)
130
+ except Exception:
131
+ # 缓存文件损坏,重新解析
132
+ result = self._parse_and_cache(cache_file)
133
+ else:
134
+ # 缓存不存在,解析 YAML 并创建缓存
135
+ result = self._parse_and_cache(cache_file)
136
+
137
+ if key:
138
+ result = result.get(key)
139
+
140
+ if is_box:
141
+ result = Box(result) if isinstance(result, dict) else result
142
+
143
+ return result
144
+
145
+ def _parse_and_cache(self, cache_file: Path) -> dict[str, Any]:
146
+ """
147
+ 解析 YAML 文件并将结果写入 JSON 缓存,同时删除该文件对应的旧缓存
148
+
149
+ @param cache_file: 新缓存文件路径
150
+ @return: 解析后的字典
151
+ """
152
+ # 删除该文件对应的旧缓存文件(基于文件路径哈希前缀匹配)
153
+ file_hash = hashlib.md5(self.file_path.encode()).hexdigest()
154
+ for f in os.listdir(self.cache_dir):
155
+ f_path = os.path.join(self.cache_dir, f)
156
+ if os.path.isfile(f_path) and f.startswith(file_hash):
157
+ try:
158
+ os.remove(f_path)
159
+ except Exception as e:
160
+ print(f"删除旧缓存失败: {e}")
161
+
162
+ # 使用 _SafeStringLoader 解析 YAML 文件
163
+ with open(self.file_path, mode="r", encoding="utf-8") as f:
164
+ result = yaml.load(f, Loader=_SafeStringLoader) or {}
165
+
166
+ # 将解析结果写入 JSON 缓存文件
167
+ with open(cache_file, "w", encoding="utf-8") as cf:
168
+ json.dump(result, cf, ensure_ascii=False, cls=_DateAwareEncoder)
169
+ return result