har2pytest 1.7.2__tar.gz → 1.7.4__tar.gz
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.
- {har2pytest-1.7.2/har2pytest.egg-info → har2pytest-1.7.4}/PKG-INFO +1 -1
- {har2pytest-1.7.2 → har2pytest-1.7.4}/docs/testcase_generation_modes.md +44 -18
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/__main__.py +23 -1
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/api_generator.py +1 -1
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/api_metadata.py +1 -1
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/parametrized_codegen.py +24 -4
- har2pytest-1.7.4/har2pytest/pytest_utils.py +118 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/p_runtime_value_method.j2 +2 -2
- har2pytest-1.7.4/har2pytest/templates/p_test_0_collect.j2 +12 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/p_test_method_assertions.j2 +2 -2
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/testcase_generator.py +27 -5
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/utils.py +15 -5
- {har2pytest-1.7.2 → har2pytest-1.7.4/har2pytest.egg-info}/PKG-INFO +1 -1
- {har2pytest-1.7.2 → har2pytest-1.7.4}/pyproject.toml +1 -1
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_api_generator.py +2 -2
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_main.py +45 -1
- har2pytest-1.7.4/tests/test_pytest_utils.py +321 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_testcase_generator.py +144 -19
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_utils.py +2 -1
- har2pytest-1.7.2/har2pytest/pytest_utils.py +0 -39
- har2pytest-1.7.2/har2pytest/templates/p_test_0_collect.j2 +0 -22
- har2pytest-1.7.2/tests/test_pytest_utils.py +0 -120
- {har2pytest-1.7.2 → har2pytest-1.7.4}/LICENSE +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/MANIFEST.in +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/README.md +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/docs/api_file_generation.md +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/docs/configuration.md +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/docs/har_file_parsing.md +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/docs/index.md +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/docs/swagger_document_parsing.md +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/__init__.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/allure_compat.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/client.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/codegen.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/config.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/har_generator.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/har_parser.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/logger.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/models.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/param_builder.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/scenario_codegen.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/step_values.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/swagger_handler.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/api_file_upload.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/api_function_def.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/api_http_method.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/api_imports.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/api_multipart_form.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/p_data_dict.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/p_list_query_data.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/p_method_body.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/p_parametrize_decorator.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/p_test_method_definition.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/s_step_asserts.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/s_step_data.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/s_step_heading.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/s_step_none.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/s_step_params.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/s_step_upload.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/s_test_method_definition.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/templates/tc_description.j2 +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/time_pair.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest/url_matcher.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest.egg-info/SOURCES.txt +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest.egg-info/dependency_links.txt +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest.egg-info/entry_points.txt +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest.egg-info/requires.txt +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest.egg-info/top_level.txt +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/har2pytest_config.json.example +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/setup.cfg +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_allure_compat.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_api_metadata.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_async_client.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_client.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_codegen.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_config.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_har_generator.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_har_parser.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_logger.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_step_values.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_swagger_handler.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_testcase_profiles.py +0 -0
- {har2pytest-1.7.2 → har2pytest-1.7.4}/tests/test_url_matcher.py +0 -0
|
@@ -133,9 +133,15 @@ flowchart TD
|
|
|
133
133
|
|
|
134
134
|
#### `test_0` 收集方法
|
|
135
135
|
|
|
136
|
-
`test_0_{function_name}`
|
|
137
|
-
|
|
138
|
-
|
|
136
|
+
`test_0_{function_name}` 发送一次默认查询,调用 `har2pytest.pytest_utils.collect_list_query_data`
|
|
137
|
+
把响应字段值收集进 `list_query_data`(原地更新类属性):
|
|
138
|
+
|
|
139
|
+
1. 精确匹配参数名(不区分大小写);
|
|
140
|
+
2. 响应字段无同名参数时降级前缀模糊匹配——参数被响应字段名包含(如参数 `operator`
|
|
141
|
+
可匹配响应字段 `operatorName`/`operatorNo`,命中多个时取第一个),或参数名包含
|
|
142
|
+
响应字段名(如参数 `demoCodeList` 包含响应字段 `demoCode`,值包装为单元素列表)。
|
|
143
|
+
|
|
144
|
+
同一参数只取首条记录的值;响应值优先:收集到的值覆盖类属性已有值(含 HAR 录制值)。
|
|
139
145
|
|
|
140
146
|
#### 数组类型参数(多选)
|
|
141
147
|
|
|
@@ -430,6 +436,21 @@ class TestClass:
|
|
|
430
436
|
3. 关键字未命中时一律回落 scenario 单请求用例(含带参数的非列表接口,如"获取协议"),
|
|
431
437
|
避免把非列表接口渲染成 list_query 形态(test_0 收集语义不符)。
|
|
432
438
|
|
|
439
|
+
#### CLI 命令与 --only-mode 过滤
|
|
440
|
+
|
|
441
|
+
# 批量生成全部接口(逐接口自动决策模式)
|
|
442
|
+
har2pytest testcase --pattern batch --api-files apis/mobile_application
|
|
443
|
+
|
|
444
|
+
# 仅生成识别为 list_query(参数化列表查询)的接口
|
|
445
|
+
har2pytest testcase --pattern batch --only-mode list_query --api-files apis/mobile_application
|
|
446
|
+
|
|
447
|
+
# 仅生成识别为 complex_scenario(场景)的接口
|
|
448
|
+
har2pytest testcase --pattern batch --only-mode complex_scenario --api-files apis/mobile_application
|
|
449
|
+
|
|
450
|
+
`--only-mode` 仅 batch 模式生效:按 `_resolve_testcase_mode()` 识别结果过滤,
|
|
451
|
+
`list_query`=参数化产物、`complex_scenario`=场景产物(含描述未命中列表关键字回落 scenario 的接口);
|
|
452
|
+
被过滤的接口不计入 `skipped`,单独计入 `filtered`。
|
|
453
|
+
|
|
433
454
|
### 模式配置化(TESTCASE_PROFILES)
|
|
434
455
|
|
|
435
456
|
在 `har2pytest_config.json` 中按 URL 显式指定模式,消除"靠中文描述关键字判定"的脆弱点。
|
|
@@ -453,18 +474,21 @@ batch 模式支持两类输入(CLI 层解析,逗号分隔混合输入):
|
|
|
453
474
|
|
|
454
475
|
```mermaid
|
|
455
476
|
flowchart TD
|
|
456
|
-
A["generate_batch_testcases<br/>api_files_list, task_id?, overwrite?, har_file_path?"] --> B["展开文件列表<br/>目录递归扫描 / 校验 api-dir 归属"]
|
|
477
|
+
A["generate_batch_testcases<br/>api_files_list, task_id?, overwrite?, har_file_path?, only_mode?"] --> B["展开文件列表<br/>目录递归扫描 / 校验 api-dir 归属"]
|
|
457
478
|
B --> C["asyncio.gather 并行处理 process_single"]
|
|
458
|
-
C --> D
|
|
459
|
-
D
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
G
|
|
464
|
-
I
|
|
465
|
-
I
|
|
466
|
-
|
|
467
|
-
|
|
479
|
+
C --> D["_resolve_testcase_mode<br/>TESTCASE_PROFILES / 关键字启发式"]
|
|
480
|
+
D --> E{指定 --only-mode<br/>且识别模式不匹配?}
|
|
481
|
+
E -->|是| F["跳过 filtered++"]
|
|
482
|
+
E -->|否| G{文件存在且未 overwrite?}
|
|
483
|
+
G -->|是| H["跳过 skipped++"]
|
|
484
|
+
G -->|否| I{识别模式}
|
|
485
|
+
I -->|parametrized| J["generate_parametrized_test_content<br/>api_file, task_id"]
|
|
486
|
+
I -->|scenario| K["generate_scenario_test_content<br/>har_file_path, [api_file], task_id, api_file, cached_requests"]
|
|
487
|
+
J --> L{内容为空?}
|
|
488
|
+
L -->|是| K
|
|
489
|
+
L -->|否| M["write_test_file 写入"]
|
|
490
|
+
K --> M
|
|
491
|
+
M --> N["汇总结果 + format_directory"]
|
|
468
492
|
```
|
|
469
493
|
|
|
470
494
|
### 详细步骤
|
|
@@ -472,20 +496,22 @@ flowchart TD
|
|
|
472
496
|
#### Step 1: `generate_batch_testcases()`(异步 + 并行)
|
|
473
497
|
|
|
474
498
|
```
|
|
475
|
-
输入: api_files_list, task_id?, overwrite=False, har_file_path?
|
|
499
|
+
输入: api_files_list, task_id?, overwrite=False, har_file_path?, only_mode?
|
|
476
500
|
└─ 展开路径: 目录 → 递归收集 .py 文件;普通文件 → 直接追加
|
|
477
501
|
└─ 校验所有文件位于 api_dir 内(否则整批失败并提示 --api-dir)
|
|
478
502
|
└─ 传入 HAR 文件时预先解析请求列表(供场景模式复用)
|
|
479
503
|
└─ asyncio.gather 并行处理,每个 api_file 独立 process_single():
|
|
480
504
|
├─ 文件不存在 → "skipped"
|
|
481
505
|
├─ 无 function_name → "failed"
|
|
506
|
+
├─ _resolve_testcase_mode(api_file) 决策模式(parametrized / scenario)
|
|
507
|
+
├─ 指定 only_mode 时按识别结果过滤:list_query=parametrized、
|
|
508
|
+
│ complex_scenario=scenario(含关键字未命中的回落接口),不匹配 → "filtered"
|
|
482
509
|
├─ 测试文件已存在且未 overwrite → "skipped"
|
|
483
|
-
├─
|
|
484
|
-
│ ├─ parametrized → generate_parametrized_test_content()
|
|
510
|
+
├─ parametrized → generate_parametrized_test_content()
|
|
485
511
|
│ └─ scenario → generate_scenario_test_content()
|
|
486
512
|
├─ parametrized 内容为空 → 回退场景模式
|
|
487
513
|
└─ write_test_file() 同步写入 → "generated"
|
|
488
|
-
└─ 汇总 {total, skipped, generated, failed, generated_files}
|
|
514
|
+
└─ 汇总 {total, skipped, generated, failed, filtered, generated_files}
|
|
489
515
|
└─ 有产出时 format_directory() 批量 ruff 格式化
|
|
490
516
|
```
|
|
491
517
|
|
|
@@ -101,6 +101,12 @@ def main():
|
|
|
101
101
|
|
|
102
102
|
# 生成复杂场景测试用例(传mark)
|
|
103
103
|
har2pytest testcase api_request.har --pattern complex_scenario --url /api/user/login --mark test_4295
|
|
104
|
+
|
|
105
|
+
# 批量生成(仅生成识别为 list_query 模式的接口)
|
|
106
|
+
har2pytest testcase --pattern batch --only-mode list_query --api-files apis/mobile_application
|
|
107
|
+
|
|
108
|
+
# 批量生成(仅生成识别为 complex_scenario 模式的接口)
|
|
109
|
+
har2pytest testcase --pattern batch --only-mode complex_scenario --api-files apis/mobile_application
|
|
104
110
|
""",
|
|
105
111
|
)
|
|
106
112
|
tc_parser.add_argument("har_file", nargs="?", default="api_request.har", help="HAR文件路径(默认 api_request.har)")
|
|
@@ -117,6 +123,15 @@ def main():
|
|
|
117
123
|
tc_parser.add_argument(
|
|
118
124
|
"--api-files", default="api_request.har", help="指定API文件或HAR文件(batch模式使用,多个文件用逗号分隔)"
|
|
119
125
|
)
|
|
126
|
+
tc_parser.add_argument(
|
|
127
|
+
"--only-mode",
|
|
128
|
+
choices=["list_query", "complex_scenario"],
|
|
129
|
+
default=None,
|
|
130
|
+
help=(
|
|
131
|
+
"仅生成指定模式的测试用例(batch模式使用):list_query=仅参数化列表查询接口,"
|
|
132
|
+
"complex_scenario=仅场景接口(按模式识别结果过滤)"
|
|
133
|
+
),
|
|
134
|
+
)
|
|
120
135
|
_add_overwrite_arg(tc_parser, "强制覆盖已存在的测试用例文件")
|
|
121
136
|
tc_parser.add_argument(
|
|
122
137
|
"--async",
|
|
@@ -237,6 +252,11 @@ async def handle_testcase(args):
|
|
|
237
252
|
output_dir = args.output
|
|
238
253
|
api_dir = args.api_dir or APIConfig.DEFAULT_API_DIR()
|
|
239
254
|
overwrite = args.overwrite
|
|
255
|
+
only_mode = args.only_mode
|
|
256
|
+
|
|
257
|
+
# --only-mode 仅 batch 模式生效;其他模式单接口生成无需过滤
|
|
258
|
+
if only_mode and pattern != "batch":
|
|
259
|
+
logger.warning(f"--only-mode 仅在 batch 模式下生效,当前模式 {pattern} 将忽略该参数")
|
|
240
260
|
|
|
241
261
|
# --mark 同时用作 @pytest.mark.<task_id> 与输出子目录名:
|
|
242
262
|
# 非标识符(如 "2025-01-01"、纯数字)会让每个接口都生成失败,直接拒绝
|
|
@@ -346,11 +366,13 @@ async def handle_testcase(args):
|
|
|
346
366
|
logger.info("-" * 50)
|
|
347
367
|
|
|
348
368
|
result = await generator.generate_batch_testcases(
|
|
349
|
-
api_files_list, task_id, overwrite=overwrite, har_file_path=har_file_for_batch
|
|
369
|
+
api_files_list, task_id, overwrite=overwrite, har_file_path=har_file_for_batch, only_mode=only_mode
|
|
350
370
|
)
|
|
351
371
|
|
|
352
372
|
logger.info("-" * 50)
|
|
353
373
|
logger.info(f"总API文件数: {result['total']}")
|
|
374
|
+
if only_mode:
|
|
375
|
+
logger.info(f"模式过滤跳过(非 {only_mode}): {result['filtered']}")
|
|
354
376
|
logger.info(f"跳过(已存在): {result['skipped']}")
|
|
355
377
|
logger.info(f"成功生成: {result['generated']}")
|
|
356
378
|
logger.info(f"失败: {result['failed']}")
|
|
@@ -279,7 +279,7 @@ class APIGenerator:
|
|
|
279
279
|
if "," not in pn and pn not in har_params:
|
|
280
280
|
har_params[pn] = ""
|
|
281
281
|
# HAR 场景从参数基线自行配对时间对(无 Swagger 备注可提取格式,
|
|
282
|
-
# 默认 %Y-%m-%d),写入 har_time_pairs 供测试生成动态计算时间参数
|
|
282
|
+
# 默认 %Y-%m-%d %H:%M:%S),写入 har_time_pairs 供测试生成动态计算时间参数
|
|
283
283
|
har_time_pairs = build_time_pairs({name: "" for name in har_params}) or None
|
|
284
284
|
# 以 param_remarks 为基准(保证所有 Swagger 定义的参数都在),
|
|
285
285
|
# 用类型感知默认值覆盖(缺失的参数字符串兜底)
|
|
@@ -35,7 +35,7 @@ HAR_PARAM_VALUES_FIELD = "har_param_values"
|
|
|
35
35
|
# HAR 分析得出的参数基线值(常量参数 + 首条请求的所有参数值)
|
|
36
36
|
HAR_PARAMS_FIELD = "har_params"
|
|
37
37
|
|
|
38
|
-
# HAR 分析得出的时间参数对(从 HAR 参数基线自行配对,无 Swagger 备注时格式默认 %Y-%m-%d)
|
|
38
|
+
# HAR 分析得出的时间参数对(从 HAR 参数基线自行配对,无 Swagger 备注时格式默认 %Y-%m-%d %H:%M:%S)
|
|
39
39
|
HAR_TIME_PAIRS_FIELD = "har_time_pairs"
|
|
40
40
|
|
|
41
41
|
|
|
@@ -123,6 +123,16 @@ def gen_test_case_imports(
|
|
|
123
123
|
]
|
|
124
124
|
)
|
|
125
125
|
|
|
126
|
+
if is_list_query:
|
|
127
|
+
# test_0 收集逻辑收口到 pytest_utils.collect_list_query_data,产物只调用;
|
|
128
|
+
# 断言侧明细提取统一用 extract_list_items(兼容 lists/list/records 等键名)
|
|
129
|
+
content.extend(
|
|
130
|
+
[
|
|
131
|
+
"from har2pytest.pytest_utils import collect_list_query_data, extract_list_items",
|
|
132
|
+
"",
|
|
133
|
+
]
|
|
134
|
+
)
|
|
135
|
+
|
|
126
136
|
if api_files:
|
|
127
137
|
service_imports: dict[str | None, list[str]] = {}
|
|
128
138
|
for api_file in api_files:
|
|
@@ -472,12 +482,20 @@ def gen_batch_parametrized_test_methods(
|
|
|
472
482
|
title_param = title_param.split(" ")[0]
|
|
473
483
|
|
|
474
484
|
search_enabled = "," not in param_name
|
|
485
|
+
is_list_param = param_name.lower().endswith("list")
|
|
475
486
|
verify_assert = ""
|
|
476
487
|
if search_enabled:
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
488
|
+
if is_list_param:
|
|
489
|
+
# List 集合参数期望值是列表(收集时包装),断言逐元素比较
|
|
490
|
+
verify_assert = (
|
|
491
|
+
f'assert v is None or any(str(v) == str(x) for x in self.list_query_data["{param_name}"]), '
|
|
492
|
+
f"f'字段 {{k}} 值 {{v}} 与搜索条件 {param_name}={{self.list_query_data[\"{param_name}\"]}} 不一致'"
|
|
493
|
+
)
|
|
494
|
+
else:
|
|
495
|
+
verify_assert = (
|
|
496
|
+
f'assert v is None or str(v) == str(self.list_query_data["{param_name}"]), '
|
|
497
|
+
f"f'字段 {{k}} 值 {{v}} 与搜索条件 {param_name}={{self.list_query_data[\"{param_name}\"]}} 不一致'"
|
|
498
|
+
)
|
|
481
499
|
|
|
482
500
|
content.extend(
|
|
483
501
|
render_lines(
|
|
@@ -497,6 +515,7 @@ def gen_batch_parametrized_test_methods(
|
|
|
497
515
|
param_name_lower=param_name.lower(),
|
|
498
516
|
verify_assert=verify_assert,
|
|
499
517
|
with_keyword=render_ctx["with_keyword"],
|
|
518
|
+
list_suffix=is_list_param,
|
|
500
519
|
)
|
|
501
520
|
)
|
|
502
521
|
|
|
@@ -637,6 +656,7 @@ def gen_test_method_assertions(
|
|
|
637
656
|
search_enabled=search_enabled,
|
|
638
657
|
search_param=param_name.lower() if search_enabled else "",
|
|
639
658
|
verify_assert=verify_assert,
|
|
659
|
+
list_suffix=search_enabled and param_name.lower().endswith("list"),
|
|
640
660
|
)
|
|
641
661
|
content.append("")
|
|
642
662
|
return content
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""pytest 测试工具函数"""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed
|
|
7
|
+
|
|
8
|
+
from .config import APIConfig
|
|
9
|
+
from .logger import logger
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def retry_step(counts: int = 2, times: int = 20) -> Callable:
|
|
13
|
+
"""
|
|
14
|
+
测试步骤断言失败后重试装饰器。
|
|
15
|
+
支持同步和异步函数(tenacity 自动适配)。
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
counts: 最大执行次数(含首次)
|
|
19
|
+
times: 每次重试间隔秒数
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
def after(retry_state):
|
|
23
|
+
# 最后一次失败后没有下一次重试,提示语不再说“Xs后重试”
|
|
24
|
+
is_last = retry_state.attempt_number >= counts
|
|
25
|
+
suffix = f"{times}s后重试" if not is_last else "重试次数已用完"
|
|
26
|
+
logger.warning(
|
|
27
|
+
"[retry_step] %s 第%d次失败, %s: %s",
|
|
28
|
+
retry_state.fn.__name__,
|
|
29
|
+
retry_state.attempt_number,
|
|
30
|
+
suffix,
|
|
31
|
+
retry_state.outcome.exception(),
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
decorator = retry(
|
|
35
|
+
stop=stop_after_attempt(counts),
|
|
36
|
+
wait=wait_fixed(times),
|
|
37
|
+
retry=retry_if_exception_type(AssertionError),
|
|
38
|
+
reraise=True,
|
|
39
|
+
after=after,
|
|
40
|
+
)
|
|
41
|
+
return decorator # pyright: ignore[reportReturnType]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def extract_list_items(resp_data: Any) -> list:
|
|
45
|
+
"""从响应 data 中提取明细列表。
|
|
46
|
+
|
|
47
|
+
优先识别 ``lists``/``list`` 键;均不存在时降级取第一个元素为 dict 的
|
|
48
|
+
非空列表值(覆盖 ``records``/``rows`` 等命名);无匹配时返回空列表。
|
|
49
|
+
"""
|
|
50
|
+
if not isinstance(resp_data, dict):
|
|
51
|
+
return []
|
|
52
|
+
for key in ("lists", "list"):
|
|
53
|
+
items = resp_data.get(key)
|
|
54
|
+
if isinstance(items, list):
|
|
55
|
+
return items
|
|
56
|
+
return next(
|
|
57
|
+
(
|
|
58
|
+
v
|
|
59
|
+
for v in resp_data.values()
|
|
60
|
+
if isinstance(v, list) and v and all(isinstance(i, dict) for i in v)
|
|
61
|
+
),
|
|
62
|
+
[],
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def collect_list_query_data(data: Any, list_query_data: dict[str, Any]) -> None:
|
|
67
|
+
"""从响应 JSON 收集字段值到 list_query_data(原地更新)。
|
|
68
|
+
|
|
69
|
+
优先精确匹配参数名(不区分大小写),响应字段无同名参数时降级前缀模糊匹配
|
|
70
|
+
(双向包含:响应字段名以参数名开头,如参数 ``operator`` 可匹配响应字段
|
|
71
|
+
``operatorNo``/``operatorName``,命中多个时取第一个;或参数名包含响应
|
|
72
|
+
字段名,如参数 ``demoCodeList`` 包含响应字段 ``demoCode``,值包装为
|
|
73
|
+
单元素列表);响应值优先:首条记录的匹配值覆盖已有值(含录制值),
|
|
74
|
+
同一参数只收集一次。时间参数(``APIConfig.is_time_param`` 命中)不参与
|
|
75
|
+
收集:其值由 list_query_data 的 datetime 表达式动态提供,避免响应记录中的
|
|
76
|
+
同语义时间戳字段(如 ``commitTime``)污染搜索条件。
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
data: 接口响应 JSON(``await r.json()`` 结果)
|
|
80
|
+
list_query_data: list_query_data 类属性字典(原地写入)
|
|
81
|
+
"""
|
|
82
|
+
resp_data = data.get("data", {}) if isinstance(data, dict) else {}
|
|
83
|
+
items = extract_list_items(resp_data)
|
|
84
|
+
# 时间参数不参与收集:值由 list_query_data 的 datetime 表达式动态提供
|
|
85
|
+
collectable_params = [p for p in list_query_data if not APIConfig.is_time_param(p)]
|
|
86
|
+
collected = set()
|
|
87
|
+
for item in items:
|
|
88
|
+
if isinstance(item, dict):
|
|
89
|
+
for k, v in item.items():
|
|
90
|
+
if isinstance(v, (str, int, float)) and v not in ("", None):
|
|
91
|
+
param_name = next(
|
|
92
|
+
(p for p in collectable_params if p.lower() == k.lower()), None
|
|
93
|
+
)
|
|
94
|
+
if param_name is None:
|
|
95
|
+
# 响应字段名以参数名开头(参数被响应字段名包含)
|
|
96
|
+
param_name = next(
|
|
97
|
+
(
|
|
98
|
+
p
|
|
99
|
+
for p in collectable_params
|
|
100
|
+
if k.lower().startswith(p.lower()) and p not in collected
|
|
101
|
+
),
|
|
102
|
+
None,
|
|
103
|
+
)
|
|
104
|
+
is_reverse_match = False
|
|
105
|
+
if param_name is None:
|
|
106
|
+
# 参数名包含响应字段名(如 demoCodeList 包含 demoCode)
|
|
107
|
+
param_name = next(
|
|
108
|
+
(
|
|
109
|
+
p
|
|
110
|
+
for p in collectable_params
|
|
111
|
+
if p.lower().startswith(k.lower()) and p not in collected
|
|
112
|
+
),
|
|
113
|
+
None,
|
|
114
|
+
)
|
|
115
|
+
is_reverse_match = True
|
|
116
|
+
if param_name and param_name not in collected:
|
|
117
|
+
collected.add(param_name)
|
|
118
|
+
list_query_data[param_name] = [v] if is_reverse_match else v
|
|
@@ -10,10 +10,10 @@
|
|
|
10
10
|
{% if search_enabled %}{{ body_indent }} # 验证返回数据符合搜索条件(降级:若 test_0 未收集到值则跳过验证)
|
|
11
11
|
{{ body_indent }} if self.list_query_data["{{ param_name }}"]:
|
|
12
12
|
{{ body_indent }} resp_data = data.get("data")
|
|
13
|
-
{{ body_indent }} items =
|
|
13
|
+
{{ body_indent }} items = extract_list_items(resp_data)
|
|
14
14
|
{{ body_indent }} for item in items:
|
|
15
15
|
{{ body_indent }} if isinstance(item, dict):
|
|
16
16
|
{{ body_indent }} for k, v in item.items():
|
|
17
|
-
{{ body_indent }} if k.lower() == "{{ param_name_lower }}":
|
|
17
|
+
{{ body_indent }} if k.lower() == "{{ param_name_lower }}"{% if list_suffix %} or k.lower() == "{{ param_name_lower }}".removesuffix("list"){% endif %}:
|
|
18
18
|
{{ body_indent }} {{ verify_assert }}
|
|
19
19
|
{% endif %}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
@allure.title("{{ api_description }}: 获取响应数据")
|
|
2
|
+
{{ def_prefix }}test_0_{{ function_name }}(self):
|
|
3
|
+
{{ body_indent }}{{ param_var_name }} = {
|
|
4
|
+
{% for key, value in data_items %}{{ body_indent }} "{{ key }}": {{ value }},
|
|
5
|
+
{% endfor %}{{ body_indent }}}
|
|
6
|
+
{{ body_indent }}{{ with_keyword }} {{ function_name }}({{ param_var_name }}={{ param_var_name }}, headers=self.headers) as r:
|
|
7
|
+
{{ body_indent }} assert r.{{ status_attr }} == 200
|
|
8
|
+
{{ body_indent }} data = {{ json_call }}
|
|
9
|
+
{{ body_indent }} assert data["code"] == 200
|
|
10
|
+
{{ body_indent }} # 收集响应字段值到 list_query_data(精确匹配优先、无则前缀模糊匹配;响应值优先覆盖),逻辑见 pytest_utils.collect_list_query_data
|
|
11
|
+
{{ body_indent }} collect_list_query_data(data, self.__class__.list_query_data)
|
|
12
|
+
|
|
@@ -9,10 +9,10 @@
|
|
|
9
9
|
{% endif %}{% if search_enabled %}
|
|
10
10
|
# 验证返回数据符合搜索条件
|
|
11
11
|
resp_data = data.get('data')
|
|
12
|
-
items =
|
|
12
|
+
items = extract_list_items(resp_data)
|
|
13
13
|
for item in items:
|
|
14
14
|
if isinstance(item, dict):
|
|
15
15
|
for k, v in item.items():
|
|
16
|
-
if k.lower() == '{{ search_param }}':
|
|
16
|
+
if k.lower() == '{{ search_param }}'{% if list_suffix %} or k.lower() == '{{ search_param }}'.removesuffix('list'){% endif %}:
|
|
17
17
|
{{ verify_assert }}
|
|
18
18
|
{% endif %}
|
|
@@ -318,8 +318,15 @@ class TestCaseGenerator:
|
|
|
318
318
|
task_id: str | None = None,
|
|
319
319
|
overwrite: bool = False,
|
|
320
320
|
har_file_path: str | None = None,
|
|
321
|
+
only_mode: str | None = None,
|
|
321
322
|
) -> dict[str, Any]:
|
|
322
|
-
"""批量生成测试用例(异步 + 并行处理)。
|
|
323
|
+
"""批量生成测试用例(异步 + 并行处理)。
|
|
324
|
+
|
|
325
|
+
Args:
|
|
326
|
+
only_mode: 仅生成指定模式的用例(list_query/complex_scenario),None 表示不过滤。
|
|
327
|
+
按 _resolve_testcase_mode 识别结果过滤:list_query=参数化产物,
|
|
328
|
+
complex_scenario=场景产物(含描述无列表关键字回落 scenario 的接口)。
|
|
329
|
+
"""
|
|
323
330
|
expanded_api_files: list[str] = []
|
|
324
331
|
for api_path in api_files_list:
|
|
325
332
|
if os.path.isdir(api_path):
|
|
@@ -341,6 +348,7 @@ class TestCaseGenerator:
|
|
|
341
348
|
generated_count = 0
|
|
342
349
|
skipped_count = 0
|
|
343
350
|
failed_count = 0
|
|
351
|
+
filtered_count = 0
|
|
344
352
|
generated_files_list: list[str] = []
|
|
345
353
|
|
|
346
354
|
invalid_files = [f for f in expanded_api_files if not self._is_within_api_dir(f)]
|
|
@@ -353,7 +361,7 @@ class TestCaseGenerator:
|
|
|
353
361
|
)
|
|
354
362
|
return {
|
|
355
363
|
"total": len(expanded_api_files), "skipped": 0, "generated": 0,
|
|
356
|
-
"failed": len(invalid_files), "generated_files": [],
|
|
364
|
+
"failed": len(invalid_files), "filtered": 0, "generated_files": [],
|
|
357
365
|
}
|
|
358
366
|
|
|
359
367
|
os.makedirs(self.output_dir, exist_ok=True)
|
|
@@ -376,6 +384,19 @@ class TestCaseGenerator:
|
|
|
376
384
|
logger.warning(f" [任务跳过] {api_basename} 无法提取 API 信息")
|
|
377
385
|
return "failed", None
|
|
378
386
|
|
|
387
|
+
# 模式过滤(--only-mode):先于存在性检查判定识别模式,
|
|
388
|
+
# 不匹配的接口不计入 skipped(避免与"已存在"语义混淆),单独计入 filtered
|
|
389
|
+
mode = self._resolve_testcase_mode(api_file)
|
|
390
|
+
if only_mode is not None:
|
|
391
|
+
expected_mode = "parametrized" if only_mode == "list_query" else "scenario"
|
|
392
|
+
if mode != expected_mode:
|
|
393
|
+
elapsed = time.time() - task_start
|
|
394
|
+
logger.info(
|
|
395
|
+
f" [任务跳过] {api_basename} 识别模式 {mode} 不在筛选范围"
|
|
396
|
+
f"(--only-mode {only_mode}) (耗时 {elapsed:.2f}s)"
|
|
397
|
+
)
|
|
398
|
+
return "filtered", None
|
|
399
|
+
|
|
379
400
|
test_filename = f"test_{api_info.function_name}.py"
|
|
380
401
|
test_filepath = os.path.join(self.output_dir, test_filename)
|
|
381
402
|
|
|
@@ -385,7 +406,6 @@ class TestCaseGenerator:
|
|
|
385
406
|
logger.debug(f" [任务跳过] {api_basename} 测试文件已存在 (耗时 {elapsed:.2f}s)")
|
|
386
407
|
return "skipped", None
|
|
387
408
|
|
|
388
|
-
mode = self._resolve_testcase_mode(api_file)
|
|
389
409
|
test_content = None
|
|
390
410
|
if mode == "parametrized":
|
|
391
411
|
test_content = self.generate_parametrized_test_content(api_file, task_id)
|
|
@@ -424,10 +444,12 @@ class TestCaseGenerator:
|
|
|
424
444
|
skipped_count += 1
|
|
425
445
|
elif status == "failed":
|
|
426
446
|
failed_count += 1
|
|
447
|
+
elif status == "filtered":
|
|
448
|
+
filtered_count += 1
|
|
427
449
|
|
|
428
450
|
logger.info(
|
|
429
451
|
f"[并行处理] 完成! 成功: {generated_count}, 跳过: {skipped_count}, "
|
|
430
|
-
f"失败: {failed_count}, 总耗时: {parallel_elapsed:.2f}s"
|
|
452
|
+
f"失败: {failed_count}, 模式过滤: {filtered_count}, 总耗时: {parallel_elapsed:.2f}s"
|
|
431
453
|
)
|
|
432
454
|
|
|
433
455
|
if generated_count > 0:
|
|
@@ -436,7 +458,7 @@ class TestCaseGenerator:
|
|
|
436
458
|
return {
|
|
437
459
|
"total": len(expanded_api_files), "skipped": skipped_count,
|
|
438
460
|
"generated": generated_count, "failed": failed_count,
|
|
439
|
-
"generated_files": generated_files_list,
|
|
461
|
+
"filtered": filtered_count, "generated_files": generated_files_list,
|
|
440
462
|
}
|
|
441
463
|
|
|
442
464
|
# ==================== 测试用例内容生成 ====================
|
|
@@ -296,16 +296,26 @@ def _extract_date_format_from_remark(remark: str) -> str:
|
|
|
296
296
|
remark: 参数备注文本(如 "领取时间开始时间(yyyy-MM-dd)")
|
|
297
297
|
|
|
298
298
|
Returns:
|
|
299
|
-
strftime 格式字符串(如 "%Y-%m-%d"
|
|
299
|
+
strftime 格式字符串(如 "%Y-%m-%d");未识别到日期格式时默认
|
|
300
|
+
"%Y-%m-%d %H:%M:%S"(年月日时分秒)
|
|
300
301
|
"""
|
|
301
302
|
match = re.search(r"[\(\uff08]([^\)\uff09]+)[\)\uff09]", remark)
|
|
302
303
|
if not match:
|
|
303
|
-
return "%Y-%m-%d"
|
|
304
|
+
return "%Y-%m-%d %H:%M:%S"
|
|
304
305
|
fmt = match.group(1)
|
|
305
306
|
# Java 风格日期格式 → Python strftime
|
|
306
|
-
fmt =
|
|
307
|
-
|
|
308
|
-
|
|
307
|
+
fmt = (
|
|
308
|
+
fmt.replace("yyyy", "%Y")
|
|
309
|
+
.replace("yy", "%y")
|
|
310
|
+
.replace("MM", "%m")
|
|
311
|
+
.replace("dd", "%d")
|
|
312
|
+
.replace("HH", "%H")
|
|
313
|
+
.replace("mm", "%M")
|
|
314
|
+
.replace("ss", "%S")
|
|
315
|
+
)
|
|
316
|
+
# 括号内容不含任何日期 token(如 "含")时视为未识别,回落默认完整日期时间格式
|
|
317
|
+
if "%" not in fmt:
|
|
318
|
+
return "%Y-%m-%d %H:%M:%S"
|
|
309
319
|
return fmt
|
|
310
320
|
|
|
311
321
|
|
|
@@ -1233,9 +1233,9 @@ def test_generate_api_file_har_time_pairs(tmp_path):
|
|
|
1233
1233
|
assert filepath is not None
|
|
1234
1234
|
with open(filepath[: -len(".py")] + ".api.json", encoding="utf-8") as f:
|
|
1235
1235
|
meta = json.load(f)
|
|
1236
|
-
# 无 Swagger 备注可提取格式,默认 %Y-%m-%d;按基础名 commit 配对 start/end
|
|
1236
|
+
# 无 Swagger 备注可提取格式,默认 %Y-%m-%d %H:%M:%S;按基础名 commit 配对 start/end
|
|
1237
1237
|
assert meta["har_time_pairs"] == {
|
|
1238
|
-
"commit": {"start": "commitStartTime", "end": "commitEndTime", "format": "%Y-%m-%d"},
|
|
1238
|
+
"commit": {"start": "commitStartTime", "end": "commitEndTime", "format": "%Y-%m-%d %H:%M:%S"},
|
|
1239
1239
|
}
|
|
1240
1240
|
|
|
1241
1241
|
|
|
@@ -33,6 +33,7 @@ def _tc_args(**overrides):
|
|
|
33
33
|
api_files="api_request.har",
|
|
34
34
|
overwrite=False,
|
|
35
35
|
async_mode=False,
|
|
36
|
+
only_mode=None,
|
|
36
37
|
)
|
|
37
38
|
defaults.update(overrides)
|
|
38
39
|
return SimpleNamespace(**defaults)
|
|
@@ -311,12 +312,55 @@ async def test_handle_testcase_batch_success(monkeypatch, caplog):
|
|
|
311
312
|
await main_module.handle_testcase(args)
|
|
312
313
|
|
|
313
314
|
generator_instance.generate_batch_testcases.assert_awaited_once_with(
|
|
314
|
-
["api1.py", "api2.py"], "test_4295", overwrite=False, har_file_path=None
|
|
315
|
+
["api1.py", "api2.py"], "test_4295", overwrite=False, har_file_path=None, only_mode=None
|
|
315
316
|
)
|
|
316
317
|
assert "总API文件数: 2" in caplog.text
|
|
317
318
|
assert "成功生成: 2" in caplog.text
|
|
318
319
|
|
|
319
320
|
|
|
321
|
+
@allure.feature("CLI入口")
|
|
322
|
+
@allure.story("testcase命令处理")
|
|
323
|
+
@allure.title("测试batch模式仅生成指定模式(--only-mode)")
|
|
324
|
+
async def test_handle_testcase_batch_only_mode(monkeypatch, caplog):
|
|
325
|
+
caplog.set_level(logging.INFO, logger="har2pytest")
|
|
326
|
+
generator_instance = MagicMock()
|
|
327
|
+
generator_instance.swagger_handler.close = AsyncMock()
|
|
328
|
+
generator_instance.generate_batch_testcases = AsyncMock(
|
|
329
|
+
return_value={
|
|
330
|
+
"total": 3, "skipped": 0, "generated": 1, "failed": 0, "filtered": 2,
|
|
331
|
+
"generated_files": ["a.py"],
|
|
332
|
+
}
|
|
333
|
+
)
|
|
334
|
+
monkeypatch.setattr(main_module, "TestCaseGenerator", MagicMock(return_value=generator_instance))
|
|
335
|
+
|
|
336
|
+
args = _tc_args(pattern="batch", api_files="api1.py", only_mode="list_query")
|
|
337
|
+
await main_module.handle_testcase(args)
|
|
338
|
+
|
|
339
|
+
generator_instance.generate_batch_testcases.assert_awaited_once_with(
|
|
340
|
+
["api1.py"], None, overwrite=False, har_file_path=None, only_mode="list_query"
|
|
341
|
+
)
|
|
342
|
+
assert "模式过滤跳过(非 list_query): 2" in caplog.text
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@allure.feature("CLI入口")
|
|
346
|
+
@allure.story("testcase命令处理")
|
|
347
|
+
@allure.title("测试非batch模式传--only-mode时警告忽略")
|
|
348
|
+
async def test_handle_testcase_only_mode_ignored_non_batch(monkeypatch, caplog):
|
|
349
|
+
caplog.set_level(logging.WARNING, logger="har2pytest")
|
|
350
|
+
generator_instance = MagicMock()
|
|
351
|
+
generator_instance.swagger_handler.close = AsyncMock()
|
|
352
|
+
generator_instance.generate_scenario_testcase = AsyncMock(return_value=None)
|
|
353
|
+
monkeypatch.setattr(main_module, "TestCaseGenerator", MagicMock(return_value=generator_instance))
|
|
354
|
+
|
|
355
|
+
args = _tc_args(pattern="complex_scenario", url="/api/login", only_mode="list_query")
|
|
356
|
+
await main_module.handle_testcase(args)
|
|
357
|
+
|
|
358
|
+
assert any("--only-mode 仅在 batch 模式下生效" in r.getMessage() for r in caplog.records)
|
|
359
|
+
generator_instance.generate_scenario_testcase.assert_awaited_once_with(
|
|
360
|
+
"api_request.har", "/api/login", None, overwrite=False
|
|
361
|
+
)
|
|
362
|
+
|
|
363
|
+
|
|
320
364
|
# ==================== handle_* 命令处理函数测试 ====================
|
|
321
365
|
|
|
322
366
|
|