pystepmap 0.1.0__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.
@@ -0,0 +1,648 @@
1
+ """平台的第五条流程:运行测试并核对(run_project_tests)。只有平台接口(api.py 的 POST /api/projects/{id}/runs)导入
2
+ 这个模块;pystepmap mcp 的进程(mcp_server.py 只导入 store、mcp_tools)、分析子进程(worker.py)、另外四条流程(flows.py)
3
+ 都不导入它,所以也带不进执行项目代码的 runner.py——分析那条只读的路和"运行项目测试"这条执行的路按导入分开(测试真的
4
+ 走一遍 pystepmap mcp 和分析子进程的入口,再查 sys.modules)。
5
+
6
+ 按 flow-style 写(.claude/skills/flow-style/SKILL.md):编排函数只写走向,干活的事都在步骤里,判断函数只看步骤的结果。
7
+ 共用的步骤(读取项目、检查项目目录、运行分析、比较、保存分析、清理旧分析)和标记 / 项目锁来自 flows.py。
8
+
9
+ 结局:kind "ok" 或 "failed",failed 带 reason(中文)和 code(状态码见 flows 的说明)。流程在后台线程里跑
10
+ (runner.launch),拿到项目的锁之前的结局(not_found、no_command、confirm、invalid、busy)由接口直接回给界面;之后的
11
+ 失败接口已经回过 202 了,由 runner.last_failure 告诉界面。测试命令没跑完(超时、取消、没能启动)时结局是 failed,code
12
+ 为 timeout / cancelled / failed_to_start,同时已经存下一条运行(带 run_id)。
13
+
14
+ 执行项目代码的只有它调用的 runner.run_tests(见 runner.py 的说明),和分析的子进程(worker.py,只读)是分开的两条路。
15
+ 它拿和分析同一个标记、同一把项目锁(mark_busy),一直拿到这次运行存好:测试跑着的时候分析、标为已看、另一次运行都得到
16
+ busy;/status、项目列表照常应答(它们只是探一下锁)。
17
+ - 图过期(和 /status 同一个口径)时先用重新分析的那几个步骤分析并保存,再跑测试,这次运行用新的那次分析;
18
+ - 临时文件(图的副本、记录文件)在 <数据目录>/runs/tmp-<随机>(0700,文件 0600),每个结局之前都删掉(被 Exception
19
+ 以外的异常打断时由步骤删,_clean_up_if_aborted;服务被强杀时由 runner 的看门狗删);
20
+ - 状态:有失败或出错的用例 tests_failed;否则命令退出码 0 ok,其余 error;记录文件读不了 error;一条记录(执行记录和
21
+ 测试结果都算)都没收到 error;超时 timeout、取消 cancelled(服务停止时被中止的也是 cancelled,说明不同)、没能启动
22
+ error(这几种没有路径)。记录读不了、一条记录都没收到是编排函数里的两个判断,图上看得见;
23
+ - 说明(note)在命令以非 0 退出、或者没收到记录时先说退出码的意思(127 / 126 命令找不到 / 不能执行,5 pytest 一个
24
+ 测试都没收集到,4 参数或路径不对,3 pytest 内部错误(常见原因:被测项目的 Python 低于 3.12,记录插件装不上),2 被
25
+ 中断或收集测试时出错,其余"命令以退出码 N 结束"),没收到记录、命令里给 PYTHONPATH 赋了值又没接上原来的时说
26
+ "命令里设了 PYTHONPATH,把记录插件挡住了(写成 PYTHONPATH=src:$PYTHONPATH)",再说别的可能,最后"原文见运行输出";
27
+ - 运行期间代码变了(核对时图里的文件和分析时不同):照样核对(allow_stale),stale 里列出这些文件,说明里写明;
28
+ - 被测项目自己又挂了一份不看单份启用记号的旧版插件、两份都在记时,插件写一行 SecondPlugin 记号,说明里提醒
29
+ "记录文件里有两份记录插件的输出……数字可能重复";
30
+ - 库里不存任何取值:pytest 的输出只在 runner 的内存里;插件 error 行只存类型名和个数(原文进内存里的输出末尾);
31
+ 记录读不了、核对或汇总出错时说明里只写异常的类型名。
32
+ 汇总(runs.summary_json):
33
+ {"tests", "passed", "failed", "skipped", "errors"(用例数,按测试结果行;errors 是 setup / teardown 出错的),
34
+ "seconds"(测试命令跑了几秒),
35
+ "verify": {"ok"(核对没有不符;一条记录都没收到时 null——什么都没核对), "mismatches": {"edge", "end", "call"}(各类
36
+ 不符的次数), "functions_seen", "distinct_paths", "steps_total", "plugin_errors"(个数),
37
+ "plugin_error_types": {类型名: 个数}, "truncated_records", "stale": [运行期间变了的文件,最多 20 个]}
38
+ | null(没跑完、记录读不了时),
39
+ "coverage": runpath.covered_summary 的结果 | null,
40
+ "mismatch_list": [{kind, function(函数 sid), from_line, to_line, detail(引擎给的结构性说明), count}],最多 30 条,
41
+ "note": 中文说明,没有就是 ""}
42
+ 每个测试一项(runs.tests_json):{test(node id,去掉参数化后缀;"" 是测试之外的执行), outcome, seconds, cases,
43
+ functions(这个测试执行到的图里的函数个数)}。
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ import json
49
+ import logging
50
+ import re
51
+ import threading
52
+ import time
53
+ from collections import Counter, deque
54
+ from collections.abc import Iterable, Iterator
55
+ from contextlib import contextmanager
56
+ from datetime import UTC, datetime
57
+ from pathlib import Path
58
+
59
+ from pystepkit import condition, outcome, step, workflow
60
+ from pystepmap.model import ProjectGraph, from_json
61
+ from pystepmap.runpath import build_run_paths, covered_summary, run_paths_to_json
62
+ from pystepmap.verify import (
63
+ RecordError,
64
+ VerifyReport,
65
+ read_records,
66
+ stale_files,
67
+ verify,
68
+ )
69
+
70
+ from . import runner
71
+ from .flows import (
72
+ analysis_failed,
73
+ check_project_directory,
74
+ clear_mark,
75
+ clear_mark_if_aborted,
76
+ compare_with_previous,
77
+ directory_is_unusable,
78
+ load_project,
79
+ project_is_missing,
80
+ prune_old_analyses,
81
+ run_analysis,
82
+ save_analysis,
83
+ take_mark,
84
+ )
85
+ from .live import LiveRun
86
+ from .shared import load_facts, tests_on_line
87
+ from .status import staleness
88
+ from .store import NewRun, ProjectMissingError, Store, StoreError, private_file
89
+ from .worker import Analyzer
90
+
91
+ logger = logging.getLogger(__name__)
92
+
93
+ KEEP_RUNS = 5 # 每个项目最多保留最近几次测试运行
94
+ MAX_STALE_FILES = 20 # 运行的汇总里最多列几个运行期间变了的文件
95
+ MAX_MISMATCHES = 30 # 运行的汇总里最多列几条不符
96
+ _ERROR_TYPE = re.compile(r"[A-Za-z_][A-Za-z0-9_.]{0,99}")
97
+ # 标记里的 title、group 要写成字面量:引擎只认字面量,写成常量名时图上取不到
98
+
99
+ # 退出码的意思(pytest 的约定,127 / 126 是 shell 的)
100
+ _EXIT_MEANING = {
101
+ 127: "命令找不到(退出码 127)",
102
+ 126: "命令不能执行(退出码 126)",
103
+ 5: "pytest 一个测试都没收集到(退出码 5)",
104
+ 4: "pytest 的参数或路径不对(退出码 4)",
105
+ 3: "pytest 内部错误(退出码 3;常见原因:被测项目的 Python 低于 3.12,记录插件装不上)",
106
+ 2: "测试被中断了,或者收集测试时出错(退出码 2;常见原因:测试文件导入失败)",
107
+ }
108
+ SHUTDOWN_NOTE = "服务停止时测试还在跑,被中止了"
109
+ SECOND_PLUGIN = "SecondPlugin" # 插件写的记号(core/src/pystepmap/trace.py 的 pytest_sessionstart)
110
+ SECOND_PLUGIN_NOTE = "记录文件里有两份记录插件的输出(被测项目的环境里装了旧版 pystepmap 的插件?),数字可能重复。"
111
+ SHUTDOWN_BEFORE_START = "服务停止时正在重新分析,测试还没开始"
112
+ SHUTDOWN_PREPARING = "服务停止时测试还没开始"
113
+ _MAYBE = ("其他可能:命令没有运行 pytest;被测项目的 Python 低于 3.12(记录插件要用 sys.monitoring);记录插件被禁用了"
114
+ "(比如 PYTEST_ADDOPTS 被命令覆盖、-p no:pystepmap_trace_plugin)。")
115
+ _PYTHONPATH_HINT = "命令里设了 PYTHONPATH,把记录插件挡住了(写成 PYTHONPATH=src:$PYTHONPATH)。"
116
+ _SETS_PYTHONPATH = re.compile(r"(?<![\w$])PYTHONPATH=(\S*)")
117
+ # 全量运行(不挑测试)时"挑出来的测试"的样子:没有名单、没有范围
118
+ ALL_TESTS = {"ok": True, "tests": None, "scope": None, "reason": "", "code": ""}
119
+ _NONE_FOUND = "名单里的测试一个都没找到(可能改名或删掉了):重新运行一次全部测试,再跑这条线。"
120
+
121
+
122
+ # ---------- 普通函数:步骤共用的计算 ----------
123
+
124
+ def _now() -> str:
125
+ return datetime.now(UTC).isoformat(timespec="seconds")
126
+
127
+
128
+ @contextmanager
129
+ def _clean_up_if_aborted(mark: dict | None, prepared: dict | None) -> Iterator[None]:
130
+ """同 flows.clear_mark_if_aborted,另外删掉这次运行的临时目录(图的副本、记录文件)。"""
131
+ try:
132
+ yield
133
+ except BaseException:
134
+ if prepared is not None:
135
+ runner.remove_scratch(prepared.get("scratch"))
136
+ clear_mark(mark)
137
+ raise
138
+
139
+
140
+ def pythonpath_hint(command: str) -> str:
141
+ """命令里给 PYTHONPATH 赋了值、又没接上原来的($PYTHONPATH):平台放在 PYTHONPATH 里的记录插件目录被挡住了,给一句
142
+ 怎么写;否则空串。"""
143
+ sets = [m.group(1) for m in _SETS_PYTHONPATH.finditer(command)]
144
+ return _PYTHONPATH_HINT if any("PYTHONPATH" not in value for value in sets) else ""
145
+
146
+
147
+ def exit_text(code: int | None) -> str:
148
+ """退出码说成中文(见模块说明)。"""
149
+ if code is None:
150
+ return "命令没有退出码"
151
+ if code in _EXIT_MEANING:
152
+ return _EXIT_MEANING[code]
153
+ if code == 0:
154
+ return "命令正常结束(退出码 0)"
155
+ if code < 0:
156
+ return f"命令被信号 {-code} 结束"
157
+ return f"命令以退出码 {code} 结束"
158
+
159
+
160
+ def _error_type(text: str) -> str:
161
+ """插件 error 行("类型: 信息")的类型名;信息不要(可能带插件自己的异常信息),认不出类型名时"未知"。"""
162
+ name = text.split(":", 1)[0].strip()
163
+ return name if _ERROR_TYPE.fullmatch(name) else "未知"
164
+
165
+
166
+ def _counted(records: Iterable[dict], counts: Counter, errors: list[str]) -> Iterator[dict]:
167
+ """原样给出记录,顺便数:执行记录几条(executions)、测试结果按 outcome 各几个用例(results 是总数)、插件 error 行。"""
168
+ for rec in records:
169
+ if "fn" in rec:
170
+ counts["executions"] += 1
171
+ elif "outcome" in rec:
172
+ n = rec.get("n", 1)
173
+ counts[rec["outcome"]] += n
174
+ counts["results"] += n
175
+ elif "error" in rec:
176
+ errors.append(str(rec["error"]))
177
+ yield rec
178
+
179
+
180
+ def _verify_records(prepared: dict) -> dict:
181
+ """read_and_verify 的实际工作:读图的副本,边读记录边数、边核对(图过期也照样核对),再看哪些文件和分析时不同。"""
182
+ graph = from_json(Path(prepared["graph_path"]).read_text(encoding="utf-8"))
183
+ counts: Counter = Counter()
184
+ errors: list[str] = []
185
+ report = verify(graph, _counted(read_records(prepared["trace_path"]), counts, errors), allow_stale=True)
186
+ changed, unreadable = stale_files(graph)
187
+ return {"ok": True, "graph": graph, "report": report, "stale": sorted(set(changed) | set(unreadable)),
188
+ "counts": counts, "errors": errors, "error_types": Counter(_error_type(e) for e in errors),
189
+ "received": bool(counts["executions"] or counts["results"]), "problem": ""}
190
+
191
+
192
+ def _empty_summary(seconds: float, note: str) -> dict:
193
+ """没有记录可汇总时(没跑完、记录读不了)的汇总:计数都是 0,verify、coverage 为 None。"""
194
+ return {"tests": 0, "passed": 0, "failed": 0, "skipped": 0, "errors": 0, "seconds": seconds, "verify": None,
195
+ "coverage": None, "mismatch_list": [], "note": note}
196
+
197
+
198
+ def _verify_summary(checked: dict) -> dict:
199
+ report: VerifyReport = checked["report"]
200
+ kinds = Counter({"edge": 0, "end": 0, "call": 0})
201
+ for m in report.mismatches:
202
+ kinds[m.kind] += m.count
203
+ return {"ok": report.ok if checked["received"] else None, "mismatches": dict(kinds),
204
+ "functions_seen": report.functions_seen, "distinct_paths": report.distinct_paths,
205
+ "steps_total": report.steps_total, "plugin_errors": report.plugin_errors,
206
+ "plugin_error_types": dict(checked["error_types"]), "truncated_records": report.truncated_records,
207
+ "stale": checked["stale"][:MAX_STALE_FILES]}
208
+
209
+
210
+ def _mismatch_list(graph: ProjectGraph, report: VerifyReport) -> list[dict]:
211
+ """不符的前 MAX_MISMATCHES 条(按次数从多到少):函数按 sid;detail 是引擎给的结构性说明(节点标题、函数 key)。"""
212
+ out = []
213
+ for m in report.mismatches[:MAX_MISMATCHES]:
214
+ fg = graph.functions.get(m.fn)
215
+ out.append({"kind": m.kind, "function": (fg.sid or m.fn) if fg is not None else m.fn,
216
+ "from_line": m.from_line, "to_line": m.to_line, "detail": m.detail, "count": m.count})
217
+ return out
218
+
219
+
220
+ def _plugin_note(checked: dict) -> str:
221
+ """插件 error 行的说明。SecondPlugin 是新版插件写的记号:同一个进程里还有一份不看单份启用记号的旧版插件也在记录
222
+ (被测项目自己挂的),两份的记录都在文件里——单独说成"数字可能重复",不当作插件出错。"""
223
+ types = Counter(checked["error_types"])
224
+ note = SECOND_PLUGIN_NOTE if types.pop(SECOND_PLUGIN, 0) else ""
225
+ if types:
226
+ note += (f"记录插件报错:{'、'.join(f'{k} ×{n}' for k, n in sorted(types.items()))}(原文见运行输出),"
227
+ f"这次的记录可能不全。")
228
+ return note
229
+
230
+
231
+ def _files_text(files: list[str]) -> str:
232
+ shown = "、".join(files[:5])
233
+ return shown + (f" 等 {len(files)} 个文件" if len(files) > 5 else "")
234
+
235
+
236
+ def _summarize(prepared: dict, ran: dict, checked: dict) -> dict:
237
+ """summarize_run 的实际工作(收到了记录、记录读得了),返回要保存的 {"status", "exit_code", "summary", "tests",
238
+ "paths", "function_index"}。function_index:运行里的函数 sid 每个一次(排序)、每个测试的下标——按功能线数一个测试
239
+ 执行了几个函数时用,不用解开整份路径。"""
240
+ seconds, exit_code = ran["seconds"], ran["exit_code"]
241
+ graph, report, counts = checked["graph"], checked["report"], checked["counts"]
242
+ paths = build_run_paths(graph, read_records(prepared["trace_path"]))
243
+ failed = counts["failed"] + counts["error"]
244
+ status = "tests_failed" if failed else ("ok" if exit_code == 0 else "error")
245
+ notes = []
246
+ if status == "error":
247
+ notes.append(f"{exit_text(exit_code)},但没有失败的测试:可能是收集测试时出错,或者命令本身出错,原文见运行输出。")
248
+ if checked["stale"]:
249
+ notes.append(f"运行期间代码有改动({_files_text(checked['stale'])}),路径可能对不上图,核对里的不符不一定是图的"
250
+ f"问题。")
251
+ if not counts["executions"]:
252
+ notes.append("测试没有执行到图里的任何函数(没有执行记录),运行路径是空的。")
253
+ notes.append(_plugin_note(checked))
254
+ tests = [{"test": t.test, "outcome": t.outcome, "seconds": round(t.seconds, 6), "cases": t.cases,
255
+ "functions": len(t.functions)} for t in paths.tests]
256
+ names = sorted({f for t in paths.tests for f in t.functions})
257
+ at = {f: i for i, f in enumerate(names)}
258
+ function_index = {"functions": names, "tests": {t.test: sorted(at[f] for f in t.functions) for t in paths.tests}}
259
+ summary = {"tests": counts["results"], "passed": counts["passed"], "failed": counts["failed"],
260
+ "skipped": counts["skipped"], "errors": counts["error"], "seconds": seconds,
261
+ "verify": _verify_summary(checked), "coverage": covered_summary(graph, paths),
262
+ "mismatch_list": _mismatch_list(graph, report), "note": "".join(notes)}
263
+ return {"status": status, "exit_code": exit_code, "summary": summary, "tests": tests,
264
+ "paths": run_paths_to_json(paths), "function_index": function_index}
265
+
266
+
267
+ def _no_paths(status: str, exit_code: int | None, summary: dict) -> dict:
268
+ return {"status": status, "exit_code": exit_code, "summary": summary, "tests": None, "paths": None,
269
+ "function_index": None}
270
+
271
+
272
+ # ---------- 步骤 ----------
273
+
274
+ @step(title="标记这个项目正在忙")
275
+ def mark_busy(store: Store, project_id: str) -> dict:
276
+ """和分析用同一个标记、同一把锁(flows.take_mark):测试跑着的时候分析、标为已看、另一次运行都得到"正在忙"。拿到
277
+ 了再记下开始的时间(started_at、t0),并告诉进程内的运行表"开始了"(runner.announce:接口据此回 202)。"""
278
+ mark = take_mark(store, project_id)
279
+ if mark["marked"]:
280
+ mark["started_at"], mark["t0"] = _now(), time.monotonic()
281
+ runner.announce(store.path.parent, project_id)
282
+ return mark
283
+
284
+
285
+ @step(title="取消正在忙的标记")
286
+ def unmark_busy(mark: dict) -> None:
287
+ """运行测试用的标记就是分析的那个:同样取消、放开项目锁。"""
288
+ clear_mark(mark)
289
+
290
+
291
+ @step(title="说明正在运行前重新分析")
292
+ def note_reanalysis(store: Store, project_id: str, mark: dict | None = None) -> None:
293
+ """图过期、运行前要先重新分析:运行表里的阶段改成 analyzing(这时取消说"正在重新分析,分析完就停",项目列表说正在分析)。
294
+ 之前一直是 preparing:没有重新分析的运行不会报成"正在分析"。"""
295
+ with clear_mark_if_aborted(mark):
296
+ runner.set_phase(store.path.parent, project_id, "analyzing")
297
+
298
+
299
+ @step(title="检查图是否过期")
300
+ def check_graph_freshness(store: Store, project: dict, mark: dict | None = None) -> dict:
301
+ """最新一次分析之后项目里的 .py 有没有改过(改、增、删,和 /status 同一个口径:按那次分析的配置和指纹比)。返回
302
+ {"stale", "analysis_id"};没有分析、没法检查时算过期(重新分析时会说清原因)。"""
303
+ with clear_mark_if_aborted(mark):
304
+ latest = store.latest_analysis(project["id"])
305
+ facts = None if latest is None else load_facts(store, latest["id"])
306
+ if facts is None:
307
+ return {"stale": True, "analysis_id": None}
308
+ config = facts.config if facts.config is not None else project["config"]
309
+ st = staleness(project["root"], config, facts.hashes, facts.file_lines)
310
+ return {"stale": not st.get("checked") or bool(st["stale"]), "analysis_id": latest["id"]}
311
+
312
+
313
+ def _cannot_select(code: str, reason: str) -> dict:
314
+ return {"ok": False, "tests": None, "scope": None, "reason": reason, "code": code}
315
+
316
+
317
+ def pick_line_tests(store: Store, project_id: str, analysis_id: int | None, line: str) -> dict:
318
+ """从最近一次跑完的**全量**运行里,找出执行过这条功能线上函数的测试(线上的函数按 analysis_id 那次分析的图)。
319
+ 返回 {"ok", "tests": [测试 id], "scope": {"line", "line_title", "tests": 个数, "base_run"}, "reason", "code"};
320
+ 挑不出来时 ok 为假:no_full_run 还没有跑完的全量运行 / no_line 图里没有这条线 / no_index 那次全量运行没有记下每个
321
+ 测试走过的函数 / no_tests 没有测试走过这条线 / storage 读库出错。接口(开始运行之前先问一遍、给界面数个数)和
322
+ 流程的步骤都用它。局限:全量运行之后新写的测试不在名单里(平台还不知道它走哪条线)。"""
323
+ try:
324
+ base = store.latest_full_run(project_id)
325
+ if base is None:
326
+ return _cannot_select("no_full_run", "还没有跑完的全量测试运行:先运行一次全部测试,平台才知道哪些测试走过这条功能线")
327
+ text = None if analysis_id is None else store.graph_json(analysis_id)
328
+ if text is None:
329
+ return _cannot_select("storage", "要用的分析不在了")
330
+ graph = from_json(text)
331
+ try:
332
+ tests = tests_on_line(store, project_id, base["id"], graph, line)
333
+ except LookupError:
334
+ return _cannot_select("no_line", f"最新的图里没有这条功能线:{line}")
335
+ except (StoreError, ValueError, OSError) as e:
336
+ return _cannot_select("storage", f"读全量运行的记录出错:{type(e).__name__}")
337
+ if tests is None:
338
+ return _cannot_select("no_index", f"全量运行 #{base['id']} 没有记下每个测试走过哪些函数:重新运行一次全部测试")
339
+ if not tests:
340
+ return _cannot_select("no_tests", f"全量运行 #{base['id']} 里没有测试走过这条功能线:先给它写测试,再运行一次全部测试")
341
+ title = next(ln.title for ln in graph.lines if (ln.sid or ln.id) == line)
342
+ return {"ok": True, "tests": tests, "reason": "", "code": "",
343
+ "scope": {"line": line, "line_title": title, "tests": len(tests), "base_run": base["id"]}}
344
+
345
+
346
+ @step(title="挑出走过这条功能线的测试")
347
+ def select_line_tests(store: Store, project_id: str, analysis_id: int | None, line: str, mark: dict | None = None) -> dict:
348
+ """只跑一条功能线的测试时:按这次运行要用的分析的图挑(pick_line_tests)。"""
349
+ with clear_mark_if_aborted(mark):
350
+ return pick_line_tests(store, project_id, analysis_id, line)
351
+
352
+
353
+ @step(title="准备运行(插件、图的副本、记录文件)")
354
+ def prepare_run(store: Store, analysis_id: int | None, mark: dict | None = None, selected: dict | None = None) -> dict:
355
+ """在 <数据目录>/runs/tmp-<随机>(0700)下放这次分析的图的副本(插件按它记录)和空的记录文件(0600),写好插件
356
+ 目录;selected(select_line_tests 的结果)里有名单时再放一个名单文件 only.json(插件只跑名单里的测试)。返回
357
+ {"ok", "scratch", "graph_path", "trace_path", "plugin_dir", "analysis_id", "only_path", "scope", "reason"};写不了时
358
+ ok 为假,已经建的临时目录删掉。"""
359
+ with clear_mark_if_aborted(mark):
360
+ home = store.path.parent
361
+ scratch = None
362
+ try:
363
+ text = None if analysis_id is None else store.graph_json(analysis_id)
364
+ if text is None:
365
+ return {"ok": False, "reason": "准备运行失败:这次运行要用的分析不在了"}
366
+ scratch = runner.make_scratch(home)
367
+ graph_path, trace_path = scratch / "graph.json", scratch / "trace.jsonl"
368
+ private_file(graph_path)
369
+ graph_path.write_text(text, encoding="utf-8")
370
+ private_file(trace_path)
371
+ only_path = None
372
+ if selected is not None and selected["tests"] is not None:
373
+ only_path = scratch / "only.json"
374
+ private_file(only_path)
375
+ only_path.write_text(json.dumps(selected["tests"], ensure_ascii=False), encoding="utf-8")
376
+ plugin_dir = runner.write_plugin_dir(home)
377
+ except (OSError, StoreError) as e:
378
+ runner.remove_scratch(scratch)
379
+ return {"ok": False, "reason": f"准备运行失败:{getattr(e, 'strerror', None) or e}"}
380
+ except BaseException:
381
+ runner.remove_scratch(scratch)
382
+ raise
383
+ return {"ok": True, "scratch": scratch, "graph_path": graph_path, "trace_path": trace_path,
384
+ "plugin_dir": plugin_dir, "analysis_id": analysis_id, "only_path": only_path,
385
+ "scope": None if selected is None else selected["scope"], "reason": ""}
386
+
387
+
388
+ @step(title="运行测试命令")
389
+ def run_test_command(store: Store, project: dict, prepared: dict, cancel: threading.Event, timeout: float | None,
390
+ mark: dict | None = None) -> dict:
391
+ """在项目根目录里用 /bin/sh -c 跑测试命令(runner.run_tests:挂记录插件、自成进程组,超时、取消时结束整个进程组;
392
+ 超时默认取 PYSTEPMAP_TEST_TIMEOUT)。输出边跑边放进进程内的运行表(GET …/runs/output),只在内存里;跑着的时候运行表
393
+ 上挂着这次运行的进度(live.LiveRun:GET …/runs 的 running.progress),命令一结束就取下。服务退出时被
394
+ 中止的(runner.cancel_reason 为 shutdown)说明写"服务停止时测试还在跑,被中止了"(测试还没开始的:在运行前的重新分析
395
+ 里时写"服务停止时正在重新分析,测试还没开始",否则"服务停止时测试还没开始")。返回
396
+ {"status", "exit_code", "seconds", "reason", "output", "command"(跑的命令原文,只在这次运行的内存里)}。"""
397
+ with _clean_up_if_aborted(mark, prepared):
398
+ home = store.path.parent
399
+ before = (runner.running(home, project["id"]) or {}).get("phase") # 测试开始之前在哪个阶段(服务停止时的说法用)
400
+ runner.set_live(home, project["id"], LiveRun(prepared["trace_path"], prepared["graph_path"]))
401
+ runner.set_phase(home, project["id"], "testing")
402
+ live: deque[str] = deque(maxlen=runner.TAIL_LINES)
403
+ runner.keep_output(home, project["id"], live)
404
+ try:
405
+ result = runner.run_tests(project["root"], project["test_command"], graph_path=prepared["graph_path"],
406
+ trace_path=prepared["trace_path"], plugin_dir=prepared["plugin_dir"],
407
+ timeout=runner.run_timeout() if timeout is None else timeout, cancel=cancel,
408
+ output=live, scratch=prepared["scratch"], only_path=prepared.get("only_path"))
409
+ finally:
410
+ runner.set_live(home, project["id"], None) # 测试命令结束了:运行中的进度不再给
411
+ reason = result.reason
412
+ if result.status == "cancelled" and runner.cancel_reason(home, project["id"]) == "shutdown": # 和用户点的取消分开说
413
+ if result.reason != runner.CANCELLED_BEFORE_START:
414
+ reason = SHUTDOWN_NOTE
415
+ else:
416
+ reason = SHUTDOWN_BEFORE_START if before == "analyzing" else SHUTDOWN_PREPARING
417
+ if reason:
418
+ live.append(f"[pystepmap] {reason}")
419
+ return {"status": result.status, "exit_code": result.exit_code, "seconds": result.seconds,
420
+ "reason": reason, "output": live, "command": project["test_command"]}
421
+
422
+
423
+ @step(title="记下没跑完的运行")
424
+ def describe_unfinished_run(ran: dict, prepared: dict, mark: dict | None = None) -> dict:
425
+ """超时、被取消、没能启动:状态 timeout / cancelled / error,没有路径,说明写原因。"""
426
+ with _clean_up_if_aborted(mark, prepared):
427
+ status = {"timeout": "timeout", "cancelled": "cancelled"}.get(ran["status"], "error")
428
+ return _no_paths(status, None, _empty_summary(ran["seconds"], ran["reason"]))
429
+
430
+
431
+ @step(title="读记录并核对")
432
+ def read_and_verify(store: Store, project_id: str, prepared: dict, ran: dict, mark: dict | None = None) -> dict:
433
+ """读记录文件、数用例和插件错误、沿这次用的图核对(verify,图过期也照样核对),再看哪些文件在运行期间变了。返回
434
+ {"ok", "received", "graph", "report", "stale", "counts", "errors", "error_types", "problem"}:ok 为假是记录读不了
435
+ (或核对出错),received 为假是一条记录都没收到。problem 里只有中文说明和异常的类型名;原文(插件 error 行、读不了
436
+ 的那一行,可能带记录里的内容)只进内存里的输出末尾。"""
437
+ with _clean_up_if_aborted(mark, prepared):
438
+ runner.set_phase(store.path.parent, project_id, "processing")
439
+ try:
440
+ checked = _verify_records(prepared)
441
+ except RecordError as e:
442
+ ran["output"].append(f"[pystepmap] 记录文件读不了:{e}")
443
+ return {"ok": False, "received": False, "problem": "记录文件读不了(有一行格式不对,原文见运行输出)。"}
444
+ except Exception as e: # 引擎的缺陷等:变成一次 error 的运行,不让流程带着锁出去
445
+ logger.exception("核对项目 %s 的执行记录时出错", project_id)
446
+ ran["output"].append(f"[pystepmap] 核对时出错:{type(e).__name__}")
447
+ return {"ok": False, "received": False, "problem": f"核对执行记录时出错({type(e).__name__})。"}
448
+ for e in checked["errors"]: # 插件 error 行的原文只进内存里的输出末尾
449
+ ran["output"].append(f"[pystepmap] 记录插件报错:{e}")
450
+ return checked
451
+
452
+
453
+ @step(title="记下记录读不了的运行")
454
+ def describe_unreadable_records(ran: dict, checked: dict, prepared: dict, mark: dict | None = None) -> dict:
455
+ """状态 error,没有路径,说明写读不了的原因(只有类型名,原文在运行输出里)。"""
456
+ with _clean_up_if_aborted(mark, prepared):
457
+ return _no_paths("error", ran["exit_code"], _empty_summary(ran["seconds"], checked["problem"]))
458
+
459
+
460
+ @step(title="记下没收到记录的运行")
461
+ def describe_run_without_records(ran: dict, checked: dict, prepared: dict, mark: dict | None = None) -> dict:
462
+ """一条记录都没收到:状态 error,没有路径;说明先说退出码的意思,命令里覆盖了 PYTHONPATH 时说是它挡住了记录插件,
463
+ 再说别的可能,最后"原文见运行输出";verify 照带(插件报错的个数和类型),ok 为 null(什么都没核对)。"""
464
+ with _clean_up_if_aborted(mark, prepared):
465
+ none_found = _NONE_FOUND if prepared.get("scope") and ran["exit_code"] == 5 else ""
466
+ note = (f"{exit_text(ran['exit_code'])},没有收到任何记录(执行记录和测试结果都没有)。{none_found}"
467
+ f"{pythonpath_hint(ran.get('command') or '')}{_MAYBE}{_plugin_note(checked)}原文见运行输出。")
468
+ summary = {**_empty_summary(ran["seconds"], note), "verify": _verify_summary(checked)}
469
+ return _no_paths("error", ran["exit_code"], summary)
470
+
471
+
472
+ @step(title="汇总运行路径")
473
+ def summarize_run(prepared: dict, ran: dict, checked: dict, mark: dict | None = None) -> dict:
474
+ """把记录汇总成运行路径(build_run_paths),定这次的状态(有失败的测试 tests_failed;命令退出码 0 ok;否则
475
+ error),算覆盖、整理不符的前几条、写中文说明。返回 {"status", "exit_code", "summary", "tests", "paths",
476
+ "function_index"}。出错时状态 error、没有路径,说明里只有异常的类型名。"""
477
+ with _clean_up_if_aborted(mark, prepared):
478
+ try:
479
+ return _summarize(prepared, ran, checked)
480
+ except Exception as e:
481
+ logger.exception("汇总运行路径时出错")
482
+ ran["output"].append(f"[pystepmap] 汇总运行路径时出错:{type(e).__name__}")
483
+ return _no_paths("error", ran["exit_code"],
484
+ _empty_summary(ran["seconds"], f"汇总运行路径时出错({type(e).__name__})。"))
485
+
486
+
487
+ @step(title="清理这次运行的临时文件")
488
+ def remove_run_files(prepared: dict) -> None:
489
+ runner.remove_scratch(prepared["scratch"])
490
+
491
+
492
+ @step(title="保存这次运行")
493
+ def save_run(store: Store, project: dict, prepared: dict, record: dict, mark: dict | None = None) -> int:
494
+ """连同用的哪次分析、开始和结束的时间、命令原文一起存。项目不存在了(运行期间被删)时抛 ProjectMissingError,
495
+ 写不进去时抛 StoreError。"""
496
+ with clear_mark_if_aborted(mark):
497
+ return store.add_run(project["id"], NewRun(
498
+ analysis_id=prepared["analysis_id"], started_at=mark["started_at"], finished_at=_now(),
499
+ command=project["test_command"], status=record["status"], exit_code=record["exit_code"],
500
+ summary=record["summary"], tests=record["tests"], paths=record["paths"],
501
+ function_index=record["function_index"], scope=prepared.get("scope")))
502
+
503
+
504
+ @step(title="清理旧的运行(全量、单条线各留最近 5 次)") # 标题要写成字面量;改 KEEP_RUNS 时一起改
505
+ def prune_old_runs(store: Store, project_id: str, mark: dict | None = None) -> int:
506
+ """清理失败不影响这次运行的结果:记下来,下次再清。"""
507
+ with clear_mark_if_aborted(mark):
508
+ try:
509
+ return store.prune_runs(project_id, keep=KEEP_RUNS)
510
+ except StoreError:
511
+ logger.exception("清理项目 %s 的旧运行失败", project_id)
512
+ return 0
513
+
514
+
515
+ # ---------- 判断:只看步骤的结果 ----------
516
+
517
+ @condition(title="没有填测试命令?")
518
+ def lacks_test_command(found: dict) -> bool:
519
+ return not found["project"]["test_command"]
520
+
521
+
522
+ @condition(title="测试命令还没确认过?")
523
+ def command_is_unconfirmed(found: dict) -> bool:
524
+ return not found["project"]["test_confirmed"]
525
+
526
+
527
+ @condition(title="这个项目正在分析或运行测试?")
528
+ def project_is_busy(mark: dict) -> bool:
529
+ return not mark["marked"]
530
+
531
+
532
+ @condition(title="只跑一条功能线的测试?")
533
+ def scoped_to_line(line: str | None) -> bool:
534
+ return line is not None
535
+
536
+
537
+ @condition(title="挑不出这条功能线的测试?")
538
+ def selection_failed(selected: dict) -> bool:
539
+ return not selected["ok"]
540
+
541
+
542
+ @condition(title="图过期了?")
543
+ def graph_is_outdated(fresh: dict) -> bool:
544
+ return fresh["stale"]
545
+
546
+
547
+ @condition(title="准备失败?")
548
+ def preparation_failed(prepared: dict) -> bool:
549
+ return not prepared["ok"]
550
+
551
+
552
+ @condition(title="测试命令没有跑完?")
553
+ def command_did_not_finish(ran: dict) -> bool:
554
+ return ran["status"] != "finished"
555
+
556
+
557
+ @condition(title="记录读不了?")
558
+ def records_unreadable(checked: dict) -> bool:
559
+ return not checked["ok"]
560
+
561
+
562
+ @condition(title="一条记录都没收到?")
563
+ def nothing_recorded(checked: dict) -> bool:
564
+ return not checked["received"]
565
+
566
+
567
+ # ---------- 流程 ----------
568
+
569
+ @workflow(name="run_project_tests", title="运行测试并核对", group="项目管理")
570
+ def run_project_tests(store: Store, project_id: str, *, cancel: threading.Event, timeout: float | None = None,
571
+ analyzer: Analyzer | None = None, line: str | None = None) -> dict:
572
+ """取项目 → 有测试命令、确认过 → 检查目录 → 标记正在忙(和分析同一把锁,一直拿到存好;阶段 preparing)→ 图过期
573
+ 就先重新分析并保存(阶段 analyzing)→ 准备临时文件 → 在项目根目录里跑测试命令(挂记录插件)→ 读记录、核对(读不了、一条记录都没收到时各自记下)
574
+ → 汇总运行路径 → 删临时文件 → 存这次运行、只留最近 5 次 → 取消标记。命令没跑完(超时、取消、没能启动)时照样存
575
+ 一条没有路径的运行。cancel:置位时结束测试命令;timeout:秒,None 时取 PYSTEPMAP_TEST_TIMEOUT(默认 1800);
576
+ analyzer:测试注入的假引擎。line:给出时(功能线的 sid)只跑走过这条线的测试——名单取自最近一次跑完的全量运行
577
+ (select_line_tests),命令不改,由记录插件按名单挑;存下的运行带着范围(scope)。"""
578
+ found = load_project(store, project_id)
579
+ if project_is_missing(found):
580
+ return outcome("failed", title="项目不存在", reason=found["reason"], code="not_found")
581
+ if lacks_test_command(found):
582
+ return outcome("failed", title="没有填测试命令,没有运行", reason="还没有填测试命令:先在项目的测试命令里填一条",
583
+ code="no_command")
584
+ if command_is_unconfirmed(found):
585
+ return outcome("failed", title="测试命令还没确认过,没有运行", reason="第一次运行这条测试命令之前要先确认它的影响",
586
+ code="confirm")
587
+ directory = check_project_directory(found["project"]["root"])
588
+ if directory_is_unusable(directory):
589
+ return outcome("failed", title="项目目录不可用,没有运行", reason=directory["reason"], code="invalid")
590
+ mark = mark_busy(store, project_id)
591
+ if project_is_busy(mark):
592
+ return outcome("failed", title="正在分析或运行测试,这次没有运行", reason="这个项目正在分析或运行测试,等它结束再运行",
593
+ code="busy")
594
+ fresh = check_graph_freshness(store, found["project"], mark)
595
+ analysis_id = fresh["analysis_id"]
596
+ if graph_is_outdated(fresh):
597
+ note_reanalysis(store, project_id, mark)
598
+ result = run_analysis(store, found["project"]["root"], found["project"]["config"], analyzer, mark)
599
+ if analysis_failed(result):
600
+ unmark_busy(mark)
601
+ return outcome("failed", title="运行前的分析失败,没有运行测试", reason=result["reason"], code=result["code"])
602
+ compared = compare_with_previous(store, project_id, result, mark)
603
+ try:
604
+ analysis_id = save_analysis(store, project_id, result, found["project"]["config"], compared, mark)
605
+ except ProjectMissingError as e:
606
+ unmark_busy(mark)
607
+ return outcome("failed", title="项目在运行前的分析期间被删除了", reason=str(e), code="not_found")
608
+ except StoreError as e:
609
+ unmark_busy(mark)
610
+ return outcome("failed", title="保存运行前的分析失败,没有运行测试", reason=str(e), code="storage")
611
+ prune_old_analyses(store, project_id, mark)
612
+ selected = ALL_TESTS
613
+ if scoped_to_line(line):
614
+ selected = select_line_tests(store, project_id, analysis_id, line, mark)
615
+ if selection_failed(selected):
616
+ unmark_busy(mark)
617
+ return outcome("failed", title="挑不出这条功能线的测试,没有运行", reason=selected["reason"],
618
+ code=selected["code"])
619
+ prepared = prepare_run(store, analysis_id, mark, selected)
620
+ if preparation_failed(prepared):
621
+ unmark_busy(mark)
622
+ return outcome("failed", title="准备运行失败,没有运行测试", reason=prepared["reason"], code="prepare")
623
+ ran = run_test_command(store, found["project"], prepared, cancel, timeout, mark)
624
+ if command_did_not_finish(ran):
625
+ record = describe_unfinished_run(ran, prepared, mark)
626
+ else:
627
+ checked = read_and_verify(store, project_id, prepared, ran, mark)
628
+ if records_unreadable(checked):
629
+ record = describe_unreadable_records(ran, checked, prepared, mark)
630
+ elif nothing_recorded(checked):
631
+ record = describe_run_without_records(ran, checked, prepared, mark)
632
+ else:
633
+ record = summarize_run(prepared, ran, checked, mark)
634
+ remove_run_files(prepared)
635
+ try:
636
+ run_id = save_run(store, found["project"], prepared, record, mark)
637
+ except ProjectMissingError as e:
638
+ unmark_busy(mark)
639
+ return outcome("failed", title="项目在运行测试期间被删除了", reason=str(e), code="not_found")
640
+ except StoreError as e:
641
+ unmark_busy(mark)
642
+ return outcome("failed", title="保存运行结果失败", reason=str(e), code="storage")
643
+ prune_old_runs(store, project_id, mark)
644
+ unmark_busy(mark)
645
+ if command_did_not_finish(ran):
646
+ return outcome("failed", title="测试没有跑完,已记下这次运行", reason=ran["reason"], code=ran["status"],
647
+ run_id=run_id)
648
+ return outcome("ok", title="测试已运行并核对", run_id=run_id, status=record["status"])