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
framework/db/mysql_db.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""MySQL 数据库操作模块,提供数据库连接池管理与 CRUD 操作封装。"""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import ssl
|
|
5
|
+
import threading
|
|
6
|
+
from decimal import Decimal
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
|
|
10
|
+
import retry
|
|
11
|
+
import pymysql
|
|
12
|
+
from pymysql import MySQLError
|
|
13
|
+
from dbutils.pooled_db import PooledDB
|
|
14
|
+
|
|
15
|
+
import framework.settings as settings
|
|
16
|
+
from framework.utils.log_util import logger
|
|
17
|
+
from framework.exceptions import MysqlDBError
|
|
18
|
+
from typing import Any, Callable
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LazyMysqlPool:
|
|
22
|
+
"""按 db 名懒创建 MysqlDB,首次访问时建立连接池,线程安全。"""
|
|
23
|
+
|
|
24
|
+
def __init__(self, mysql_config: dict):
|
|
25
|
+
"""
|
|
26
|
+
初始化懒加载连接池管理器。
|
|
27
|
+
|
|
28
|
+
@param mysql_config: dict, 数据库配置字典,key 为数据库名称,value 为连接参数
|
|
29
|
+
"""
|
|
30
|
+
self._config = mysql_config
|
|
31
|
+
self._conns: dict[str, "MysqlDB"] = {}
|
|
32
|
+
self._lock = threading.Lock()
|
|
33
|
+
|
|
34
|
+
def get(self, db: str) -> "MysqlDB":
|
|
35
|
+
"""
|
|
36
|
+
获取指定数据库的 MysqlDB 实例,不存在则懒创建。
|
|
37
|
+
|
|
38
|
+
@param db: str, 数据库名称
|
|
39
|
+
@return: MysqlDB 实例
|
|
40
|
+
"""
|
|
41
|
+
if db not in self._conns:
|
|
42
|
+
with self._lock:
|
|
43
|
+
# 双重检查锁定,确保线程安全
|
|
44
|
+
if db not in self._conns:
|
|
45
|
+
self._conns[db] = MysqlDB(**self._config[db])
|
|
46
|
+
return self._conns[db]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def safe_mysql_call(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
50
|
+
"""装饰器:捕获 Mysql 异常并转成 MysqlDBError"""
|
|
51
|
+
|
|
52
|
+
def wrapper(self, *args, **kwargs):
|
|
53
|
+
sql = args[0] if args and isinstance(args[0], str) else kwargs.get('sql')
|
|
54
|
+
try:
|
|
55
|
+
return func(self, *args, **kwargs)
|
|
56
|
+
except MySQLError as e:
|
|
57
|
+
logger.error(f"{func.__name__}执行SQL出错: {sql}: {e}")
|
|
58
|
+
raise MysqlDBError(e)
|
|
59
|
+
except Exception as e:
|
|
60
|
+
logger.error(f"{func.__name__} 未知错误: {e}")
|
|
61
|
+
raise MysqlDBError(e)
|
|
62
|
+
|
|
63
|
+
return wrapper
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class MysqlDB:
|
|
67
|
+
"""MySQL 数据库操作封装,提供连接池、CRUD、事务支持,异常统一转为 MysqlDBError。"""
|
|
68
|
+
|
|
69
|
+
def __init__(self, host: str, username: str, password: str, port: int, db: str, max_connections: int = settings.MYSQL_MAX_CONNECTIONS) -> None:
|
|
70
|
+
"""
|
|
71
|
+
初始化 MysqlDB 并创建连接池。
|
|
72
|
+
|
|
73
|
+
@param host: str, 数据库主机地址
|
|
74
|
+
@param username: str, 用户名
|
|
75
|
+
@param password: str, 密码
|
|
76
|
+
@param port: int, 端口号
|
|
77
|
+
@param db: str, 数据库名
|
|
78
|
+
@param max_connections: int, 最大连接数,默认从 settings 获取
|
|
79
|
+
"""
|
|
80
|
+
self.__create_pool(host, username, password, port, db, max_connections)
|
|
81
|
+
|
|
82
|
+
@retry.retry(tries=settings.MYSQL_RETRIES, delay=settings.MYSQL_DELAY, logger=logger)
|
|
83
|
+
def __create_pool(self, host: str, username: str, password: str, port: int, db: str, max_connections: int) -> None:
|
|
84
|
+
"""创建数据库连接池,遇到连接失败自动重试。"""
|
|
85
|
+
self.pool = PooledDB(
|
|
86
|
+
creator=pymysql,
|
|
87
|
+
maxconnections=max_connections,
|
|
88
|
+
mincached=1,
|
|
89
|
+
maxcached=max_connections,
|
|
90
|
+
blocking=True,
|
|
91
|
+
maxusage=None,
|
|
92
|
+
setsession=[],
|
|
93
|
+
ping=0,
|
|
94
|
+
host=host,
|
|
95
|
+
user=username,
|
|
96
|
+
password=password,
|
|
97
|
+
db=db,
|
|
98
|
+
port=port,
|
|
99
|
+
charset='utf8',
|
|
100
|
+
# RDS 开了 require_secure_transport=ON,不走 TLS 会被服务端拒掉
|
|
101
|
+
# (error 3159)。证书不校验:连的是内网测试库,没有自带 CA
|
|
102
|
+
ssl={"check_hostname": False, "verify_mode": ssl.CERT_NONE},
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
@contextmanager
|
|
106
|
+
def _cursor(self) -> Any:
|
|
107
|
+
"""
|
|
108
|
+
上下文管理器,获取连接和游标,退出时自动释放资源。
|
|
109
|
+
|
|
110
|
+
出错时先回滚再归还连接,避免未提交的事务状态被下一个取到该连接的人继承。
|
|
111
|
+
|
|
112
|
+
@yield: (connection, cursor) 元组
|
|
113
|
+
"""
|
|
114
|
+
connection = self.pool.connection()
|
|
115
|
+
cursor = connection.cursor(pymysql.cursors.DictCursor)
|
|
116
|
+
try:
|
|
117
|
+
yield connection, cursor
|
|
118
|
+
except Exception:
|
|
119
|
+
try:
|
|
120
|
+
connection.rollback()
|
|
121
|
+
except Exception as e:
|
|
122
|
+
logger.warning(f"回滚失败: {e}")
|
|
123
|
+
raise
|
|
124
|
+
finally:
|
|
125
|
+
cursor.close()
|
|
126
|
+
connection.close()
|
|
127
|
+
|
|
128
|
+
@safe_mysql_call
|
|
129
|
+
def query(self, sql: str, log: bool = True) -> Any:
|
|
130
|
+
"""
|
|
131
|
+
执行查询 SQL,返回结果。单条记录返回 dict,多条返回 list of dict,无结果返回 None。
|
|
132
|
+
|
|
133
|
+
@param sql: str, SQL 查询语句
|
|
134
|
+
@param log: bool, 是否记录日志,默认 True
|
|
135
|
+
@return: dict | list[dict] | None
|
|
136
|
+
"""
|
|
137
|
+
with self._cursor() as (_, cursor):
|
|
138
|
+
cursor.execute(sql)
|
|
139
|
+
if log:
|
|
140
|
+
logger.info(f"执行SQL: {sql}")
|
|
141
|
+
result = cursor.fetchall()
|
|
142
|
+
# 统一返回格式:单条取首元素,空结果返回 None
|
|
143
|
+
if len(result) == 1:
|
|
144
|
+
result = result[0]
|
|
145
|
+
elif len(result) == 0:
|
|
146
|
+
result = None
|
|
147
|
+
if log:
|
|
148
|
+
if isinstance(result, (dict, list)):
|
|
149
|
+
logger.info(f"SQL执行结果: {json.dumps(result, default=MysqlDB.custom_serializer)}")
|
|
150
|
+
else:
|
|
151
|
+
logger.info(f"SQL执行结果: {result}")
|
|
152
|
+
return result
|
|
153
|
+
|
|
154
|
+
@safe_mysql_call
|
|
155
|
+
def insert(self, sql: str, log: bool = True) -> int:
|
|
156
|
+
"""
|
|
157
|
+
执行插入 SQL,返回自增主键 ID。
|
|
158
|
+
|
|
159
|
+
@param sql: str, SQL 插入语句
|
|
160
|
+
@param log: bool, 是否记录日志,默认 True
|
|
161
|
+
@return: int, 插入记录的主键 ID
|
|
162
|
+
"""
|
|
163
|
+
with self._cursor() as (connection, cursor):
|
|
164
|
+
cursor.execute(sql)
|
|
165
|
+
if log:
|
|
166
|
+
logger.info(f"执行SQL: {sql}")
|
|
167
|
+
connection.commit()
|
|
168
|
+
inserted_id = cursor.lastrowid
|
|
169
|
+
if log:
|
|
170
|
+
logger.info(f"插入的记录的主键ID: {inserted_id}")
|
|
171
|
+
return inserted_id
|
|
172
|
+
|
|
173
|
+
@safe_mysql_call
|
|
174
|
+
def execute(self, sql: str, log: bool = True) -> int:
|
|
175
|
+
"""
|
|
176
|
+
执行更新/删除 SQL,返回受影响行数。
|
|
177
|
+
|
|
178
|
+
@param sql: str, SQL 语句
|
|
179
|
+
@param log: bool, 是否记录日志,默认 True
|
|
180
|
+
@return: int, 受影响行数
|
|
181
|
+
"""
|
|
182
|
+
with self._cursor() as (connection, cursor):
|
|
183
|
+
result = cursor.execute(sql)
|
|
184
|
+
if log:
|
|
185
|
+
logger.info(f"执行SQL: {sql}")
|
|
186
|
+
connection.commit()
|
|
187
|
+
if log:
|
|
188
|
+
logger.info(f"SQL执行结果: {result}")
|
|
189
|
+
return result
|
|
190
|
+
|
|
191
|
+
@safe_mysql_call
|
|
192
|
+
def executemany(self, sql: str, data: list[tuple[Any, ...]], log: bool = True) -> None:
|
|
193
|
+
"""
|
|
194
|
+
批量执行 SQL(如批量插入),自动提交事务。
|
|
195
|
+
|
|
196
|
+
@param sql: str, SQL 模板语句
|
|
197
|
+
@param data: list[tuple], 批量参数数据
|
|
198
|
+
@param log: bool, 是否记录日志,默认 True
|
|
199
|
+
"""
|
|
200
|
+
with self._cursor() as (connection, cursor):
|
|
201
|
+
cursor.executemany(sql, data)
|
|
202
|
+
if log:
|
|
203
|
+
logger.info(f"执行SQL: {sql}")
|
|
204
|
+
connection.commit()
|
|
205
|
+
if log:
|
|
206
|
+
logger.info(f"{cursor.rowcount} records inserted.")
|
|
207
|
+
|
|
208
|
+
@staticmethod
|
|
209
|
+
def custom_serializer(obj: Any) -> Any:
|
|
210
|
+
"""
|
|
211
|
+
自定义 JSON 序列化器,处理 datetime、Decimal、bytes 等特殊类型。
|
|
212
|
+
|
|
213
|
+
@param obj: 待序列化的对象
|
|
214
|
+
@return: 可 JSON 序列化的值
|
|
215
|
+
"""
|
|
216
|
+
try:
|
|
217
|
+
if isinstance(obj, datetime):
|
|
218
|
+
return obj.strftime('%Y-%m-%d %H:%M:%S')
|
|
219
|
+
elif isinstance(obj, Decimal):
|
|
220
|
+
return float(obj)
|
|
221
|
+
elif isinstance(obj, bytes):
|
|
222
|
+
return obj.decode(errors='ignore', encoding='utf-8')
|
|
223
|
+
# 不处理的类型:直接返回原对象
|
|
224
|
+
return obj
|
|
225
|
+
except Exception:
|
|
226
|
+
return obj
|
framework/db/redis_db.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Redis 数据库操作模块,提供连接池管理与 String/Hash/List/Queue 等数据结构操作封装。"""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import threading
|
|
5
|
+
import retry
|
|
6
|
+
from redis import Redis, ConnectionPool
|
|
7
|
+
|
|
8
|
+
import framework.settings as settings
|
|
9
|
+
from framework.utils.log_util import logger
|
|
10
|
+
from framework.exceptions import RedisDBError
|
|
11
|
+
from typing import Any, Callable
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class LazyRedisPool:
|
|
15
|
+
"""按名称懒创建 RedisDB,首次访问时建立连接,线程安全。
|
|
16
|
+
|
|
17
|
+
支持两层结构:
|
|
18
|
+
- 外层池:_db_info = {"database": LazyRedisPool, ...},按名称查找返回内层池
|
|
19
|
+
- 内层池:_db_info = {"host": ..., "port": ..., "password": ...}(不含 db),
|
|
20
|
+
__getitem__(index) 返回 RedisDB(**config, db=index)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, db_info: dict):
|
|
24
|
+
"""
|
|
25
|
+
初始化懒加载 Redis 连接池管理器。
|
|
26
|
+
|
|
27
|
+
@param db_info: dict, Redis 连接配置
|
|
28
|
+
"""
|
|
29
|
+
# 过滤掉 "db" 键,传给 RedisDB 时通过 __getitem__ 的 index 参数传入
|
|
30
|
+
self._db_info = {k: v for k, v in db_info.items() if k != "db"}
|
|
31
|
+
self._conns: dict[str | int, "RedisDB"] = {}
|
|
32
|
+
self._lock = threading.Lock()
|
|
33
|
+
|
|
34
|
+
def __getitem__(self, name: str | int) -> "RedisDB":
|
|
35
|
+
"""
|
|
36
|
+
按名称或索引获取连接实例。
|
|
37
|
+
|
|
38
|
+
@param name: str 时查找命名子配置;int 时创建 RedisDB(db=name)
|
|
39
|
+
@return: RedisDB 或 LazyRedisPool 实例
|
|
40
|
+
"""
|
|
41
|
+
if isinstance(name, int):
|
|
42
|
+
# 内层池:用 index 作为 db 参数创建 RedisDB
|
|
43
|
+
if name not in self._conns:
|
|
44
|
+
with self._lock:
|
|
45
|
+
if name not in self._conns:
|
|
46
|
+
self._conns[name] = RedisDB(**self._db_info, db=name)
|
|
47
|
+
return self._conns[name]
|
|
48
|
+
|
|
49
|
+
# 外层池:按名称查找
|
|
50
|
+
entry = self._db_info.get(name)
|
|
51
|
+
if isinstance(entry, LazyRedisPool):
|
|
52
|
+
return entry
|
|
53
|
+
if name not in self._conns:
|
|
54
|
+
with self._lock:
|
|
55
|
+
if name not in self._conns:
|
|
56
|
+
self._conns[name] = RedisDB(**entry or {})
|
|
57
|
+
return self._conns[name]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def safe_redis_call(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
61
|
+
"""装饰器:捕获 Redis 异常并转成 RedisDBError"""
|
|
62
|
+
|
|
63
|
+
def wrapper(self, *args, **kwargs):
|
|
64
|
+
try:
|
|
65
|
+
return func(self, *args, **kwargs)
|
|
66
|
+
except Exception as e:
|
|
67
|
+
raise RedisDBError(f"{func.__name__}: {e}")
|
|
68
|
+
|
|
69
|
+
return wrapper
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class RedisDB:
|
|
73
|
+
"""Redis 数据库操作封装,支持 String / Hash / List 等数据结构操作,异常统一转为 RedisDBError。"""
|
|
74
|
+
|
|
75
|
+
def __init__(self, host: str, port: int, password: str, db: int, max_connections: int | None = None) -> None:
|
|
76
|
+
"""
|
|
77
|
+
初始化 RedisDB,创建连接池并测试连通性。
|
|
78
|
+
|
|
79
|
+
@param host: str, Redis 主机地址
|
|
80
|
+
@param port: int, 端口号
|
|
81
|
+
@param password: str, 密码
|
|
82
|
+
@param db: int, 数据库编号
|
|
83
|
+
@param max_connections: int, 最大连接数,默认从 settings 获取
|
|
84
|
+
"""
|
|
85
|
+
self.db = db
|
|
86
|
+
self.conn = self.__connect(host, port, password, db, max_connections or settings.REDIS_MAX_CONNECTIONS)
|
|
87
|
+
|
|
88
|
+
@retry.retry(tries=settings.REDIS_RETRIES, delay=settings.REDIS_DELAY, logger=logger)
|
|
89
|
+
def __connect(self, host: str, port: int, password: str, db: int, max_connections: int) -> Redis:
|
|
90
|
+
"""建立 Redis 连接池并测试连接,失败自动重试。"""
|
|
91
|
+
pool = ConnectionPool(
|
|
92
|
+
host=host,
|
|
93
|
+
port=port,
|
|
94
|
+
password=password,
|
|
95
|
+
db=db,
|
|
96
|
+
decode_responses=False,
|
|
97
|
+
max_connections=max_connections,
|
|
98
|
+
)
|
|
99
|
+
conn = Redis(connection_pool=pool)
|
|
100
|
+
conn.ping()
|
|
101
|
+
return conn
|
|
102
|
+
|
|
103
|
+
# -------------------- string --------------------
|
|
104
|
+
@safe_redis_call
|
|
105
|
+
def set_string(self, name: str, value: Any, ex: int | None = None, log: bool = True) -> bool:
|
|
106
|
+
"""
|
|
107
|
+
设置字符串类型键值。
|
|
108
|
+
|
|
109
|
+
@param name: str, 键名
|
|
110
|
+
@param value: 值
|
|
111
|
+
@param ex: int | None, 过期时间(秒)
|
|
112
|
+
@param log: bool, 是否记录日志,默认 True
|
|
113
|
+
@return: bool
|
|
114
|
+
"""
|
|
115
|
+
res = self.conn.set(name, value, ex=ex)
|
|
116
|
+
if log:
|
|
117
|
+
logger.info(f"set {name}={value}, ex={ex} -> {res}")
|
|
118
|
+
return res
|
|
119
|
+
|
|
120
|
+
@safe_redis_call
|
|
121
|
+
def get_string(self, name: str, log: bool = True) -> bytes | None:
|
|
122
|
+
"""
|
|
123
|
+
获取字符串类型值。
|
|
124
|
+
|
|
125
|
+
@param name: str, 键名
|
|
126
|
+
@param log: bool, 是否记录日志,默认 True
|
|
127
|
+
@return: bytes | None
|
|
128
|
+
"""
|
|
129
|
+
if log:
|
|
130
|
+
logger.info(f"get {name}")
|
|
131
|
+
return self.conn.get(name)
|
|
132
|
+
|
|
133
|
+
# -------------------- hash --------------------
|
|
134
|
+
@safe_redis_call
|
|
135
|
+
def set_hash(self, name: str, mapping: dict[str, Any], log: bool = True) -> int:
|
|
136
|
+
"""
|
|
137
|
+
设置 Hash 类型字段映射。
|
|
138
|
+
|
|
139
|
+
@param name: str, 键名
|
|
140
|
+
@param mapping: dict, 字段映射
|
|
141
|
+
@param log: bool, 是否记录日志,默认 True
|
|
142
|
+
@return: int, 新增字段数
|
|
143
|
+
"""
|
|
144
|
+
res = self.conn.hset(name, mapping=mapping)
|
|
145
|
+
if log:
|
|
146
|
+
logger.info(f"hset {name} {mapping} -> {res}")
|
|
147
|
+
return res
|
|
148
|
+
|
|
149
|
+
@safe_redis_call
|
|
150
|
+
def get_hash(self, name: str, log: bool = True) -> dict[str, Any]:
|
|
151
|
+
"""
|
|
152
|
+
获取 Hash 类型所有字段和值。
|
|
153
|
+
|
|
154
|
+
@param name: str, 键名
|
|
155
|
+
@param log: bool, 是否记录日志,默认 True
|
|
156
|
+
@return: dict
|
|
157
|
+
"""
|
|
158
|
+
if log:
|
|
159
|
+
logger.info(f"hgetall {name}")
|
|
160
|
+
return self.conn.hgetall(name)
|
|
161
|
+
|
|
162
|
+
# -------------------- list --------------------
|
|
163
|
+
@safe_redis_call
|
|
164
|
+
def set_list(self, name: str, value: Any, log: bool = True) -> int:
|
|
165
|
+
"""
|
|
166
|
+
向列表头部(左侧)推入元素。支持 dict/list/str/int/None 类型自动序列化。
|
|
167
|
+
|
|
168
|
+
@param name: str, 键名
|
|
169
|
+
@param value: 值,支持 dict/list/str/int/None
|
|
170
|
+
@param log: bool, 是否记录日志,默认 True
|
|
171
|
+
@return: int, 列表长度
|
|
172
|
+
"""
|
|
173
|
+
# 将 None 转为 JSON 字符串 "null" 存储
|
|
174
|
+
if value is None:
|
|
175
|
+
return self.conn.lpush(name, json.dumps(None))
|
|
176
|
+
|
|
177
|
+
# 统一将各类类型转为 JSON 字符串列表
|
|
178
|
+
if isinstance(value, dict):
|
|
179
|
+
value = [json.dumps(value, ensure_ascii=False)]
|
|
180
|
+
elif isinstance(value, list):
|
|
181
|
+
value = [json.dumps(item, ensure_ascii=False) for item in value]
|
|
182
|
+
else:
|
|
183
|
+
value = [str(value)]
|
|
184
|
+
|
|
185
|
+
res = self.conn.lpush(name, *value)
|
|
186
|
+
if log:
|
|
187
|
+
logger.info(f"lpush {name} {value} -> {res}")
|
|
188
|
+
return res
|
|
189
|
+
|
|
190
|
+
@safe_redis_call
|
|
191
|
+
def get_list(self, name: str) -> list[Any]:
|
|
192
|
+
"""
|
|
193
|
+
获取列表所有元素,自动 JSON 反序列化。
|
|
194
|
+
|
|
195
|
+
@param name: str, 键名
|
|
196
|
+
@return: list, 反序列化后的元素列表
|
|
197
|
+
"""
|
|
198
|
+
res = self.conn.lrange(name, 0, -1)
|
|
199
|
+
return [json.loads(item) for item in res] if res else []
|
|
200
|
+
|
|
201
|
+
@safe_redis_call
|
|
202
|
+
def lpop_all(self, name: str) -> list[bytes]:
|
|
203
|
+
"""
|
|
204
|
+
从左到右弹出队列中所有元素(会清空队列)。
|
|
205
|
+
|
|
206
|
+
@param name: str, 键名
|
|
207
|
+
@return: list[bytes]
|
|
208
|
+
"""
|
|
209
|
+
items = []
|
|
210
|
+
while True:
|
|
211
|
+
val = self.conn.lpop(name)
|
|
212
|
+
if val is None:
|
|
213
|
+
break
|
|
214
|
+
items.append(val)
|
|
215
|
+
return items
|
|
216
|
+
|
|
217
|
+
@safe_redis_call
|
|
218
|
+
def lrange_all(self, name: str) -> list[bytes]:
|
|
219
|
+
"""
|
|
220
|
+
获取队列中所有元素(不会清空队列)。
|
|
221
|
+
|
|
222
|
+
@param name: str, 键名
|
|
223
|
+
@return: list[bytes]
|
|
224
|
+
"""
|
|
225
|
+
res = self.conn.lrange(name, 0, -1)
|
|
226
|
+
return res if res else []
|
|
227
|
+
|
|
228
|
+
# -------------------- meta --------------------
|
|
229
|
+
@safe_redis_call
|
|
230
|
+
def set_ttl(self, name: str, ttl: int, log: bool = True) -> bool:
|
|
231
|
+
"""
|
|
232
|
+
设置键的过期时间。
|
|
233
|
+
|
|
234
|
+
@param name: str, 键名
|
|
235
|
+
@param ttl: int, 过期时间(秒)
|
|
236
|
+
@param log: bool, 是否记录日志,默认 True
|
|
237
|
+
@return: bool
|
|
238
|
+
"""
|
|
239
|
+
res = self.conn.expire(name, ttl)
|
|
240
|
+
if log:
|
|
241
|
+
logger.info(f"expire {name} {ttl} -> {res}")
|
|
242
|
+
return res
|
|
243
|
+
|
|
244
|
+
@safe_redis_call
|
|
245
|
+
def get_ttl(self, name: str, log: bool = True) -> int:
|
|
246
|
+
"""
|
|
247
|
+
获取键的剩余过期时间。
|
|
248
|
+
|
|
249
|
+
@param name: str, 键名
|
|
250
|
+
@param log: bool, 是否记录日志,默认 True
|
|
251
|
+
@return: int, 剩余秒数,-1 表示永不过期,-2 表示键不存在
|
|
252
|
+
"""
|
|
253
|
+
ttl = self.conn.ttl(name)
|
|
254
|
+
if log:
|
|
255
|
+
logger.info(f"ttl {name} -> {ttl}")
|
|
256
|
+
return ttl
|
|
257
|
+
|
|
258
|
+
@safe_redis_call
|
|
259
|
+
def exists(self, name: str) -> int:
|
|
260
|
+
"""
|
|
261
|
+
检查键是否存在。
|
|
262
|
+
|
|
263
|
+
@param name: str, 键名
|
|
264
|
+
@return: int, 存在返回 1,不存在返回 0
|
|
265
|
+
"""
|
|
266
|
+
return self.conn.exists(name)
|
|
267
|
+
|
|
268
|
+
@safe_redis_call
|
|
269
|
+
def delete(self, name: str) -> int:
|
|
270
|
+
"""
|
|
271
|
+
删除键。
|
|
272
|
+
|
|
273
|
+
@param name: str, 键名
|
|
274
|
+
@return: int, 被删除的键数量
|
|
275
|
+
"""
|
|
276
|
+
return self.conn.delete(name)
|
|
277
|
+
|
|
278
|
+
# -------------------- queue --------------------
|
|
279
|
+
@safe_redis_call
|
|
280
|
+
def lpush(self, name: str, *values: Any) -> int:
|
|
281
|
+
"""
|
|
282
|
+
从左侧推入一个或多个值到队列。
|
|
283
|
+
|
|
284
|
+
@param name: str, 键名
|
|
285
|
+
@param values: 一个或多个要推入的值
|
|
286
|
+
@return: int, 队列长度
|
|
287
|
+
"""
|
|
288
|
+
return self.conn.lpush(name, *values)
|
|
289
|
+
|
|
290
|
+
@safe_redis_call
|
|
291
|
+
def rpush(self, name: str, *values: Any) -> int:
|
|
292
|
+
"""
|
|
293
|
+
从右侧推入一个或多个值到队列。
|
|
294
|
+
|
|
295
|
+
@param name: str, 键名
|
|
296
|
+
@param values: 一个或多个要推入的值
|
|
297
|
+
@return: int, 队列长度
|
|
298
|
+
"""
|
|
299
|
+
return self.conn.rpush(name, *values)
|
|
300
|
+
|
|
301
|
+
@safe_redis_call
|
|
302
|
+
def lpop(self, name: str) -> bytes | None:
|
|
303
|
+
"""
|
|
304
|
+
从左侧弹出一个元素。
|
|
305
|
+
|
|
306
|
+
@param name: str, 键名
|
|
307
|
+
@return: bytes | None
|
|
308
|
+
"""
|
|
309
|
+
return self.conn.lpop(name)
|
|
310
|
+
|
|
311
|
+
@safe_redis_call
|
|
312
|
+
def rpop(self, name: str) -> bytes | None:
|
|
313
|
+
"""
|
|
314
|
+
从右侧弹出一个元素。
|
|
315
|
+
|
|
316
|
+
@param name: str, 键名
|
|
317
|
+
@return: bytes | None
|
|
318
|
+
"""
|
|
319
|
+
return self.conn.rpop(name)
|
framework/exceptions.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""
|
|
2
|
+
框架自定义异常定义模块。
|
|
3
|
+
|
|
4
|
+
定义测试框架中使用的各种自定义异常类,用于区分不同类型的运行时错误。
|
|
5
|
+
"""
|
|
6
|
+
class LoginException(Exception):
|
|
7
|
+
"""登录异常,在用户认证/登录流程失败时抛出。"""
|
|
8
|
+
...
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class MysqlDBError(Exception):
|
|
12
|
+
"""MySQL 数据库操作异常,在数据库连接或查询失败时抛出。"""
|
|
13
|
+
...
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class RedisDBError(Exception):
|
|
17
|
+
"""Redis 缓存操作异常,在 Redis 连接或缓存操作失败时抛出。"""
|
|
18
|
+
...
|
|
19
|
+
|
|
20
|
+
class MQError(Exception):
|
|
21
|
+
"""消息队列操作异常,在 MQ 连接或消息收发失败时抛出。"""
|
|
22
|
+
...
|
framework/exit_code.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""
|
|
2
|
+
框架退出码定义模块。
|
|
3
|
+
|
|
4
|
+
定义 pytest 测试框架的自定义退出码枚举,用于标识测试执行过程中的特定错误类型。
|
|
5
|
+
"""
|
|
6
|
+
from enum import Enum, unique
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@unique
|
|
10
|
+
class ExitCode(Enum):
|
|
11
|
+
"""pytest 自定义退出码枚举。
|
|
12
|
+
|
|
13
|
+
用于在测试执行过程中以退出码方式标识框架级别的错误状态,
|
|
14
|
+
方便 CI/CD 集成时快速识别错误类型。
|
|
15
|
+
|
|
16
|
+
@param ENV_NOT_EXIST: 测试环境不存在(10001)
|
|
17
|
+
@param APP_NOT_EXIST: 测试系统/应用不存在(10002)
|
|
18
|
+
"""
|
|
19
|
+
ENV_NOT_EXIST = 10001 # 测试环境不存在
|
|
20
|
+
APP_NOT_EXIST = 10002 # 测试系统不存在
|