mtkit 1.16.1__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.
mtkit/normalize.py ADDED
@@ -0,0 +1,480 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Input tree normalization: convert any shape of case tree input into the mtkit internal dict tree format.
4
+
5
+ Supported input shapes (arbitrarily nested and mixed):
6
+ 1. dict tree: {"t": title, "c": [child nodes]}
7
+ 2. tuple tree: (title, [child nodes])
8
+ 3. string leaf: "text"
9
+
10
+ Also supports converting between zen and history case description styles:
11
+ - zen style: case children are "pc:"/"步骤:"/"预期:" flat description lines (legacy generation script convention)
12
+ - history style: case children are multi-level nodes like 「操作步骤」「预期结果」(legacy iteration case xmind format)
13
+ """
14
+ import re
15
+
16
+ from .builder import CASE_TITLE_PATTERN
17
+ from .parsers import circle_text
18
+ from .tb import split_items
19
+
20
+ # title aliases for the "operation steps" node in history style
21
+ HISTORY_STEP_TITLES = ("操作步骤", "步骤", "测试步骤", "执行步骤")
22
+ HISTORY_EXPECT_TITLES = ("预期结果", "预期", "期望结果")
23
+ # titles of the "preconditions" node in history style (legacy spellings compatible)
24
+ HISTORY_PC_TITLES = ("pc:", "pc:", "前置条件", "前置", "pc")
25
+
26
+ # zen style prefix recognition for validation
27
+ ZEN_PC_PREFIX = "pc:"
28
+ ZEN_STEP_PREFIX = "步骤:"
29
+ ZEN_EXPECT_PREFIX = "预期:"
30
+ ZEN_SQL_PREFIX = "SQL核对:"
31
+
32
+ # SQL node title signature (recognizes existing SQL check content in require_sql validation)
33
+ SQL_TITLE_PATTERN = re.compile(r"SQL核对", re.IGNORECASE)
34
+ # checkpoint node title signature (recognizes DB-interaction case declaration in require_sql validation)
35
+ CHECKPOINT_TITLE_PATTERN = re.compile(r"数据库Checkpoint|Checkpoint", re.IGNORECASE)
36
+ # SQL text signature: SQL keyword after start/colon/whitespace, compatible with "数据库Checkpoint:SELECT ..." prefix
37
+ SQL_TEXT_PATTERN = re.compile(
38
+ r"(?:^|[::]|\s)(SELECT|UPDATE|INSERT|DELETE|EXEC|EXECUTE|DECLARE|CREATE|ALTER|DROP|USE|IF)\b",
39
+ re.IGNORECASE,
40
+ )
41
+ # no-DB-interaction declaration (skips require_sql validation when present)
42
+ NO_DB_PATTERN = re.compile(r"无\s*DB\s*交互|不产生\s*SQL|无数据库交互|不涉及数据库")
43
+
44
+ # DB-interaction case title keywords (for diff coverage comparison etc)
45
+ DB_ACTION_KEYWORDS = (
46
+ "申请支付", "表数据确认", "导入", "导出", "发票池", "数据权限", "同步",
47
+ "红冲", "撤销", "状态流转", "核销",
48
+ )
49
+
50
+ # precondition step signatures (auto precondition split):
51
+ # 1. starts with 造/前置/准备/预置
52
+ # 2. starts with 用/使用/以/分别用…账号|角色|身份 (within 40 chars)
53
+ # 3. 账号|角色|部门|用户 appears within the first 40 chars (e.g. "系统管理员账号", "客户主任角色")
54
+ # 4. 当前…账号|角色|部门|用户
55
+ # 5. scenario prefixes like 拥有/模拟/场景/两个用户/Excel 中/报销单存在/上传文件/扫码模式/扫码多张/申请支付成功后
56
+ # 6. starts with Status=
57
+ PRECONDITION_HINT_PATTERN = re.compile(
58
+ r"^(造|前置|准备|预置)"
59
+ r"|^(用|使用|以|分别用|分别以)[^,,;;。]{0,40}(账号|角色|身份|部门)"
60
+ r"|^[^,,;;。]{0,40}(账号|角色|部门|用户)"
61
+ r"|^当前[^,,;;。]{0,40}(账号|角色|部门|用户)"
62
+ r"|^(拥有|模拟|场景|两个用户|Excel 中|报销单存在|上传文件|扫码(模式|多张)|申请支付成功后)"
63
+ r"|^Status\s*[==]"
64
+ r"|前置条件"
65
+ )
66
+ # intra-sentence split separator (single line "造单…扫码" mixed spelling split for preconditions)
67
+ _SENTENCE_SPLIT_PATTERN = re.compile(r"[,,;;。]")
68
+ # action verbs (verb-splitting: punctuation-free single line "用XX账号搜索" split for preconditions)
69
+ _ACTION_VERB_PATTERN = re.compile(
70
+ r"(搜索|点击|扫码|登录|进入|操作|观察|检查|执行|提交|勾选|上传|导出|调用|打开|查询|查看|验证|核对|导入|驳回)"
71
+ )
72
+
73
+
74
+ def normalize_node(node):
75
+ """Normalize any node shape (string/dict/tuple) into dict(t=title, c=[children]).
76
+
77
+ :param node: string leaf / {"t":..,"c":..} / (title, [children])
78
+ :return: {"t": title, "c": [children]} (c omitted when no children)
79
+ """
80
+ if isinstance(node, str):
81
+ return {"t": node}
82
+ if isinstance(node, dict):
83
+ title = node.get("t") or ""
84
+ children = node.get("c") or []
85
+ if not title and children:
86
+ raise ValueError("dict 节点缺少标题字段 t: %r" % node)
87
+ item = {"t": title}
88
+ if children:
89
+ item["c"] = normalize_tree(children)
90
+ return item
91
+ if isinstance(node, (tuple, list)) and node and isinstance(node[0], str):
92
+ # (title, [children]) tuple form; empty tuple / insufficient length treated as title node
93
+ title = node[0]
94
+ children = node[1] if len(node) > 1 else []
95
+ item = {"t": title}
96
+ if children:
97
+ item["c"] = normalize_tree(children)
98
+ return item
99
+ raise ValueError("不支持的节点形态: %r" % (node,))
100
+
101
+
102
+ def normalize_tree(nodes):
103
+ """Normalize any shape of case tree list into a dict tree list.
104
+
105
+ :param nodes: list of nodes in any shape
106
+ :return: [{"t":.., "c":[..]}, ...]
107
+ """
108
+ return [normalize_node(node) for node in nodes]
109
+
110
+
111
+ def detect_style(tree):
112
+ """Detect the case tree description style: return "zen" / "history" / "mixed".
113
+
114
+ count all case node child titles: zen prefix lines count zen, history node titles count history,
115
+ majority wins; none of both defaults to "zen".
116
+
117
+ :param tree: dict case tree
118
+ :return: style name
119
+ """
120
+ zen = 0
121
+ history = 0
122
+
123
+ def walk(nodes):
124
+ nonlocal zen, history
125
+ for node in nodes:
126
+ if CASE_TITLE_PATTERN.match(node.get("t") or ""):
127
+ subs = [c.get("t") or "" for c in node.get("c") or []]
128
+ for title in subs:
129
+ if title.startswith((ZEN_STEP_PREFIX, ZEN_EXPECT_PREFIX, ZEN_PC_PREFIX)):
130
+ zen += 1
131
+ if title in HISTORY_STEP_TITLES + HISTORY_EXPECT_TITLES + HISTORY_PC_TITLES:
132
+ history += 1
133
+ else:
134
+ walk(node.get("c") or [])
135
+
136
+ walk(tree)
137
+ if history > zen:
138
+ return "history"
139
+ if zen > 0 and history == 0:
140
+ return "zen"
141
+ if history > 0 and zen == 0:
142
+ return "history"
143
+ if zen > 0 and history > 0:
144
+ return "mixed"
145
+ return "zen"
146
+
147
+
148
+ def _circle_lines(lines):
149
+ """Multi-line text to circled description string: single item returned as-is, multiple items circled per line (same rules as parsers.circle_text)."""
150
+ texts = []
151
+ for line in lines:
152
+ line = (line or "").strip()
153
+ if line:
154
+ texts.append(line)
155
+ if not texts:
156
+ return ""
157
+ if len(texts) == 1:
158
+ return texts[0]
159
+ return circle_text("\n".join(texts))
160
+
161
+
162
+ def case_to_zen(case_node):
163
+ """Convert a history style case node to zen style (flat pc:/步骤:/预期: lines).
164
+
165
+ multi-level nodes like 「操作步骤」「预期结果」are flattened into prefix description lines;
166
+ SQL related nodes and other nodes are kept as-is.
167
+
168
+ :param case_node: history style case node dict
169
+ :return: zen style case node dict
170
+ """
171
+ children = []
172
+ steps = []
173
+ expects = []
174
+ for child in case_node.get("c") or []:
175
+ title = child.get("t") or ""
176
+ if title in HISTORY_STEP_TITLES:
177
+ steps.extend([c.get("t") or "" for c in child.get("c") or []])
178
+ elif title in HISTORY_EXPECT_TITLES:
179
+ expects.extend([c.get("t") or "" for c in child.get("c") or []])
180
+ elif title in HISTORY_PC_TITLES:
181
+ children.append({"t": ZEN_PC_PREFIX + " " + _circle_lines([c.get("t") or "" for c in child.get("c") or []])})
182
+ else:
183
+ children.append(child)
184
+ if steps:
185
+ children.insert(0, {"t": ZEN_STEP_PREFIX + " " + _circle_lines(steps)})
186
+ if expects:
187
+ # expect lines inserted after step lines
188
+ insert_at = 1 if steps else 0
189
+ children.insert(insert_at, {"t": ZEN_EXPECT_PREFIX + " " + _circle_lines(expects)})
190
+ result = {"t": case_node.get("t")}
191
+ if children:
192
+ result["c"] = children
193
+ return result
194
+
195
+
196
+ def case_to_history(case_node):
197
+ """Convert a zen style case node to history style (操作步骤/预期结果 multi-level nodes).
198
+
199
+ :param case_node: zen style case node dict
200
+ :return: history style case node dict
201
+ """
202
+ children = []
203
+ for child in case_node.get("c") or []:
204
+ title = child.get("t") or ""
205
+ if title.startswith(ZEN_STEP_PREFIX):
206
+ items = split_items(circle_text(title[len(ZEN_STEP_PREFIX):].strip()))
207
+ children.append({"t": "操作步骤", "c": [{"t": item} for item in items]})
208
+ elif title.startswith(ZEN_EXPECT_PREFIX):
209
+ items = split_items(circle_text(title[len(ZEN_EXPECT_PREFIX):].strip()))
210
+ children.append({"t": "预期结果", "c": [{"t": item} for item in items]})
211
+ elif title.startswith(ZEN_PC_PREFIX) or title.startswith("pc:"):
212
+ # pc stays a flat description line (same as zen style), kept as-is without multi-level split
213
+ children.append(child)
214
+ elif title.startswith(ZEN_SQL_PREFIX):
215
+ text = title[len(ZEN_SQL_PREFIX):].strip()
216
+ children.append({"t": "SQL核对", "c": [{"t": text}] if text else []})
217
+ else:
218
+ children.append(child)
219
+ result = {"t": case_node.get("t")}
220
+ if children:
221
+ result["c"] = children
222
+ return result
223
+
224
+
225
+ def to_zen(tree):
226
+ """Convert the whole tree history -> zen (only case nodes converted, chapter/group nodes kept).
227
+
228
+ :param tree: history style dict tree
229
+ :return: zen style dict tree
230
+ """
231
+ out = []
232
+ for node in tree:
233
+ if CASE_TITLE_PATTERN.match(node.get("t") or ""):
234
+ out.append(case_to_zen(node))
235
+ else:
236
+ children = to_zen(node.get("c") or [])
237
+ item = {"t": node.get("t")}
238
+ if children:
239
+ item["c"] = children
240
+ out.append(item)
241
+ return out
242
+
243
+
244
+ def to_history(tree):
245
+ """Convert the whole tree zen -> history (only case nodes converted).
246
+
247
+ :param tree: zen style dict tree
248
+ :return: history style dict tree
249
+ """
250
+ out = []
251
+ for node in tree:
252
+ if CASE_TITLE_PATTERN.match(node.get("t") or ""):
253
+ out.append(case_to_history(node))
254
+ else:
255
+ children = to_history(node.get("c") or [])
256
+ item = {"t": node.get("t")}
257
+ if children:
258
+ item["c"] = children
259
+ out.append(item)
260
+ return out
261
+
262
+
263
+ def case_has_sql(case_node):
264
+ """Check whether a case node contains SQL check content.
265
+
266
+ :param case_node: case node dict
267
+ :return: whether it has a SQL node or SQL text
268
+ """
269
+
270
+ def walk(nodes):
271
+ for node in nodes:
272
+ title = node.get("t") or ""
273
+ if SQL_TITLE_PATTERN.search(title):
274
+ return True
275
+ if SQL_TEXT_PATTERN.search(title):
276
+ return True
277
+ if walk(node.get("c") or []):
278
+ return True
279
+ return False
280
+
281
+ return walk(case_node.get("c") or [])
282
+
283
+
284
+ def _split_sentence_precondition(text):
285
+ """Intra-line split: when the first sentence is a precondition, split out (precondition sentence, remaining step), else return None.
286
+
287
+ applies to single-line mixed spellings like "造单:Status='03',用账务付款专员扫码".
288
+
289
+ :param text: single-line step text
290
+ :return: (precondition text, remaining step text) or None
291
+ """
292
+ parts = [part.strip() for part in _SENTENCE_SPLIT_PATTERN.split(text) if part.strip()]
293
+ if len(parts) < 2:
294
+ return None
295
+ if PRECONDITION_HINT_PATTERN.match(parts[0]):
296
+ return parts[0], ",".join(parts[1:])
297
+ return None
298
+
299
+
300
+ def _split_verb_precondition(text):
301
+ """Single-line verb split: when the line starts with a precondition signature and the text before the verb ends with an account-type word, split out the precondition.
302
+
303
+ applies to punctuation-free spellings like "用XX账号搜索" / "客户主任角色(…)执行导出".
304
+ constraint: text before the verb must end with 账号/角色/身份/用户/部门 (or a paren-wrapped account phrase),
305
+ avoiding false splits like "扫码报销单号输入框" which contains a verb.
306
+
307
+ "登录/进入" verb boundary handling:
308
+ - verb followed by punctuation (e.g. "账号登录,检查…") -> 登录 merged into the precondition
309
+ - verb followed by an object (e.g. "账号登录 HRO" / "账号登录操作") -> verb stays in the step
310
+ - verb at line end -> return None (fallback, no empty step)
311
+
312
+ :param text: single-line step text
313
+ :return: (precondition text, remaining step text) or None
314
+ """
315
+ if not PRECONDITION_HINT_PATTERN.match(text):
316
+ return None
317
+ for match in _ACTION_VERB_PATTERN.finditer(text):
318
+ verb = match.group(1)
319
+ pre = text[:match.start()].strip()
320
+ if not pre:
321
+ continue
322
+ if pre.endswith(("账号", "角色", "身份", "用户", "部门")):
323
+ if verb in ("登录", "进入"):
324
+ rest = text[match.end():]
325
+ rest_stripped = rest.strip(",,;;。 ")
326
+ if not rest_stripped:
327
+ # verb at line end: cannot form a step, fallback to no split
328
+ return None
329
+ if rest and rest[0] in ",,;;。":
330
+ # verb followed by punctuation: "账号登录" stays precondition as a whole
331
+ pre = text[:match.end()].strip()
332
+ return pre, rest_stripped
333
+ # verb followed by object: verb stays in step
334
+ return pre, text[match.start():]
335
+ step = text[match.end():].strip(",,;;。 ")
336
+ if not step:
337
+ # verb at line end and not login/enter: no remaining step, fallback to no split
338
+ return None
339
+ return pre, step
340
+ if pre.endswith(")") and re.search(r"(账号|角色|身份|用户|部门)", pre):
341
+ step = text[match.start():].strip(",,;;。 ")
342
+ if not step:
343
+ return None
344
+ return pre, step
345
+ return None
346
+
347
+
348
+ def _sanitize_children(children):
349
+ """过滤空文本叶子节点(拆分边界场景的通用防御)。
350
+
351
+ :param children: 子节点列表
352
+ :return: 过滤后的子节点列表
353
+ """
354
+ out = []
355
+ for child in children:
356
+ title = (child.get("t") or "").strip()
357
+ sub = child.get("c") or []
358
+ if not title and not sub:
359
+ continue
360
+ out.append(child)
361
+ return out
362
+
363
+
364
+ def split_preconditions(case_node, fill_empty=False):
365
+ """把 history 风格用例「操作步骤」中的前置类步骤拆分为 `pc:` 平铺描述行。
366
+
367
+ 前置类步骤判定:以"造/前置/准备/预置"开头或含"前置条件"字样
368
+ (如 "造一条 Status=03 的报销单"、"前置条件分别造数:...")。
369
+ 拆分结果与 zen 风格约定一致:pc 为平铺行(多条内容编圈拼接),
370
+ 步骤/预期仍为多级节点(history 风格)。
371
+
372
+ 回退规则:拆分后操作步骤为空(全部步骤均为前置类,常见于"造单…扫码"单行写法)时
373
+ 保持原样不拆分,避免丢失操作步骤。
374
+
375
+ :param case_node: history 风格用例节点 dict
376
+ :param fill_empty: 无前置条件时自动补 `pc:无` 行(保证每个用例都有 pc)
377
+ :return: 拆分后的用例节点 dict
378
+ """
379
+ if not CASE_TITLE_PATTERN.match(case_node.get("t") or ""):
380
+ return case_node
381
+ children = []
382
+ for child in case_node.get("c") or []:
383
+ title = child.get("t") or ""
384
+ if title not in HISTORY_STEP_TITLES:
385
+ children.append(child)
386
+ continue
387
+ sub_items = child.get("c") or []
388
+
389
+ # 1) 单行:优先动词切分、再句内分句拆分(精度高于整行判断)
390
+ if len(sub_items) == 1:
391
+ text = sub_items[0].get("t") or ""
392
+ verb_split = _split_verb_precondition(text)
393
+ if verb_split:
394
+ pre_text, step_text = verb_split
395
+ children.append({"t": ZEN_PC_PREFIX + pre_text})
396
+ children.append({"t": "操作步骤", "c": [{"t": step_text}]})
397
+ continue
398
+ sentence_split = _split_sentence_precondition(text)
399
+ if sentence_split:
400
+ pre_text, step_text = sentence_split
401
+ children.append({"t": ZEN_PC_PREFIX + pre_text})
402
+ children.append({"t": "操作步骤", "c": [{"t": step_text}]})
403
+ continue
404
+
405
+ # 2) 整行拆分:前置类行→pc 平铺行,其余→操作步骤
406
+ pre = []
407
+ steps = []
408
+ for item in sub_items:
409
+ text = item.get("t") or ""
410
+ if PRECONDITION_HINT_PATTERN.match(text):
411
+ pre.append(item)
412
+ else:
413
+ steps.append(item)
414
+ if pre and steps:
415
+ children.append({"t": ZEN_PC_PREFIX + _circle_lines([c.get("t") or "" for c in pre])})
416
+ children.append({"t": "操作步骤", "c": steps})
417
+ elif pre:
418
+ # 全部行均为前置类(如"造数…"+"用XX账号…"):拆出 pc 行,操作步骤保留原文不丢信息
419
+ children.append({"t": ZEN_PC_PREFIX + _circle_lines([c.get("t") or "" for c in pre])})
420
+ children.append(child)
421
+ else:
422
+ # 全部为操作类:保持原样
423
+ children.append(child)
424
+ # fill_empty:保证每个用例都有 `pc:` 前置条件(无前置明示"无")
425
+ if fill_empty and children and not any(
426
+ (c.get("t") or "").startswith((ZEN_PC_PREFIX, "pc:")) or (c.get("t") or "") in HISTORY_PC_TITLES
427
+ for c in children
428
+ ):
429
+ children.insert(0, {"t": ZEN_PC_PREFIX + "无"})
430
+ children = _sanitize_children(children)
431
+ result = {"t": case_node.get("t")}
432
+ if children:
433
+ result["c"] = children
434
+ return result
435
+
436
+
437
+ def split_preconditions_tree(tree, fill_empty=False):
438
+ """整棵树应用前置条件自动拆分(仅处理用例节点,章节递归)。
439
+
440
+ :param tree: history 风格 dict 树
441
+ :param fill_empty: 无前置条件的用例自动补「前置条件:无」
442
+ :return: 拆分后的树
443
+ """
444
+ out = []
445
+ for node in tree:
446
+ if CASE_TITLE_PATTERN.match(node.get("t") or ""):
447
+ out.append(split_preconditions(node, fill_empty))
448
+ else:
449
+ children = split_preconditions_tree(node.get("c") or [], fill_empty)
450
+ item = {"t": node.get("t")}
451
+ if children:
452
+ item["c"] = children
453
+ out.append(item)
454
+ return out
455
+
456
+
457
+ def case_needs_sql(case_node):
458
+ """判断用例是否需要 SQL 核对内容(require_sql 校验的候选)。
459
+
460
+ 规则(高置信、无误伤):用例子树中存在「数据库Checkpoint」类节点且未声明
461
+ "无 DB 交互",即视为数据库交互用例。测试用例编写约定:涉及数据库交互的
462
+ checkpoint 必须写「数据库Checkpoint」节点,因此该规则与用例编写规范自洽。
463
+
464
+ :param case_node: 用例节点 dict
465
+ :return: 是否需要 SQL 核对
466
+ """
467
+
468
+ def walk(nodes):
469
+ for node in nodes:
470
+ text = node.get("t") or ""
471
+ if CHECKPOINT_TITLE_PATTERN.search(text):
472
+ # 声明了无 DB 交互的豁免
473
+ if NO_DB_PATTERN.search(text):
474
+ continue
475
+ return True
476
+ if walk(node.get("c") or []):
477
+ return True
478
+ return False
479
+
480
+ return walk(case_node.get("c") or [])