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,871 @@
|
|
|
1
|
+
"""
|
|
2
|
+
测试用例基类模块。
|
|
3
|
+
|
|
4
|
+
提供 BaseTestCase 基类,封装了 HTTP/WebSocket 请求、MQ 操作、数据库连接、
|
|
5
|
+
变量提取与断言、webhook 获取、热钱包重置等通用测试能力。
|
|
6
|
+
所有测试用例类均继承自本基类。
|
|
7
|
+
"""
|
|
8
|
+
import ast
|
|
9
|
+
import copy
|
|
10
|
+
import uuid
|
|
11
|
+
import time
|
|
12
|
+
import json
|
|
13
|
+
import inspect
|
|
14
|
+
import textwrap
|
|
15
|
+
import traceback
|
|
16
|
+
import warnings
|
|
17
|
+
import requests
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Callable, Union
|
|
20
|
+
from urllib.parse import urljoin, urlparse, urlunparse
|
|
21
|
+
|
|
22
|
+
import allure
|
|
23
|
+
import pytest
|
|
24
|
+
from box import Box
|
|
25
|
+
from faker import Faker
|
|
26
|
+
|
|
27
|
+
import framework.settings as settings
|
|
28
|
+
from framework.db.mysql_db import MysqlDB
|
|
29
|
+
from framework.db.redis_db import RedisDB
|
|
30
|
+
from framework.core.extract import Extract
|
|
31
|
+
from framework.utils.log_util import logger
|
|
32
|
+
from framework.core.validate import Validate
|
|
33
|
+
from framework.utils.date_util import DateUtil
|
|
34
|
+
from framework.utils.encrypt import b64_encode
|
|
35
|
+
from framework.core.render_data import RenderData
|
|
36
|
+
from framework.utils.common import SingletonFaker, snake_to_pascal
|
|
37
|
+
from framework.utils.yaml_util import CachedYamlLoader
|
|
38
|
+
from framework.assertion.retry_assert import eventually
|
|
39
|
+
from framework.core.hooks.session import get_login_instance, set_token_expire_time
|
|
40
|
+
from framework.assertion.webhook_assert import WebhookAssert
|
|
41
|
+
from framework.core.hooks.filters import find_data_path_by_case, deep_merge
|
|
42
|
+
from framework.settings import FAKER_LANGUAGE, UNAUTHORIZED_CODE
|
|
43
|
+
from framework.core.models import CaseData, RequestData, Scenario
|
|
44
|
+
from framework.client.crrm_client import CrrmClient, crrm_config
|
|
45
|
+
from framework.client.http_client import HttpClient, ResponseUtil
|
|
46
|
+
from framework.settings import GET_WEBHOOK_TIMEOUT, GET_WEBHOOK_TRIES
|
|
47
|
+
from framework.client.websocket_client import RequestMode, WebsocketClient
|
|
48
|
+
from framework.core.global_attribute import CONTEXT, CONFIG, GlobalAttribute, FRAMEWORK_CONTEXT
|
|
49
|
+
from framework.utils.mock_util import get_customized_kytmock, set_customized_kytmock, mock_mq, PaymentType, RiskLevel, \
|
|
50
|
+
IsDelayed
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class BaseTestCase(object):
|
|
54
|
+
"""
|
|
55
|
+
测试用例基类,所有接口测试用例均继承此类。
|
|
56
|
+
|
|
57
|
+
提供统一的请求入口(request / websocket)、数据渲染、变量提取与断言、
|
|
58
|
+
MQ 消息收发、数据库连接、webhook 获取、热钱包重置等能力。
|
|
59
|
+
各子类可直接使用 self.http()、self.get()、self.post() 等方法发起请求。
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
# data完整数据
|
|
63
|
+
data: Union[CaseData, dict] = None
|
|
64
|
+
# 当前case所属app
|
|
65
|
+
app = None
|
|
66
|
+
# 重试断言
|
|
67
|
+
retry_assert = eventually
|
|
68
|
+
# 当前场景数据
|
|
69
|
+
scenario: Scenario | Box = None
|
|
70
|
+
# http响应
|
|
71
|
+
response: ResponseUtil = None
|
|
72
|
+
# socket消息
|
|
73
|
+
message: ResponseUtil = None
|
|
74
|
+
# faker方法文档 https://testerhome.com/topics/38053
|
|
75
|
+
faker: Faker = SingletonFaker(locale=FAKER_LANGUAGE).faker
|
|
76
|
+
# 日志对象
|
|
77
|
+
logger: logger = logger
|
|
78
|
+
# 数据库枚举
|
|
79
|
+
db = None
|
|
80
|
+
# 日期工具
|
|
81
|
+
date_util: DateUtil = DateUtil
|
|
82
|
+
payment_type: PaymentType = PaymentType
|
|
83
|
+
risk_level: RiskLevel = RiskLevel
|
|
84
|
+
is_delayed: IsDelayed = IsDelayed
|
|
85
|
+
|
|
86
|
+
def request(self, app=None, account=None, data=None, **kwargs) -> ResponseUtil | None:
|
|
87
|
+
"""
|
|
88
|
+
发起 HTTP 请求的统一入口。
|
|
89
|
+
|
|
90
|
+
:param app: 应用名称,不传则使用当前 case 所属 app
|
|
91
|
+
:param account: 账号名,用于获取对应鉴权 token
|
|
92
|
+
:param data: 请求数据,不传则使用 self.data
|
|
93
|
+
:param kwargs: 额外参数透传给 HttpClient.request()
|
|
94
|
+
:return: ResponseUtil 对象,请求失败时 pytest.fail
|
|
95
|
+
"""
|
|
96
|
+
try:
|
|
97
|
+
app = self.default_app(app)
|
|
98
|
+
data = RenderData(data or self.data).render()
|
|
99
|
+
domain = self.global_context.get(app).get("domain")
|
|
100
|
+
data.request.url = self.replace_domain(data.request.url, domain)
|
|
101
|
+
if account:
|
|
102
|
+
# run_case 传的 account 优先级最高
|
|
103
|
+
final_account = getattr(self, '_account_override', None) or account
|
|
104
|
+
app_http_session = getattr(self.http_session, app)
|
|
105
|
+
client = getattr(app_http_session, final_account, HttpClient())
|
|
106
|
+
else:
|
|
107
|
+
client = HttpClient()
|
|
108
|
+
self.response = client.request(data=data, **kwargs)
|
|
109
|
+
# 如果响应状态码为未授权(token 过期),则重新登录并更新 token 过期时间
|
|
110
|
+
if self.response.status_code in UNAUTHORIZED_CODE:
|
|
111
|
+
http_session = FRAMEWORK_CONTEXT.get(key="http_session")
|
|
112
|
+
setattr(http_session, app, get_login_instance(app))
|
|
113
|
+
# 同上,先按配置估一个,下次请求真正登录时用响应里的 expires_in 覆盖
|
|
114
|
+
set_token_expire_time(app)
|
|
115
|
+
return self.response
|
|
116
|
+
|
|
117
|
+
except Exception as e:
|
|
118
|
+
logger.error(e)
|
|
119
|
+
traceback.print_exc()
|
|
120
|
+
pytest.fail(str(e))
|
|
121
|
+
|
|
122
|
+
def websocket(self, account=None, data=None, msg_mode=RequestMode.MATCHER, request_key=None, timeout=None,
|
|
123
|
+
matcher=None, auto_close=False, **kwargs) -> ResponseUtil:
|
|
124
|
+
"""
|
|
125
|
+
发起 WebSocket 请求。
|
|
126
|
+
|
|
127
|
+
:param account: 账号名,传入时通过 ws_session 连接池获取已鉴权连接
|
|
128
|
+
:param data: 请求数据
|
|
129
|
+
:param msg_mode: 消息匹配模式,默认 RequestMode.MATCHER
|
|
130
|
+
:param request_key: 请求标识 key
|
|
131
|
+
:param timeout: 超时时间(秒)
|
|
132
|
+
:param matcher: 自定义匹配器
|
|
133
|
+
:param auto_close: 是否自动关闭连接,默认 False。连接池连接不会被关闭
|
|
134
|
+
:param kwargs: 额外 headers
|
|
135
|
+
:return: ResponseUtil 对象
|
|
136
|
+
"""
|
|
137
|
+
data = RenderData(data or self.data).render()
|
|
138
|
+
request = data.get("request")
|
|
139
|
+
|
|
140
|
+
self.ws, from_pool = self._get_ws_client(
|
|
141
|
+
account, url=request.url, headers=request.headers,
|
|
142
|
+
params=request.get("params"), timeout=timeout, auto_close=auto_close, **kwargs,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
if from_pool:
|
|
146
|
+
self.ws.send(request.message)
|
|
147
|
+
self.message = self.ws.wait_message(condition=matcher, timeout=timeout)
|
|
148
|
+
else:
|
|
149
|
+
self.message = self.ws.request(mode=msg_mode, message=request.message, request_key=request_key,
|
|
150
|
+
timeout=timeout, matcher=matcher)
|
|
151
|
+
if auto_close:
|
|
152
|
+
self.ws.close()
|
|
153
|
+
|
|
154
|
+
validates = data.get("validate")
|
|
155
|
+
if validates:
|
|
156
|
+
with allure.step("结果断言"):
|
|
157
|
+
Validate(data, self.message).valid(validates)
|
|
158
|
+
|
|
159
|
+
expressions = data.get("extract")
|
|
160
|
+
if expressions:
|
|
161
|
+
with allure.step("提取变量"):
|
|
162
|
+
Extract(self.message, self.app).extracts(expressions)
|
|
163
|
+
return self.message
|
|
164
|
+
|
|
165
|
+
def subscribe(self, account=None, data=None, timeout=None):
|
|
166
|
+
"""发送 WebSocket 订阅消息,返回生成器持续接收所有推送。
|
|
167
|
+
|
|
168
|
+
for msg in self.subscribe(account="xxx"):
|
|
169
|
+
print(msg.data)
|
|
170
|
+
if 满足条件:
|
|
171
|
+
break
|
|
172
|
+
|
|
173
|
+
:param account: 账号名
|
|
174
|
+
:param data: 请求数据
|
|
175
|
+
:param timeout: 单次接收超时(秒)
|
|
176
|
+
:yield: ResponseUtil 对象
|
|
177
|
+
"""
|
|
178
|
+
data = RenderData(data or self.data).render()
|
|
179
|
+
request = data.get("request")
|
|
180
|
+
|
|
181
|
+
self.ws, _ = self._get_ws_client(
|
|
182
|
+
account, url=request.url, headers=request.headers,
|
|
183
|
+
params=request.get("params"), timeout=timeout,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
self.ws.send(request.message)
|
|
187
|
+
yield from self.ws.listen(timeout=timeout)
|
|
188
|
+
|
|
189
|
+
def close_ws(self):
|
|
190
|
+
"""关闭当前 WebSocket 连接。"""
|
|
191
|
+
ws = getattr(self, "ws", None)
|
|
192
|
+
if ws:
|
|
193
|
+
ws.close()
|
|
194
|
+
self.ws = None
|
|
195
|
+
|
|
196
|
+
def load_case(self, case) -> Union[Box, CaseData]:
|
|
197
|
+
"""
|
|
198
|
+
加载并准备 case 数据,不发送请求。返回的 Box 可自由修改后再传给 run_case()。
|
|
199
|
+
|
|
200
|
+
支持两种传参方式:
|
|
201
|
+
- 方法引用: self.load_case(TestCreateCryptoCheckout.test_create_crypto_checkout)
|
|
202
|
+
- 字符串: self.load_case("test_create_crypto_checkout.test_participant_code_empty")
|
|
203
|
+
格式: '<模块名(不含.py)>.<case方法名>'
|
|
204
|
+
|
|
205
|
+
:param case: case 的方法引用或字符串路径
|
|
206
|
+
:return: Box,包含请求数据及 app、_account 等上下文
|
|
207
|
+
"""
|
|
208
|
+
self.case = case
|
|
209
|
+
case_file_name, case_name, case_app, case_account = self._resolve_case(case)
|
|
210
|
+
app = case_app or self.app
|
|
211
|
+
account = case_account or ""
|
|
212
|
+
|
|
213
|
+
data_path = find_data_path_by_case(app, case_file_name)
|
|
214
|
+
if not data_path:
|
|
215
|
+
pytest.fail(f"load_case 找不到数据文件: app={app}, file={case_file_name}.yml")
|
|
216
|
+
|
|
217
|
+
test_data = CachedYamlLoader(data_path).load_yml() or {}
|
|
218
|
+
case_data = test_data.get(case_name)
|
|
219
|
+
if not case_data:
|
|
220
|
+
pytest.fail(f"load_case 在 {case_file_name}.yml 中找不到 case: {case_name}")
|
|
221
|
+
|
|
222
|
+
# 深拷贝后再加工,避免把加工结果和调用方的改动写回 CachedYamlLoader 的缓存,
|
|
223
|
+
# 污染同一个 case 在正常参数化路径下的数据
|
|
224
|
+
case_data = copy.deepcopy(case_data)
|
|
225
|
+
|
|
226
|
+
case_common = test_data.get("case_common") or {}
|
|
227
|
+
case_data.setdefault("request", {})
|
|
228
|
+
case_data["request"].setdefault("headers", {})
|
|
229
|
+
case_data["app"] = app
|
|
230
|
+
case_data["_account"] = account
|
|
231
|
+
case_data["_scenario"] = {"data": {}}
|
|
232
|
+
|
|
233
|
+
# --- base_json/base_params 合并 ---
|
|
234
|
+
# 与 conftest 的参数化路径保持一致,否则 run_case 调用依赖 base_json 的 case 时会发出空 body
|
|
235
|
+
base_data = case_common.get("base_json")
|
|
236
|
+
if base_data:
|
|
237
|
+
case_json = case_data["request"].get("json")
|
|
238
|
+
if isinstance(case_json, dict):
|
|
239
|
+
case_data["request"]["json"] = deep_merge(base_data, case_json)
|
|
240
|
+
else:
|
|
241
|
+
case_data["request"]["json"] = copy.deepcopy(base_data)
|
|
242
|
+
base_params = case_common.get("base_params")
|
|
243
|
+
if base_params:
|
|
244
|
+
case_params = case_data["request"].get("params")
|
|
245
|
+
if isinstance(case_params, dict):
|
|
246
|
+
case_data["request"]["params"] = deep_merge(base_params, case_params)
|
|
247
|
+
else:
|
|
248
|
+
case_data["request"]["params"] = copy.deepcopy(base_params)
|
|
249
|
+
|
|
250
|
+
domain = self.global_context.get(key="domain", app=app)
|
|
251
|
+
if domain and not domain.startswith("http"):
|
|
252
|
+
domain = f"https://{domain}"
|
|
253
|
+
|
|
254
|
+
url = case_data["request"].get("url") or case_common.get("url") or ""
|
|
255
|
+
if domain and url and not url.strip().startswith(("${", "http")):
|
|
256
|
+
url = urljoin(domain, url)
|
|
257
|
+
case_data["request"]["url"] = url
|
|
258
|
+
|
|
259
|
+
if not case_data["request"].get("method"):
|
|
260
|
+
case_data["request"]["method"] = case_common.get("method")
|
|
261
|
+
return Box(case_data)
|
|
262
|
+
|
|
263
|
+
def run_case(self, case=None, account=None, data=None, **kwargs) -> ResponseUtil | None:
|
|
264
|
+
"""
|
|
265
|
+
主动调用一个已有 case 作为前置执行,完整执行测试方法体(含断言、context 读写等全部逻辑)。
|
|
266
|
+
|
|
267
|
+
case 内的 extract 会自动写入 CONTEXT。
|
|
268
|
+
可通过 load_case() 加载数据,修改后传入 data 参数,实现灵活定制。
|
|
269
|
+
|
|
270
|
+
使用方式:
|
|
271
|
+
- 直接执行: self.run_case(TestCreateCryptoCheckout.test_create_crypto_checkout)
|
|
272
|
+
- 修改后执行: d = self.load_case(TestCase.test_method)
|
|
273
|
+
d.request.json.orderAmount = "100.00"
|
|
274
|
+
self.run_case(data=d)
|
|
275
|
+
|
|
276
|
+
:param case: case 的方法引用或字符串路径
|
|
277
|
+
:param account: 账号名,不传则自动从源码解析 account 参数
|
|
278
|
+
:param data: 可选,从 load_case 获取的预加载数据,修改后传入
|
|
279
|
+
:param kwargs: 额外参数透传给 request()
|
|
280
|
+
:return: ResponseUtil 对象(如有 self.response),否则 None
|
|
281
|
+
"""
|
|
282
|
+
if data is None:
|
|
283
|
+
data = self.load_case(case)
|
|
284
|
+
|
|
285
|
+
app = data.get("app") or self.app
|
|
286
|
+
account = account or data.get("_account") or ""
|
|
287
|
+
|
|
288
|
+
# 构建类似 pytest nodeid 的日志格式
|
|
289
|
+
if case is not None:
|
|
290
|
+
case_file_name, case_name = self._resolve_case(case)[:2]
|
|
291
|
+
if callable(case):
|
|
292
|
+
case_file_path = Path(inspect.getfile(case))
|
|
293
|
+
rel_path = case_file_path.relative_to(settings.CASES_DIR)
|
|
294
|
+
qualname_parts = case.__qualname__.rsplit(".", 1)
|
|
295
|
+
class_name = qualname_parts[0] if len(qualname_parts) > 1 else ""
|
|
296
|
+
node_id = f"{rel_path}::{class_name}::{case.__name__}"
|
|
297
|
+
else:
|
|
298
|
+
node_id = f"{case_file_name}::{case_name}"
|
|
299
|
+
else:
|
|
300
|
+
node_id = data.get("_node_id", "custom_data")
|
|
301
|
+
|
|
302
|
+
logger.info(f"前置执行case: {node_id}(app={app}, account={account})")
|
|
303
|
+
# 加载数据,完整执行测试方法体(含断言、context 读写等全部逻辑)。
|
|
304
|
+
# self.data / _account_override 都是临时借用,执行完(含抛异常)必须还原,
|
|
305
|
+
# 否则前置 case 的数据会残留到调用方后续的 self.request()
|
|
306
|
+
previous_data = self.data
|
|
307
|
+
self.data = data
|
|
308
|
+
self._account_override = account
|
|
309
|
+
call_case = case or self.case
|
|
310
|
+
try:
|
|
311
|
+
call_case(self)
|
|
312
|
+
finally:
|
|
313
|
+
self.__dict__.pop("_account_override", None)
|
|
314
|
+
self.data = previous_data
|
|
315
|
+
return getattr(self, "response", None)
|
|
316
|
+
|
|
317
|
+
def get(self, app=None, *, account, url, params=None, **kwargs) -> ResponseUtil:
|
|
318
|
+
"""发起 HTTP GET 请求。
|
|
319
|
+
|
|
320
|
+
:param app: 应用名称,不传则使用当前 case 所属 app
|
|
321
|
+
:param account: 账号名,用于获取对应鉴权 token
|
|
322
|
+
:param url: 请求 URL
|
|
323
|
+
:param params: URL 查询参数
|
|
324
|
+
:param kwargs: 额外参数透传给 request()
|
|
325
|
+
:return: ResponseUtil 对象
|
|
326
|
+
"""
|
|
327
|
+
return self._request("get", app, account, url, params=params, **kwargs)
|
|
328
|
+
|
|
329
|
+
def post(self, app: str | None = None, *, account: str = "", url: str, data: Any = None, json: Any = None,
|
|
330
|
+
**kwargs: Any) -> "ResponseUtil":
|
|
331
|
+
"""发起 HTTP POST 请求。
|
|
332
|
+
|
|
333
|
+
:param app: 应用名称,不传则使用当前 case 所属 app
|
|
334
|
+
:param account: 账号名,用于获取对应鉴权 token
|
|
335
|
+
:param url: 请求 URL
|
|
336
|
+
:param data: 表单请求体
|
|
337
|
+
:param json: JSON 请求体
|
|
338
|
+
:param kwargs: 额外参数透传给 request()
|
|
339
|
+
:return: ResponseUtil 对象
|
|
340
|
+
"""
|
|
341
|
+
return self._request("post", app, account, url, data=data, json=json, **kwargs)
|
|
342
|
+
|
|
343
|
+
def put(self, app=None, *, account, url, data=None, json=None, **kwargs) -> ResponseUtil:
|
|
344
|
+
"""发起 HTTP PUT 请求。
|
|
345
|
+
|
|
346
|
+
:param app: 应用名称,不传则使用当前 case 所属 app
|
|
347
|
+
:param account: 账号名,用于获取对应鉴权 token
|
|
348
|
+
:param url: 请求 URL
|
|
349
|
+
:param data: 表单请求体
|
|
350
|
+
:param json: JSON 请求体
|
|
351
|
+
:param kwargs: 额外参数透传给 request()
|
|
352
|
+
:return: ResponseUtil 对象
|
|
353
|
+
"""
|
|
354
|
+
return self._request("put", app, account, url, data=data, json=json, **kwargs)
|
|
355
|
+
|
|
356
|
+
def delete(self, app=None, *, account, url, **kwargs) -> ResponseUtil:
|
|
357
|
+
"""发起 HTTP DELETE 请求。
|
|
358
|
+
|
|
359
|
+
:param app: 应用名称,不传则使用当前 case 所属 app
|
|
360
|
+
:param account: 账号名,用于获取对应鉴权 token
|
|
361
|
+
:param url: 请求 URL
|
|
362
|
+
:param kwargs: 额外参数透传给 request()
|
|
363
|
+
:return: ResponseUtil 对象
|
|
364
|
+
"""
|
|
365
|
+
return self._request("delete", app, account, url, **kwargs)
|
|
366
|
+
|
|
367
|
+
def patch(self, app=None, *, account, url, data=None, json=None, **kwargs) -> ResponseUtil:
|
|
368
|
+
"""发起 HTTP PATCH 请求。
|
|
369
|
+
|
|
370
|
+
:param app: 应用名称,不传则使用当前 case 所属 app
|
|
371
|
+
:param account: 账号名,用于获取对应鉴权 token
|
|
372
|
+
:param url: 请求 URL
|
|
373
|
+
:param data: 请求体
|
|
374
|
+
:param json: JSON 请求体
|
|
375
|
+
:param kwargs: 额外参数透传给 request()
|
|
376
|
+
:return: ResponseUtil 对象
|
|
377
|
+
"""
|
|
378
|
+
return self._request("patch", app, account, url, data=data, json=json, **kwargs)
|
|
379
|
+
|
|
380
|
+
def head(self, app=None, *, account, url, **kwargs) -> ResponseUtil:
|
|
381
|
+
"""发起 HTTP HEAD 请求。
|
|
382
|
+
|
|
383
|
+
:param app: 应用名称,不传则使用当前 case 所属 app
|
|
384
|
+
:param account: 账号名,用于获取对应鉴权 token
|
|
385
|
+
:param url: 请求 URL
|
|
386
|
+
:param kwargs: 额外参数透传给 request()
|
|
387
|
+
:return: ResponseUtil 对象
|
|
388
|
+
"""
|
|
389
|
+
return self._request("head", app, account, url, **kwargs)
|
|
390
|
+
|
|
391
|
+
def options(self, app=None, *, account, url, **kwargs) -> ResponseUtil:
|
|
392
|
+
"""发起 HTTP OPTIONS 请求。
|
|
393
|
+
|
|
394
|
+
:param app: 应用名称,不传则使用当前 case 所属 app
|
|
395
|
+
:param account: 账号名,用于获取对应鉴权 token
|
|
396
|
+
:param url: 请求 URL
|
|
397
|
+
:param kwargs: 额外参数透传给 request()
|
|
398
|
+
:return: ResponseUtil 对象
|
|
399
|
+
"""
|
|
400
|
+
return self._request("options", app, account, url, **kwargs)
|
|
401
|
+
|
|
402
|
+
def crrm(self, service: str, user_id) -> CrrmClient:
|
|
403
|
+
"""换一个 crrm token,返回带着这个 token 的客户端。
|
|
404
|
+
|
|
405
|
+
返回的不是响应而是客户端,所以能接着点下去:
|
|
406
|
+
|
|
407
|
+
self.crrm(service="debug-no-prod", user_id=1233).get()
|
|
408
|
+
self.crrm(service="debug-no-prod", user_id=1233).post(json={...})
|
|
409
|
+
self.crrm(service="debug-no-prod", user_id=1233).get("/v2.0/xxx", params={...})
|
|
410
|
+
|
|
411
|
+
url 留空打 settings.CRRM_BASE_URL,传相对路径则和它拼接,
|
|
412
|
+
传完整地址则直接用。
|
|
413
|
+
|
|
414
|
+
全程只用原生 requests,不碰框架的 HttpClient 和 self.response,
|
|
415
|
+
所以不会把用例自己的响应顶掉。
|
|
416
|
+
|
|
417
|
+
:param service: crrm 的服务名
|
|
418
|
+
:param user_id: 要换谁的凭证
|
|
419
|
+
:return: CrrmClient,token 挂在 .token 上
|
|
420
|
+
"""
|
|
421
|
+
resp = requests.get(
|
|
422
|
+
settings.GET_TOKEN_URL,
|
|
423
|
+
params={"service": service,
|
|
424
|
+
"env": crrm_config(self.env).env,
|
|
425
|
+
"user_id": user_id},
|
|
426
|
+
headers={"X-Api-Key": settings.X_API_KEY},
|
|
427
|
+
timeout=30,
|
|
428
|
+
)
|
|
429
|
+
# 取不到就当场报,别揣着空 token 往下发——那样错会出现在很远的地方
|
|
430
|
+
token = (resp.json().get("data") or {}).get("final_token")
|
|
431
|
+
assert token, (f"crrm 没换到 token: service={service} user_id={user_id} "
|
|
432
|
+
f"env={self.env} -> {resp.status_code} {resp.text}")
|
|
433
|
+
|
|
434
|
+
return CrrmClient(token=token, user_id=user_id, env=self.env)
|
|
435
|
+
|
|
436
|
+
def mysql_conn(self, db, app=None) -> MysqlDB | None:
|
|
437
|
+
"""
|
|
438
|
+
获取 MySQL 数据库连接。
|
|
439
|
+
|
|
440
|
+
:param db: 数据库名称(在 config 中配置的 key)
|
|
441
|
+
:param app: 应用名称,不传则使用当前 case 的 app
|
|
442
|
+
:return: MysqlDB 对象,失败时返回 None
|
|
443
|
+
"""
|
|
444
|
+
try:
|
|
445
|
+
return FRAMEWORK_CONTEXT.get(app=self.default_app(app), key="mysql").get(db)
|
|
446
|
+
except AttributeError as e:
|
|
447
|
+
logger.error(f"获取mysql连接异常: {e} {self.default_app(app)} {app} {db} ")
|
|
448
|
+
traceback.print_exc()
|
|
449
|
+
|
|
450
|
+
def redis_conn(self, db, index=0, app=None) -> RedisDB | None:
|
|
451
|
+
"""
|
|
452
|
+
获取 Redis 数据库连接。
|
|
453
|
+
|
|
454
|
+
:param db: 数据库名称(在 config 中配置的 key)
|
|
455
|
+
:param index: Redis 数据库索引,默认 0
|
|
456
|
+
:param app: 应用名称,不传则使用当前 case 的 app
|
|
457
|
+
:return: RedisDB 对象,失败时返回 None
|
|
458
|
+
"""
|
|
459
|
+
try:
|
|
460
|
+
return FRAMEWORK_CONTEXT.get(app=self.default_app(app), key="redis")[db][index]
|
|
461
|
+
except AttributeError as e:
|
|
462
|
+
logger.error(f"获取redis连接异常: {e}")
|
|
463
|
+
traceback.print_exc()
|
|
464
|
+
|
|
465
|
+
def mq_publish(self, exchange: str, message: str | dict, routing_key: str = "", content_type: str | None = None,
|
|
466
|
+
app: str | None = None, vhost: str = "/") -> None:
|
|
467
|
+
"""
|
|
468
|
+
发送 MQ 消息到指定 exchange。
|
|
469
|
+
|
|
470
|
+
:param exchange: 交换机名称(对应 database.{env}.yaml 中 exchanges 下的 key)
|
|
471
|
+
:param message: 消息内容(str 或 dict,dict 自动序列化为 JSON)
|
|
472
|
+
:param routing_key: 路由键
|
|
473
|
+
:param content_type: 消息类型,不传则 dict→application/json,str→text/plain
|
|
474
|
+
:param app: 所属 app,不传则使用当前 case 的 app
|
|
475
|
+
:param vhost: 虚拟主机,默认 "/"
|
|
476
|
+
"""
|
|
477
|
+
try:
|
|
478
|
+
pool = FRAMEWORK_CONTEXT.get(app=self.default_app(app), key="mq")
|
|
479
|
+
pool.get(exchange, vhost=vhost).publish(message, routing_key, content_type)
|
|
480
|
+
except AttributeError as e:
|
|
481
|
+
logger.error(f"获取MQ连接异常: {e}")
|
|
482
|
+
traceback.print_exc()
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def mq_consume(self, exchange: str, routing_key: str = "#", timeout: int = 30, app: str | None = None,
|
|
486
|
+
callback: Callable[[dict], bool] | None = None, vhost: str = "/") -> dict | str | None:
|
|
487
|
+
"""
|
|
488
|
+
消费一条 MQ 消息(仅读取副本,不影响服务端正常消费)。
|
|
489
|
+
|
|
490
|
+
通过创建临时队列绑定到 exchange 获取消息副本,用完自动删除。
|
|
491
|
+
适用于断言服务端是否发出了预期的 MQ 消息。
|
|
492
|
+
|
|
493
|
+
:param exchange: 交换机名称
|
|
494
|
+
:param routing_key: 绑定键,默认 # 匹配该 exchange 所有消息
|
|
495
|
+
:param timeout: 等待超时(秒),超时返回 None
|
|
496
|
+
:param app: 所属 app
|
|
497
|
+
:param callback: 过滤回调,接收消息体,返回 True 表示命中。
|
|
498
|
+
不传则返回第一条收到的消息。
|
|
499
|
+
:param vhost: 虚拟主机,默认 "/"
|
|
500
|
+
:return: 消息体(dict/str)或 None(超时)
|
|
501
|
+
"""
|
|
502
|
+
try:
|
|
503
|
+
pool = FRAMEWORK_CONTEXT.get(app=self.default_app(app), key="mq")
|
|
504
|
+
return pool.get(exchange, vhost=vhost).consume(routing_key, timeout, callback)
|
|
505
|
+
except AttributeError as e:
|
|
506
|
+
logger.error(f"获取MQ连接异常: {e}")
|
|
507
|
+
traceback.print_exc()
|
|
508
|
+
return None
|
|
509
|
+
|
|
510
|
+
def default_app(self, app: str | None) -> str:
|
|
511
|
+
"""
|
|
512
|
+
返回 app 参数,如果为 None 则使用当前 case 所属 app。
|
|
513
|
+
|
|
514
|
+
:param app: 指定的 app 名称
|
|
515
|
+
:return: 有效的 app 名称
|
|
516
|
+
"""
|
|
517
|
+
return app or self.app
|
|
518
|
+
|
|
519
|
+
@property
|
|
520
|
+
def payload(self) -> RequestData | None | Box:
|
|
521
|
+
"""请求体内容。优先返回 json,其次是 params,最后是 data。
|
|
522
|
+
如果 json 和 params 同时存在,返回包含 json 和 params 字段的对象。"""
|
|
523
|
+
req = self.data.request if self.data else None
|
|
524
|
+
if req is None:
|
|
525
|
+
return None
|
|
526
|
+
has_json = hasattr(req, 'json') and req.json
|
|
527
|
+
has_params = hasattr(req, 'params') and req.params
|
|
528
|
+
has_data = hasattr(req, 'data') and req.data
|
|
529
|
+
if has_json and has_params:
|
|
530
|
+
return Box({'json': req.json, 'params': req.params})
|
|
531
|
+
if has_data and has_params:
|
|
532
|
+
return Box({'data': req.data, 'params': req.params})
|
|
533
|
+
if has_json:
|
|
534
|
+
return req.json
|
|
535
|
+
if has_params:
|
|
536
|
+
return req.params
|
|
537
|
+
if has_data:
|
|
538
|
+
return req.data
|
|
539
|
+
return req
|
|
540
|
+
|
|
541
|
+
@property
|
|
542
|
+
def global_context(self) -> GlobalAttribute | Box:
|
|
543
|
+
"""全局上下文(CONTEXT 单例)。"""
|
|
544
|
+
return CONTEXT
|
|
545
|
+
|
|
546
|
+
@property
|
|
547
|
+
def app_context(self) -> GlobalAttribute | Box:
|
|
548
|
+
"""当前 app 上下文。"""
|
|
549
|
+
return CONTEXT.get(key=self.app) if self.app else None
|
|
550
|
+
|
|
551
|
+
@property
|
|
552
|
+
def global_config(self) -> GlobalAttribute | Box:
|
|
553
|
+
"""全局配置(CONFIG 单例)。"""
|
|
554
|
+
return CONFIG
|
|
555
|
+
|
|
556
|
+
@property
|
|
557
|
+
def app_config(self) -> GlobalAttribute | Box:
|
|
558
|
+
"""当前 app 配置。"""
|
|
559
|
+
return CONFIG.get(key=self.app) if self.app else None
|
|
560
|
+
|
|
561
|
+
@property
|
|
562
|
+
def http_session(self):
|
|
563
|
+
"""HTTP 会话对象,挂载各应用登录实例。"""
|
|
564
|
+
return FRAMEWORK_CONTEXT.get(key="http_session")
|
|
565
|
+
|
|
566
|
+
@property
|
|
567
|
+
def ws_session(self):
|
|
568
|
+
"""WebSocket 登录容器。"""
|
|
569
|
+
return FRAMEWORK_CONTEXT.get(key="ws_session")
|
|
570
|
+
|
|
571
|
+
@property
|
|
572
|
+
def env(self) -> str | None:
|
|
573
|
+
"""当前执行环境。"""
|
|
574
|
+
return CONTEXT.get(key="env")
|
|
575
|
+
|
|
576
|
+
@staticmethod
|
|
577
|
+
def replace_domain(url: str, new_base: str) -> str:
|
|
578
|
+
"""替换 URL 的协议和域名部分。"""
|
|
579
|
+
if not url or not new_base:
|
|
580
|
+
return url or ""
|
|
581
|
+
|
|
582
|
+
# mce.sg 是内部测试域名,即使已完整也始终替换
|
|
583
|
+
if url.startswith("http") and "mce.sg" not in url:
|
|
584
|
+
return url
|
|
585
|
+
|
|
586
|
+
# 确保 new_base 有 scheme,否则 urlparse 会把它当成 path
|
|
587
|
+
if "://" not in new_base:
|
|
588
|
+
new_base = f"https://{new_base}"
|
|
589
|
+
|
|
590
|
+
parsed_url = urlparse(url)
|
|
591
|
+
new_base_parsed = urlparse(new_base)
|
|
592
|
+
return urlunparse(parsed_url._replace(
|
|
593
|
+
scheme=new_base_parsed.scheme,
|
|
594
|
+
netloc=new_base_parsed.netloc,
|
|
595
|
+
))
|
|
596
|
+
|
|
597
|
+
@staticmethod
|
|
598
|
+
def _resolve_case(case: Any) -> tuple[str, str, str | None, str | None]:
|
|
599
|
+
"""
|
|
600
|
+
解析 case 参数,返回 (文件名, case名, app名, account名)。
|
|
601
|
+
|
|
602
|
+
字符串格式 '<yaml文件名>.<case名>' 返回 (文件名, case名, None, None)。
|
|
603
|
+
方法引用格式从源码路径推断 app,从 AST 解析 account。
|
|
604
|
+
|
|
605
|
+
:param case: 字符串路径或可调用对象
|
|
606
|
+
:return: (case_file_name, case_name, app, account)
|
|
607
|
+
"""
|
|
608
|
+
if callable(case):
|
|
609
|
+
case_file_path = Path(inspect.getfile(case))
|
|
610
|
+
try:
|
|
611
|
+
app = case_file_path.relative_to(settings.CASES_DIR).parts[0]
|
|
612
|
+
except ValueError:
|
|
613
|
+
app = None
|
|
614
|
+
return case_file_path.stem, case.__name__, app, BaseTestCase._extract_account(case)
|
|
615
|
+
|
|
616
|
+
pytest.fail(f"run_case 不支持的类型: {type(case).__name__}")
|
|
617
|
+
return None
|
|
618
|
+
|
|
619
|
+
@staticmethod
|
|
620
|
+
def _extract_account(func: Callable[..., Any]) -> str | None:
|
|
621
|
+
"""
|
|
622
|
+
从 case 函数源码中解析 self.http(account=...) 的参数值。
|
|
623
|
+
|
|
624
|
+
通过 AST 解析源码,定位 account 关键字参数的常量值。
|
|
625
|
+
|
|
626
|
+
:param func: case 函数
|
|
627
|
+
:return: account 字符串,未找到则返回 None
|
|
628
|
+
"""
|
|
629
|
+
try:
|
|
630
|
+
tree = ast.parse(textwrap.dedent(inspect.getsource(func)))
|
|
631
|
+
except (OSError, TypeError, SyntaxError):
|
|
632
|
+
return None
|
|
633
|
+
# 遍历 AST 节点,查找 self.http(account="xxx") 调用
|
|
634
|
+
for node in ast.walk(tree):
|
|
635
|
+
if not isinstance(node, ast.Call):
|
|
636
|
+
continue
|
|
637
|
+
for kw in node.keywords:
|
|
638
|
+
if kw.arg == "account" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
|
|
639
|
+
return kw.value.value
|
|
640
|
+
return None
|
|
641
|
+
|
|
642
|
+
def _get_ws_client(self, account, url, headers=None, params=None, timeout=None, auto_close=False, **kwargs):
|
|
643
|
+
"""获取 WebSocket 客户端:有 account 走 ws_session 连接池,否则新建。"""
|
|
644
|
+
if account and self.ws_session:
|
|
645
|
+
ws_login = getattr(self.ws_session, self.app, None)
|
|
646
|
+
if ws_login is None:
|
|
647
|
+
raise AttributeError(f"{self.app} 未实现 {snake_to_pascal(self.app)}WsLogin 登录类,"
|
|
648
|
+
f"无法通过 account={account} 建立 websocket 连接")
|
|
649
|
+
return ws_login.connect(account, url=url), True
|
|
650
|
+
return WebsocketClient(url=url, headers=headers, params=params,
|
|
651
|
+
timeout=timeout, auto_close=auto_close, **kwargs), False
|
|
652
|
+
|
|
653
|
+
def _request(self, method, app, account, url, **kwargs) -> ResponseUtil:
|
|
654
|
+
"""
|
|
655
|
+
GET/POST/PUT/DELETE/PATCH/HEAD/OPTIONS 请求的底层统一实现。
|
|
656
|
+
|
|
657
|
+
带 app 时自动拼接 domain 并走带 token 的 request 流程;
|
|
658
|
+
不带 app 时直接通过 HttpClient 发送(不携带 token)。
|
|
659
|
+
|
|
660
|
+
:param method: HTTP 方法(get/post/put/delete/patch/head/options)
|
|
661
|
+
:param app: 应用名称
|
|
662
|
+
:param account: 账号名
|
|
663
|
+
:param url: 请求 URL
|
|
664
|
+
:param kwargs: 额外参数(params、data、json 等)
|
|
665
|
+
:return: ResponseUtil 对象
|
|
666
|
+
"""
|
|
667
|
+
request = {"method": method, "url": url, "headers": {}, **kwargs}
|
|
668
|
+
if app:
|
|
669
|
+
domain = self.global_context.get(app).get("domain")
|
|
670
|
+
request["url"] = urljoin(domain, url)
|
|
671
|
+
return self.request(app=app, account=account, data=Box({"request": request}))
|
|
672
|
+
|
|
673
|
+
# 不需要 token 发送请求的(直接使用 HttpClient 而不经过鉴权)
|
|
674
|
+
# kwargs 在上面构建 request 时已经合并进去了,这里不能再透传一次,
|
|
675
|
+
# 否则 kwargs 里的 data 会和 request() 的 data 形参撞名
|
|
676
|
+
data = RenderData(Box({"request": request})).render()
|
|
677
|
+
self.response = HttpClient().request(data=data)
|
|
678
|
+
return self.response
|
|
679
|
+
|
|
680
|
+
def get_customized_kytmock(self, request_id: str) -> Any:
|
|
681
|
+
"""
|
|
682
|
+
获取自定义 kytmock 的 mock 配置信息。
|
|
683
|
+
|
|
684
|
+
:param request_id: 请求 ID
|
|
685
|
+
:return: mock 配置信息
|
|
686
|
+
"""
|
|
687
|
+
return get_customized_kytmock(self.global_context.get("env"), request_id)
|
|
688
|
+
|
|
689
|
+
def set_customized_kytmock(self, request_id, payment_type: PaymentType, risk_level: RiskLevel,
|
|
690
|
+
is_delayed: IsDelayed = IsDelayed.NO_DELAY):
|
|
691
|
+
"""
|
|
692
|
+
设置自定义 kytmock 的 mock 配置。
|
|
693
|
+
|
|
694
|
+
:param request_id: 请求 ID
|
|
695
|
+
:param payment_type: 支付类型枚举
|
|
696
|
+
:param risk_level: 风险等级枚举
|
|
697
|
+
:param is_delayed: 是否延迟枚举,默认不延迟
|
|
698
|
+
:return: 接口响应的 JSON 字典,失败则返回 None
|
|
699
|
+
"""
|
|
700
|
+
return set_customized_kytmock(self.global_context.get("env"), request_id, payment_type, risk_level, is_delayed)
|
|
701
|
+
|
|
702
|
+
def mock_mq_message(self, target_exchange, exchange_type, message, routing_key: str = None):
|
|
703
|
+
"""
|
|
704
|
+
模拟发送 MQ 消息(用于 mock 测试环境中触发服务端逻辑)。
|
|
705
|
+
|
|
706
|
+
:param target_exchange: 目标交换机名称
|
|
707
|
+
:param exchange_type: 交换机类型,枚举:fanout, direct, topic, header
|
|
708
|
+
:param message: 消息体,json 格式
|
|
709
|
+
:param routing_key: 路由关键字,默认为 None
|
|
710
|
+
:return: mock 结果
|
|
711
|
+
"""
|
|
712
|
+
return mock_mq(self.global_context.get("env"), target_exchange, exchange_type, message, routing_key)
|
|
713
|
+
|
|
714
|
+
def regenerate_hot_wallet_for_psp(self, participant_code: str) -> Any:
|
|
715
|
+
"""
|
|
716
|
+
为 PSP(partner 或 end-user)重新生成热钱包。
|
|
717
|
+
|
|
718
|
+
依次清除 wallet_service、blockchain_service、crm 三个库中的钱包数据,
|
|
719
|
+
然后调用 camp_admin 接口重新生成新钱包。
|
|
720
|
+
|
|
721
|
+
:param participant_code: partner 或 end-user 的 code
|
|
722
|
+
"""
|
|
723
|
+
self.logger.info(f"重置{participant_code}热钱包")
|
|
724
|
+
wallet_service = self.mysql_conn(db=self.db.DB_WALLET_SERVICE)
|
|
725
|
+
wallet_service.execute(
|
|
726
|
+
f"delete from tbl_wallet_coin where wallet_key in (select wallet_key from tbl_wallet where participant_code='{participant_code}');")
|
|
727
|
+
wallet_service.execute(f"delete from tbl_wallet where participant_code='{participant_code}';")
|
|
728
|
+
self.mysql_conn(self.db.DB_BLOCKCHAIN_SERVICE).execute(
|
|
729
|
+
f"delete from hot_wallethsm where participant_code='{participant_code}';")
|
|
730
|
+
crm = self.mysql_conn(db=self.db.DB_CAMP_CRM)
|
|
731
|
+
crm.execute(
|
|
732
|
+
f"delete from tbl_crypto_wallet where id in (select wallet_id from tbl_participant_crypto_wallet where wallet_tag ='MY HOT WALLET' and participant_code='{participant_code}');")
|
|
733
|
+
crm.execute(
|
|
734
|
+
f"delete from tbl_participant_crypto_wallet where wallet_tag ='MY HOT WALLET' and participant_code='{participant_code}';")
|
|
735
|
+
|
|
736
|
+
self.post(
|
|
737
|
+
app="camp_admin",
|
|
738
|
+
account="admin",
|
|
739
|
+
url="/prod-api/crm/participant/createHotWallet.do",
|
|
740
|
+
json={"participantCode": participant_code}
|
|
741
|
+
)
|
|
742
|
+
assert self.response.code == 0
|
|
743
|
+
|
|
744
|
+
def regenerate_hot_wallet_for_buyer(self, partner_account, merchant_participant_code, buyer_participant_code):
|
|
745
|
+
"""
|
|
746
|
+
为买家重新生成热钱包。
|
|
747
|
+
|
|
748
|
+
依次清除 wallet_service、blockchain_service、crm 三个库中的钱包数据,
|
|
749
|
+
然后调用 psp_api 接口重新生成新钱包。
|
|
750
|
+
|
|
751
|
+
:param partner_account: partner 账号
|
|
752
|
+
:param merchant_participant_code: merchant code
|
|
753
|
+
:param buyer_participant_code: buyer code
|
|
754
|
+
"""
|
|
755
|
+
self.logger.info(f"重置{buyer_participant_code}热钱包")
|
|
756
|
+
wallet_service = self.mysql_conn(db=self.db.DB_WALLET_SERVICE)
|
|
757
|
+
wallet_service.execute(
|
|
758
|
+
f"delete from tbl_wallet_coin where wallet_key in (select wallet_key from tbl_wallet where participant_code='{buyer_participant_code}');")
|
|
759
|
+
wallet_service.execute(f"delete from tbl_wallet where participant_code='{buyer_participant_code}';")
|
|
760
|
+
self.mysql_conn(self.db.DB_BLOCKCHAIN_SERVICE).execute(
|
|
761
|
+
f"delete from hot_wallethsm where participant_code='{buyer_participant_code}';")
|
|
762
|
+
crm = self.mysql_conn(db=self.db.DB_CAMP_CRM)
|
|
763
|
+
crm.execute(
|
|
764
|
+
f"delete from tbl_crypto_wallet where id in (select crypto_wallet_id from tbl_buyer_crypto_wallet where wallet_tag ='MY HOT WALLET' and participant_code='{buyer_participant_code}');")
|
|
765
|
+
crm.execute(
|
|
766
|
+
f"delete from tbl_buyer_crypto_wallet where wallet_tag ='MY HOT WALLET' and participant_code='{buyer_participant_code}';")
|
|
767
|
+
|
|
768
|
+
self.post(
|
|
769
|
+
app="psp_api",
|
|
770
|
+
account=partner_account,
|
|
771
|
+
url="/v1.0/crm/deposit/createWallet",
|
|
772
|
+
json={
|
|
773
|
+
"participantCode": merchant_participant_code,
|
|
774
|
+
"buyerId": buyer_participant_code,
|
|
775
|
+
"expiry": 0
|
|
776
|
+
}
|
|
777
|
+
)
|
|
778
|
+
assert self.response.code == 200
|
|
779
|
+
|
|
780
|
+
def set_webhook_url(self, account: str, app: str | None = None):
|
|
781
|
+
"""
|
|
782
|
+
修改 webhook url 地址,在原地址基础上拼接上/uuid,保证地址唯一。
|
|
783
|
+
|
|
784
|
+
:param account: 账户名
|
|
785
|
+
:param app: 应用名称
|
|
786
|
+
:return: self,支持链式调用
|
|
787
|
+
"""
|
|
788
|
+
app = self.default_app(app)
|
|
789
|
+
account_info = self.app_context.get("accounts").get(account)
|
|
790
|
+
try:
|
|
791
|
+
info = self.mysql_conn("db_camp_crm").query(
|
|
792
|
+
f"SELECT webhook_url FROM tbl_participant WHERE participant_code = '{account_info.client_id}';",
|
|
793
|
+
log=False)
|
|
794
|
+
if not info.get("webhook_url"):
|
|
795
|
+
return self
|
|
796
|
+
except Exception as e:
|
|
797
|
+
return self
|
|
798
|
+
original_webhook_url = info.get("webhook_url").rsplit("/", 1)[0]
|
|
799
|
+
new_webhook_url = f"{original_webhook_url}/{str(uuid.uuid4()).replace('-', '_')}"
|
|
800
|
+
try:
|
|
801
|
+
self.mysql_conn("db_camp_crm").execute(
|
|
802
|
+
f"UPDATE tbl_participant set webhook_url = '{new_webhook_url}' WHERE participant_code = '{account_info.client_id}';",
|
|
803
|
+
log=False)
|
|
804
|
+
self.app_context.set(f"{account_info.client_id}_webhook", urlparse(new_webhook_url).path)
|
|
805
|
+
except Exception as e:
|
|
806
|
+
self.logger.error(f"账号{account}修改webhook地址异常: {e}")
|
|
807
|
+
return self
|
|
808
|
+
|
|
809
|
+
def get_webhook(self, account, count=None, timeout=GET_WEBHOOK_TIMEOUT, interval=GET_WEBHOOK_TRIES):
|
|
810
|
+
"""
|
|
811
|
+
获取 webhook 日志,若为空则重试。
|
|
812
|
+
|
|
813
|
+
:param account: 账户名
|
|
814
|
+
:param count: 期望日志条数(None 表示只要非空即可)
|
|
815
|
+
:param timeout: 最大等待时间(秒)
|
|
816
|
+
:param interval: 重试间隔(秒)
|
|
817
|
+
:return: webhook 日志列表 or []
|
|
818
|
+
"""
|
|
819
|
+
account_info = self.app_context.get("accounts").get(account)
|
|
820
|
+
webhook_url = self.app_context.get(f"{account_info.client_id}_webhook")
|
|
821
|
+
|
|
822
|
+
if not webhook_url:
|
|
823
|
+
self.logger.warning(f"账号{account}未配置webhook地址")
|
|
824
|
+
return
|
|
825
|
+
webhook_url = webhook_url.replace("/webhook_vmock", "")
|
|
826
|
+
base64_webhook_url = b64_encode(webhook_url.encode("utf8"))
|
|
827
|
+
self.logger.info(f'原始webhook_url: {webhook_url}, base64格式webhook_url: {base64_webhook_url}')
|
|
828
|
+
|
|
829
|
+
redis_key = f"vmock_webhook_log:{base64_webhook_url}"
|
|
830
|
+
redis = self.redis_conn(db="database")
|
|
831
|
+
end_time = time.time() + timeout
|
|
832
|
+
webhook_list = []
|
|
833
|
+
while time.time() < end_time:
|
|
834
|
+
webhook_list = redis.lrange_all(redis_key)
|
|
835
|
+
if webhook_list:
|
|
836
|
+
webhook_list = [
|
|
837
|
+
json.loads(raw[raw.find(b"{"):].decode("utf-8"))
|
|
838
|
+
for raw in webhook_list
|
|
839
|
+
if isinstance(raw, (bytes, bytearray)) and raw.find(b"{") != -1
|
|
840
|
+
]
|
|
841
|
+
current_count = len(webhook_list)
|
|
842
|
+
if count is None:
|
|
843
|
+
self.logger.info(f"获取webhook{current_count}条: {json.dumps(webhook_list)}")
|
|
844
|
+
redis.lpop_all(redis_key)
|
|
845
|
+
return webhook_list
|
|
846
|
+
|
|
847
|
+
if current_count >= count:
|
|
848
|
+
self.logger.info(f"获取webhook{current_count}条: {json.dumps(webhook_list)}")
|
|
849
|
+
redis.lpop_all(redis_key)
|
|
850
|
+
return webhook_list
|
|
851
|
+
|
|
852
|
+
self.logger.info(f"已获取webhook {current_count} 条,未达到预期 {count} 条,{interval} 秒后重试...")
|
|
853
|
+
else:
|
|
854
|
+
self.logger.info(f"暂未收到webhook,{interval} 秒后重试...")
|
|
855
|
+
time.sleep(interval)
|
|
856
|
+
current_count = len(webhook_list)
|
|
857
|
+
if current_count == 0:
|
|
858
|
+
self.logger.warning(f"等待webhook超时({GET_WEBHOOK_TIMEOUT} 秒),redis key: {redis_key}")
|
|
859
|
+
raise AssertionError('暂未收到webhook')
|
|
860
|
+
self.logger.info(f"已获取部分webhook: {json.dumps(webhook_list)}")
|
|
861
|
+
redis.lpop_all(redis_key)
|
|
862
|
+
raise AssertionError(f'非预期webhook条数,当前条数: {current_count} 期望条数: {count}')
|
|
863
|
+
|
|
864
|
+
def webhook(self, webhook_info: Any):
|
|
865
|
+
"""
|
|
866
|
+
获取 WebhookAssert 断言对象,用于验证 get_webhook 获取的 webhook 日志内容。
|
|
867
|
+
使用前需先调用 get_webhook 获取日志数据。
|
|
868
|
+
|
|
869
|
+
:return: WebhookAssert 实例
|
|
870
|
+
"""
|
|
871
|
+
return WebhookAssert(webhook_info)
|