Skip to content

Commit c4dbabc

Browse files
committed
fix(python): bound discovery and require exact pytest selectors
1 parent a2ae524 commit c4dbabc

5 files changed

Lines changed: 158 additions & 356 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA
2121
4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems` & `buildProviders`)**
2222
- `python`:通过纯 Python 构建提供者 `scripts/build_provider.py --cache ${workspaceStateDir}`(`python -I -B`,`executesProjectCode: true`,`mayUseNetwork: false`)承载:
2323
- `lithe/build/model`:复用 `scripts/build_model.py` 纯 `ast` + `tomllib`(Python 3.9–3.10 自动回退内置 `vendor/tomli`)静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 运行目标(绝不执行用户代码),派生 7 类声明式 `run` 配置;
24-
- `lithe/build/discoverTests`:运行有界、可随 `$/cancelRequest` 整组终止的 `pytest --collect-only` 收集函数、类方法与 `@pytest.mark.parametrize` 参数化用例(缓存写入 `${workspaceStateDir}`,不向工作区写 `.pytest_cache`),返回标准 `litheTestDiscovery` v0;
25-
- `lithe/build/test`:支持从动态测试树精确 nodeid 或 JUnit XML 类名运行单个用例和套件,实时推送 `lithe/build/progress` 并产出 `.pytest_cache/lithe-junit.xml` 供 Core `junitXml` 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。
24+
- `lithe/build/discoverTests`:运行可随 `$/cancelRequest` 整组终止的 `pytest --collect-only`,收集函数、类方法与参数化用例,按 Core 的条数和 UTF-8 字节限制返回 `litheTestDiscovery` v0。缓存写入 `${workspaceStateDir}`。
25+
- `lithe/build/test`:通过 pytest node ID 精确运行套件或单个用例,也接受 JUnit XML 类名。指定用例时须同时给出套件。运行时推送 `lithe/build/progress`,并产出 `.pytest_cache/lithe-junit.xml` 供 Core 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。
2626
- `lithe/build/runEntrypoints`:协商 `litheBuild` 1 时按文件静态识别入口并抑制高频成功日志;
2727
- 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。
2828
- `uv`(`uv.lock`):`uv sync`、`uv lock`。
@@ -52,7 +52,7 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA
5252
| `pyrefly.resolveLaunch` | `backend.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)<br>恢复:`plugins.operation.recovery_finished`(`code: "tool_hint_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `invalid_tool_hint`、`tool_hint_restored`、`python.unknownServer`、`internal_error` |
5353
| `python.inspectEnvironment` | `backend.py` | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`internal_error` |
5454
| `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)<br>恢复:`plugins.operation.recovery_finished`(`code: "pyproject_restored"`,`count: 1`) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `pyproject_parse_failed`、`pyproject_restored`、`python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
55-
| `lithe/build/discoverTests` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "test_discovery_truncated"`,`count` 为超出 10,000 上限被截断的条目数) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `test_discovery_truncated`、`python.pytestUnavailable`、`python.pytestTimedOut`、`python.pytestCollectionFailed`、`python.interpreterUnavailable`、`python.cacheUnavailable` |
55+
| `lithe/build/discoverTests` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "test_discovery_truncated"`,`count` 为超出条数、大小或无法表示为有效选择器而省略的条目数) | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `test_discovery_truncated`、`python.pytestUnavailable`、`python.pytestTimedOut`、`python.pytestCollectionFailed`、`python.interpreterUnavailable`、`python.cacheUnavailable` |
5656
| `lithe/build/test` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`;测试断言失败仍属正常协议返回 `exitCode != 0`,失效/越界选择器、进程级超时或解释器缺失才记 `ERROR`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidTestSelector`、`python.staleTestSelector`、`python.pytestTimedOut`、`python.interpreterUnavailable`、`python.projectUnavailable`、`internal_error` |
5757
| `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` |
5858
| `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` |
@@ -92,6 +92,8 @@ Python language support plugin for Lithe (`v0.2.0`, `schemaVersion: 0`, `pluginA
9292

9393
### 常用命令
9494

