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,1268 @@
|
|
|
1
|
+
"""根据 OpenAPI / Swagger 规范自动生成 YAML 测试用例骨架及 Python 测试脚本的模块。"""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import re
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from urllib.parse import unquote
|
|
9
|
+
import urllib.request
|
|
10
|
+
import ssl
|
|
11
|
+
|
|
12
|
+
from framework.settings import DEL_FLAG, DATA_DIR, CASES_DIR
|
|
13
|
+
|
|
14
|
+
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# ---------------------------------------------------------------------------
|
|
19
|
+
# Helpers
|
|
20
|
+
# ---------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
def camel_to_snake(name: str) -> str:
|
|
23
|
+
"""将驼峰命名转为蛇形命名(如:TestName -> test_name)。"""
|
|
24
|
+
s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', name)
|
|
25
|
+
s2 = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
|
|
26
|
+
return re.sub(r'_+', '_', s2).strip('_')
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def snake_to_pascal(name: str) -> str:
|
|
30
|
+
"""将蛇形命名转为帕斯卡命名(如:test_name -> TestName)。"""
|
|
31
|
+
return ''.join(w.capitalize() for w in name.split('_'))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def tag_to_module(tag: str) -> str:
|
|
35
|
+
"""取第二个及之后的全部 tag 段落作为目录层级,下划线拼接。跳过首层。"""
|
|
36
|
+
parts = tag.split('/')[1:]
|
|
37
|
+
result = []
|
|
38
|
+
for part in parts:
|
|
39
|
+
words = re.split(r'[\s_]+', part.strip())
|
|
40
|
+
converted = '_'.join(w.lower() for w in words if w)
|
|
41
|
+
if converted:
|
|
42
|
+
result.append(converted)
|
|
43
|
+
return '/'.join(result) if result else '_'.join(w.lower() for w in re.split(r'[\s_]+', tag.split('/')[0].strip()) if w)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def tag_to_yaml_module(tag: str) -> str:
|
|
47
|
+
"""取第二个 tag 段落作为 YAML module 字段值。"""
|
|
48
|
+
parts = tag.split('/')
|
|
49
|
+
idx = 1 if len(parts) > 1 else 0
|
|
50
|
+
part = parts[idx]
|
|
51
|
+
words = re.split(r'[\s_]+', part.strip())
|
|
52
|
+
return '_'.join(w.lower() for w in words if w)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def tag_to_marks(tag: str) -> list[str]:
|
|
56
|
+
"""取第三个及之后的 tag 段落作为 marks,下划线拼接。"""
|
|
57
|
+
parts = tag.split('/')[2:]
|
|
58
|
+
marks = []
|
|
59
|
+
for part in parts:
|
|
60
|
+
words = re.split(r'[\s_]+', part.strip())
|
|
61
|
+
converted = '_'.join(w.lower() for w in words if w)
|
|
62
|
+
if converted:
|
|
63
|
+
marks.append(converted)
|
|
64
|
+
return marks
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def resolve_ref(ref: str, spec: dict) -> dict:
|
|
68
|
+
"""根据 JSON 引用路径(如 #/components/schemas/User)从规范字典中查找定义。"""
|
|
69
|
+
parts = ref.lstrip('#/').split('/')
|
|
70
|
+
node = spec
|
|
71
|
+
for p in parts:
|
|
72
|
+
node = node.get(unquote(p), {})
|
|
73
|
+
return node
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def resolve_schema(schema: dict, spec: dict) -> dict:
|
|
77
|
+
"""递归解析 schema,消除 $ref 引用,并合并 Apifox 扩展引用。"""
|
|
78
|
+
while '$ref' in schema:
|
|
79
|
+
ref_result = resolve_ref(schema['$ref'], spec)
|
|
80
|
+
if ref_result:
|
|
81
|
+
schema = ref_result
|
|
82
|
+
else:
|
|
83
|
+
schema = {k: v for k, v in schema.items() if k != '$ref'}
|
|
84
|
+
return _merge_apifox_refs(schema, spec)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _merge_apifox_refs(schema: dict, spec: dict) -> dict:
|
|
88
|
+
"""Merge Apifox x-apifox-refs into standard properties/required."""
|
|
89
|
+
apifox_refs = schema.get('x-apifox-refs', {})
|
|
90
|
+
if not apifox_refs:
|
|
91
|
+
return schema
|
|
92
|
+
props = dict(schema.get('properties', {}))
|
|
93
|
+
required = list(schema.get('required', []))
|
|
94
|
+
for ref_entry in apifox_refs.values():
|
|
95
|
+
ref_path = ref_entry.get('$ref')
|
|
96
|
+
if not ref_path:
|
|
97
|
+
continue
|
|
98
|
+
overrides = ref_entry.get('x-apifox-overrides', {})
|
|
99
|
+
ref_schema = resolve_ref(ref_path, spec)
|
|
100
|
+
for field, field_schema in ref_schema.get('properties', {}).items():
|
|
101
|
+
if field in overrides and overrides[field] is None:
|
|
102
|
+
continue
|
|
103
|
+
if field not in props:
|
|
104
|
+
props[field] = field_schema
|
|
105
|
+
for field in ref_schema.get('required', []):
|
|
106
|
+
if field in overrides and overrides[field] is None:
|
|
107
|
+
continue
|
|
108
|
+
if field not in required:
|
|
109
|
+
required.append(field)
|
|
110
|
+
return {**schema, 'properties': props, 'required': required}
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _is_idcode_scalar(field: str, resolved: dict) -> bool:
|
|
114
|
+
return (resolved.get('type') not in ('object', 'array') and 'properties' not in resolved
|
|
115
|
+
and ('id' in field.lower() or 'code' in field.lower()))
|
|
116
|
+
|
|
117
|
+
def _find_extract_fields(schema: dict, spec: dict, path: str = '$') -> list[tuple[str, str]]:
|
|
118
|
+
resolved = resolve_schema(schema, spec)
|
|
119
|
+
results = []
|
|
120
|
+
for field, field_schema in resolved.get('properties', {}).items():
|
|
121
|
+
field_path = f'{path}.{field}'
|
|
122
|
+
fr = resolve_schema(field_schema, spec)
|
|
123
|
+
if field in set(resolved.get('required', [])) and _is_idcode_scalar(field, fr):
|
|
124
|
+
if not (field.lower() == 'code' and path == '$'):
|
|
125
|
+
results.append((field, field_path))
|
|
126
|
+
if 'properties' in fr or fr.get('type') == 'object':
|
|
127
|
+
results.extend(_find_extract_fields(fr, spec, field_path))
|
|
128
|
+
return results
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def extract_response_fields(operation: dict, spec: dict) -> list[tuple[str, str]]:
|
|
132
|
+
"""从操作的 200 响应中提取必需 id/code 字段的 (字段名, JSONPath) 对,用于测试用例提取。"""
|
|
133
|
+
responses = operation.get('responses', {})
|
|
134
|
+
for status, resp in responses.items():
|
|
135
|
+
if str(status).startswith('2'):
|
|
136
|
+
schema = resp.get('content', {}).get('application/json', {}).get('schema', {})
|
|
137
|
+
return _find_extract_fields(schema, spec)
|
|
138
|
+
return []
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def get_response_root_props(operation: dict, spec: dict) -> dict:
|
|
142
|
+
"""获取操作 200 响应 schema 的顶层 properties 字典。"""
|
|
143
|
+
responses = operation.get('responses', {})
|
|
144
|
+
for status, resp in responses.items():
|
|
145
|
+
if str(status).startswith('2'):
|
|
146
|
+
schema = resp.get('content', {}).get('application/json', {}).get('schema', {})
|
|
147
|
+
resolved = resolve_schema(schema, spec)
|
|
148
|
+
return resolved.get('properties', {})
|
|
149
|
+
return {}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _find_data_nested_fields(data_schema: dict, spec: dict) -> list[str]:
|
|
153
|
+
resolved = resolve_schema(data_schema, spec)
|
|
154
|
+
required = set(resolved.get('required', []))
|
|
155
|
+
return [f for f, fs in resolved.get('properties', {}).items()
|
|
156
|
+
if f in required and _is_idcode_scalar(f, resolve_schema(fs, spec))]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def build_validate(root_props: dict, spec: dict, is_success: bool) -> str:
|
|
160
|
+
"""构建 YAML 格式的 validate 断言块。"""
|
|
161
|
+
lines = [' validate: # 断言响应内容']
|
|
162
|
+
lines.append(f' - eq: status_code, {"200" if is_success else "400"}')
|
|
163
|
+
if 'code' in root_props:
|
|
164
|
+
lines.append(f' - eq: $.code, {"200" if is_success else "400"}')
|
|
165
|
+
if 'data' in root_props:
|
|
166
|
+
if is_success:
|
|
167
|
+
for field in _find_data_nested_fields(root_props['data'], spec):
|
|
168
|
+
lines.append(f' - not_null: $.data.{field}')
|
|
169
|
+
return '\n'.join(lines)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def extract_properties(schema: dict, spec: dict) -> tuple[dict, list]:
|
|
173
|
+
"""递归提取 schema 的所有 properties 和 required 列表,处理 allOf/oneOf/anyOf。"""
|
|
174
|
+
schema = resolve_schema(schema, spec)
|
|
175
|
+
|
|
176
|
+
if 'allOf' in schema:
|
|
177
|
+
merged_props, merged_req = {}, []
|
|
178
|
+
for sub in schema['allOf']:
|
|
179
|
+
props, req = extract_properties(sub, spec)
|
|
180
|
+
merged_props.update(props)
|
|
181
|
+
merged_req.extend(req)
|
|
182
|
+
return merged_props, merged_req
|
|
183
|
+
|
|
184
|
+
for key in ('oneOf', 'anyOf'):
|
|
185
|
+
if key in schema:
|
|
186
|
+
return extract_properties(schema[key][0], spec)
|
|
187
|
+
|
|
188
|
+
return schema.get('properties', {}), schema.get('required', [])
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _format_scalar(val) -> str:
|
|
192
|
+
"""将标量值格式化为 YAML 兼容字符串。${...} 占位符不加引号。"""
|
|
193
|
+
if isinstance(val, bool):
|
|
194
|
+
return 'true' if val else 'false'
|
|
195
|
+
if isinstance(val, (int, float)):
|
|
196
|
+
return str(val)
|
|
197
|
+
s = str(val)
|
|
198
|
+
if s.startswith('${') and s.endswith('}'):
|
|
199
|
+
return s
|
|
200
|
+
if any(c in s for c in (':', '#', '{', '}', '[', ']', ',')):
|
|
201
|
+
return f'"{s}"'
|
|
202
|
+
return s
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
_FAKER_FALLBACK = {
|
|
206
|
+
'string': '${word()}',
|
|
207
|
+
'integer': '${random_int()}',
|
|
208
|
+
'number': '${random_float()}',
|
|
209
|
+
'boolean': '${pybool()}',
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _faker_for(resolved: dict, field_name: str = None, field_mappings: dict = None) -> str | None:
|
|
214
|
+
if field_mappings and field_name:
|
|
215
|
+
expr = field_mappings.get(field_name)
|
|
216
|
+
if expr:
|
|
217
|
+
if expr.startswith('${'):
|
|
218
|
+
return expr
|
|
219
|
+
# 含 '(' 的是 Faker 表达式,需 ${} 包裹;不含的是静态文案,直接使用
|
|
220
|
+
if '(' in expr:
|
|
221
|
+
return '${' + expr + '}'
|
|
222
|
+
return expr
|
|
223
|
+
ft = resolved.get('type', '')
|
|
224
|
+
return _FAKER_FALLBACK.get(ft)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _field_yaml_lines(field: str, schema: dict, spec: dict, indent: int,
|
|
228
|
+
null_value: bool = False, commented: bool = False,
|
|
229
|
+
base_indent: int = None, example=None,
|
|
230
|
+
required: set = None, field_mappings: dict = None) -> list[str]:
|
|
231
|
+
"""递归为一个字段生成 YAML 行,展开嵌套对象和处理各种 schema 组合。
|
|
232
|
+
|
|
233
|
+
@param required: set, 当前层级的必填字段名集合,用于标注 # required
|
|
234
|
+
"""
|
|
235
|
+
if commented:
|
|
236
|
+
if base_indent is None:
|
|
237
|
+
base_indent = indent
|
|
238
|
+
extra = indent - base_indent
|
|
239
|
+
line_start = ' ' * base_indent + '# ' + ' ' * extra
|
|
240
|
+
else:
|
|
241
|
+
line_start = ' ' * indent
|
|
242
|
+
|
|
243
|
+
if null_value:
|
|
244
|
+
return [f"{line_start}{field}: null"]
|
|
245
|
+
|
|
246
|
+
resolved = resolve_schema(schema, spec)
|
|
247
|
+
field_type = resolved.get('type', '')
|
|
248
|
+
req = required or set()
|
|
249
|
+
is_req = field in req
|
|
250
|
+
type_comment_parts = []
|
|
251
|
+
if field_type:
|
|
252
|
+
type_comment_parts.append(field_type)
|
|
253
|
+
if is_req:
|
|
254
|
+
type_comment_parts.append('required')
|
|
255
|
+
type_comment = f' # {", ".join(type_comment_parts)}' if type_comment_parts else ''
|
|
256
|
+
|
|
257
|
+
nested_req = set(resolved.get('required', []))
|
|
258
|
+
|
|
259
|
+
# AI 语义映射优先级高于 example
|
|
260
|
+
if field_mappings and field in field_mappings:
|
|
261
|
+
expr = field_mappings[field]
|
|
262
|
+
if expr is not None:
|
|
263
|
+
if expr.startswith('${'):
|
|
264
|
+
val = expr
|
|
265
|
+
elif '(' in expr:
|
|
266
|
+
val = '${' + expr + '}'
|
|
267
|
+
else:
|
|
268
|
+
val = _format_scalar(expr)
|
|
269
|
+
return [f"{line_start}{field}: {val}{type_comment}"]
|
|
270
|
+
|
|
271
|
+
if isinstance(example, dict):
|
|
272
|
+
lines = [f"{line_start}{field}:"]
|
|
273
|
+
for k, v in example.items():
|
|
274
|
+
lines.extend(_field_yaml_lines(k, {}, spec, indent + 2,
|
|
275
|
+
commented=commented, base_indent=base_indent,
|
|
276
|
+
example=v, required=nested_req,
|
|
277
|
+
field_mappings=field_mappings))
|
|
278
|
+
return lines
|
|
279
|
+
|
|
280
|
+
if example is not None:
|
|
281
|
+
return [f"{line_start}{field}: {_format_scalar(example)}{type_comment}"]
|
|
282
|
+
|
|
283
|
+
schema_example = resolved.get('example')
|
|
284
|
+
if schema_example is not None:
|
|
285
|
+
enum = resolved.get('enum')
|
|
286
|
+
if enum:
|
|
287
|
+
example_str = str(schema_example) if not isinstance(schema_example, str) else schema_example
|
|
288
|
+
if example_str not in enum:
|
|
289
|
+
first = enum[0]
|
|
290
|
+
val = str(first) if not isinstance(first, str) else first
|
|
291
|
+
return [f"{line_start}{field}: {val}{type_comment}"]
|
|
292
|
+
return [f"{line_start}{field}: {_format_scalar(schema_example)}{type_comment}"]
|
|
293
|
+
|
|
294
|
+
if 'allOf' in resolved:
|
|
295
|
+
merged = {}
|
|
296
|
+
for sub in resolved['allOf']:
|
|
297
|
+
sub_r = resolve_schema(sub, spec)
|
|
298
|
+
merged.update(sub_r.get('properties', {}))
|
|
299
|
+
if merged:
|
|
300
|
+
lines = [f"{line_start}{field}:"]
|
|
301
|
+
for nf, ns in merged.items():
|
|
302
|
+
lines.extend(_field_yaml_lines(nf, ns, spec, indent + 2,
|
|
303
|
+
commented=commented, base_indent=base_indent,
|
|
304
|
+
required=nested_req,
|
|
305
|
+
field_mappings=field_mappings))
|
|
306
|
+
return lines
|
|
307
|
+
return [f"{line_start}{field}: # allOf, fill in manually"]
|
|
308
|
+
|
|
309
|
+
for key in ('oneOf', 'anyOf'):
|
|
310
|
+
if key in resolved:
|
|
311
|
+
for i, variant in enumerate(resolved[key], 1):
|
|
312
|
+
v = resolve_schema(variant, spec)
|
|
313
|
+
vr = set(v.get('required', []))
|
|
314
|
+
nested = v.get('properties', {})
|
|
315
|
+
if nested:
|
|
316
|
+
lines = [f"{line_start}{field}: # {key}, showing variant {i}"]
|
|
317
|
+
for nf, ns in nested.items():
|
|
318
|
+
lines.extend(_field_yaml_lines(nf, ns, spec, indent + 2,
|
|
319
|
+
commented=commented, base_indent=base_indent,
|
|
320
|
+
required=vr,
|
|
321
|
+
field_mappings=field_mappings))
|
|
322
|
+
return lines
|
|
323
|
+
return [f"{line_start}{field}: # {key}, fill in manually"]
|
|
324
|
+
|
|
325
|
+
nested = resolved.get('properties', {})
|
|
326
|
+
if nested:
|
|
327
|
+
lines = [f"{line_start}{field}:"]
|
|
328
|
+
for nf, ns in nested.items():
|
|
329
|
+
lines.extend(_field_yaml_lines(nf, ns, spec, indent + 2,
|
|
330
|
+
commented=commented, base_indent=base_indent,
|
|
331
|
+
required=nested_req,
|
|
332
|
+
field_mappings=field_mappings))
|
|
333
|
+
return lines
|
|
334
|
+
|
|
335
|
+
if resolved.get('type') == 'object':
|
|
336
|
+
return [f"{line_start}{field}: # object, fill in manually"]
|
|
337
|
+
|
|
338
|
+
if resolved.get('type') == 'array':
|
|
339
|
+
return [f"{line_start}{field}: # array, fill in manually"]
|
|
340
|
+
|
|
341
|
+
enum = resolved.get('enum')
|
|
342
|
+
if enum:
|
|
343
|
+
first = enum[0]
|
|
344
|
+
val = str(first) if not isinstance(first, str) else first
|
|
345
|
+
return [f"{line_start}{field}: {val}{type_comment}"]
|
|
346
|
+
|
|
347
|
+
faker_val = _faker_for(resolved, field_name=field, field_mappings=field_mappings)
|
|
348
|
+
if faker_val:
|
|
349
|
+
return [f"{line_start}{field}: {faker_val}{type_comment}"]
|
|
350
|
+
return [f"{line_start}{field}:{type_comment}"]
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
# ---------------------------------------------------------------------------
|
|
354
|
+
# YAML builder
|
|
355
|
+
# ---------------------------------------------------------------------------
|
|
356
|
+
|
|
357
|
+
class CaseBuilder:
|
|
358
|
+
"""根据 OpenAPI 操作定义,构建 YAML 测试用例文件与 Python 测试脚本。"""
|
|
359
|
+
|
|
360
|
+
def __init__(self, *, url, method, summary, op_id, tag,
|
|
361
|
+
required, optional, props, required_params, optional_params,
|
|
362
|
+
path_params=None,
|
|
363
|
+
example, extract_fields, response_root_props, spec,
|
|
364
|
+
field_mappings=None, marks=None, yaml_module=None):
|
|
365
|
+
self.spec = spec
|
|
366
|
+
self.field_mappings = field_mappings
|
|
367
|
+
self.path_params = path_params or []
|
|
368
|
+
# 用 path param 的 example / schema 默认值替换 URL 中的 {param} 占位符
|
|
369
|
+
self.url = url
|
|
370
|
+
for pp in self.path_params:
|
|
371
|
+
pname = pp['name']
|
|
372
|
+
placeholder = '{' + pname + '}'
|
|
373
|
+
if placeholder in self.url:
|
|
374
|
+
replacement = self._path_param_value(pp)
|
|
375
|
+
self.url = self.url.replace(placeholder, replacement)
|
|
376
|
+
self.method = method.lower()
|
|
377
|
+
self.summary = summary
|
|
378
|
+
raw = re.sub(r'[^a-zA-Z0-9]+', '_', summary).strip('_') or re.sub(r'[^a-zA-Z0-9]+', '_', op_id).strip('_')
|
|
379
|
+
self.op_id = camel_to_snake(raw)
|
|
380
|
+
self.module = tag_to_module(tag)
|
|
381
|
+
self.required = required
|
|
382
|
+
self.optional = optional
|
|
383
|
+
self.props = props
|
|
384
|
+
self.required_params = required_params
|
|
385
|
+
self.optional_params = optional_params
|
|
386
|
+
self.example = example or {}
|
|
387
|
+
self.extract_fields = extract_fields
|
|
388
|
+
self._success_validate = build_validate(response_root_props, spec, is_success=True)
|
|
389
|
+
self._fail_validate = build_validate(response_root_props, spec, is_success=False)
|
|
390
|
+
self.marks = marks or []
|
|
391
|
+
self.yaml_module = yaml_module or self.module
|
|
392
|
+
self._has_body = bool(self.required or self.optional)
|
|
393
|
+
self._has_params = bool(self.required_params or self.optional_params)
|
|
394
|
+
self._str_kinds = ('empty', 'missing', 'blank')
|
|
395
|
+
self._kinds = ('empty', 'missing')
|
|
396
|
+
|
|
397
|
+
def _diff(self, kind: str, target: str, prefix=' json:', schema: dict = None) -> list[str]:
|
|
398
|
+
if kind == 'missing':
|
|
399
|
+
return [f'{prefix}', f' {target}: {DEL_FLAG}']
|
|
400
|
+
if kind == 'type_invalid':
|
|
401
|
+
resolved = schema or self._resolve_field(target)
|
|
402
|
+
val = self._type_invalid_value_for(resolved)
|
|
403
|
+
elif kind == 'enum_invalid':
|
|
404
|
+
val = self._enum_invalid_value(target)
|
|
405
|
+
else:
|
|
406
|
+
val = {'empty': 'null', 'blank': '""'}[kind]
|
|
407
|
+
return [f'{prefix}', f' {target}: {val}']
|
|
408
|
+
|
|
409
|
+
def _resolve_field(self, field: str) -> dict:
|
|
410
|
+
"""Resolve a field name (dot-path for body, plain for param) to its schema."""
|
|
411
|
+
parts = field.split('.')
|
|
412
|
+
root = parts[0]
|
|
413
|
+
if not self.props or root not in self.props:
|
|
414
|
+
return self._param_schema(field)
|
|
415
|
+
schema = self.props.get(root, {})
|
|
416
|
+
resolved = resolve_schema(schema, self.spec)
|
|
417
|
+
for p in parts[1:]:
|
|
418
|
+
props = resolved.get('properties', {})
|
|
419
|
+
resolved = resolve_schema(props.get(p, {}), self.spec)
|
|
420
|
+
if not resolved:
|
|
421
|
+
return self._param_schema(field)
|
|
422
|
+
return resolved
|
|
423
|
+
|
|
424
|
+
def _enum_invalid_value(self, field: str) -> str:
|
|
425
|
+
resolved = self._resolve_field(field)
|
|
426
|
+
enum = resolved.get('enum', [])
|
|
427
|
+
if not enum:
|
|
428
|
+
return 'INVALID'
|
|
429
|
+
ft = resolved.get('type', '')
|
|
430
|
+
if ft == 'integer':
|
|
431
|
+
return str(max(enum) + 1)
|
|
432
|
+
return 'INVALID'
|
|
433
|
+
|
|
434
|
+
def _type_invalid_value_for(self, resolved: dict) -> str:
|
|
435
|
+
ft = resolved.get('type', '')
|
|
436
|
+
if ft == 'string':
|
|
437
|
+
return '${pyint(min_value=1, max_value=100)}'
|
|
438
|
+
if ft == 'integer':
|
|
439
|
+
return '${pyint(min_value=1, max_value=100):str}'
|
|
440
|
+
if ft == 'number':
|
|
441
|
+
return '${pyfloat(min_value=10, max_value=100):str}'
|
|
442
|
+
if ft == 'boolean':
|
|
443
|
+
return '${pybool():str}'
|
|
444
|
+
if ft in ('object', 'array'):
|
|
445
|
+
return '${pystr()}'
|
|
446
|
+
return '${uuid()}'
|
|
447
|
+
|
|
448
|
+
def _param_schema(self, name: str) -> dict:
|
|
449
|
+
for p in self.required_params + self.optional_params:
|
|
450
|
+
if p['name'] == name:
|
|
451
|
+
return resolve_schema(p.get('schema', {}), self.spec)
|
|
452
|
+
return {}
|
|
453
|
+
|
|
454
|
+
def _request(self, kind: str = None, field: str = None, is_param: bool = False) -> str:
|
|
455
|
+
lines = [' request:']
|
|
456
|
+
if self._has_params and is_param:
|
|
457
|
+
ps = self._param_schema(field)
|
|
458
|
+
lines.extend(self._diff(kind, field, ' params:', ps))
|
|
459
|
+
if self._has_body and not is_param:
|
|
460
|
+
lines.extend(self._diff(kind, field))
|
|
461
|
+
return '\n'.join(lines)
|
|
462
|
+
|
|
463
|
+
# ---- case generators ----
|
|
464
|
+
|
|
465
|
+
@property
|
|
466
|
+
def _extract_block(self) -> str:
|
|
467
|
+
if not self.extract_fields:
|
|
468
|
+
return ''
|
|
469
|
+
lines = [' extract: # 提取响应内容']
|
|
470
|
+
for field, jsonpath in self.extract_fields:
|
|
471
|
+
lines.append(f' - {camel_to_snake(field)}: {jsonpath}')
|
|
472
|
+
return '\n' + '\n'.join(lines)
|
|
473
|
+
|
|
474
|
+
def _case_str(self, suffix: str, title_suffix: str, level: str, req_block: str, validate: str = None, inline_req: str = None) -> str:
|
|
475
|
+
req = f" request: {inline_req}\n" if inline_req else f" request:\n{req_block}\n"
|
|
476
|
+
return (
|
|
477
|
+
f"test_{self.op_id}{suffix}:\n"
|
|
478
|
+
f" title: {self.summary}-{title_suffix}\n"
|
|
479
|
+
f" level: {level}\n"
|
|
480
|
+
f"{req}"
|
|
481
|
+
f"{validate or self._success_validate}"
|
|
482
|
+
f"{self._extract_block}"
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
def _success(self) -> str:
|
|
486
|
+
req_lines = []
|
|
487
|
+
if self.required_params or self.optional_params:
|
|
488
|
+
req_lines.append(' params: {}')
|
|
489
|
+
if self.required or self.optional:
|
|
490
|
+
req_lines.append(' json: {}')
|
|
491
|
+
if not req_lines:
|
|
492
|
+
return self._case_str('', '成功', 'p0', '', inline_req='{}')
|
|
493
|
+
return self._case_str('', '成功', 'p0', '\n'.join(req_lines))
|
|
494
|
+
|
|
495
|
+
def _is_param_field(self, name: str) -> bool:
|
|
496
|
+
return name in {p['name'] for p in self.required_params + self.optional_params}
|
|
497
|
+
|
|
498
|
+
def _success_variant(self, json_data: dict, suffix: str, desc: str) -> str:
|
|
499
|
+
# 判断前缀
|
|
500
|
+
fill_vals = [v for _, v in json_data.items() if v is not None and v != DEL_FLAG]
|
|
501
|
+
has_body_fields = any(not self._is_param_field(k.split('.')[0]) for k in json_data)
|
|
502
|
+
prefix = ' json:' if has_body_fields else ' params:'
|
|
503
|
+
json_lines = [prefix]
|
|
504
|
+
# 先输出非 dot 键(如 buyerInfo: __DEL__),再输出 dot-path 键
|
|
505
|
+
ordered = sorted(json_data.items(), key=lambda kv: '.' in kv[0])
|
|
506
|
+
for k, v in ordered:
|
|
507
|
+
if v is None:
|
|
508
|
+
json_lines.append(f' {k}: null')
|
|
509
|
+
elif v == DEL_FLAG:
|
|
510
|
+
json_lines.append(f' {k}: {DEL_FLAG}')
|
|
511
|
+
else:
|
|
512
|
+
json_lines.append(f' {k}: {_format_scalar(v)}')
|
|
513
|
+
return self._case_str(f'_{suffix}', f'成功({desc})', 'p0', '\n'.join(json_lines))
|
|
514
|
+
|
|
515
|
+
_DESC_MAP = {'empty': '{}为空-失败', 'missing': '{}字段缺失-失败',
|
|
516
|
+
'type_invalid': '{}类型无效-失败', 'blank': '{}为空字符串-失败',
|
|
517
|
+
'enum_invalid': '{}枚举值无效-失败', 'invalid_value': '{}值无效-失败'}
|
|
518
|
+
|
|
519
|
+
def _path_param_value(self, param: dict) -> str:
|
|
520
|
+
"""用 spec 中 path param 的 example 或 faker 默认值生成替换值。"""
|
|
521
|
+
pname = param['name']
|
|
522
|
+
schema = param.get('schema', {})
|
|
523
|
+
resolved = resolve_schema(schema, self.spec) if schema else {}
|
|
524
|
+
# 1. param 自身的 example
|
|
525
|
+
ex = param.get('example') if param.get('example') is not None else schema.get('example')
|
|
526
|
+
if ex is not None:
|
|
527
|
+
return str(ex)
|
|
528
|
+
# 2. field mappings
|
|
529
|
+
if self.field_mappings and pname in self.field_mappings:
|
|
530
|
+
expr = self.field_mappings[pname]
|
|
531
|
+
return '${' + expr + '}' if not expr.startswith('${') else expr
|
|
532
|
+
# 3. 在 response properties 中查找同名字段的 example
|
|
533
|
+
for resp in self._response_schemas():
|
|
534
|
+
props = resp.get('properties', {})
|
|
535
|
+
data = props.get('data', {})
|
|
536
|
+
data_props = resolve_schema(data, self.spec).get('properties', {})
|
|
537
|
+
if pname in data_props:
|
|
538
|
+
field_ex = data_props[pname].get('example') or data_props[pname].get('examples')
|
|
539
|
+
if field_ex:
|
|
540
|
+
return str(field_ex[0] if isinstance(field_ex, list) else field_ex)
|
|
541
|
+
elif pname in props:
|
|
542
|
+
field_ex = props[pname].get('example') or props[pname].get('examples')
|
|
543
|
+
if field_ex:
|
|
544
|
+
return str(field_ex[0] if isinstance(field_ex, list) else field_ex)
|
|
545
|
+
# 4. enum
|
|
546
|
+
enum = resolved.get('enum', [])
|
|
547
|
+
if enum:
|
|
548
|
+
return str(enum[0])
|
|
549
|
+
# 5. faker
|
|
550
|
+
faker = _faker_for(resolved, field_name=pname)
|
|
551
|
+
if faker:
|
|
552
|
+
return faker
|
|
553
|
+
return pname.upper()
|
|
554
|
+
|
|
555
|
+
def _response_schemas(self) -> list[dict]:
|
|
556
|
+
"""从 spec 中提取所有 response schema dict。"""
|
|
557
|
+
schemas = []
|
|
558
|
+
# 需要在 __init__ 之后用 self.spec 来找
|
|
559
|
+
for path, path_item in (self.spec.get('paths') or {}).items():
|
|
560
|
+
for method, operation in path_item.items():
|
|
561
|
+
if not isinstance(operation, dict):
|
|
562
|
+
continue
|
|
563
|
+
responses = operation.get('responses', {})
|
|
564
|
+
for code, resp in responses.items():
|
|
565
|
+
if not isinstance(resp, dict):
|
|
566
|
+
continue
|
|
567
|
+
content = resp.get('content', {})
|
|
568
|
+
json_content = content.get('application/json', {})
|
|
569
|
+
schema = json_content.get('schema', {})
|
|
570
|
+
if schema:
|
|
571
|
+
schemas.append(resolve_schema(schema, self.spec))
|
|
572
|
+
return schemas
|
|
573
|
+
|
|
574
|
+
def _path_param_error_cases(self) -> list[str]:
|
|
575
|
+
"""为 path 参数生成错误用例(仅 invalid_value,因为 empty/missing 会导致路径不匹配)。"""
|
|
576
|
+
cases = []
|
|
577
|
+
for pp in self.path_params:
|
|
578
|
+
pname = pp['name']
|
|
579
|
+
short = camel_to_snake(pname)
|
|
580
|
+
name = f"test_{short}_invalid_value"
|
|
581
|
+
# 用无效值替换 URL 中已渲染的值
|
|
582
|
+
valid_value = self._path_param_value(pp)
|
|
583
|
+
invalid_value = 'INVALID_' + pname.upper()
|
|
584
|
+
invalid_url = self.url.replace(valid_value, invalid_value)
|
|
585
|
+
req_lines = []
|
|
586
|
+
if self._has_body:
|
|
587
|
+
req_lines.append(' json: {}')
|
|
588
|
+
if self.required_params or self.optional_params:
|
|
589
|
+
req_lines.append(' params: {}')
|
|
590
|
+
if not req_lines:
|
|
591
|
+
req_body = ' request: {}'
|
|
592
|
+
else:
|
|
593
|
+
req_body = '\n'.join(req_lines)
|
|
594
|
+
case = (f"{name}:\n"
|
|
595
|
+
f" title: {pname}值无效-失败\n"
|
|
596
|
+
f" level: p1\n"
|
|
597
|
+
f" url: {invalid_url}\n"
|
|
598
|
+
f"{req_body}\n"
|
|
599
|
+
f"{self._fail_validate}")
|
|
600
|
+
cases.append(case)
|
|
601
|
+
return cases
|
|
602
|
+
|
|
603
|
+
def _error_case(self, field: str, kind: str, is_param: bool = False) -> str:
|
|
604
|
+
short = field.rsplit('.', 1)[-1]
|
|
605
|
+
name = f"test_{camel_to_snake(short)}_{kind}"
|
|
606
|
+
desc = self._DESC_MAP[kind].format(short)
|
|
607
|
+
req = self._request(kind=kind, field=field, is_param=is_param)
|
|
608
|
+
return f"{name}:\n title: {desc}\n level: p1\n{req}\n{self._fail_validate}"
|
|
609
|
+
|
|
610
|
+
def _is_string_field(self, field: str) -> bool:
|
|
611
|
+
resolved = resolve_schema(self.props.get(field, {}), self.spec)
|
|
612
|
+
return resolved.get('type') == 'string'
|
|
613
|
+
|
|
614
|
+
def _is_string_param(self, param: dict) -> bool:
|
|
615
|
+
resolved = resolve_schema(param.get('schema', {}), self.spec)
|
|
616
|
+
return resolved.get('type') == 'string'
|
|
617
|
+
|
|
618
|
+
def _is_enum_field(self, field: str) -> bool:
|
|
619
|
+
resolved = resolve_schema(self.props.get(field, {}), self.spec)
|
|
620
|
+
return bool(resolved.get('enum'))
|
|
621
|
+
|
|
622
|
+
def _resolve_enter_oneof(self, schema: dict) -> dict:
|
|
623
|
+
"""Resolve $ref, then enter oneOf/anyOf first variant if present."""
|
|
624
|
+
resolved = resolve_schema(schema, self.spec) if isinstance(schema, dict) else {}
|
|
625
|
+
for key in ('oneOf', 'anyOf'):
|
|
626
|
+
if key in resolved:
|
|
627
|
+
return resolve_schema(resolved[key][0], self.spec)
|
|
628
|
+
return resolved
|
|
629
|
+
|
|
630
|
+
def _all_scalar_fields(self) -> list[str]:
|
|
631
|
+
"""所有标量字段的 dot-path 列表(不含 enum 字段,由 enum_invalid 覆盖)。"""
|
|
632
|
+
enum_paths = {p for p, _ in self._all_enum_fields()}
|
|
633
|
+
result = []
|
|
634
|
+
def walk(props_dict, prefix):
|
|
635
|
+
for fn, fs in (props_dict or {}).items():
|
|
636
|
+
full = f'{prefix}.{fn}' if prefix else fn
|
|
637
|
+
r = resolve_schema(fs, self.spec) if isinstance(fs, dict) else {}
|
|
638
|
+
if 'oneOf' in r or 'anyOf' in r:
|
|
639
|
+
continue
|
|
640
|
+
nested = r.get('properties')
|
|
641
|
+
if nested:
|
|
642
|
+
walk(nested, full)
|
|
643
|
+
elif full not in enum_paths:
|
|
644
|
+
result.append(full)
|
|
645
|
+
walk({**{f: self.props.get(f, {}) for f in self.required},
|
|
646
|
+
**{f: self.props.get(f, {}) for f in self.optional}}, '')
|
|
647
|
+
# params
|
|
648
|
+
for p in self.required_params + self.optional_params:
|
|
649
|
+
name = p['name']
|
|
650
|
+
if name not in enum_paths and name not in result:
|
|
651
|
+
result.append(name)
|
|
652
|
+
return result
|
|
653
|
+
|
|
654
|
+
def _non_scalar_fields(self) -> list[str]:
|
|
655
|
+
"""非标量字段(oneOf/anyOf/object/array)的 dot-path 列表。"""
|
|
656
|
+
result = []
|
|
657
|
+
def walk(props_dict, prefix):
|
|
658
|
+
for fn, fs in (props_dict or {}).items():
|
|
659
|
+
full = f'{prefix}.{fn}' if prefix else fn
|
|
660
|
+
r = resolve_schema(fs, self.spec) if isinstance(fs, dict) else {}
|
|
661
|
+
if 'oneOf' in r or 'anyOf' in r or r.get('type') in ('object', 'array') or r.get('properties'):
|
|
662
|
+
result.append(full)
|
|
663
|
+
if r.get('properties'):
|
|
664
|
+
walk(r['properties'], full)
|
|
665
|
+
walk({**{f: self.props.get(f, {}) for f in self.required},
|
|
666
|
+
**{f: self.props.get(f, {}) for f in self.optional}}, '')
|
|
667
|
+
return result
|
|
668
|
+
|
|
669
|
+
def _all_enum_fields(self) -> list[tuple[str, list]]:
|
|
670
|
+
result = []
|
|
671
|
+
def walk(props_dict, prefix):
|
|
672
|
+
for fn, fs in (props_dict or {}).items():
|
|
673
|
+
full = f'{prefix}.{fn}' if prefix else fn
|
|
674
|
+
r = self._resolve_enter_oneof(fs)
|
|
675
|
+
enum = r.get('enum', [])
|
|
676
|
+
if enum and len(enum) > 1:
|
|
677
|
+
result.append((full, list(enum)))
|
|
678
|
+
if r.get('properties'):
|
|
679
|
+
walk(r['properties'], full)
|
|
680
|
+
walk({**{f: self.props.get(f, {}) for f in self.required},
|
|
681
|
+
**{f: self.props.get(f, {}) for f in self.optional}}, '')
|
|
682
|
+
# query 参数中的枚举
|
|
683
|
+
for p in self.required_params + self.optional_params:
|
|
684
|
+
r = resolve_schema(p.get('schema', {}), self.spec)
|
|
685
|
+
enum = r.get('enum', [])
|
|
686
|
+
if enum and len(enum) > 1:
|
|
687
|
+
result.append((p['name'], list(enum)))
|
|
688
|
+
return result
|
|
689
|
+
|
|
690
|
+
@staticmethod
|
|
691
|
+
def _short_tag(ref: str) -> str:
|
|
692
|
+
name = re.sub(r'(Buyer|Seller|Merchant|Beneficiary|Bank)?Info$', '', ref.rsplit('/', 1)[-1])
|
|
693
|
+
name = re.sub(r'(Request|Response|Details|Schema|Config|Configuration)$', '', name, flags=re.IGNORECASE)
|
|
694
|
+
return camel_to_snake(name) or camel_to_snake(ref.rsplit('/', 1)[-1])
|
|
695
|
+
|
|
696
|
+
def _nested_optional_dotpaths(self) -> list[str]:
|
|
697
|
+
paths = []
|
|
698
|
+
def walk(container_schema, prefix):
|
|
699
|
+
r = self._resolve_enter_oneof(container_schema)
|
|
700
|
+
props = r.get('properties', {})
|
|
701
|
+
reqs = set(r.get('required', []))
|
|
702
|
+
for fn, fs in props.items():
|
|
703
|
+
full = f'{prefix}.{fn}' if prefix else fn
|
|
704
|
+
fr = self._resolve_enter_oneof(fs)
|
|
705
|
+
nested = fr.get('properties', {})
|
|
706
|
+
if nested:
|
|
707
|
+
if fn in reqs:
|
|
708
|
+
walk(fr, full)
|
|
709
|
+
else:
|
|
710
|
+
paths.append(full)
|
|
711
|
+
elif fn not in reqs and fr.get('type') != 'object':
|
|
712
|
+
paths.append(full)
|
|
713
|
+
for f in self.required:
|
|
714
|
+
walk(self.props.get(f, {}), f)
|
|
715
|
+
return paths
|
|
716
|
+
|
|
717
|
+
def _oneof_variant_cases(self):
|
|
718
|
+
fms = self.field_mappings
|
|
719
|
+
def _fallback(ps_r, field_name=None):
|
|
720
|
+
enum = ps_r.get('enum', [])
|
|
721
|
+
return enum[0] if enum else _faker_for(ps_r, field_name=field_name, field_mappings=fms)
|
|
722
|
+
|
|
723
|
+
def _nested_dict(schema, mode='full'):
|
|
724
|
+
result = {}
|
|
725
|
+
r = resolve_schema(schema, self.spec) if isinstance(schema, dict) else {}
|
|
726
|
+
reqs = set(r.get('required', []))
|
|
727
|
+
for pn, ps in r.get('properties', {}).items():
|
|
728
|
+
ps_r = resolve_schema(ps, self.spec)
|
|
729
|
+
has_nested = bool(ps_r.get('properties'))
|
|
730
|
+
if has_nested:
|
|
731
|
+
if pn in reqs:
|
|
732
|
+
result[pn] = _nested_dict(ps, mode=mode)
|
|
733
|
+
else:
|
|
734
|
+
result[pn] = DEL_FLAG if mode == 'required' else (None if mode == 'null' else _nested_dict(ps, mode=mode))
|
|
735
|
+
elif pn not in reqs:
|
|
736
|
+
result[pn] = DEL_FLAG if mode == 'required' else (None if mode == 'null' else _fallback(ps_r, field_name=pn))
|
|
737
|
+
else:
|
|
738
|
+
result[pn] = _fallback(ps_r, field_name=pn)
|
|
739
|
+
return result
|
|
740
|
+
|
|
741
|
+
def _to_dotpaths(d, prefix=''):
|
|
742
|
+
result = {}
|
|
743
|
+
for k, v in d.items():
|
|
744
|
+
full = f'{prefix}.{k}' if prefix else k
|
|
745
|
+
if v == DEL_FLAG:
|
|
746
|
+
result[full] = DEL_FLAG
|
|
747
|
+
elif isinstance(v, dict):
|
|
748
|
+
result.update(_to_dotpaths(v, full))
|
|
749
|
+
else:
|
|
750
|
+
result[full] = v
|
|
751
|
+
return result
|
|
752
|
+
|
|
753
|
+
_MODES = [('', '{}', '{}'), ('_required', '{}仅必填参数', 'required'), ('_optional_null', '{}选填字段为null', 'null')]
|
|
754
|
+
cases = []
|
|
755
|
+
# 全局选填字段,排除属于 oneOf 变体字段内的嵌套路径
|
|
756
|
+
all_opt = self.optional + self._nested_optional_dotpaths()
|
|
757
|
+
for f in self.required:
|
|
758
|
+
r = resolve_schema(self.props.get(f, {}), self.spec)
|
|
759
|
+
variants = r.get('oneOf') or r.get('anyOf') or []
|
|
760
|
+
if len(variants) <= 1:
|
|
761
|
+
continue
|
|
762
|
+
for variant in variants[1:]:
|
|
763
|
+
ref_name = variant.get('$ref', '').rsplit('/', 1)[-1]
|
|
764
|
+
ftag = self._short_tag(variant.get('$ref', ''))
|
|
765
|
+
# 所有以 variant 父字段 f 开头的嵌套选填路径,由 _nested_dict 处理,此处排除
|
|
766
|
+
global_opt = [dp for dp in all_opt if not dp.startswith(f + '.')]
|
|
767
|
+
for suffix_fmt, desc_fmt, mode in _MODES:
|
|
768
|
+
flat = _to_dotpaths(_nested_dict(variant, mode=mode), f)
|
|
769
|
+
flat[f] = DEL_FLAG
|
|
770
|
+
if mode == 'required':
|
|
771
|
+
for dp in global_opt:
|
|
772
|
+
if dp not in flat:
|
|
773
|
+
flat[dp] = DEL_FLAG
|
|
774
|
+
elif mode == 'null':
|
|
775
|
+
for dp in global_opt:
|
|
776
|
+
flat.setdefault(dp, None)
|
|
777
|
+
cases.append(self._success_variant(flat, suffix=f'{ftag}{suffix_fmt}',
|
|
778
|
+
desc=desc_fmt.format(ref_name)))
|
|
779
|
+
return cases
|
|
780
|
+
|
|
781
|
+
def _optional_tree(self, value):
|
|
782
|
+
"""构建选填字段的嵌套树,每个选填叶节点赋 value。"""
|
|
783
|
+
tree = {}
|
|
784
|
+
for f in self.optional:
|
|
785
|
+
tree[f] = value
|
|
786
|
+
for path in self._nested_optional_dotpaths():
|
|
787
|
+
parts = path.split('.')
|
|
788
|
+
t = tree
|
|
789
|
+
for p in parts[:-1]:
|
|
790
|
+
t = t.setdefault(p, {})
|
|
791
|
+
if not isinstance(t, dict):
|
|
792
|
+
t = {}
|
|
793
|
+
t[parts[-1]] = value
|
|
794
|
+
return tree
|
|
795
|
+
|
|
796
|
+
@staticmethod
|
|
797
|
+
def _dict_to_yaml_lines(d, indent=6):
|
|
798
|
+
"""递归将嵌套 dict 转为 YAML 行。"""
|
|
799
|
+
lines = []
|
|
800
|
+
for k, v in d.items():
|
|
801
|
+
prefix = ' ' * indent
|
|
802
|
+
if isinstance(v, dict):
|
|
803
|
+
lines.append(f'{prefix}{k}:')
|
|
804
|
+
lines.extend(CaseBuilder._dict_to_yaml_lines(v, indent + 2))
|
|
805
|
+
elif v is None:
|
|
806
|
+
lines.append(f'{prefix}{k}: null')
|
|
807
|
+
elif v == DEL_FLAG:
|
|
808
|
+
lines.append(f'{prefix}{k}: {DEL_FLAG}')
|
|
809
|
+
else:
|
|
810
|
+
lines.append(f'{prefix}{k}: {_format_scalar(v)}')
|
|
811
|
+
return lines
|
|
812
|
+
|
|
813
|
+
def _minimal_case(self, enum_overrides=None):
|
|
814
|
+
tree = self._optional_tree(DEL_FLAG)
|
|
815
|
+
injected = self._inject_overrides(tree, enum_overrides)
|
|
816
|
+
json_lines = [' json:'] + self._dict_to_yaml_lines(tree)
|
|
817
|
+
return self._case_str('_required', '成功(仅必填参数)', 'p0', '\n'.join(json_lines)), injected
|
|
818
|
+
|
|
819
|
+
def _optional_null_case(self, enum_overrides=None):
|
|
820
|
+
tree = self._optional_tree(None)
|
|
821
|
+
injected = self._inject_overrides(tree, enum_overrides)
|
|
822
|
+
json_lines = [' json:'] + self._dict_to_yaml_lines(tree)
|
|
823
|
+
return self._case_str('_optional_null', '成功(选填字段为null)', 'p0', '\n'.join(json_lines)), injected
|
|
824
|
+
|
|
825
|
+
def _required_case(self) -> str:
|
|
826
|
+
json_lines = [' params:']
|
|
827
|
+
for p in self.optional_params:
|
|
828
|
+
json_lines.append(f' {p["name"]}: {DEL_FLAG}')
|
|
829
|
+
return self._case_str('_required', '成功(仅必填参数)', 'p0', '\n'.join(json_lines))
|
|
830
|
+
|
|
831
|
+
def _optional_null_params_case(self) -> str:
|
|
832
|
+
json_lines = [' params:']
|
|
833
|
+
for p in self.optional_params:
|
|
834
|
+
json_lines.append(f' {p["name"]}: null')
|
|
835
|
+
return self._case_str('_optional_null', '成功(选填参数为null)', 'p0', '\n'.join(json_lines))
|
|
836
|
+
|
|
837
|
+
@staticmethod
|
|
838
|
+
def _inject_overrides(tree: dict, overrides: dict) -> bool:
|
|
839
|
+
"""Return True if at least one override was injected."""
|
|
840
|
+
injected = False
|
|
841
|
+
if not overrides:
|
|
842
|
+
return injected
|
|
843
|
+
for k, v in overrides.items():
|
|
844
|
+
parts = k.split('.')
|
|
845
|
+
t = tree
|
|
846
|
+
for p in parts[:-1]:
|
|
847
|
+
if t.get(p) in (DEL_FLAG, None):
|
|
848
|
+
break
|
|
849
|
+
if p not in t or not isinstance(t[p], dict):
|
|
850
|
+
t[p] = {}
|
|
851
|
+
t = t[p]
|
|
852
|
+
else:
|
|
853
|
+
t[parts[-1]] = _format_scalar(v)
|
|
854
|
+
injected = True
|
|
855
|
+
return injected
|
|
856
|
+
|
|
857
|
+
# ---- full file ----
|
|
858
|
+
|
|
859
|
+
def _base_params_lines(self) -> str:
|
|
860
|
+
lines = [' base_params:']
|
|
861
|
+
req_set = set(p['name'] for p in self.required_params)
|
|
862
|
+
for p in self.required_params + self.optional_params:
|
|
863
|
+
name = p['name']
|
|
864
|
+
schema = p.get('schema', {})
|
|
865
|
+
resolved = resolve_schema(schema, self.spec) if schema else {}
|
|
866
|
+
ft = resolved.get('type', '')
|
|
867
|
+
ex = p.get('example') if p.get('example') is not None else schema.get('example')
|
|
868
|
+
type_parts = [ft] if ft else []
|
|
869
|
+
if name in req_set:
|
|
870
|
+
type_parts.append('required')
|
|
871
|
+
type_comment = f' # {", ".join(type_parts)}' if type_parts else ''
|
|
872
|
+
if self.field_mappings and name in self.field_mappings:
|
|
873
|
+
expr = self.field_mappings[name]
|
|
874
|
+
if expr is not None:
|
|
875
|
+
val = '${' + expr + '}' if not expr.startswith('${') else expr
|
|
876
|
+
lines.append(f' {name}: {val}{type_comment}')
|
|
877
|
+
elif ex is not None:
|
|
878
|
+
lines.append(f' {name}: {_format_scalar(ex)}{type_comment}')
|
|
879
|
+
else:
|
|
880
|
+
enum = resolved.get('enum', [])
|
|
881
|
+
if enum:
|
|
882
|
+
lines.append(f' {name}: {_format_scalar(enum[0])}{type_comment}')
|
|
883
|
+
else:
|
|
884
|
+
faker = _faker_for(resolved, field_name=name, field_mappings=self.field_mappings)
|
|
885
|
+
if faker:
|
|
886
|
+
lines.append(f' {name}: {faker}{type_comment}')
|
|
887
|
+
else:
|
|
888
|
+
lines.append(f' {name}:{type_comment}')
|
|
889
|
+
return '\n'.join(lines)
|
|
890
|
+
|
|
891
|
+
def _base_json_lines(self) -> str:
|
|
892
|
+
lines = [' base_json:']
|
|
893
|
+
req_set = set(self.required)
|
|
894
|
+
for f in [*self.required, *self.optional]:
|
|
895
|
+
lines.extend(_field_yaml_lines(f, self.props.get(f, {}), self.spec, indent=4,
|
|
896
|
+
example=self.example.get(f), required=req_set,
|
|
897
|
+
field_mappings=self.field_mappings))
|
|
898
|
+
return '\n'.join(lines)
|
|
899
|
+
|
|
900
|
+
@property
|
|
901
|
+
def _enum_rounds(self):
|
|
902
|
+
return max((len(ev) for _, ev in self._all_enum_fields()), default=0)
|
|
903
|
+
|
|
904
|
+
def _variant_methods(self, prefix=''):
|
|
905
|
+
for f in self.required:
|
|
906
|
+
r = resolve_schema(self.props.get(f, {}), self.spec)
|
|
907
|
+
for variant in (r.get('oneOf') or r.get('anyOf') or [])[1:]:
|
|
908
|
+
for sfx in ('', '_required', '_optional_null'):
|
|
909
|
+
yield f'{prefix}_{self._short_tag(variant.get("$ref", ""))}{sfx}'
|
|
910
|
+
|
|
911
|
+
def _enum_combos(self):
|
|
912
|
+
"""枚举交叉值列表,不含 combo 0。"""
|
|
913
|
+
return [{fn: evals[i % len(evals)] for fn, evals in self._all_enum_fields() if len(evals) > 1}
|
|
914
|
+
for i in range(1, self._enum_rounds)]
|
|
915
|
+
|
|
916
|
+
def build(self) -> str:
|
|
917
|
+
all_marks = ', '.join(self.marks + [self.op_id])
|
|
918
|
+
case_common = (f"case_common:\n module: {self.yaml_module}\n describe: {self.summary}\n"
|
|
919
|
+
f" ignore_failed: true\n marks: [{all_marks}]\n"
|
|
920
|
+
f" url: {self.url}\n method: {self.method}")
|
|
921
|
+
if self._has_body:
|
|
922
|
+
case_common += '\n' + self._base_json_lines()
|
|
923
|
+
if self._has_params:
|
|
924
|
+
case_common += '\n' + self._base_params_lines()
|
|
925
|
+
|
|
926
|
+
combos = self._enum_combos()
|
|
927
|
+
ci = 0
|
|
928
|
+
parts = [case_common, self._success()]
|
|
929
|
+
|
|
930
|
+
# 枚举交叉紧跟 base case,在 oneOf 变体之前
|
|
931
|
+
for i in range(ci, len(combos)):
|
|
932
|
+
parts.append(self._success_variant(combos[i], suffix=str(i + 2), desc='遍历枚举'))
|
|
933
|
+
|
|
934
|
+
if self.optional:
|
|
935
|
+
parts.append(self._minimal_case()[0])
|
|
936
|
+
parts.append(self._optional_null_case()[0])
|
|
937
|
+
if self.optional_params:
|
|
938
|
+
parts.append(self._required_case())
|
|
939
|
+
parts.append(self._optional_null_params_case())
|
|
940
|
+
|
|
941
|
+
parts += self._oneof_variant_cases()
|
|
942
|
+
|
|
943
|
+
# 错误用例:必填字段完整覆盖,选填字段只校验类型+枚举
|
|
944
|
+
param_names = {p['name'] for p in self.required_params + self.optional_params}
|
|
945
|
+
type_seen = set()
|
|
946
|
+
for f in self.required:
|
|
947
|
+
self._append_error_cases(parts, f, is_param=f in param_names)
|
|
948
|
+
type_seen.add(f)
|
|
949
|
+
for p in self.required_params:
|
|
950
|
+
self._append_error_cases(parts, p['name'], is_param=True)
|
|
951
|
+
type_seen.add(p['name'])
|
|
952
|
+
# 可选字段:type_invalid + enum_invalid
|
|
953
|
+
for f in self.optional:
|
|
954
|
+
parts.append(self._error_case(f, 'type_invalid'))
|
|
955
|
+
type_seen.add(f)
|
|
956
|
+
for p in self.optional_params:
|
|
957
|
+
name = p['name']
|
|
958
|
+
if name not in type_seen:
|
|
959
|
+
parts.append(self._error_case(name, 'type_invalid', is_param=True))
|
|
960
|
+
type_seen.add(name)
|
|
961
|
+
resolved = self._param_schema(name)
|
|
962
|
+
if resolved.get('enum'):
|
|
963
|
+
parts.append(self._error_case(name, 'enum_invalid', is_param=True))
|
|
964
|
+
# 嵌套字段:enum_invalid → type_invalid(顶层已覆盖的跳过)
|
|
965
|
+
for dotpath, _ in self._all_enum_fields():
|
|
966
|
+
if dotpath not in type_seen and dotpath.rsplit('.', 1)[-1] not in type_seen:
|
|
967
|
+
is_p = dotpath.rsplit('.', 1)[-1] in param_names
|
|
968
|
+
parts.append(self._error_case(dotpath, 'enum_invalid', is_param=is_p))
|
|
969
|
+
type_seen.add(dotpath)
|
|
970
|
+
for dp in self._all_scalar_fields() + self._non_scalar_fields():
|
|
971
|
+
if dp not in type_seen and dp.rsplit('.', 1)[-1] not in type_seen:
|
|
972
|
+
is_p = dp.rsplit('.', 1)[-1] in param_names
|
|
973
|
+
parts.append(self._error_case(dp, 'type_invalid', is_param=is_p))
|
|
974
|
+
type_seen.add(dp)
|
|
975
|
+
# path param 错误用例
|
|
976
|
+
parts += self._path_param_error_cases()
|
|
977
|
+
return '\n\n\n'.join(parts) + '\n'
|
|
978
|
+
|
|
979
|
+
def _append_error_cases(self, parts, name, is_param=False, type_seen=None, enum_paths=None, scalar_dp_by_short=None):
|
|
980
|
+
"""为单个字段按顺序追加 empty→missing→blank→type_invalid→enum_invalid。"""
|
|
981
|
+
is_str = self._is_string_param({'name': name, 'schema': self._param_schema(name)}) if is_param else self._is_string_field(name)
|
|
982
|
+
for k in self._str_kinds if is_str else self._kinds:
|
|
983
|
+
parts.append(self._error_case(name, k, is_param=is_param))
|
|
984
|
+
dp = scalar_dp_by_short.get(name, name) if scalar_dp_by_short else name
|
|
985
|
+
if type_seen is None or name not in type_seen:
|
|
986
|
+
parts.append(self._error_case(dp, 'type_invalid', is_param=is_param))
|
|
987
|
+
if type_seen is not None:
|
|
988
|
+
type_seen.add(name)
|
|
989
|
+
resolved = self._param_schema(name) if is_param else self._resolve_field(name)
|
|
990
|
+
if resolved.get('enum'):
|
|
991
|
+
parts.append(self._error_case(dp if enum_paths and dp in enum_paths else name, 'enum_invalid', is_param=is_param))
|
|
992
|
+
|
|
993
|
+
def build_py(self, account: str) -> str:
|
|
994
|
+
class_name = snake_to_pascal(self.op_id)
|
|
995
|
+
m = f' self.request(account="{account}")'
|
|
996
|
+
setup = ' def test_setup(self):\n ...\n\n def test_teardown(self):\n ...'
|
|
997
|
+
methods = [setup, f' def test_{self.op_id}(self):\n{m}']
|
|
998
|
+
|
|
999
|
+
combos = self._enum_combos()
|
|
1000
|
+
|
|
1001
|
+
# 枚举组合(与 YAML 顺序一致:success → combos → optional → oneof → errors)
|
|
1002
|
+
for i in range(len(combos)):
|
|
1003
|
+
methods.append(f' def test_{self.op_id}_{i + 2}(self):\n{m}')
|
|
1004
|
+
if self.optional:
|
|
1005
|
+
methods.append(f' def test_{self.op_id}_required(self):\n{m}')
|
|
1006
|
+
methods.append(f' def test_{self.op_id}_optional_null(self):\n{m}')
|
|
1007
|
+
if self.optional_params:
|
|
1008
|
+
methods.append(f' def test_{self.op_id}_required(self):\n{m}')
|
|
1009
|
+
methods.append(f' def test_{self.op_id}_optional_null(self):\n{m}')
|
|
1010
|
+
for v in self._variant_methods():
|
|
1011
|
+
methods.append(f' def test_{self.op_id}{v}(self):\n{m}')
|
|
1012
|
+
def _add_py(sn, is_param=False, kinds_only=False):
|
|
1013
|
+
if not kinds_only:
|
|
1014
|
+
is_str = self._is_string_param({'name': sn, 'schema': self._param_schema(sn)}) if is_param else self._is_string_field(sn)
|
|
1015
|
+
for k in self._str_kinds if is_str else self._kinds:
|
|
1016
|
+
methods.append(f' def test_{camel_to_snake(sn)}_{k}(self):\n{m}')
|
|
1017
|
+
methods.append(f' def test_{camel_to_snake(sn)}_type_invalid(self):\n{m}')
|
|
1018
|
+
resolved = self._param_schema(sn) if is_param else self._resolve_field(sn)
|
|
1019
|
+
if resolved.get('enum'):
|
|
1020
|
+
methods.append(f' def test_{camel_to_snake(sn)}_enum_invalid(self):\n{m}')
|
|
1021
|
+
|
|
1022
|
+
type_seen = set()
|
|
1023
|
+
for f in self.required:
|
|
1024
|
+
_add_py(f)
|
|
1025
|
+
type_seen.add(camel_to_snake(f))
|
|
1026
|
+
for p in self.required_params:
|
|
1027
|
+
_add_py(p['name'], is_param=True)
|
|
1028
|
+
type_seen.add(camel_to_snake(p['name']))
|
|
1029
|
+
for f in self.optional:
|
|
1030
|
+
_add_py(f, kinds_only=True)
|
|
1031
|
+
type_seen.add(camel_to_snake(f))
|
|
1032
|
+
for p in self.optional_params:
|
|
1033
|
+
sn = camel_to_snake(p['name'])
|
|
1034
|
+
if sn not in type_seen:
|
|
1035
|
+
_add_py(p['name'], is_param=True, kinds_only=True)
|
|
1036
|
+
type_seen.add(sn)
|
|
1037
|
+
for dotpath, _ in self._all_enum_fields():
|
|
1038
|
+
sn = camel_to_snake(dotpath.rsplit('.', 1)[-1])
|
|
1039
|
+
if sn not in type_seen:
|
|
1040
|
+
methods.append(f' def test_{sn}_enum_invalid(self):\n{m}')
|
|
1041
|
+
type_seen.add(sn)
|
|
1042
|
+
for dp in self._all_scalar_fields() + self._non_scalar_fields():
|
|
1043
|
+
sn = camel_to_snake(dp.rsplit('.', 1)[-1])
|
|
1044
|
+
if sn not in type_seen:
|
|
1045
|
+
methods.append(f' def test_{sn}_type_invalid(self):\n{m}')
|
|
1046
|
+
type_seen.add(sn)
|
|
1047
|
+
# path param 错误用例
|
|
1048
|
+
for pp in self.path_params:
|
|
1049
|
+
sn = camel_to_snake(pp['name'])
|
|
1050
|
+
methods.append(f' def test_{sn}_invalid_value(self):\n{m}')
|
|
1051
|
+
|
|
1052
|
+
return (f"from test_case import BaseTestCase\n\n\n"
|
|
1053
|
+
f"class Test{class_name}(BaseTestCase):\n\n"
|
|
1054
|
+
+ '\n\n'.join(methods) + '\n')
|
|
1055
|
+
|
|
1056
|
+
|
|
1057
|
+
# ---------------------------------------------------------------------------
|
|
1058
|
+
# Entry point
|
|
1059
|
+
# ---------------------------------------------------------------------------
|
|
1060
|
+
|
|
1061
|
+
def generate(spec: dict, path_filters: list = None, field_mappings: dict = None) -> dict:
|
|
1062
|
+
"""遍历 OpenAPI 规范中的所有接口路径,生成每个操作的 CaseBuilder 对象。"""
|
|
1063
|
+
results = {}
|
|
1064
|
+
filter_set = set(path_filters) if path_filters else None
|
|
1065
|
+
|
|
1066
|
+
for path, path_item in spec.get('paths', {}).items():
|
|
1067
|
+
if filter_set and path not in filter_set:
|
|
1068
|
+
continue
|
|
1069
|
+
|
|
1070
|
+
for method, operation in path_item.items():
|
|
1071
|
+
if method in ('parameters', 'summary', 'description', 'servers'):
|
|
1072
|
+
continue
|
|
1073
|
+
if not isinstance(operation, dict):
|
|
1074
|
+
continue
|
|
1075
|
+
|
|
1076
|
+
summary = operation.get('summary', path.split('/')[-1])
|
|
1077
|
+
op_id = operation.get('operationId', '')
|
|
1078
|
+
tag = (operation.get('tags') or ['default'])[0]
|
|
1079
|
+
module = tag_to_module(tag)
|
|
1080
|
+
yaml_module = tag_to_yaml_module(tag)
|
|
1081
|
+
marks = tag_to_marks(tag)
|
|
1082
|
+
|
|
1083
|
+
all_params = path_item.get('parameters', []) + operation.get('parameters', [])
|
|
1084
|
+
path_params = [p for p in all_params if p.get('in') == 'path']
|
|
1085
|
+
query_params = [p for p in all_params if p.get('in') == 'query']
|
|
1086
|
+
required_params = [p for p in query_params if p.get('required')]
|
|
1087
|
+
optional_params = [p for p in query_params if not p.get('required')]
|
|
1088
|
+
|
|
1089
|
+
required, optional, props, example = [], [], {}, {}
|
|
1090
|
+
body = operation.get('requestBody', {})
|
|
1091
|
+
if body:
|
|
1092
|
+
json_content = body.get('content', {}).get('application/json', {})
|
|
1093
|
+
schema = json_content.get('schema', {})
|
|
1094
|
+
example = json_content.get('example') or {}
|
|
1095
|
+
if schema:
|
|
1096
|
+
props, req_list = extract_properties(schema, spec)
|
|
1097
|
+
for f in props:
|
|
1098
|
+
(required if f in req_list else optional).append(f)
|
|
1099
|
+
|
|
1100
|
+
builder = CaseBuilder(
|
|
1101
|
+
url=path,
|
|
1102
|
+
method=method,
|
|
1103
|
+
summary=summary,
|
|
1104
|
+
op_id=op_id,
|
|
1105
|
+
tag=tag,
|
|
1106
|
+
required=required,
|
|
1107
|
+
optional=optional,
|
|
1108
|
+
props=props,
|
|
1109
|
+
required_params=required_params,
|
|
1110
|
+
optional_params=optional_params,
|
|
1111
|
+
path_params=path_params,
|
|
1112
|
+
example=example,
|
|
1113
|
+
extract_fields=extract_response_fields(operation, spec),
|
|
1114
|
+
response_root_props=get_response_root_props(operation, spec),
|
|
1115
|
+
spec=spec,
|
|
1116
|
+
field_mappings=field_mappings,
|
|
1117
|
+
marks=marks,
|
|
1118
|
+
yaml_module=yaml_module,
|
|
1119
|
+
)
|
|
1120
|
+
|
|
1121
|
+
raw = re.sub(r'[^a-zA-Z0-9]+', '_', summary).strip('_') or re.sub(r'[^a-zA-Z0-9]+', '_', op_id).strip('_')
|
|
1122
|
+
filename = f"test_{camel_to_snake(raw)}.yml"
|
|
1123
|
+
results[(module, filename)] = builder
|
|
1124
|
+
|
|
1125
|
+
return results
|
|
1126
|
+
|
|
1127
|
+
|
|
1128
|
+
def _load_spec_from_url(url: str) -> dict:
|
|
1129
|
+
"""从 URL 加载 OpenAPI 规范(支持 Apifox 文档在线地址)。"""
|
|
1130
|
+
req = urllib.request.Request(url, headers={'User-Agent': 'swagger-gen/1.0',
|
|
1131
|
+
'Accept': 'application/json'})
|
|
1132
|
+
ctx = ssl.create_default_context()
|
|
1133
|
+
ctx.check_hostname = False
|
|
1134
|
+
ctx.verify_mode = ssl.CERT_NONE
|
|
1135
|
+
with urllib.request.urlopen(req, timeout=30, context=ctx) as resp:
|
|
1136
|
+
raw = resp.read().decode('utf-8')
|
|
1137
|
+
md_match = re.search(r'```(?:json|yaml|yml)?\s*\n([\s\S]*?)\n```', raw)
|
|
1138
|
+
if md_match:
|
|
1139
|
+
raw = md_match.group(1).strip()
|
|
1140
|
+
try:
|
|
1141
|
+
data = json.loads(raw)
|
|
1142
|
+
except json.JSONDecodeError:
|
|
1143
|
+
try:
|
|
1144
|
+
import yaml
|
|
1145
|
+
data = yaml.safe_load(raw)
|
|
1146
|
+
except ImportError:
|
|
1147
|
+
sys.exit("Response is YAML but PyYAML is not installed. Run: pip install pyyaml")
|
|
1148
|
+
if isinstance(data, dict) and 'data' in data and 'openapi' in data.get('data', {}):
|
|
1149
|
+
return data['data']
|
|
1150
|
+
if isinstance(data, dict) and ('openapi' in data or 'swagger' in data):
|
|
1151
|
+
return data
|
|
1152
|
+
sys.exit(f"Cannot find OpenAPI spec in response. Keys: {list(data.keys()) if isinstance(data, dict) else type(data)}")
|
|
1153
|
+
|
|
1154
|
+
|
|
1155
|
+
def _load_spec_from_file(spec_path: Path) -> dict:
|
|
1156
|
+
"""从本地文件加载 OpenAPI 规范(支持 JSON / YAML 格式)。"""
|
|
1157
|
+
if not spec_path.exists():
|
|
1158
|
+
sys.exit(f"File not found: {spec_path}")
|
|
1159
|
+
if spec_path.suffix in ('.yaml', '.yml'):
|
|
1160
|
+
try:
|
|
1161
|
+
import yaml
|
|
1162
|
+
with open(spec_path, encoding='utf-8') as f:
|
|
1163
|
+
return yaml.safe_load(f)
|
|
1164
|
+
except ImportError:
|
|
1165
|
+
sys.exit("PyYAML not installed. Run: pip install pyyaml")
|
|
1166
|
+
with open(spec_path, encoding='utf-8') as f:
|
|
1167
|
+
return json.load(f)
|
|
1168
|
+
|
|
1169
|
+
|
|
1170
|
+
def _parse_args():
|
|
1171
|
+
"""解析命令行参数。"""
|
|
1172
|
+
import argparse
|
|
1173
|
+
parser = argparse.ArgumentParser(description='根据 OpenAPI 规范生成 YAML 测试用例骨架')
|
|
1174
|
+
parser.add_argument('--app', '-a', required=True, help='应用名称(必填),如 --app aaa')
|
|
1175
|
+
parser.add_argument('--env', '-e', default='dev', help='环境名称,默认 dev(用例数据不按环境分目录,不影响输出路径)')
|
|
1176
|
+
parser.add_argument('--account', '-acc', default='user', help='self.request(account=...) 中的账号名,默认 user')
|
|
1177
|
+
parser.add_argument('--spec', '-s', required=True, help='本地文件路径(json,yml)或Apifox文档在线地址')
|
|
1178
|
+
parser.add_argument('--path', '-p', nargs='+', help='只生成指定接口路径的用例,可多个空格分隔')
|
|
1179
|
+
parser.add_argument('--output', '-o', default=None, help='附加子目录,同时追加到 YAML 和 Python 输出路径末尾')
|
|
1180
|
+
parser.add_argument('--dry-run', action='store_true', help='只预览输出内容,不写入文件')
|
|
1181
|
+
parser.add_argument('--force', '-f', action='store_true', help='强制覆盖已存在的文件')
|
|
1182
|
+
parser.add_argument('--mappings', '-m', default=None, help='AI 生成的字段→Faker 映射 JSON 对象字符串')
|
|
1183
|
+
return parser.parse_args()
|
|
1184
|
+
|
|
1185
|
+
|
|
1186
|
+
def _resolve_paths(args):
|
|
1187
|
+
"""根据参数解析输出路径。
|
|
1188
|
+
|
|
1189
|
+
必须和运行时找 YAML 的目录一致:find_data_path_by_case() 是在 {DATA_DIR}/{app}/ 下
|
|
1190
|
+
递归找同名 .yml 的,路径里不带 env。中间多一层 env 生成出来的用例运行时找不到数据文件。
|
|
1191
|
+
另外这里取 settings 里的 DATA_DIR / CASES_DIR 而不是写死相对路径,免得两边再次跑偏。
|
|
1192
|
+
"""
|
|
1193
|
+
output_base = Path(DATA_DIR) / args.app
|
|
1194
|
+
py_base = Path(CASES_DIR) / args.app
|
|
1195
|
+
if args.output:
|
|
1196
|
+
output_base = output_base / args.output
|
|
1197
|
+
py_base = py_base / args.output
|
|
1198
|
+
return output_base, py_base
|
|
1199
|
+
|
|
1200
|
+
|
|
1201
|
+
def _write_builder(builder, module, yml_filename, output_base, py_base, account, dry_run, force=False):
|
|
1202
|
+
"""将 CaseBuilder 内容写入 YAML 和 Python 文件(dry_run 模式下只输出预览)。"""
|
|
1203
|
+
yml_content = builder.build()
|
|
1204
|
+
py_filename = yml_filename.replace('.yml', '.py')
|
|
1205
|
+
py_content = builder.build_py(account)
|
|
1206
|
+
|
|
1207
|
+
if dry_run:
|
|
1208
|
+
logger.info(f"\n# {'='*58}")
|
|
1209
|
+
logger.info(f"# YAML: {output_base}/{module}/{yml_filename}")
|
|
1210
|
+
logger.info(f"# {'='*58}\n")
|
|
1211
|
+
logger.info(yml_content)
|
|
1212
|
+
logger.info(f"\n# {'='*58}")
|
|
1213
|
+
logger.info(f"# Python: {py_base}/{module}/{py_filename}")
|
|
1214
|
+
logger.info(f"# {'='*58}\n")
|
|
1215
|
+
logger.info(py_content)
|
|
1216
|
+
return
|
|
1217
|
+
|
|
1218
|
+
yml_dir = output_base / module
|
|
1219
|
+
yml_dir.mkdir(parents=True, exist_ok=True)
|
|
1220
|
+
yml_path = yml_dir / yml_filename
|
|
1221
|
+
if yml_path.exists() and not force:
|
|
1222
|
+
logger.warning(f"Skipped YAML (already exists): {yml_path}")
|
|
1223
|
+
else:
|
|
1224
|
+
yml_path.write_text(yml_content, encoding='utf-8')
|
|
1225
|
+
logger.info(f"Generated YAML: {yml_path}")
|
|
1226
|
+
|
|
1227
|
+
py_dir = py_base / module
|
|
1228
|
+
py_dir.mkdir(parents=True, exist_ok=True)
|
|
1229
|
+
p = py_dir
|
|
1230
|
+
while True:
|
|
1231
|
+
init_file = p / '__init__.py'
|
|
1232
|
+
if not init_file.exists():
|
|
1233
|
+
init_file.touch()
|
|
1234
|
+
if p == py_base.parent:
|
|
1235
|
+
break
|
|
1236
|
+
p = p.parent
|
|
1237
|
+
py_path = py_dir / py_filename
|
|
1238
|
+
if py_path.exists() and not force:
|
|
1239
|
+
logger.warning(f"Skipped PY (already exists): {py_path}")
|
|
1240
|
+
else:
|
|
1241
|
+
py_path.write_text(py_content, encoding='utf-8')
|
|
1242
|
+
logger.info(f"Generated PY: {py_path}")
|
|
1243
|
+
|
|
1244
|
+
|
|
1245
|
+
def main():
|
|
1246
|
+
"""入口函数:解析参数 -> 加载 OpenAPI 规范 -> 生成测试用例 -> 写入文件。"""
|
|
1247
|
+
args = _parse_args()
|
|
1248
|
+
|
|
1249
|
+
field_mappings = None
|
|
1250
|
+
if args.mappings:
|
|
1251
|
+
field_mappings = json.loads(args.mappings)
|
|
1252
|
+
|
|
1253
|
+
spec = (_load_spec_from_url(args.spec)
|
|
1254
|
+
if args.spec.startswith(('http://', 'https://'))
|
|
1255
|
+
else _load_spec_from_file(Path(args.spec)))
|
|
1256
|
+
|
|
1257
|
+
results = generate(spec, path_filters=args.path, field_mappings=field_mappings)
|
|
1258
|
+
if not results:
|
|
1259
|
+
logger.warning("No matching paths found.")
|
|
1260
|
+
return
|
|
1261
|
+
|
|
1262
|
+
output_base, py_base = _resolve_paths(args)
|
|
1263
|
+
for (module, yml_filename), builder in results.items():
|
|
1264
|
+
_write_builder(builder, module, yml_filename, output_base, py_base, args.account, args.dry_run, args.force)
|
|
1265
|
+
|
|
1266
|
+
|
|
1267
|
+
if __name__ == '__main__':
|
|
1268
|
+
main()
|