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,414 @@
|
|
|
1
|
+
"""
|
|
2
|
+
WebSocket 客户端模块,封装了 websocket 库,提供 WebSocket 连接管理、消息发送接收、
|
|
3
|
+
响应匹配、变量提取等功能。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import ssl
|
|
8
|
+
import time
|
|
9
|
+
import uuid
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from typing import Any, List, Callable
|
|
12
|
+
from urllib.parse import urlencode
|
|
13
|
+
from jsonpath import jsonpath as jp
|
|
14
|
+
import allure
|
|
15
|
+
import websocket
|
|
16
|
+
from box import Box, BoxList
|
|
17
|
+
|
|
18
|
+
from framework.core.extract import Extract
|
|
19
|
+
from framework.settings import WEBSOCKET_TIMEOUT
|
|
20
|
+
from framework.utils.log_util import logger
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class RequestMode(Enum):
|
|
24
|
+
"""请求匹配模式枚举。"""
|
|
25
|
+
|
|
26
|
+
REQUEST_ID = "request_id" # 按 request_id 字段匹配响应
|
|
27
|
+
MATCHER = "matcher" # 按自定义匹配函数匹配响应
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class WebsocketTimeoutError(Exception):
|
|
31
|
+
"""WebSocket 等待超时异常,当在指定时间内未收到匹配消息时抛出。"""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class WebsocketClosedError(Exception):
|
|
35
|
+
"""WebSocket 连接已关闭异常。"""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ResponseUtil(object):
|
|
39
|
+
"""WebSocket 响应工具类,封装响应数据的解析、断言和变量提取。"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, response: Any) -> None:
|
|
42
|
+
"""
|
|
43
|
+
初始化 WebSocket 响应工具类。
|
|
44
|
+
@param response: 响应数据(dict / list / 其他)
|
|
45
|
+
"""
|
|
46
|
+
self.response = response
|
|
47
|
+
if isinstance(response, dict):
|
|
48
|
+
self.box = Box(response)
|
|
49
|
+
elif isinstance(response, list):
|
|
50
|
+
self.box = BoxList(response)
|
|
51
|
+
else:
|
|
52
|
+
self.box = response
|
|
53
|
+
|
|
54
|
+
def __getattr__(self, name: str) -> Any:
|
|
55
|
+
"""获取属性,优先从 box 对象获取,若不存在则从原始 response 获取。"""
|
|
56
|
+
try:
|
|
57
|
+
return getattr(self.box, name)
|
|
58
|
+
except AttributeError:
|
|
59
|
+
return getattr(self.response, name)
|
|
60
|
+
|
|
61
|
+
def __getitem__(self, key):
|
|
62
|
+
return self.box[key]
|
|
63
|
+
|
|
64
|
+
def get(self, key, default=None):
|
|
65
|
+
return self.box.get(key, default)
|
|
66
|
+
|
|
67
|
+
def __str__(self) -> str:
|
|
68
|
+
"""返回 JSON 格式的响应字符串。"""
|
|
69
|
+
return json.dumps(self.response)
|
|
70
|
+
|
|
71
|
+
def jsonpath(self, expr: str) -> Any:
|
|
72
|
+
"""
|
|
73
|
+
使用 jsonpath 语法从响应体中提取内容。
|
|
74
|
+
@param expr: jsonpath 表达式
|
|
75
|
+
@return: 匹配结果;若匹配到单个值则直接返回,否则返回列表;无匹配时返回空字符串
|
|
76
|
+
"""
|
|
77
|
+
result = jp(self.json(), expr)
|
|
78
|
+
if result is False:
|
|
79
|
+
return ""
|
|
80
|
+
if len(result) == 1:
|
|
81
|
+
return result[0]
|
|
82
|
+
return result
|
|
83
|
+
|
|
84
|
+
def json(self) -> Any:
|
|
85
|
+
"""获取 JSON 格式的响应数据。"""
|
|
86
|
+
return self.response
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def text(self) -> str:
|
|
90
|
+
"""获取字符串格式的响应数据。"""
|
|
91
|
+
return str(self.response)
|
|
92
|
+
|
|
93
|
+
def extract(self, app: str, key: str, expression: str) -> None:
|
|
94
|
+
"""
|
|
95
|
+
从响应中提取变量并存储。
|
|
96
|
+
@param app: 应用实例
|
|
97
|
+
@param key: 变量保存的名称
|
|
98
|
+
@param expression: 变量提取表达式
|
|
99
|
+
"""
|
|
100
|
+
Extract(self.response, app).extract(key, expression)
|
|
101
|
+
|
|
102
|
+
def extracts(self, app: str, expressions: List[dict]) -> None:
|
|
103
|
+
"""
|
|
104
|
+
批量从响应中提取变量并存储。
|
|
105
|
+
@param app: 应用实例
|
|
106
|
+
@param expressions: 变量提取表达式列表
|
|
107
|
+
"""
|
|
108
|
+
Extract(self.response, app).extracts(expressions)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class WebsocketClient:
|
|
112
|
+
"""WebSocket 客户端,提供连接管理、消息发送接收、响应匹配等功能。"""
|
|
113
|
+
|
|
114
|
+
def __init__(self, url: str, headers: dict[str, str] | None = None, params: dict[str, Any] | None = None, timeout: int | float = WEBSOCKET_TIMEOUT, auto_close: bool = False, **kwargs: Any) -> None:
|
|
115
|
+
"""
|
|
116
|
+
初始化 WebSocket 客户端并建立连接。
|
|
117
|
+
@param url: WebSocket 连接地址
|
|
118
|
+
@param headers: 自定义请求头
|
|
119
|
+
@param params: URL 查询参数
|
|
120
|
+
@param timeout: 超时时间(秒)
|
|
121
|
+
@param auto_close: 匹配到响应后是否自动关闭连接
|
|
122
|
+
"""
|
|
123
|
+
self.url = self._build_url(url, params)
|
|
124
|
+
self.headers = headers or {}
|
|
125
|
+
self.timeout = timeout if timeout is not None else WEBSOCKET_TIMEOUT
|
|
126
|
+
self.auto_close = auto_close
|
|
127
|
+
self.ws = None
|
|
128
|
+
self.label = None # 连接标识,连接池赋值后用于日志
|
|
129
|
+
self._connect(**kwargs)
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def is_alive(self) -> bool:
|
|
133
|
+
"""连接是否仍保持(发送 ping + 排空 pending close frame)。"""
|
|
134
|
+
if self.ws is None:
|
|
135
|
+
return False
|
|
136
|
+
try:
|
|
137
|
+
self.ws.ping()
|
|
138
|
+
except Exception:
|
|
139
|
+
self.ws = None
|
|
140
|
+
return False
|
|
141
|
+
try:
|
|
142
|
+
self.ws.sock.setblocking(False)
|
|
143
|
+
try:
|
|
144
|
+
while True:
|
|
145
|
+
self.ws.recv_data_frame()
|
|
146
|
+
except websocket.WebSocketConnectionClosedException:
|
|
147
|
+
self.ws = None
|
|
148
|
+
except Exception:
|
|
149
|
+
pass
|
|
150
|
+
finally:
|
|
151
|
+
self.ws.sock.setblocking(True)
|
|
152
|
+
except Exception:
|
|
153
|
+
pass
|
|
154
|
+
return self.ws is not None and self.ws.connected
|
|
155
|
+
|
|
156
|
+
def _resolve_timeout(self, timeout: int | float | None) -> int | float:
|
|
157
|
+
"""解析超时时间,若未指定则使用实例默认超时。"""
|
|
158
|
+
return timeout if timeout is not None else self.timeout
|
|
159
|
+
|
|
160
|
+
@staticmethod
|
|
161
|
+
def _build_url(url: str, params: dict[str, Any] | None = None) -> str:
|
|
162
|
+
"""构建 WebSocket URL,拼接查询参数。"""
|
|
163
|
+
if params:
|
|
164
|
+
url = f"{url}?{urlencode(params)}"
|
|
165
|
+
|
|
166
|
+
return url
|
|
167
|
+
|
|
168
|
+
def _connect(self, **kwargs: Any) -> None:
|
|
169
|
+
"""建立 WebSocket 连接。"""
|
|
170
|
+
try:
|
|
171
|
+
self.ws = websocket.create_connection(
|
|
172
|
+
self.url,
|
|
173
|
+
sslopt={"cert_reqs": ssl.CERT_NONE},
|
|
174
|
+
header={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)", **self.headers},
|
|
175
|
+
timeout=self.timeout,
|
|
176
|
+
**kwargs
|
|
177
|
+
)
|
|
178
|
+
logger.info(f"WebSocket连接成功: {self.url}")
|
|
179
|
+
except Exception as e:
|
|
180
|
+
logger.exception(f"WebSocket连接失败: {e}")
|
|
181
|
+
raise
|
|
182
|
+
|
|
183
|
+
def request(self, mode: RequestMode = RequestMode.MATCHER, request_key: str | None = None, message: dict | None = None, timeout: int | float | None = None, matcher: Callable[[Any], bool] | None = None) -> ResponseUtil:
|
|
184
|
+
"""
|
|
185
|
+
发送 WebSocket 请求并等待匹配的响应。
|
|
186
|
+
@param mode: 匹配模式(REQUEST_ID 按字段匹配 / MATCHER 按自定义函数匹配)
|
|
187
|
+
@param request_key: REQUEST_ID 模式下用于匹配的字段名
|
|
188
|
+
@param message: 发送的消息数据
|
|
189
|
+
@param timeout: 等待超时时间(秒)
|
|
190
|
+
@param matcher: MATCHER 模式下的自定义匹配函数
|
|
191
|
+
@return: ResponseUtil 实例
|
|
192
|
+
@raises ValueError: 参数验证失败时抛出
|
|
193
|
+
@raises WebsocketTimeoutError: 超时未匹配到响应时抛出
|
|
194
|
+
"""
|
|
195
|
+
if message is None:
|
|
196
|
+
message = {}
|
|
197
|
+
message = message.copy()
|
|
198
|
+
timeout = self._resolve_timeout(timeout)
|
|
199
|
+
|
|
200
|
+
if mode is None:
|
|
201
|
+
mode = RequestMode.MATCHER
|
|
202
|
+
|
|
203
|
+
if mode == RequestMode.REQUEST_ID:
|
|
204
|
+
# REQUEST_ID 模式:从 payload 中提取 request_id 用于响应匹配
|
|
205
|
+
request_id = message.get(request_key)
|
|
206
|
+
if not request_id:
|
|
207
|
+
raise ValueError(f"REQUEST_ID模式, message必须提供{request_key}字段数据")
|
|
208
|
+
match_fn = lambda msg, _rid=request_id, _rk=request_key: isinstance(msg, dict) and msg.get(_rk) == _rid
|
|
209
|
+
elif mode == RequestMode.MATCHER:
|
|
210
|
+
# MATCHER 模式:使用用户提供的自定义匹配函数,未提供则接收第一条消息
|
|
211
|
+
match_fn = matcher or (lambda _: True)
|
|
212
|
+
else:
|
|
213
|
+
raise ValueError(f"未知请求模式: {mode}")
|
|
214
|
+
|
|
215
|
+
self.send(message)
|
|
216
|
+
return self._recv_until_match(match_fn, timeout)
|
|
217
|
+
|
|
218
|
+
def send(self, message: Any) -> None:
|
|
219
|
+
"""
|
|
220
|
+
发送 WebSocket 消息。
|
|
221
|
+
@param message: 要发送的消息(dict 自动转为 JSON 字符串)
|
|
222
|
+
"""
|
|
223
|
+
if isinstance(message, dict):
|
|
224
|
+
message = json.dumps(message, ensure_ascii=False)
|
|
225
|
+
elif not isinstance(message, str):
|
|
226
|
+
message = str(message)
|
|
227
|
+
self.ws.send(message)
|
|
228
|
+
self._log_send(message)
|
|
229
|
+
|
|
230
|
+
def _recv_until_match(self, match_fn: Callable[[Any], bool], timeout: int | float) -> ResponseUtil:
|
|
231
|
+
"""循环接收 WebSocket 消息,直到匹配条件满足或超时。
|
|
232
|
+
@param match_fn: 匹配函数,接收消息参数,返回 True 表示匹配
|
|
233
|
+
@param timeout: 超时时间(秒)
|
|
234
|
+
@return: ResponseUtil 实例
|
|
235
|
+
@raises WebsocketTimeoutError: 超时未匹配时抛出
|
|
236
|
+
@raises WebsocketClosedError: 连接断开时抛出
|
|
237
|
+
"""
|
|
238
|
+
start_time = time.time()
|
|
239
|
+
while True:
|
|
240
|
+
elapsed = time.time() - start_time
|
|
241
|
+
if elapsed >= timeout: # 超时检查
|
|
242
|
+
raise WebsocketTimeoutError("等待消息超时")
|
|
243
|
+
try:
|
|
244
|
+
raw = self.ws.recv()
|
|
245
|
+
except websocket.WebSocketTimeoutException: # 超时异常,继续等待
|
|
246
|
+
continue
|
|
247
|
+
except websocket.WebSocketConnectionClosedException:
|
|
248
|
+
self.ws = None
|
|
249
|
+
raise WebsocketClosedError("连接已断开")
|
|
250
|
+
|
|
251
|
+
msg = self._decode_message(raw)
|
|
252
|
+
self._log_recv(msg)
|
|
253
|
+
|
|
254
|
+
# 处理 Ping 心跳消息
|
|
255
|
+
if self._is_ping_message(msg):
|
|
256
|
+
self._handle_ping(msg)
|
|
257
|
+
continue
|
|
258
|
+
try:
|
|
259
|
+
if match_fn(msg): # 匹配到目标消息
|
|
260
|
+
if self.auto_close:
|
|
261
|
+
self.close()
|
|
262
|
+
return ResponseUtil(msg)
|
|
263
|
+
except Exception as e: # 匹配过程异常,记录日志后继续
|
|
264
|
+
logger.error(e)
|
|
265
|
+
|
|
266
|
+
def wait_message(self, condition: Callable[[Any], bool] | None = None, timeout: int | float | None = None) -> ResponseUtil:
|
|
267
|
+
"""等待接收一条 WebSocket 消息(可选按条件过滤)。
|
|
268
|
+
@param condition: 匹配条件函数,默认接收任何消息
|
|
269
|
+
@param timeout: 超时时间(秒)
|
|
270
|
+
@return: ResponseUtil 实例
|
|
271
|
+
"""
|
|
272
|
+
timeout = self._resolve_timeout(timeout)
|
|
273
|
+
return self._recv_until_match(condition or (lambda _: True), timeout)
|
|
274
|
+
|
|
275
|
+
def stream(self, message: dict | None = None, condition: Callable[[Any], bool] | None = None, stop_condition: Callable[[Any], bool] | None = None, timeout: int | float | None = None) -> Any:
|
|
276
|
+
"""发送消息并以生成器形式持续接收匹配的响应流。
|
|
277
|
+
|
|
278
|
+
@param message: 发送的消息数据
|
|
279
|
+
@param condition: 匹配条件函数
|
|
280
|
+
@param stop_condition: 停止条件函数,满足时停止接收
|
|
281
|
+
@param timeout: 单次接收超时(秒)
|
|
282
|
+
@yield: ResponseUtil 实例
|
|
283
|
+
"""
|
|
284
|
+
self.send(message)
|
|
285
|
+
yield from self.listen(condition=condition, stop_condition=stop_condition, timeout=timeout)
|
|
286
|
+
|
|
287
|
+
def listen(self, condition: Callable[[Any], bool] | None = None, stop_condition: Callable[[Any], bool] | None = None, timeout: int | float | None = None) -> Any:
|
|
288
|
+
"""持续监听 WebSocket 消息,作为 generator 逐条 yield 匹配结果。连接保持打开。
|
|
289
|
+
|
|
290
|
+
与 request() 的单次匹配不同,listen() 每次匹配后不关闭连接也不返回,
|
|
291
|
+
而是继续 yield 后续匹配的消息,直到 stop_condition 满足或连接断开。
|
|
292
|
+
|
|
293
|
+
@param condition: 匹配条件函数,None 表示接收所有消息
|
|
294
|
+
@param stop_condition: 停止条件函数,满足时生成器退出
|
|
295
|
+
@param timeout: 单次接收超时(秒),None 使用实例默认超时
|
|
296
|
+
@yield: ResponseUtil 实例
|
|
297
|
+
"""
|
|
298
|
+
match_fn = condition or (lambda _: True)
|
|
299
|
+
timeout = self._resolve_timeout(timeout)
|
|
300
|
+
|
|
301
|
+
while True:
|
|
302
|
+
start_time = time.time()
|
|
303
|
+
msg = None
|
|
304
|
+
while True:
|
|
305
|
+
elapsed = time.time() - start_time
|
|
306
|
+
if elapsed >= timeout:
|
|
307
|
+
raise WebsocketTimeoutError("等待消息超时")
|
|
308
|
+
try:
|
|
309
|
+
raw = self.ws.recv()
|
|
310
|
+
except websocket.WebSocketTimeoutException:
|
|
311
|
+
continue
|
|
312
|
+
except websocket.WebSocketConnectionClosedException:
|
|
313
|
+
return
|
|
314
|
+
|
|
315
|
+
msg = self._decode_message(raw)
|
|
316
|
+
self._log_recv(msg)
|
|
317
|
+
|
|
318
|
+
if self._is_ping_message(msg):
|
|
319
|
+
self._handle_ping(msg)
|
|
320
|
+
continue
|
|
321
|
+
|
|
322
|
+
try:
|
|
323
|
+
if match_fn(msg):
|
|
324
|
+
break
|
|
325
|
+
except Exception as e:
|
|
326
|
+
logger.error(e)
|
|
327
|
+
|
|
328
|
+
response = ResponseUtil(msg)
|
|
329
|
+
yield response
|
|
330
|
+
if stop_condition and stop_condition(response):
|
|
331
|
+
break
|
|
332
|
+
# 服务端或本端关闭后,标记连接已断开
|
|
333
|
+
if self.ws:
|
|
334
|
+
try:
|
|
335
|
+
self.ws.close()
|
|
336
|
+
except Exception:
|
|
337
|
+
pass
|
|
338
|
+
self.ws = None
|
|
339
|
+
|
|
340
|
+
@staticmethod
|
|
341
|
+
def _generate_request_id() -> str:
|
|
342
|
+
"""生成唯一的请求 ID(UUID)。"""
|
|
343
|
+
return str(uuid.uuid4())
|
|
344
|
+
|
|
345
|
+
@staticmethod
|
|
346
|
+
def _decode_message(raw: str) -> Any:
|
|
347
|
+
"""解码原始 WebSocket 消息,尝试解析为 JSON。
|
|
348
|
+
@param raw: 原始消息字符串
|
|
349
|
+
@return: 解析后的 JSON 数据,解析失败返回原始字符串
|
|
350
|
+
"""
|
|
351
|
+
try:
|
|
352
|
+
return json.loads(raw)
|
|
353
|
+
except Exception: # 非 JSON 格式,直接返回原始字符串
|
|
354
|
+
return raw
|
|
355
|
+
|
|
356
|
+
@staticmethod
|
|
357
|
+
def _is_ping_message(msg: Any) -> bool:
|
|
358
|
+
"""判断消息是否为 Ping/Pong 心跳消息。
|
|
359
|
+
@param msg: 解码后的消息
|
|
360
|
+
@return: 布尔值
|
|
361
|
+
"""
|
|
362
|
+
if isinstance(msg, str):
|
|
363
|
+
return msg.strip().lower() == "ping"
|
|
364
|
+
if isinstance(msg, dict):
|
|
365
|
+
# 检查消息中是否包含 type/event/action 字段为 ping/pong
|
|
366
|
+
msg_type = msg.get("type") or msg.get("event") or msg.get("action")
|
|
367
|
+
return str(msg_type).lower() in ["ping", "pong"]
|
|
368
|
+
return False
|
|
369
|
+
|
|
370
|
+
def _handle_ping(self, msg: Any) -> None:
|
|
371
|
+
"""处理 Ping 心跳消息,自动回复 Pong。
|
|
372
|
+
@param msg: Ping 消息
|
|
373
|
+
"""
|
|
374
|
+
if isinstance(msg, str):
|
|
375
|
+
self.send("pong")
|
|
376
|
+
return
|
|
377
|
+
# 将消息中的类型字段替换为 pong 作为回复
|
|
378
|
+
pong = msg.copy()
|
|
379
|
+
for key in ("type", "event", "action"):
|
|
380
|
+
if key in pong:
|
|
381
|
+
pong[key] = "pong"
|
|
382
|
+
break
|
|
383
|
+
self.send(pong)
|
|
384
|
+
|
|
385
|
+
@staticmethod
|
|
386
|
+
def _log_send(message: Any) -> None:
|
|
387
|
+
"""记录发送的 WebSocket 消息到日志和 Allure 报告。"""
|
|
388
|
+
with allure.step(f"发送WebSocket消息: {message}"):
|
|
389
|
+
if isinstance(message, dict):
|
|
390
|
+
message = json.dumps(message)
|
|
391
|
+
logger.info(f"发送WebSocket消息: {message}")
|
|
392
|
+
|
|
393
|
+
@staticmethod
|
|
394
|
+
def _log_recv(message: Any) -> None:
|
|
395
|
+
"""记录接收的 WebSocket 消息到日志和 Allure 报告。"""
|
|
396
|
+
with allure.step(f"接收WebSocket消息: {message}"):
|
|
397
|
+
if isinstance(message, dict):
|
|
398
|
+
message = json.dumps(message)
|
|
399
|
+
logger.info(f"接收WebSocket消息: {message}")
|
|
400
|
+
|
|
401
|
+
def close(self) -> None:
|
|
402
|
+
"""关闭 WebSocket 连接。"""
|
|
403
|
+
if self.ws:
|
|
404
|
+
self.ws.close()
|
|
405
|
+
self.ws = None
|
|
406
|
+
logger.info(f"关闭 WebSocket: {self.label or self.url}")
|
|
407
|
+
|
|
408
|
+
def __enter__(self) -> "WebsocketClient":
|
|
409
|
+
"""上下文管理器入口,支持 with 语句。"""
|
|
410
|
+
return self
|
|
411
|
+
|
|
412
|
+
def __exit__(self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: Any) -> None:
|
|
413
|
+
"""上下文管理器出口,自动关闭连接。"""
|
|
414
|
+
self.close()
|