95+
插件测试使用真实 pytest。将 pytest 安装到 `PYTHON` 对应的环境,或通过 `PYTEST_PYTHON` 指定已安装 pytest 的解释器。
96+
9597
```bash
9698
# 打包当前开发平台(例如 macOS Apple Silicon)
9799
node scripts/package.mjs --platform darwin-arm64

‎docs/feature-matrix.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
| 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 纯 Python(`python -I -B`)stdio JSON-RPC 后端 `scripts/backend.py`(协商 `litheLogging` 0 与 `litheFunctions` 0);`pyrefly.resolveLaunch` 按 `platform.os` 返回包内 `bin/pyrefly`(Unix)或 `bin/pyrefly.exe`(Windows)与 `["lsp"]`,在宿主传入 `tools.python.executable` 时自动注入 `workspaceConfiguration.python.pythonPath`(支持项目外 conda / uv / pyenv 解释器),缺失或未信任项目环境时优雅省略 `pythonPath` 回退 `pyrefly 1.4.1` 原生 `.venv` 发现 | ✅ 已验证 | ⏳ pending(`macos-x86_64` 二进制与纯 Python 后端已打包校验) | ⏳ pending(`bin/pyrefly.exe` 平台分支已通过 Core `DecodePluginLanguageServerLaunch` 校验) | ⏳ pending(`musl` 二进制与纯 Python 后端已打包校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/lithe_rpc.py`<br>`io.github.lithe-idea.python-support/scripts/backend.py`<br>`io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
1717
| 工具链与环境自动发现 (`toolDefinitions`) | `python` 4 层解析:项目绑定 → `.venv` / `venv` / `.conda`(受工作区信任门控,保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` + `PATH` → 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`) | ✅ 已验证 | ⏳ pending(清单与 Core 规则已校验) | ⏳ pending(`Scripts/python.exe` / `python.exe` 布局与环境变量发现规则已通过 Core 校验) | ⏳ pending(清单与 Core 规则已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
1818
| 构建模型与运行 (`buildSystems: python` + `provider`) | `scripts/build_provider.py`(`python -I -B`,`lithe/build/model`)复用 `scripts/build_model.py` 纯 AST + `tomllib` / `vendor/tomli` 静态提取 `[project.scripts]`、包 `__main__.py`、顶层 `__main__` 脚本、Django `manage.py`、FastAPI ASGI、Flask WSGI 并派生 7 类声明式 `run` 配置;支持损坏 `pyproject.toml` 降级与修复后恢复诊断,并在协商 `litheBuild` 1 时支持 `lithe/build/runEntrypoints` | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_model.py`<br>`io.github.lithe-idea.python-support/scripts/build_provider.py`<br>`io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
19-
| 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `lithe/build/discoverTests` 通过有界可取消 `pytest --collect-only` 收集函数、测试类方法与 `@pytest.mark.parametrize` 参数化用例(缓存重定向至 `${workspaceStateDir}`,返回 `litheTestDiscovery` v0);`lithe/build/test` 支持精确 nodeid 与 JUnit 类名重跑、`lithe/build/progress` 流式输出及 `.pytest_cache/lithe-junit.xml` 解码;保留 `pip install -r requirements.txt` 与 `mypy` 任务 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_provider.py`<br>`io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
19+
| 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `lithe/build/discoverTests` 通过有界可取消 `pytest --collect-only` 收集函数、测试类方法与 `@pytest.mark.parametrize` 参数化用例(缓存写入 `${workspaceStateDir}`,按条数和 UTF-8 字节限制返回 `litheTestDiscovery` v0);`lithe/build/test` 支持精确 node ID 与 JUnit 类名重跑,单个用例须带套件、`lithe/build/progress` 流式输出及 `.pytest_cache/lithe-junit.xml` 解码;保留 `pip install -r requirements.txt` 与 `mypy` 任务 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/scripts/build_provider.py`<br>`io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
2020
| 独立工具构建系统 (`uv` / `conda` / `ruff`) | `uv`(`sync` / `lock`)、`conda`(`env update --file environment.yml --prune`)、`ruff`(`check` 含 `lineMatcher` / `format`)按各自标记文件独立检测与规划 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
2121
| 调试器 (`debugAdapters: debugpy`) | 内置打包 `debugpy` `1.8.22`(`stdio` DAP,`["-I", "-B"]` + `scripts/debugpy_adapter.py`、`--log-dir ${logDir}`、适配器与 `launch` 双重设置 `PYTHONDONTWRITEBYTECODE=1` 保持插件目录零写入、支持远程 `attach` + `pathMappings`) | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`<br>`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`<br>`vendor-lock.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |
2222
| 终端输出跳转 (`outputLinkMatchers`) | Python Traceback `File "...", line N` 点击定位源码与行号 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`<br>`scripts/test.mjs`<br>`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` |

