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
framework/ws_server.py ADDED
@@ -0,0 +1,167 @@
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ import random
5
+ import string
6
+ from datetime import datetime
7
+ from urllib.parse import parse_qs, urlparse
8
+
9
+ import websockets
10
+ from websockets.asyncio.server import serve
11
+ from websockets.exceptions import ConnectionClosed
12
+
13
+ logging.basicConfig(
14
+ level=logging.INFO,
15
+ format="[%(asctime)s] %(message)s",
16
+ datefmt="%Y-%m-%d %H:%M:%S",
17
+ )
18
+ logger = logging.getLogger("ws_server")
19
+
20
+ # 固定鉴权凭据
21
+ FIXED_USERNAME = "admin"
22
+ FIXED_PASSWORD = "123456"
23
+ FIXED_TOKEN = "my-secret-token"
24
+
25
+
26
+ def extract_path_and_params(path):
27
+ """从请求路径中提取 path 和查询参数。"""
28
+ parsed = urlparse(path)
29
+ return parsed.path, parse_qs(parsed.query)
30
+
31
+
32
+ # --- 接口1: 用户名密码鉴权(首条消息携带凭据,连接先建立)---
33
+ async def handle_password_auth(websocket):
34
+ addr = websocket.remote_address
35
+ logger.info("[password-auth] connection open from %s", addr)
36
+
37
+ try:
38
+ first_msg = await websocket.recv()
39
+ logger.info("[password-auth] recv: %s", first_msg)
40
+ except ConnectionClosed:
41
+ logger.info("[password-auth] connection closed before auth from %s", addr)
42
+ return
43
+
44
+ try:
45
+ data = json.loads(first_msg)
46
+ username = data.get("username")
47
+ password = data.get("password")
48
+ except (json.JSONDecodeError, TypeError):
49
+ logger.warning("[password-auth] invalid message format from %s", addr)
50
+ await websocket.close(1008, "Authentication failed: invalid message format")
51
+ return
52
+
53
+ if username != FIXED_USERNAME or password != FIXED_PASSWORD:
54
+ logger.warning("[password-auth] auth failed for user=%s from %s", username, addr)
55
+ await websocket.close(1008, "Authentication failed: invalid username or password")
56
+ return
57
+
58
+ logger.info("[password-auth] auth success for user=%s from %s", username, addr)
59
+ await websocket.send(first_msg)
60
+ logger.info("[password-auth] send: %s", first_msg)
61
+ async for message in websocket:
62
+ logger.info("[password-auth] recv: %s", message)
63
+ await websocket.send(message)
64
+ logger.info("[password-auth] send: %s", message)
65
+ logger.info("[password-auth] connection closed from %s", addr)
66
+
67
+
68
+ # --- 接口2: Token 鉴权 ---
69
+ async def handle_token_auth(websocket):
70
+ addr = websocket.remote_address
71
+ logger.info("[token-auth] connection open from %s", addr)
72
+
73
+ auth_header = websocket.request.headers.get("Authorization", "")
74
+
75
+ if not auth_header.startswith("Bearer ") or auth_header[7:] != FIXED_TOKEN:
76
+ logger.warning("[token-auth] auth failed from %s", addr)
77
+ await websocket.close(1008, "Authentication failed: invalid token")
78
+ return
79
+
80
+ logger.info("[token-auth] auth success from %s", addr)
81
+ async for message in websocket:
82
+ logger.info("[token-auth] recv: %s", message)
83
+ await websocket.send(message)
84
+ logger.info("[token-auth] send: %s", message)
85
+ logger.info("[token-auth] connection closed from %s", addr)
86
+
87
+
88
+ # --- 接口3: 地址参数 Token 鉴权(每秒推送一条带时间戳的随机消息)---
89
+ async def handle_query_token_auth(websocket):
90
+ addr = websocket.remote_address
91
+ logger.info("[query-token-auth] connection open from %s", addr)
92
+
93
+ path = websocket.request.path if hasattr(websocket.request, 'path') else websocket.path
94
+ _, params = extract_path_and_params(path)
95
+
96
+ token_list = params.get("token", [])
97
+ token = token_list[0] if token_list else None
98
+
99
+ if token != FIXED_TOKEN:
100
+ logger.warning("[query-token-auth] auth failed from %s", addr)
101
+ await websocket.close(1008, "Authentication failed: invalid token")
102
+ return
103
+
104
+ logger.info("[query-token-auth] auth success from %s", addr)
105
+
106
+ cancel = asyncio.Event()
107
+
108
+ async def push_loop():
109
+ while not cancel.is_set():
110
+ msg = {
111
+ "timestamp": datetime.now().isoformat(),
112
+ "value": random.randint(1, 1000),
113
+ "text": "".join(random.choices(string.ascii_letters, k=8)),
114
+ }
115
+ logger.info("[query-token-auth] send: %s", json.dumps(msg, ensure_ascii=False))
116
+ try:
117
+ await websocket.send(json.dumps(msg, ensure_ascii=False))
118
+ except ConnectionClosed:
119
+ break
120
+ await asyncio.sleep(1)
121
+
122
+ task = asyncio.create_task(push_loop())
123
+
124
+ try:
125
+ async for message in websocket:
126
+ logger.info("[query-token-auth] recv: %s", message)
127
+ except ConnectionClosed:
128
+ pass
129
+ finally:
130
+ cancel.set()
131
+ task.cancel()
132
+ try:
133
+ await task
134
+ except asyncio.CancelledError:
135
+ pass
136
+
137
+ logger.info("[query-token-auth] connection closed from %s", addr)
138
+
139
+
140
+ # --- 路由分发 ---
141
+ async def router(websocket):
142
+ path = websocket.request.path if hasattr(websocket.request, 'path') else websocket.path
143
+ clean_path = urlparse(path).path
144
+
145
+ if clean_path == "/ws/password":
146
+ await handle_password_auth(websocket)
147
+ elif clean_path == "/ws/token":
148
+ await handle_token_auth(websocket)
149
+ elif clean_path == "/ws/query-token":
150
+ await handle_query_token_auth(websocket)
151
+ else:
152
+ logger.warning("unknown endpoint: %s from %s", clean_path, websocket.remote_address)
153
+ await websocket.close(1008, "Unknown endpoint")
154
+ return
155
+
156
+
157
+ async def main():
158
+ async with serve(router, "0.0.0.0", 8765, ping_interval=10, ping_timeout=10) as server:
159
+ logger.info("WebSocket server started on ws://0.0.0.0:8765")
160
+ logger.info(" Password auth: ws://0.0.0.0:8765/ws/password (首条消息发送 JSON: {\"username\":\"admin\",\"password\":\"123456\"})")
161
+ logger.info(" Token auth: ws://0.0.0.0:8765/ws/token (Header: Authorization: Bearer my-secret-token)")
162
+ logger.info(" Query token: ws://0.0.0.0:8765/ws/query-token?token=my-secret-token")
163
+ await server.serve_forever()
164
+
165
+
166
+ if __name__ == "__main__":
167
+ asyncio.run(main())
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytest-api-framework-alpha
3
+ Version: 1.0.5
4
+ Summary: 基于 pytest 的 API 自动化测试框架,YAML 驱动,集成 Allure 报告
5
+ Author: alpha
6
+ Author-email:
7
+ License: MIT
8
+ Classifier: Framework :: Pytest
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Topic :: Software Development :: Testing
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: allure-pytest==2.13.1
19
+ Requires-Dist: allure-python-commons==2.13.1
20
+ Requires-Dist: cn2an==0.5.19
21
+ Requires-Dist: DBUtils==3.1.0
22
+ Requires-Dist: Faker==40.23.0
23
+ Requires-Dist: jsonpath==0.82
24
+ Requires-Dist: pytest==7.2.2
25
+ Requires-Dist: PyYAML==6.0.1
26
+ Requires-Dist: python-box==7.2.0
27
+ Requires-Dist: pycryptodome==3.21.0
28
+ Requires-Dist: pycognito==2024.5.1
29
+ Requires-Dist: pyotp==2.9.0
30
+ Requires-Dist: PyMySQL==1.1.0
31
+ Requires-Dist: redis==3.5.3
32
+ Requires-Dist: requests==2.25.1
33
+ Requires-Dist: requests-toolbelt==1.0.0
34
+ Requires-Dist: retry==0.9.2
35
+ Requires-Dist: simplejson==3.20.1
36
+ Requires-Dist: websocket-client==1.9.0
37
+ Requires-Dist: python-dotenv==1.0.1
38
+ Requires-Dist: pytest-order==1.3.0
39
+ Requires-Dist: dill==0.3.8
40
+ Requires-Dist: pika==1.4.1
41
+ Requires-Dist: websockets==15.0
42
+ Dynamic: author
43
+ Dynamic: classifier
44
+ Dynamic: description
45
+ Dynamic: description-content-type
46
+ Dynamic: license
47
+ Dynamic: license-file
48
+ Dynamic: requires-dist
49
+ Dynamic: requires-python
50
+ Dynamic: summary
51
+
52
+ # pytest-api-framework-alpha
53
+
54
+ 基于 pytest 的 API 自动化测试框架,用 YAML 描述测试数据,自动生成 Allure 报告。
55
+
56
+ ## 安装
57
+
58
+ ```bash
59
+ pip install pytest-api-framework-alpha
60
+ ```
61
+
62
+ 要求 Python >= 3.6。
63
+
64
+ ## 主要能力
65
+
66
+ - **YAML 驱动**:测试数据与用例代码分离,支持变量提取、引用与动态渲染
67
+ - **多协议客户端**:HTTP、WebSocket、消息队列(RabbitMQ)
68
+ - **数据层支持**:MySQL(连接池)、Redis
69
+ - **断言**:常规断言,以及面向异步场景的重试断言(`eventually`)和 Webhook 断言
70
+ - **鉴权**:内置 AWS Cognito 登录流程封装,支持 token 过期自动重新登录
71
+ - **报告**:集成 Allure,测试结束后可自动打开报告
72
+ - **脚手架**:一条命令生成新应用的配置、用例和测试数据目录结构
73
+
74
+ ## 快速开始
75
+
76
+ 生成一个新应用的目录骨架:
77
+
78
+ ```bash
79
+ python -m framework.gen.create_app --app myapp --env dev
80
+ ```
81
+
82
+ 这会创建配置文件 `config/myapp/context.dev.yaml`,以及对应的用例和测试数据目录。
83
+ 在配置文件里填入目标环境的域名和账号信息后即可开始编写用例。
84
+
85
+ ## 配置
86
+
87
+ 框架的行为开关集中在 `framework/settings.py`,包括 Allure 输出路径、用例级别定义、
88
+ 异步断言超时、MySQL 连接池参数等。环境相关的域名、账号、数据库连接信息则放在
89
+ 使用方项目的 `config/` 目录下,按环境分文件(`context.{env}.yaml`、`database.{env}.yaml`)。
90
+
91
+ ## 基类
92
+
93
+ - `framework.core.base_class.BaseTestCase` —— pytest 用例基类
94
+ - `framework.script.BaseScript` —— 非 pytest 场景(独立脚本)的基类,子类实现 `run()` 方法
95
+
96
+ ## License
97
+
98
+ 见 LICENSE 文件。
@@ -0,0 +1,48 @@
1
+ framework/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
2
+ framework/conftest.py,sha256=EYGyqPpFoynBBaLe1jFjbsc2CtQZqTeYeum3R6J0bXc,22567
3
+ framework/exceptions.py,sha256=V-7VW3a1FWvkRKItftBqP2a1isdGuFTJbIzX8NS6RmI,635
4
+ framework/exit_code.py,sha256=N_5GqxEErdUXvtRWzUrkYsBwN3VwUP05BviU67OE_KU,658
5
+ framework/report.py,sha256=viSUI4PVoODb19DTMhcGqOOPQA5mhD6Kt7ci1ytSoJg,5013
6
+ framework/script.py,sha256=ICq0vr7pTPcJJExmj_9AssTBnn3PQohd_Tcnbk4iXvw,1078
7
+ framework/settings.py,sha256=LtTCrQhIbMV7F3Fe5OYb0AHrQB36oI0oFnfH5ofCAaM,4761
8
+ framework/ws_server.py,sha256=qV4pH0gYjBZ9u2ajBwuTxpGKfsPiqso0aZmUX7wIDXc,5979
9
+ framework/assertion/__init__.py,sha256=yZIhG_kUYTa3z2WNtIxopBmxrH1ZROnY5ZVyTxqjEcU,69
10
+ framework/assertion/retry_assert.py,sha256=9VAOzGiIspudopCUv8Kj0cjLl3NtvgFu23XD3Pvmimc,2370
11
+ framework/assertion/webhook_assert.py,sha256=6Q6gAI4TM4xeYUgPEQD2MoL7pVbj7-8iwxPOdi-gY4c,5111
12
+ framework/client/__init__.py,sha256=0xEStW9RV_kdfHnXoIadLQcmAT0-R4j-piTuyq_XxtQ,65
13
+ framework/client/crrm_client.py,sha256=wLO4_AQEnMKLQcrRbREJAl3amR8Sa1-bfJL_nIZSwqk,6891
14
+ framework/client/http_client.py,sha256=7vOq9mUXRv1AopB0hm5nI_INzaYfXlnddb4jNKULov0,14567
15
+ framework/client/mq_client.py,sha256=2zq_54AeuwnnvZGeghNMhzBQ3TAMb4eQ5uBFP_8Uxnk,7495
16
+ framework/client/websocket_client.py,sha256=rtxDdAXXUJmmo8pgnxy9BMr-r78a2EHvZJsx2EgXSdk,16037
17
+ framework/core/__init__.py,sha256=jZSTdPcx_GJY7fW0XcY9RXPKH1fd1xGPulE51qwLyTA,122
18
+ framework/core/base_class.py,sha256=udq-sWsZmyl-Q5iItYZau1dcdWrb_BfBtB8oxXflPB8,38555
19
+ framework/core/extract.py,sha256=2lH1Mdt69rTk7h37odxoXS7AqrA4gNwFBih7aa48m8c,6848
20
+ framework/core/global_attribute.py,sha256=eNwkPNVgil9CSp_ujV66kDQ9KM2CgMKOzxer1DlzssM,5654
21
+ framework/core/models.py,sha256=cqSB6vD5MK6z-dM33n-yZuYChq1oaWdZ2GetBe8XyqE,2604
22
+ framework/core/render_data.py,sha256=odZ3l40w7KTs9pVrVRR0L7pnLFmx85bS4d0S-8IFInI,12313
23
+ framework/core/validate.py,sha256=XcEIaDPbVmtaLt5HK8L5vTvV4Y0JXox4AmKHbzThiYE,23456
24
+ framework/core/hooks/__init__.py,sha256=-ZenVZ92SajbfQDR0OQqVy_kMZDVtQFGnVKzIQndWro,122
25
+ framework/core/hooks/filters.py,sha256=RYseGV7hZj_ufqpv3sopv8oAjuoDlKBDOnkTvnIZpQY,7950
26
+ framework/core/hooks/reporter.py,sha256=96ijeS58iSaDpl44pYRTUFTu2tciJDolfP2-JmJk-kk,8456
27
+ framework/core/hooks/session.py,sha256=Li1TRSctD0Zvt_vYScJVkOird6oqR48BxVvNsscKAew,13470
28
+ framework/core/hooks/sorting.py,sha256=AIJGGAWNcToQm4zfwBzE9z4k-i4iCxGrJlnVaX_pA64,3009
29
+ framework/db/__init__.py,sha256=XyOAxubiGzf8W63mEsi4m-gvk6eMwEJ5tuA1qJ0uH2U,86
30
+ framework/db/mysql_db.py,sha256=Ams360qd6cfWiSonCodAgZ3k0cumDX7HWKF2zEOUkbI,8091
31
+ framework/db/redis_db.py,sha256=BtyjJdjwEQyUE42HJNQeicl-Xxukw7UYF6JB33qRQ0Q,10326
32
+ framework/gen/__init__.py,sha256=qq5Y0UNgEqvHtPxW_A9qd-_bKQ2d6rSMnLZZj8k8GMk,113
33
+ framework/gen/case_gen.py,sha256=yvpHCUmBDlSbIL0M5IXS2Yp9a1_C1lMWMHcHOkOjvrk,56368
34
+ framework/gen/create_app.py,sha256=8mBWua13K-WUV32owVkoac0gpXmd07lP4mLx1e5iRDU,9011
35
+ framework/utils/__init__.py,sha256=F41QjWLrFUeOUmu-vrYy9DrBYd9ZCapPsbfgLXHczJw,106
36
+ framework/utils/cognito_util.py,sha256=ckJN740e51gU7674hjOopcTH39OKc_9AX-ssnc3rbKk,18616
37
+ framework/utils/common.py,sha256=NUAx8et2hT-NCFch853jD_g4akwdVI0LpzXA9fiVEGk,8849
38
+ framework/utils/date_util.py,sha256=0NZWRaRW3s54Xgq19jG2qMXhJsgOjDVI7kpjX3iHcDQ,8266
39
+ framework/utils/encrypt.py,sha256=RaRx5GihPkFRLxiVzaPg9Jhq19q-_dIIGlUpnqrovcE,17337
40
+ framework/utils/lark_util.py,sha256=y5RQ9hOowfOIPMe7w1UybD2dWyhCX5YMibZPwIsYKoo,5956
41
+ framework/utils/log_util.py,sha256=zXllJYFaiIxva9ui7RorNlZ7xeLiiwGGfFSVylMDOZc,230
42
+ framework/utils/mock_util.py,sha256=VRFNYFbOvPrMbsI2-IXEtngRYslbyva0rA1YoPqkGAA,7646
43
+ framework/utils/yaml_util.py,sha256=YhcltqX9Sh2C1zQDzTCb2VuX3ZepXGvYkrq-rU12JjU,6288
44
+ pytest_api_framework_alpha-1.0.5.dist-info/licenses/LICENSE,sha256=Gt2HldQ2so30A3xu6l8H8B6S_uCZIW6o6I9x7jZ1sno,1062
45
+ pytest_api_framework_alpha-1.0.5.dist-info/METADATA,sha256=pL3hBoVO-qlB9wSgstzDCSVTxrZzKfDLJ1dT6EaB_Dg,3319
46
+ pytest_api_framework_alpha-1.0.5.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
47
+ pytest_api_framework_alpha-1.0.5.dist-info/top_level.txt,sha256=hzpv2xEeSkKTVweFn8I8XnG5zJJOIOTB38-_zgJJSUw,10
48
+ pytest_api_framework_alpha-1.0.5.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 alpha
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ framework