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/__init__.py +36 -0
- mtkit/__main__.py +6 -0
- mtkit/asset.py +101 -0
- mtkit/audit.py +220 -0
- mtkit/builder.py +100 -0
- mtkit/cli.py +885 -0
- mtkit/conf.py +63 -0
- mtkit/coverage.py +175 -0
- mtkit/db.py +676 -0
- mtkit/evolve.py +142 -0
- mtkit/extract/__init__.py +17 -0
- mtkit/extract/code_facts.py +631 -0
- mtkit/extract/docx_loader.py +115 -0
- mtkit/extract/xmind_loader.py +125 -0
- mtkit/generate/__init__.py +10 -0
- mtkit/generate/llm.py +360 -0
- mtkit/generate/prompts.py +178 -0
- mtkit/generate/skeleton.py +59 -0
- mtkit/normalize.py +480 -0
- mtkit/parsers.py +318 -0
- mtkit/review.py +274 -0
- mtkit/selfheal.py +110 -0
- mtkit/tb.py +191 -0
- mtkit/track.py +309 -0
- mtkit/validator.py +174 -0
- mtkit/writer.py +137 -0
- mtkit-1.16.1.dist-info/METADATA +150 -0
- mtkit-1.16.1.dist-info/RECORD +31 -0
- mtkit-1.16.1.dist-info/WHEEL +5 -0
- mtkit-1.16.1.dist-info/entry_points.txt +2 -0
- mtkit-1.16.1.dist-info/top_level.txt +1 -0
mtkit/selfheal.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Self-healing support: capture unexpected runtime exceptions into the improvements cache.
|
|
4
|
+
|
|
5
|
+
Makes the self-iteration loop engine-driven: CLI failures automatically become improvement
|
|
6
|
+
suggestions instead of relying on the AI noticing them.
|
|
7
|
+
|
|
8
|
+
Conventions:
|
|
9
|
+
- user input errors (whitelisted message patterns) are NOT recorded
|
|
10
|
+
- same exception type within 24 hours is deduplicated
|
|
11
|
+
"""
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import traceback
|
|
15
|
+
from datetime import datetime, timedelta
|
|
16
|
+
|
|
17
|
+
IMPROVEMENTS_FILENAME = "improvements.json"
|
|
18
|
+
WORK_DIR_NAME = ".mtkit-work"
|
|
19
|
+
|
|
20
|
+
# user input error patterns: these are usage issues, not tool defects
|
|
21
|
+
_USER_ERROR_PATTERNS = (
|
|
22
|
+
"不存在", "取值", "缺少", "必须", "不能为空", "不支持", "无效", "错误的使用",
|
|
23
|
+
"no such file", "invalid", "missing", "required", "must be",
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_DEDUPE_WINDOW_HOURS = 24
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _find_workdir(start_dir=None):
|
|
30
|
+
"""Find .mtkit-work upward from start_dir, fallback to cwd/.mtkit-work."""
|
|
31
|
+
current = os.path.abspath(start_dir or os.getcwd())
|
|
32
|
+
while True:
|
|
33
|
+
candidate = os.path.join(current, WORK_DIR_NAME)
|
|
34
|
+
if os.path.isdir(candidate):
|
|
35
|
+
return candidate
|
|
36
|
+
parent = os.path.dirname(current)
|
|
37
|
+
if parent == current:
|
|
38
|
+
break
|
|
39
|
+
current = parent
|
|
40
|
+
return os.path.join(os.getcwd(), WORK_DIR_NAME)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _improvements_path(workdir=None):
|
|
44
|
+
workdir = workdir or _find_workdir()
|
|
45
|
+
return os.path.join(workdir, IMPROVEMENTS_FILENAME)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _load(workdir=None):
|
|
49
|
+
path = _improvements_path(workdir)
|
|
50
|
+
if not os.path.isfile(path):
|
|
51
|
+
return {"version": 1, "items": []}, path
|
|
52
|
+
with open(path, "r", encoding="utf-8-sig") as fp:
|
|
53
|
+
data = json.load(fp)
|
|
54
|
+
data.setdefault("items", [])
|
|
55
|
+
return data, path
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _save(data, path):
|
|
59
|
+
directory = os.path.dirname(path)
|
|
60
|
+
if not os.path.isdir(directory):
|
|
61
|
+
os.makedirs(directory, exist_ok=True)
|
|
62
|
+
with open(path, "w", encoding="utf-8") as fp:
|
|
63
|
+
json.dump(data, fp, ensure_ascii=False, indent=2)
|
|
64
|
+
return path
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _is_user_error(exc):
|
|
68
|
+
"""User input error whitelist: usage problems are not tool defects."""
|
|
69
|
+
message = str(exc)
|
|
70
|
+
return any(pattern in message for pattern in _USER_ERROR_PATTERNS)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _recently_recorded(data, title, now):
|
|
74
|
+
"""Same exception type within the dedupe window is skipped."""
|
|
75
|
+
cutoff = (now - timedelta(hours=_DEDUPE_WINDOW_HOURS)).strftime("%Y-%m-%dT%H:%M:%S")
|
|
76
|
+
for item in data["items"]:
|
|
77
|
+
if item.get("title") == title and (item.get("created_at") or "") >= cutoff:
|
|
78
|
+
return True
|
|
79
|
+
return False
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def capture_failure(exc, argv=None, workdir=None):
|
|
83
|
+
"""Record an unexpected exception as an improvement suggestion, return the item or None.
|
|
84
|
+
|
|
85
|
+
:param exc: exception instance
|
|
86
|
+
:param argv: command args list (sys.argv)
|
|
87
|
+
:param workdir: workdir override (tests)
|
|
88
|
+
:return: recorded item dict, or None when skipped (user error / deduplicated)
|
|
89
|
+
"""
|
|
90
|
+
if _is_user_error(exc):
|
|
91
|
+
return None
|
|
92
|
+
data, path = _load(workdir)
|
|
93
|
+
now = datetime.now()
|
|
94
|
+
command = " ".join(argv) if argv else ""
|
|
95
|
+
title = "%s | %s" % (type(exc).__name__, command[:60])
|
|
96
|
+
if _recently_recorded(data, title, now):
|
|
97
|
+
return None
|
|
98
|
+
item = {
|
|
99
|
+
"id": "imp-runtime-%s" % now.strftime("%Y%m%d%H%M%S"),
|
|
100
|
+
"type": "缺陷",
|
|
101
|
+
"title": title,
|
|
102
|
+
"detail": "".join(traceback.format_exception_only(type(exc), exc)).strip()[:800],
|
|
103
|
+
"proposal": "运行时异常自动捕获,待分析修复",
|
|
104
|
+
"source": "运行时捕获",
|
|
105
|
+
"status": "pending",
|
|
106
|
+
"created_at": now.strftime("%Y-%m-%dT%H:%M:%S"),
|
|
107
|
+
}
|
|
108
|
+
data["items"].append(item)
|
|
109
|
+
_save(data, path)
|
|
110
|
+
return item
|
mtkit/tb.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
TB(Teambition) mind map import format: hierarchy build and validation
|
|
4
|
+
|
|
5
|
+
TB import rules (source: mind map import test case spec):
|
|
6
|
+
1. root node info is not used by the system
|
|
7
|
+
2. case groups: plain nodes become groups, max 0-8 levels; cases declared directly under the root (level 0) go into 「未分组的用例」;
|
|
8
|
+
imported groups must contain cases (empty groups unsupported)
|
|
9
|
+
3. test cases: title must be declared with tc + CN/EN colon (e.g. tc:case name); - joins level and type, e.g.:
|
|
10
|
+
tc-P1:测试用例1 -> level P1
|
|
11
|
+
tc-功能测试:测试用例2 -> type 功能测试
|
|
12
|
+
tc-P2-性能测试:测试用例3 -> level P2 + type 性能测试
|
|
13
|
+
4. steps and expects: case children default to step descriptions, max 20 steps; step children default to expected results,
|
|
14
|
+
multiple expects merged, max 200 chars
|
|
15
|
+
5. preconditions: case children declared with pc + CN/EN colon (e.g. pc:precondition content)
|
|
16
|
+
|
|
17
|
+
this module converts mtkit flat case trees (pc:/步骤:/预期: description lines) into the TB hierarchy
|
|
18
|
+
and parses/normalizes tb case titles.
|
|
19
|
+
"""
|
|
20
|
+
import re
|
|
21
|
+
|
|
22
|
+
from .builder import CASE_TITLE_PATTERN
|
|
23
|
+
from .parsers import circle_text
|
|
24
|
+
|
|
25
|
+
# step/expect item splitter: circled numbers or semicolons
|
|
26
|
+
_ITEM_SPLIT_PATTERN = re.compile(r"[;;]|①|②|③|④|⑤|⑥|⑦|⑧|⑨|⑩|⑪|⑫|⑬|⑭|⑮|⑯|⑰|⑱|⑲|⑳")
|
|
27
|
+
# pc line declaration (both CN/EN colons accepted)
|
|
28
|
+
_PC_LINE_PATTERN = re.compile(r"^pc\s*[::]\s*", re.IGNORECASE)
|
|
29
|
+
|
|
30
|
+
# case levels
|
|
31
|
+
LEVELS = ("P0", "P1", "P2", "P3")
|
|
32
|
+
|
|
33
|
+
# TB limits
|
|
34
|
+
MAX_GROUP_DEPTH = 8
|
|
35
|
+
MAX_STEPS = 20
|
|
36
|
+
MAX_EXPECT_CHARS = 200
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def parse_case_title(title):
|
|
40
|
+
"""Parse a tb case title, return (level, case_type, name); None for non-case titles.
|
|
41
|
+
|
|
42
|
+
supported shapes:
|
|
43
|
+
tc:测试用例1 -> (None, None, 测试用例1)
|
|
44
|
+
tc-p1: 测试用例3 -> (P1, None, 测试用例3)
|
|
45
|
+
tc-接口测试:测试用例4 -> (None, 接口测试, 测试用例4)
|
|
46
|
+
tc-P2-性能测试:测试用例3 -> (P2, 性能测试, 测试用例3)
|
|
47
|
+
tc-P0-功能测试:新建-前期 -> (P0, 功能测试, 新建-前期)
|
|
48
|
+
"""
|
|
49
|
+
match = re.match(r"^tc\s*[::-]\s*(.+)$", title, re.IGNORECASE)
|
|
50
|
+
if not match:
|
|
51
|
+
return None
|
|
52
|
+
body = match.group(1).strip()
|
|
53
|
+
level = None
|
|
54
|
+
|
|
55
|
+
# split at colon first: left side is level/type declaration, right side is the case name
|
|
56
|
+
parts = re.split(r"\s*[::]\s*", body, maxsplit=1)
|
|
57
|
+
if len(parts) == 2:
|
|
58
|
+
head, tail = parts
|
|
59
|
+
segments = [s.strip() for s in head.split("-") if s.strip()]
|
|
60
|
+
for seg in segments:
|
|
61
|
+
if seg.upper() in LEVELS:
|
|
62
|
+
level = seg.upper()
|
|
63
|
+
non_level = [s for s in segments if s.upper() not in LEVELS]
|
|
64
|
+
case_type = "-".join(non_level) or None
|
|
65
|
+
return level, case_type, tail.strip()
|
|
66
|
+
|
|
67
|
+
# no colon: split by -, recognize level, join the rest as name
|
|
68
|
+
segments = [s.strip() for s in body.split("-") if s.strip()]
|
|
69
|
+
rest = []
|
|
70
|
+
for seg in segments:
|
|
71
|
+
if seg.upper() in LEVELS:
|
|
72
|
+
level = seg.upper()
|
|
73
|
+
else:
|
|
74
|
+
rest.append(seg)
|
|
75
|
+
if not rest:
|
|
76
|
+
return level, None, ""
|
|
77
|
+
if len(rest) == 1:
|
|
78
|
+
return level, None, rest[0]
|
|
79
|
+
return level, rest[0], "-".join(rest[1:])
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def normalize_case_title(title, default_type=None):
|
|
83
|
+
"""Normalize a case title into the tb standard shape tc-[level-][type]:name"""
|
|
84
|
+
parsed = parse_case_title(title)
|
|
85
|
+
if parsed is None:
|
|
86
|
+
return title
|
|
87
|
+
level, case_type, name = parsed
|
|
88
|
+
case_type = case_type or default_type
|
|
89
|
+
segments = [s for s in (level, case_type) if s]
|
|
90
|
+
prefix = "tc-" + "-".join(segments) if segments else "tc"
|
|
91
|
+
return prefix + ":" + name
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def split_items(text):
|
|
95
|
+
"""Split item text like 「①a;②b」 into an item list"""
|
|
96
|
+
if not text:
|
|
97
|
+
return []
|
|
98
|
+
parts = _ITEM_SPLIT_PATTERN.split(text)
|
|
99
|
+
return [p.strip() for p in parts if p.strip()]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def to_tb_case(case_node, keep_extra=False):
|
|
103
|
+
"""Flat case node -> TB hierarchy case node (step nodes + expect child nodes + pc node)"""
|
|
104
|
+
title = normalize_case_title(case_node["t"])
|
|
105
|
+
children = []
|
|
106
|
+
pc = None
|
|
107
|
+
steps = []
|
|
108
|
+
expects = []
|
|
109
|
+
for child in case_node.get("c") or []:
|
|
110
|
+
text = child["t"]
|
|
111
|
+
pc_match = _PC_LINE_PATTERN.match(text)
|
|
112
|
+
if pc_match:
|
|
113
|
+
pc = "pc:" + circle_text(text[pc_match.end():].strip())
|
|
114
|
+
elif text.startswith("步骤:"):
|
|
115
|
+
steps = split_items(circle_text(text[3:].strip()))
|
|
116
|
+
elif text.startswith("预期:"):
|
|
117
|
+
expects = split_items(circle_text(text[3:].strip()))
|
|
118
|
+
elif keep_extra:
|
|
119
|
+
children.append({"t": text})
|
|
120
|
+
if pc:
|
|
121
|
+
children.append({"t": pc})
|
|
122
|
+
for index, step in enumerate(steps, 1):
|
|
123
|
+
step_node = {"t": "步骤 %d" % index + (":" + step if step else "")}
|
|
124
|
+
if index <= len(expects) and expects[index - 1]:
|
|
125
|
+
step_node["c"] = [{"t": "预期结果 %d:" % index + expects[index - 1]}]
|
|
126
|
+
children.append(step_node)
|
|
127
|
+
return {"t": title, "c": children} if children else {"t": title}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def to_tb_tree(tree, keep_extra=False):
|
|
131
|
+
"""扁平用例树 -> TB 层级用例树。
|
|
132
|
+
|
|
133
|
+
- 章节节点转为分组,分组下无用例(空分组)会被丢弃(TB 不支持空分组)
|
|
134
|
+
- 根下直挂用例保持不变(TB 归入「未分组的用例」)
|
|
135
|
+
|
|
136
|
+
:param tree: mtkit 用例树 [{t=..., c=[...]}, ...]
|
|
137
|
+
:param keep_extra: 是否保留 SQL核对/日志核对/实际 等附加描述行(保留时作为步骤节点)
|
|
138
|
+
:return: TB 层级用例树
|
|
139
|
+
"""
|
|
140
|
+
out = []
|
|
141
|
+
for node in tree:
|
|
142
|
+
if CASE_TITLE_PATTERN.match(node["t"]):
|
|
143
|
+
out.append(to_tb_case(node, keep_extra))
|
|
144
|
+
else:
|
|
145
|
+
children = to_tb_tree(node.get("c") or [], keep_extra)
|
|
146
|
+
if children:
|
|
147
|
+
out.append({"t": node["t"], "c": children})
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def count_tb_cases(nodes):
|
|
152
|
+
"""统计 TB 树中的用例数"""
|
|
153
|
+
total = 0
|
|
154
|
+
for node in nodes:
|
|
155
|
+
if CASE_TITLE_PATTERN.match(node["t"]):
|
|
156
|
+
total += 1
|
|
157
|
+
else:
|
|
158
|
+
total += count_tb_cases(node.get("c") or [])
|
|
159
|
+
return total
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def check_tb_tree(nodes, depth=0, errors=None):
|
|
163
|
+
"""校验 TB 层级树,返回错误信息列表。
|
|
164
|
+
|
|
165
|
+
规则:
|
|
166
|
+
1. 分组层级 ≤ 8 级
|
|
167
|
+
2. 用例步骤(除 pc 外的子节点)≤ 20 步
|
|
168
|
+
3. 预期结果内容 ≤ 200 字符
|
|
169
|
+
|
|
170
|
+
:param nodes: TB 用例树
|
|
171
|
+
:param depth: 当前分组深度(根下用例为 0 级)
|
|
172
|
+
:param errors: 外部传入的错误列表,缺省新建
|
|
173
|
+
:return: 错误信息列表,空列表表示通过
|
|
174
|
+
"""
|
|
175
|
+
errors = errors if errors is not None else []
|
|
176
|
+
for node in nodes:
|
|
177
|
+
if CASE_TITLE_PATTERN.match(node["t"]):
|
|
178
|
+
steps = [c for c in node.get("c") or [] if not _PC_LINE_PATTERN.match(c["t"])]
|
|
179
|
+
if len(steps) > MAX_STEPS:
|
|
180
|
+
errors.append("用例步骤超过 %d 步: %s(%d 步)" % (MAX_STEPS, node["t"], len(steps)))
|
|
181
|
+
for step in steps:
|
|
182
|
+
for expect in step.get("c") or []:
|
|
183
|
+
if len(expect["t"]) > MAX_EXPECT_CHARS:
|
|
184
|
+
errors.append(
|
|
185
|
+
"预期结果超过 %d 字符: %s" % (MAX_EXPECT_CHARS, expect["t"][:30] + "...")
|
|
186
|
+
)
|
|
187
|
+
else:
|
|
188
|
+
if depth + 1 > MAX_GROUP_DEPTH:
|
|
189
|
+
errors.append("分组层级超过 %d 级: %s" % (MAX_GROUP_DEPTH, node["t"]))
|
|
190
|
+
check_tb_tree(node.get("c") or [], depth + 1, errors)
|
|
191
|
+
return errors
|
mtkit/track.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""
|
|
3
|
+
Test management store: structured execution records + defect library, supporting the
|
|
4
|
+
plan -> execute -> defect -> regression loop.
|
|
5
|
+
|
|
6
|
+
Data file (project side .mtkit-work/testdb.json):
|
|
7
|
+
{
|
|
8
|
+
"version": 1,
|
|
9
|
+
"executions": [{"case": "...", "result": "pass|fail|blocked", "note": "", "at": "..."}],
|
|
10
|
+
"bugs": [{"id": "BUG-001", "title": "...", "severity": "P0|P1|P2", "case": "...",
|
|
11
|
+
"status": "open|fixed|closed", "note": "", "created_at": "...", "updated_at": "..."}]
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
Conventions:
|
|
15
|
+
- consecutive fail threshold: a case with its latest 3 executions all fail is flagged 'long-term failing'
|
|
16
|
+
- all reads/writes use utf-8-sig (tolerate Windows BOM)
|
|
17
|
+
"""
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
from datetime import datetime
|
|
21
|
+
|
|
22
|
+
from .builder import CASE_TITLE_PATTERN
|
|
23
|
+
|
|
24
|
+
DB_FILENAME = "testdb.json"
|
|
25
|
+
WORK_DIR_NAME = ".mtkit-work"
|
|
26
|
+
CONSECUTIVE_FAIL = 3
|
|
27
|
+
|
|
28
|
+
VALID_RESULTS = ("pass", "fail", "blocked")
|
|
29
|
+
VALID_SEVERITIES = ("P0", "P1", "P2")
|
|
30
|
+
VALID_STATUSES = ("open", "fixed", "closed")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _now():
|
|
34
|
+
return datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def find_db_path(start_dir=None):
|
|
38
|
+
"""Find .mtkit-work upward from start_dir, return the testdb.json path.
|
|
39
|
+
|
|
40
|
+
:return: absolute path (cwd/.mtkit-work/testdb.json when no dir found)
|
|
41
|
+
"""
|
|
42
|
+
current = os.path.abspath(start_dir or os.getcwd())
|
|
43
|
+
while True:
|
|
44
|
+
candidate = os.path.join(current, WORK_DIR_NAME)
|
|
45
|
+
if os.path.isdir(candidate):
|
|
46
|
+
return os.path.join(candidate, DB_FILENAME)
|
|
47
|
+
parent = os.path.dirname(current)
|
|
48
|
+
if parent == current:
|
|
49
|
+
break
|
|
50
|
+
current = parent
|
|
51
|
+
return os.path.join(os.getcwd(), WORK_DIR_NAME, DB_FILENAME)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def load_db(db_path=None):
|
|
55
|
+
"""Load test management store (empty structure when missing)."""
|
|
56
|
+
path = db_path or find_db_path()
|
|
57
|
+
if not os.path.isfile(path):
|
|
58
|
+
return {"version": 1, "executions": [], "bugs": []}, path
|
|
59
|
+
with open(path, "r", encoding="utf-8-sig") as fp:
|
|
60
|
+
data = json.load(fp)
|
|
61
|
+
data.setdefault("executions", [])
|
|
62
|
+
data.setdefault("bugs", [])
|
|
63
|
+
return data, path
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def save_db(data, db_path):
|
|
67
|
+
"""Save test management store (create dir, utf-8 without BOM)."""
|
|
68
|
+
directory = os.path.dirname(db_path)
|
|
69
|
+
if not os.path.isdir(directory):
|
|
70
|
+
os.makedirs(directory, exist_ok=True)
|
|
71
|
+
with open(db_path, "w", encoding="utf-8") as fp:
|
|
72
|
+
json.dump(data, fp, ensure_ascii=False, indent=2)
|
|
73
|
+
return db_path
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def record_execution(case, result, note="", source="", chapter="", db_path=None):
|
|
77
|
+
"""Append an execution record (may link case asset and chapter), returns (record, db path)."""
|
|
78
|
+
if result not in VALID_RESULTS:
|
|
79
|
+
raise ValueError("result 取值: %s" % "/".join(VALID_RESULTS))
|
|
80
|
+
data, path = load_db(db_path)
|
|
81
|
+
record = {"case": case, "result": result, "note": note,
|
|
82
|
+
"source": source, "chapter": chapter, "at": _now()}
|
|
83
|
+
data["executions"].append(record)
|
|
84
|
+
save_db(data, path)
|
|
85
|
+
return record, path
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def add_bug(title, severity, case="", note="", db_path=None):
|
|
89
|
+
"""Register a defect (auto number BUG-NNN), returns (bug, db path)."""
|
|
90
|
+
if severity not in VALID_SEVERITIES:
|
|
91
|
+
raise ValueError("severity 取值: %s" % "/".join(VALID_SEVERITIES))
|
|
92
|
+
data, path = load_db(db_path)
|
|
93
|
+
number = len(data["bugs"]) + 1
|
|
94
|
+
bug = {
|
|
95
|
+
"id": "BUG-%03d" % number,
|
|
96
|
+
"title": title,
|
|
97
|
+
"severity": severity,
|
|
98
|
+
"case": case,
|
|
99
|
+
"status": "open",
|
|
100
|
+
"note": note,
|
|
101
|
+
"created_at": _now(),
|
|
102
|
+
"updated_at": _now(),
|
|
103
|
+
}
|
|
104
|
+
data["bugs"].append(bug)
|
|
105
|
+
save_db(data, path)
|
|
106
|
+
return bug, path
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _find_bug(data, bug_id):
|
|
110
|
+
for bug in data["bugs"]:
|
|
111
|
+
if bug.get("id") == bug_id:
|
|
112
|
+
return bug
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def close_bug(bug_id, note="", db_path=None):
|
|
117
|
+
"""Close a defect (status transition), returns (bug, db path)."""
|
|
118
|
+
data, path = load_db(db_path)
|
|
119
|
+
bug = _find_bug(data, bug_id)
|
|
120
|
+
if bug is None:
|
|
121
|
+
raise ValueError("缺陷不存在: %s" % bug_id)
|
|
122
|
+
bug["status"] = "closed"
|
|
123
|
+
if note:
|
|
124
|
+
bug["note"] = (bug.get("note") or "") + (" | " if bug.get("note") else "") + note
|
|
125
|
+
bug["updated_at"] = _now()
|
|
126
|
+
save_db(data, path)
|
|
127
|
+
return bug, path
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def list_bugs(status=None, db_path=None):
|
|
131
|
+
"""Defect list (filter by status)."""
|
|
132
|
+
data, _ = load_db(db_path)
|
|
133
|
+
bugs = data["bugs"]
|
|
134
|
+
if status:
|
|
135
|
+
bugs = [b for b in bugs if b.get("status") == status]
|
|
136
|
+
return bugs
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def defect_summary(db_path=None):
|
|
140
|
+
"""Defect distribution summary: totals/status distribution/top 10 defect-prone cases.
|
|
141
|
+
|
|
142
|
+
:return: {"total", "status": {...}, "top_cases": [{"case", "count"}]}
|
|
143
|
+
"""
|
|
144
|
+
data, _ = load_db(db_path)
|
|
145
|
+
bugs = data["bugs"]
|
|
146
|
+
status = {"open": 0, "fixed": 0, "closed": 0}
|
|
147
|
+
by_case = {}
|
|
148
|
+
for bug in bugs:
|
|
149
|
+
key = bug.get("status") or "open"
|
|
150
|
+
status[key] = status.get(key, 0) + 1
|
|
151
|
+
case = bug.get("case") or ""
|
|
152
|
+
if case:
|
|
153
|
+
by_case[case] = by_case.get(case, 0) + 1
|
|
154
|
+
top_cases = sorted(
|
|
155
|
+
({"case": case, "count": count} for case, count in by_case.items()),
|
|
156
|
+
key=lambda item: item["count"], reverse=True,
|
|
157
|
+
)[:10]
|
|
158
|
+
return {"total": len(bugs), "status": status, "top_cases": top_cases}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def asset_execution(asset_path, db_path=None):
|
|
162
|
+
"""Asset execution rate: case asset vs execution records, output never-executed case list.
|
|
163
|
+
|
|
164
|
+
:param asset_path: .xmind case asset path
|
|
165
|
+
:return: {"total", "never", "rate"}
|
|
166
|
+
"""
|
|
167
|
+
from .extract.xmind_loader import load_xmind_tree
|
|
168
|
+
|
|
169
|
+
tree = load_xmind_tree(asset_path)
|
|
170
|
+
titles = []
|
|
171
|
+
for node in tree:
|
|
172
|
+
if CASE_TITLE_PATTERN.match(node.get("t") or ""):
|
|
173
|
+
titles.append(node["t"])
|
|
174
|
+
for child in node.get("c") or []:
|
|
175
|
+
if CASE_TITLE_PATTERN.match(child.get("t") or ""):
|
|
176
|
+
titles.append(child["t"])
|
|
177
|
+
data, _ = load_db(db_path)
|
|
178
|
+
executed = {r["case"] for r in data["executions"]}
|
|
179
|
+
never = [t for t in titles if t not in executed]
|
|
180
|
+
total = len(titles)
|
|
181
|
+
return {
|
|
182
|
+
"total": total,
|
|
183
|
+
"never": never,
|
|
184
|
+
"rate": (1 - len(never) / total) if total else 0.0,
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def find_consecutive_fails(data):
|
|
189
|
+
"""Find consecutive-fail cases: cases whose latest 3 executions are all fail."""
|
|
190
|
+
recent = {}
|
|
191
|
+
for record in data["executions"]:
|
|
192
|
+
recent.setdefault(record["case"], []).append(record["result"])
|
|
193
|
+
failing = set()
|
|
194
|
+
for case, results in recent.items():
|
|
195
|
+
if len(results) >= CONSECUTIVE_FAIL and all(r == "fail" for r in results[-CONSECUTIVE_FAIL:]):
|
|
196
|
+
failing.add(case)
|
|
197
|
+
return failing
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def build_report(db_path=None):
|
|
201
|
+
"""Stats report: execution count/pass rate/fail & blocked lists/long-term fails/open defects.
|
|
202
|
+
|
|
203
|
+
:return: {"total", "passed", "failed", "blocked", "pass_rate",
|
|
204
|
+
"fail_cases", "blocked_cases", "consecutive_fails", "open_bugs", "bugs"}
|
|
205
|
+
"""
|
|
206
|
+
data, _ = load_db(db_path)
|
|
207
|
+
executions = data["executions"]
|
|
208
|
+
passed = sum(1 for r in executions if r["result"] == "pass")
|
|
209
|
+
failed = sum(1 for r in executions if r["result"] == "fail")
|
|
210
|
+
blocked = sum(1 for r in executions if r["result"] == "blocked")
|
|
211
|
+
fail_cases = sorted({r["case"] for r in executions if r["result"] == "fail"})
|
|
212
|
+
blocked_cases = sorted({r["case"] for r in executions if r["result"] == "blocked"})
|
|
213
|
+
bugs = data["bugs"]
|
|
214
|
+
open_bugs = [b for b in bugs if b.get("status") == "open"]
|
|
215
|
+
return {
|
|
216
|
+
"total": len(executions),
|
|
217
|
+
"passed": passed,
|
|
218
|
+
"failed": failed,
|
|
219
|
+
"blocked": blocked,
|
|
220
|
+
"pass_rate": (passed / len(executions) * 100) if executions else 0.0,
|
|
221
|
+
"fail_cases": fail_cases,
|
|
222
|
+
"blocked_cases": blocked_cases,
|
|
223
|
+
"consecutive_fails": sorted(find_consecutive_fails(data)),
|
|
224
|
+
"open_bugs": open_bugs,
|
|
225
|
+
"bugs": bugs,
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def render_report(report):
|
|
230
|
+
"""Stats report markdown text."""
|
|
231
|
+
lines = ["测试管理报告", ""]
|
|
232
|
+
lines.append("| 指标 | 值 |")
|
|
233
|
+
lines.append("|---|---|")
|
|
234
|
+
lines.append("| 总执行数 | %d |" % report["total"])
|
|
235
|
+
lines.append("| 通过 | %d |" % report["passed"])
|
|
236
|
+
lines.append("| 失败 | %d |" % report["failed"])
|
|
237
|
+
lines.append("| 阻塞 | %d |" % report["blocked"])
|
|
238
|
+
lines.append("| 通过率 | %.1f%% |" % report["pass_rate"])
|
|
239
|
+
lines.append("| 长期失败用例 | %d |" % len(report["consecutive_fails"]))
|
|
240
|
+
lines.append("| 未关闭缺陷 | %d |" % len(report["open_bugs"]))
|
|
241
|
+
lines.append("")
|
|
242
|
+
if report["fail_cases"]:
|
|
243
|
+
lines.append("失败用例: " + "、".join(report["fail_cases"]))
|
|
244
|
+
lines.append("")
|
|
245
|
+
if report["blocked_cases"]:
|
|
246
|
+
lines.append("阻塞用例: " + "、".join(report["blocked_cases"]))
|
|
247
|
+
lines.append("")
|
|
248
|
+
if report["consecutive_fails"]:
|
|
249
|
+
lines.append("长期失败(连续 %d 次): %s" % (CONSECUTIVE_FAIL, "、".join(report["consecutive_fails"])))
|
|
250
|
+
lines.append("")
|
|
251
|
+
if report["open_bugs"]:
|
|
252
|
+
lines.append("未关闭缺陷:")
|
|
253
|
+
for bug in report["open_bugs"]:
|
|
254
|
+
lines.append("- %s [%s] %s (关联: %s)" % (
|
|
255
|
+
bug["id"], bug.get("severity") or "?", bug.get("title") or "?",
|
|
256
|
+
bug.get("case") or "-"))
|
|
257
|
+
lines.append("")
|
|
258
|
+
return "\n".join(lines)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def build_trend(db_path=None):
|
|
262
|
+
"""Execution & defect trends: aggregate by date, output quality dashboard data.
|
|
263
|
+
|
|
264
|
+
:return: {"daily": [{"date", "total", "pass", "fail", "blocked"}],
|
|
265
|
+
"bug_daily": [{"date", "count"}]}
|
|
266
|
+
"""
|
|
267
|
+
data, _ = load_db(db_path)
|
|
268
|
+
daily = {}
|
|
269
|
+
for record in data["executions"]:
|
|
270
|
+
date = (record.get("at") or "")[:10]
|
|
271
|
+
if not date:
|
|
272
|
+
continue
|
|
273
|
+
entry = daily.setdefault(date, {"total": 0, "pass": 0, "fail": 0, "blocked": 0})
|
|
274
|
+
entry["total"] += 1
|
|
275
|
+
entry[record.get("result") or "blocked"] = entry.get(record.get("result"), 0) + 1
|
|
276
|
+
bug_daily = {}
|
|
277
|
+
for bug in data["bugs"]:
|
|
278
|
+
date = (bug.get("created_at") or "")[:10]
|
|
279
|
+
if not date:
|
|
280
|
+
continue
|
|
281
|
+
bug_daily[date] = bug_daily.get(date, 0) + 1
|
|
282
|
+
return {
|
|
283
|
+
"daily": [{"date": d, **v} for d, v in sorted(daily.items())],
|
|
284
|
+
"bug_daily": [{"date": d, "count": c} for d, c in sorted(bug_daily.items())],
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def render_trend(trend):
|
|
289
|
+
"""Quality trend dashboard markdown text."""
|
|
290
|
+
lines = ["质量趋势看板", ""]
|
|
291
|
+
if trend["daily"]:
|
|
292
|
+
lines.append("| 日期 | 执行数 | 通过 | 失败 | 阻塞 | 通过率 |")
|
|
293
|
+
lines.append("|---|---|---|---|---|---|")
|
|
294
|
+
for entry in trend["daily"]:
|
|
295
|
+
total = entry["total"]
|
|
296
|
+
rate = (entry["pass"] / total * 100) if total else 0.0
|
|
297
|
+
lines.append("| %s | %d | %d | %d | %d | %.0f%% |" % (
|
|
298
|
+
entry["date"], total, entry["pass"], entry["fail"], entry["blocked"], rate))
|
|
299
|
+
lines.append("")
|
|
300
|
+
else:
|
|
301
|
+
lines.append("暂无执行数据")
|
|
302
|
+
lines.append("")
|
|
303
|
+
if trend["bug_daily"]:
|
|
304
|
+
lines.append("| 日期 | 缺陷登记数 |")
|
|
305
|
+
lines.append("|---|---|")
|
|
306
|
+
for entry in trend["bug_daily"]:
|
|
307
|
+
lines.append("| %s | %d |" % (entry["date"], entry["count"]))
|
|
308
|
+
lines.append("")
|
|
309
|
+
return "\n".join(lines)
|