‎e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go‎

Lines changed: 7 additions & 134 deletions
Original file line numberDiff line numberDiff line change
@@ -102,134 +102,17 @@ func pythonFileURI(path string) string {
102102
return (&url.URL{Scheme: "file", Path: slashed}).String()
103103
}
104104

105-
func hasPytestInstalled(ctx context.Context, pythonExec string, extraEnv map[string]string) bool {
106-
if pythonExec == "" {
107-
return false
108-
}
109-
cmd := exec.CommandContext(ctx, pythonExec, "-B", "-c", "import pytest")
110-
cmd.Env = os.Environ()
111-
for k, v := range extraEnv {
112-
cmd.Env = append(cmd.Env, k+"="+v)
113-
}
114-
return cmd.Run() == nil
115-
}
116-
117-
// resolvePytestToolForE2E returns a Python executable + optional environment that can run pytest,
118-
// preferring systemPython, then local developer virtualenvs, and finally a tiny hermetic pytest module.
119105
func resolvePytestToolForE2E(t *testing.T, ctx context.Context, systemPython string) core.BuildTool {
120106
t.Helper()
121-
if hasPytestInstalled(ctx, systemPython, nil) {
122-
return core.BuildTool{Executable: systemPython}
123-
}
124-
if home, err := os.UserHomeDir(); err == nil {
125-
entries, _ := os.ReadDir(home)
126-
for _, entry := range entries {
127-
name := entry.Name()
128-
if strings.HasPrefix(name, ".venv") || strings.Contains(name, "conda") || strings.HasPrefix(name, "miniforge") {
129-
cand := filepath.Join(home, name, "bin", "python3")
130-
if runtime.GOOS == "windows" {
131-
cand = filepath.Join(home, name, "Scripts", "python.exe")
132-
}
133-
if info, statErr := os.Stat(cand); statErr == nil && !info.IsDir() && hasPytestInstalled(ctx, cand, nil) {
134-
return core.BuildTool{Executable: cand}
135-
}
136-
}
137-
}
138-
}
139-
140-
// Hermetic offline fallback so air-gapped hosts never require PyPI access.
141-
shimDir := t.TempDir()
142-
pkgDir := filepath.Join(shimDir, "pytest")
143-
if err := os.MkdirAll(pkgDir, 0o755); err != nil {
144-
t.Fatal(err)
145-
}
146-
shimInit := `import importlib.util, inspect, pathlib, sys, xml.etree.ElementTree as ET
147-
class _Item:
148-
def __init__(self, nodeid, path, name, fn):
149-
self.nodeid, self.path, self.name, self.fn = nodeid, path, name, fn
150-
class _Config:
151-
def __init__(self, rootpath):
152-
self.rootpath = rootpath
153-
def _parametrize(argnames, argvalues):
154-
names = [n.strip() for n in argnames.split(",")] if isinstance(argnames, str) else list(argnames)
155-
def _deco(fn):
156-
fn._parametrize = (names, list(argvalues))
157-
return fn
158-
return _deco
159-
class _Mark:
160-
parametrize = staticmethod(_parametrize)
161-
mark = _Mark()
162-
def _discover(root):
163-
items = []
164-
for p in sorted(root.rglob("test_*.py")):
165-
rel = p.relative_to(root).as_posix()
166-
spec = importlib.util.spec_from_file_location(rel.replace("/", "_").replace(".py", ""), p)
167-
mod = importlib.util.module_from_spec(spec)
168-
spec.loader.exec_module(mod)
169-
for k, v in vars(mod).items():
170-
if callable(v) and k.startswith("test_"):
171-
prm = getattr(v, "_parametrize", None)
172-
if prm:
173-
pnames, pvals = prm
174-
for row in pvals:
175-
vals = row if isinstance(row, (tuple, list)) else (row,)
176-
lbl = "-".join(str(x) for x in vals)
177-
kw = dict(zip(pnames, vals))
178-
items.append(_Item(f"{rel}::{k}[{lbl}]", p, f"{k}[{lbl}]", lambda fn=v, kw=kw: fn(**kw)))
179-
else:
180-
items.append(_Item(f"{rel}::{k}", p, k, v))
181-
return items
182-
def main(args=None, plugins=None):
183-
argv = list(args or sys.argv[1:])
184-
collect_only = "--collect-only" in argv
185-
junit_xml = None
186-
selectors = []
187-
i = 0
188-
while i < len(argv):
189-
a = argv[i]
190-
if a == "--":
191-
selectors.extend(argv[i + 1:])
192-
break
193-
elif a.startswith("--junitxml="):
194-
junit_xml = a.split("=", 1)[1]
195-
elif a in ("-o", "-k"):
196-
i += 1
197-
elif not a.startswith("-"):
198-
selectors.append(a)
199-
i += 1
200-
cwd = pathlib.Path.cwd().resolve()
201-
items = _discover(cwd)
202-
if selectors:
203-
items = [it for it in items if any(it.nodeid == s or it.nodeid.startswith(s + "::") for s in selectors)]
204-
cfg = _Config(cwd)
205-
for plug in (plugins or []):
206-
if hasattr(plug, "pytest_collection_modifyitems"):
207-
plug.pytest_collection_modifyitems(None, cfg, items)
208-
if not items:
209-
return 5
210-
if collect_only:
211-
return 0
212-
suite_el = ET.Element("testsuite", name="pytest", tests=str(len(items)), failures="0")
213-
for it in items:
214-
cname = it.path.relative_to(cwd).with_suffix("").as_posix().replace("/", ".")
215-
ET.SubElement(suite_el, "testcase", classname=cname, name=it.name, time="0.001")
216-
it.fn()
217-
if junit_xml:
218-
out_p = cwd / junit_xml
219-
out_p.parent.mkdir(parents=True, exist_ok=True)
220-
ET.ElementTree(suite_el).write(out_p, encoding="utf-8", xml_declaration=True)
221-
return 0
222-
`
223-
if err := os.WriteFile(filepath.Join(pkgDir, "__init__.py"), []byte(shimInit), 0o644); err != nil {
224-
t.Fatal(err)
225-
}
226-
if err := os.WriteFile(filepath.Join(pkgDir, "__main__.py"), []byte("import pytest, sys\nraise SystemExit(pytest.main(sys.argv[1:]))\n"), 0o644); err != nil {
227-
t.Fatal(err)
107+
executable := os.Getenv("PYTEST_PYTHON")
108+
if executable == "" {
109+
executable = systemPython
228110
}
229-
return core.BuildTool{
230-
Executable: systemPython,
231-
Environment: map[string]string{"PYTHONPATH": shimDir},
111+
cmd := exec.CommandContext(ctx, executable, "-B", "-c", "import pytest")
112+
if err := cmd.Run(); err != nil {
113+
t.Fatalf("pytest is required for the host test; set PYTEST_PYTHON to an interpreter with pytest: %v", err)
232114
}
115+
return core.BuildTool{Executable: executable}
233116
}
234117

235118
func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
@@ -715,16 +598,6 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) {
715598
t.Fatal(err)
716599
}
717600
testProviderParams["tool"] = map[string]any{"executable": pytestTool.Executable}
718-
if len(pytestTool.Environment) > 0 {
719-
envObj, _ := testProviderParams["environment"].(map[string]any)
720-
if envObj == nil {
721-
envObj = map[string]any{}
722-
}
723-
for k, v := range pytestTool.Environment {
724-
envObj[k] = v
725-
}
726-
testProviderParams["environment"] = envObj
727-
}
728601
enrichedTestParams, err := json.Marshal(testProviderParams)
729602
if err != nil {
730603
t.Fatal(err)

0 commit comments

Comments
 (0)