From 250383fc218acdc25ea70b19db0b3848e00697fe Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Thu, 19 Nov 2026 15:30:15 +0800 Subject: [PATCH] feat(python): discover pytest cases with a build command --- .github/workflows/release.yml | 2 +- README.md | 14 +- docs/feature-matrix.md | 4 +- docs/releases/v1.0.0.md | 4 +- .../python_support_plugin_e2e_test.go | 73 ++++-- e2e/host/lithe-host.json | 2 +- .../plugin.json | 16 +- .../scripts/build_model.py | 12 + .../scripts/build_provider.py | 245 +----------------- .../scripts/discover_tests.py | 129 +++++++++ scripts/package/archives.test.mjs | 5 + scripts/test.mjs | 164 +++++++----- 12 files changed, 318 insertions(+), 352 deletions(-) create mode 100644 io.github.lithe-idea.python-support/scripts/discover_tests.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c9223c2..cb190bf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -58,7 +58,7 @@ jobs: - name: Publish GitHub Release env: GH_TOKEN: ${{ github.token }} - # v1.0.0 requires a host that advertises toolchainProviders 0. + # v1.0.0 requires a host that advertises toolchainProviders 0 and buildSystems 1. PRERELEASE_TAGS: v0.1.0 v0.1.1 v1.0.0 run: | release_flags=() diff --git a/README.md b/README.md index ab15821..432c31d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Python Support for Lithe (`io.github.lithe-idea.python-support`) -Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for fast static type checking and LSP navigation, [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging, a packaged Rust backend for interpreter discovery and language-server startup, and a Python build provider for model, run, and pytest integration. +Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: 0`), bundling [Pyrefly](https://github.com/facebook/pyrefly) `1.4.1` for static type checking and LSP navigation and [debugpy](https://github.com/microsoft/debugpy) `1.8.22` for source-level debugging. A Rust backend discovers interpreters and starts the language server. The build integration uses a pytest discovery command and a Python provider for build models, run entries, and test execution. 遵循 Lithe 插件契约 v1(`schemaVersion: 0`),为 Lithe 桌面端(macOS / Windows / Linux)提供开箱即用的 Python 语言支持、宿主工具链驱动的 `Pyrefly` 解释器注入、`.venv` / `.conda` / `conda` / `uv` / `pyenv` 多来源环境发现、动态 `pytest` 测试树收集与执行、`uv` / `conda` / `Ruff` 构建任务、源码级断点调试及新建项目向导。跨平台实现与验证记录详见 [docs/feature-matrix.md](docs/feature-matrix.md)。 @@ -19,10 +19,10 @@ Python language support plugin for Lithe (`schemaVersion: 0`, `pluginAPIVersion: - 严格按 Core 4 层优先级解析:项目级显式绑定 → 项目内环境(`.venv` / `venv` / `.conda`,`projectKind: "environment"`,受宿主工作区信任门控并保留字面软链路径)→ 全局设置 → `VIRTUAL_ENV` 与 `PATH`(`python3` / `python`)→ 16 条跨平台自动发现规则(覆盖 `UV_PYTHON_INSTALL_DIR`、`XDG_DATA_HOME`、`PYENV_ROOT`、`CONDA_ENVS_PATH`、`CONDA_PREFIX`、`WORKON_HOME`、`LOCALAPPDATA`、`APPDATA`、Homebrew、macOS Framework、`~/.pyenv`、`~/.local/share/uv`、`*conda*/envs/*`、`miniforge*/envs/*`)。 - Rust 提供者读取 conda 环境登记表和安装元数据,以及 uv、pyenv、Poetry、Pipenv 管理的外部环境。项目中的 `.python-version` 选择版本,同一目录的 `pyproject.toml` 限制可选版本。宿主观察这些输入并在变化后重新查询。 - 需要支持 `toolchainProviders: 0` 的 Lithe 桌面端。外部环境的解释器链接若指向环境目录之外,Core 会拒绝将该环境作为提供者候选。常见于以链接方式创建的 Unix Poetry/Pipenv 环境。使用常规可执行文件副本的环境可被发现,项目内 `.venv` 继续使用宿主的信任流程。 -4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems` & `buildProviders`)** - - `python`:通过纯 Python 构建提供者 `scripts/build_provider.py --cache ${workspaceStateDir}`(`python -I -B`,`executesProjectCode: true`,`mayUseNetwork: false`)承载: +4. **4 个独立构建系统与动态 `pytest` 测试树(`buildSystems: 1` 与 `buildProviders`)** + - `python` 通过 `test.discoveryCommand` 启动 `python -I -B scripts/discover_tests.py`。宿主使用选定解释器和构建实例目录运行命令,并提供 `${outputFile}`。命令运行 `pytest --collect-only`,汇报函数、类方法和参数化用例的精确选择器。发现为空时写入有效的 `litheTestDiscovery` v0 空列表。选择器或报告超出契约限制时整次发现失败。pytest 缓存与报告位于宿主 `${workspaceStateDir}` 下的本次发现目录,由宿主在操作结束时清理。宿主负责取消并回收整个进程树,收集脚本保留 45 秒的 pytest 超时。 + - Python 构建提供者 `scripts/build_provider.py` 使用 `python -I -B` 启动,处理以下请求。 - `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` 配置; - - `lithe/build/discoverTests`:运行可随 `$/cancelRequest` 整组终止的 `pytest --collect-only`,收集函数、类方法与参数化用例,按 Core 的条数和 UTF-8 字节限制返回 `litheTestDiscovery` v0。缓存写入 `${workspaceStateDir}`。 - `lithe/build/test`:通过 pytest node ID 精确运行套件或单个用例,也接受 JUnit XML 类名。指定用例时须同时给出套件。运行时推送 `lithe/build/progress`,并产出 `.pytest_cache/lithe-junit.xml` 供 Core 解码。构建请求在排队时即可取消,执行进程的所有权随请求结束。macOS 和 Linux 使用 POSIX 进程组,Windows 使用 Job Object。 - `lithe/build/runEntrypoints`:协商 `litheBuild` 1 时按文件静态识别入口并抑制高频成功日志; - 同时保留声明式任务 `pip install -r requirements.txt` 与 `mypy`(带诊断 `lineMatcher`)。 @@ -53,7 +53,6 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 | `pyrefly.resolveLaunch` | Rust 后端 | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "invalid_tool_hint"`,`count: 1`)
恢复:`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` | | `python.inspectEnvironment` | Rust 后端 | **已启用 `suppressSuccessDiagnostics`**(高频只读查询成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidExecutable`、`python.environmentUnavailable`、`internal_error` | | `lithe/build/model` | `build_provider.py` | `plugins.operation.finished`(`INFO`,含 `duration_ms` 与 `op`) | 降级:`plugins.operation.fallback_selected`(`code: "pyproject_parse_failed"`,`count: 1`)
恢复:`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` | -| `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` | | `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` | | `lithe/build/runEntrypoints` | `build_provider.py` | **已启用 `suppressSuccessDiagnostics`**(打开文件高频静态入口探测成功不发 `INFO`) | — | `plugins.operation.failed`(含 `duration_ms` 与 `code`) | `python.invalidRoot`、`python.projectUnavailable`、`internal_error` | | `notification` / `result-encoding` / `shutdown` | `lithe_rpc.py` | — | — | `plugins.operation.failed`(`ERROR`) | `framing_error`、`result_encoding_failed`、`internal_error` | @@ -62,12 +61,13 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 ### 2. 宿主代记的声明式插件操作(通道:`plugins/io.github.lithe-idea.python-support/host`) -声明式启动的语言服务器子进程与调试适配器由宿主与 Core 经 `diagnostics.recordPluginOperation` 将唯一终态代记到 `plugins/io.github.lithe-idea.python-support/host`(用户主动取消或停止不记录): +声明式启动的语言服务器子进程、调试适配器和测试发现命令由宿主与 Core 经 `diagnostics.recordPluginOperation` 将唯一终态代记到 `plugins/io.github.lithe-idea.python-support/host`。用户主动取消或停止不记录。 | `operation` | 声明来源 | 记录方 | 成功事件与级别 | 失败事件与级别 | 可能的 `host.*` 失败类别标识(`code`) | | --- | --- | --- | --- | --- | --- | | `languageServer/start` | `languageServers[]`(`pyrefly.resolveLaunch` 解析后的 `pyrefly lsp` 进程) | 启动前失败由桌面宿主记录;进入启动后经 `lsp.startServer.startupOperation` 交由 Core 记录唯一终态 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.exitedEarly`、`host.initializeFailed`、`host.timedOut` | | `debugAdapter/start` | `debugAdapters[]`(`debugpy`) | 桌面宿主(`op` 为调试会话 ID;用户停止与 Core 拒绝建会话不记录) | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.executableUnavailable`、`host.launchFailed`、`host.exitedEarly`、`host.initializeFailed`、`host.timedOut` | +| `lithe/build/discoverTests` | `buildSystems[].test.discoveryCommand`(`pytest --collect-only`) | 桌面宿主 | `plugins.operation.finished`(`INFO`,含 `duration_ms`) | `plugins.operation.failed`(`ERROR`,含 `duration_ms` 与 `code`) | `host.planFailed`、`host.executableUnavailable`、`host.launchFailed`、`host.commandFailed`、`host.timedOut`、`host.outputInvalid` | ### 3. 上游子进程通道、隐私红线与原生日志文件 @@ -76,7 +76,7 @@ Rust SDK 和构建提供者的 `scripts/lithe_rpc.py` 通过 stdio JSON-RPC 2.0 | Rust 后端 / `build_provider.py` | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`
未分类 `stderr`:`plugins.host.stderr.received`(`DEBUG`) | **零自建日志文件**;会话启动与握手由 Core 记录 `plugins.host.process.started` / `plugins.host.protocol.initialized` / `plugins.host.session.updated`;未预期异常在 `stderr` 仅输出 `: ()` 受控短词,**绝不拼接文件路径、命令参数、源码片段、输出内容或环境变量值**。Core 对 `stderr` 按每行 4 KiB 限流并脱敏截断,仅在详细诊断开启时落盘。 | | `pyrefly lsp`(语言服务器) | 结构化通道:`plugins/io.github.lithe-idea.python-support/host`(或宿主内置 `lsp/python`) | Core 记录 `plugins.host.process.started`、`plugins.host.protocol.initialized`、`plugins.host.session.updated`;`window/logMessage` 与 `window/showMessage` 保留显式 `ERROR`/`WARN`/`INFO`/`DEBUG` 级别;未分类 `stderr` 经 `plugins.host.stderr.received` 记为 `DEBUG`(仅详细诊断开启时落盘);详细诊断开启(15 分钟单次到期)时仅接纳 `$/logTrace.message` 摘要,拒绝 `verbose` 载荷。`pyrefly` 不写任何插件内文件。 | | `debugpy`(调试适配器与启动器) | 结构化通道:`debug/debugpy`
原生日志文件:`sessions//plugins/io.github.lithe-idea.python-support/files/debugpy.*.log` | 结构化会话事件写入 `debug/debugpy`;上游 `debugpy` 原生日志通过 `--log-dir ${logDir}` 定向写入宿主 `Store.PluginFilesDirectory` 创建的当前会话专属目录(权限 `0700`,逐段校验拒绝软链越界,绝不写插件安装目录或 app bundle),按 `` 建文件并随宿主日志会话生命周期统一保留与清理。 | -| `pytest`、构建任务与项目生成 | 构建/测试面板流式输出(`lithe/build/progress`)与 JUnit XML(`.pytest_cache/lithe-junit.xml`) | `lithe/build/discoverTests` 将 `pytest` 缓存重定向至 `${workspaceStateDir}`;进程 `stdout`、用户测试代码与环境变量值仅进入协议进度流或报告文件,绝不进入 v2 结构化诊断日志。 | +| `pytest`、构建任务与项目生成 | 测试发现报告(`${outputFile}`)、构建/测试面板流式输出(`lithe/build/progress`)与 JUnit XML(`.pytest_cache/lithe-junit.xml`) | `pytest --collect-only` 的缓存与报告同目录,随宿主发现操作结束清理。宿主可向用户展示失败命令的部分输出。v2 结构化诊断只保存阶段类别和耗时。 | --- diff --git a/docs/feature-matrix.md b/docs/feature-matrix.md index 663561b..e753d20 100644 --- a/docs/feature-matrix.md +++ b/docs/feature-matrix.md @@ -16,7 +16,7 @@ | 插件后端与语言服务器启动解析 (`backend` + `languageServers`) | 包内 Rust SDK 后端协商 `litheLogging` 0 与 `litheFunctions` 0。解析 `pyrefly lsp` 启动,传入宿主提供的解释器,缺失时使用 Pyrefly 原生检测。 | ✅ 已验证(兼容候选宿主) | ⏳ 归档已校验 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-19(macOS ARM64,候选宿主) | `backend/src/pyrefly.rs`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 工具链与环境自动发现 (`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`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 构建模型与运行 (`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`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | -| 动态 `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`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | +| 动态 `pytest` 测试树与测试执行 (`litheTestDiscovery` + `junitXml`) | `test.discoveryCommand` 通过 `python -I -B` 启动包内 `discover_tests.py`。`pytest --collect-only` 收集函数、类方法、参数化用例与 doctest,并将 `litheTestDiscovery` v0 写入宿主提供的 `${outputFile}`。无测试时返回空列表,收集失败或选择器超出契约时整次失败。报告与缓存由宿主清理。`lithe/build/test` 以精确 node ID 或 JUnit 类名重跑,继续提供流式进度和 JUnit 报告。 | ✅ 已验证(兼容候选宿主) | ⏳ 待实机验证 | ⏳ 待 CI 与宿主验收 | ⏳ 待 CI 与宿主验收 | 2026-11-19(macOS ARM64,候选宿主) | `io.github.lithe-idea.python-support/scripts/discover_tests.py`
`io.github.lithe-idea.python-support/scripts/build_provider.py`
`io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 独立工具构建系统 (`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`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 调试器 (`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`
`io.github.lithe-idea.python-support/scripts/debugpy_adapter.py`
`vendor-lock.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | | 终端输出跳转 (`outputLinkMatchers`) | Python Traceback `File "...", line N` 点击定位源码与行号 | ✅ 已验证 | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | ⏳ pending(归档已校验) | `2026-11-18`(`darwin-arm64`) | `io.github.lithe-idea.python-support/plugin.json`
`scripts/test.mjs`
`e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go` | @@ -26,6 +26,6 @@ ## 宿主版本与验证 -- 插件要求 `toolchainProviders: 0`。已发布的 Lithe 桌面 v0.8.6 无此能力,仅用于此前版本的回归。当前归档须在宣布该能力的兼容候选宿主上验收。 +- 插件要求宿主声明 `toolchainProviders: 0` 和 `buildSystems: 1`。旧版桌面用于此前插件版本的回归。当前归档须在同时声明这两项能力的候选宿主上验收。 - 候选宿主测试使用实际安装的插件、Conda 登记表和外部解释器副本,覆盖项目要求变更后切换解释器、全局候选、原生项目解释器信任及包文件哈希。 - 宿主按 Core 的文件事实校验安装。外部虚拟环境里指向环境外的 Python 链接不可作为提供者候选,项目内环境由宿主信任流程单独处理。 diff --git a/docs/releases/v1.0.0.md b/docs/releases/v1.0.0.md index bacbf65..86e76aa 100644 --- a/docs/releases/v1.0.0.md +++ b/docs/releases/v1.0.0.md @@ -6,7 +6,7 @@ ### 升级与兼容性 -升级需要支持 `toolchainProviders` 0 的 Lithe 桌面版。确认桌面已支持该能力后,再安装对应操作系统和架构的插件 ZIP。使用较早桌面版本时,可继续使用 Python Support v0.1.1。 +升级需要支持 `toolchainProviders` 0 和 `buildSystems` 1 的 Lithe 桌面版。确认桌面已支持这两项能力后,再安装对应操作系统和架构的插件 ZIP。使用较早桌面版本时,可继续使用 Python Support v0.1.1。 --- @@ -18,4 +18,4 @@ ### Upgrade and compatibility -This upgrade requires a Lithe desktop version that supports `toolchainProviders` 0. Once your desktop version supports it, install the plugin ZIP for your operating system and architecture. Python Support v0.1.1 remains available for earlier versions of Lithe. +This upgrade requires a Lithe desktop version that supports `toolchainProviders` 0 and `buildSystems` 1. Once your desktop version supports both capabilities, install the plugin ZIP for your operating system and architecture. Python Support v0.1.1 remains available for earlier versions of Lithe. diff --git a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go index cfcd37d..038d20a 100644 --- a/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go +++ b/e2e/host/desktop/internal/workbench/python_support_plugin_e2e_test.go @@ -22,10 +22,12 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/buildprovider" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginsettings" "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust" "github.com/1lck/Lithe-IDEA/desktop/internal/store" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" @@ -491,15 +493,18 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { _ = dapCmd.Process.Kill() _ = dapCmd.Wait() - // 6. Detect all 4 build systems (conda, python, ruff, uv), start real build_provider.py, - // and verify lithe/build/model, lithe/build/discoverTests, and lithe/build/test + junitXml! + // 6. Detect all four build systems and exercise the Python model, discovery and test run. detection, err := kernel.DetectBuildSystems(ctx, workspace, []json.RawMessage{normalizedManifest}) if err != nil { t.Fatalf("DetectBuildSystems: %v", err) } var detectedIDs []string + var pythonInstance core.BuildInstance for _, inst := range detection.Instances { detectedIDs = append(detectedIDs, inst.BuildSystemID) + if inst.BuildSystemID == "python" { + pythonInstance = inst + } } slices.Sort(detectedIDs) if !slices.Equal(detectedIDs, []string{"conda", "python", "ruff", "uv"}) { @@ -569,32 +574,49 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("expected derived Run entries for ws-cli and main.py, got %+v", decodedModel.Run) } - // 6b. Provider lithe/build/discoverTests -> DecodeBuildTestDiscovery. - discPlan, err := kernel.PlanBuildTestDiscovery(ctx, normalizedManifest, "python", core.BuildPlanRequest{ - Root: ".", - WorkspaceRoot: workspace, - Tool: &pytestTool, - }) + // 6b. Run the installed plugin's discovery through the workbench command path. + entries, err := service.Manager.Installed() if err != nil { - t.Fatalf("PlanBuildTestDiscovery: %v", err) + t.Fatal(err) + } + buildPlugins, err := service.BuildPlugins(ctx, entries) + if err != nil || len(buildPlugins) != 1 || buildPlugins[0].PluginID != pythonSupportPluginID { + t.Fatalf("expected the installed Python build plugin: %+v (%v)", buildPlugins, err) + } + buildPlugin := buildPlugins[0] + instance := buildInstance{ + BuildInstance: pythonInstance, + PluginID: buildPlugin.PluginID, + Version: buildPlugin.Version, + Manifest: buildPlugin.Manifest, + PackageDirectory: buildPlugin.Directory, + System: buildPlugin.Systems["python"], } - if discPlan.Provider == nil || discPlan.Provider.Method != "lithe/build/discoverTests" { - t.Fatalf("expected provider testDiscoveryPlan, got %+v", discPlan) + if instance.System.Test == nil || !instance.System.Test.DiscoveryCommand { + t.Fatal("installed Python build system did not expose command discovery") } - discOp, err := providerClient.Execute(ctx, discPlan.Provider.Method, discPlan.Provider.Params, 45_000) + preferences := pluginsettings.New(kernel, appStore.Dir()) + settings, err := preferences.Load(ctx, instance.Manifest, workspace) if err != nil { - t.Fatalf("providerClient.Execute(lithe/build/discoverTests): %v", err) + t.Fatal(err) } - discRawResult, err := discOp.Wait(ctx) + pythonSetting, err := json.Marshal(pytestTool.Executable) if err != nil { - t.Fatalf("discOp.Wait: %v", err) + t.Fatal(err) } - decodedDiscovery, err := kernel.DecodeBuildTestDiscovery(ctx, normalizedManifest, "python", core.BuildDecodeTestDiscoveryRequest{ - Root: ".", - Result: discRawResult, - }) + if _, err := preferences.Save(ctx, settings, "global", []core.PluginSettingEdit{{ID: "pythonExecutable", Value: pythonSetting}}, nil); err != nil { + t.Fatalf("set the test interpreter: %v", err) + } + workbench := &App{kernel: kernel, plugins: service, store: appStore, text: i18n.For(i18n.English)} + discoveryOperation := core.NewOperation() + discoveryCtx := core.WithOrigin(ctx, core.Origin{Operation: discoveryOperation}) + decodedDiscovery, err := workbench.buildTestDiscovery(discoveryCtx, &project{root: workspace}, instance, kernel, false) if err != nil { - t.Fatalf("DecodeBuildTestDiscovery: %v", err) + t.Fatalf("workbench command discovery: %v", err) + } + discoveryFiles, err := os.ReadDir(buildStateDirectory(service.Root, workspace, instance)) + if err != nil || len(discoveryFiles) != 0 { + t.Fatalf("discovery left workspace state entries %v (%v)", discoveryFiles, err) } if len(decodedDiscovery.Tests) != 3 { t.Fatalf("discovered tests = %+v, want 3 items (test_alpha, test_scale[2-6], test_scale[4-12])", decodedDiscovery.Tests) @@ -668,8 +690,7 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { t.Fatalf("unexpected decoded JUnit XML results: %+v", decodedResults) } - // Verify Core validated and forwarded structured lithe/log events for both backend and build provider - // with zero plugins.diagnostics.rejected events! + // Verify plugin RPC diagnostics and the workbench's command terminal event. drained, err := kernel.DrainCoreEvents(ctx) if err != nil { t.Fatalf("DrainCoreEvents: %v", err) @@ -677,9 +698,13 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { logMu.Lock() captured := slices.Clone(recordedEvents) logMu.Unlock() + var discoveryTerminals []string for _, ev := range drained.Events { op, _ := ev.Fields["operation"].(string) captured = append(captured, fmt.Sprintf("%s:%s", ev.Event, op)) + if op == "lithe/build/discoverTests" && ev.Op == discoveryOperation { + discoveryTerminals = append(discoveryTerminals, ev.Event) + } if ev.Event == "plugins.diagnostics.rejected" { t.Fatalf("unexpected rejected plugin diagnostic from Core: %+v", ev) } @@ -692,8 +717,8 @@ func TestPythonSupportPluginContractPlansInstallAndImmutability(t *testing.T) { if !slices.Contains(captured, "plugins.operation.finished:pyrefly.resolveLaunch") { t.Fatalf("expected plugins.operation.finished:pyrefly.resolveLaunch in Core log facts, got %v", captured) } - if !slices.Contains(captured, "plugins.operation.finished:lithe/build/discoverTests") { - t.Fatalf("expected plugins.operation.finished:lithe/build/discoverTests in Core log facts, got %v", captured) + if !slices.Equal(discoveryTerminals, []string{"plugins.operation.finished"}) { + t.Fatalf("expected one successful command discovery terminal, got %v (Core events %v)", discoveryTerminals, captured) } // 7. Verify Python Traceback outputLinkMatchers. diff --git a/e2e/host/lithe-host.json b/e2e/host/lithe-host.json index fbfce81..f44fd00 100644 --- a/e2e/host/lithe-host.json +++ b/e2e/host/lithe-host.json @@ -1,6 +1,6 @@ { "repository": "https://github.com/Mucheen/Lithe-IDEA.git", - "revision": "8b80afb5031f55daad5a769bca7126f9e632cf59", + "revision": "9fe390d08ccb16586294fbfb64a83964221093dd", "packages": { "./internal/projectgen": "^TestPythonPlugin", "./internal/workbench": "^TestPythonSupportPlugin" diff --git a/io.github.lithe-idea.python-support/plugin.json b/io.github.lithe-idea.python-support/plugin.json index 334f564..535f78e 100644 --- a/io.github.lithe-idea.python-support/plugin.json +++ b/io.github.lithe-idea.python-support/plugin.json @@ -13,7 +13,7 @@ "requires": { "backend": 0, "buildProviders": 0, - "buildSystems": 0, + "buildSystems": 1, "debugAdapters": 0, "languageServers": 0, "languages": 0, @@ -503,7 +503,6 @@ "runtimeArguments": ["-I", "-B"], "entry": "scripts/build_provider.py" }, - "arguments": ["--cache", "${workspaceStateDir}"], "executesProjectCode": true, "mayUseNetwork": false }, @@ -639,7 +638,18 @@ "scopes": ["workspace", "project", "target"], "targetTags": ["test"], "filters": ["suite", "case"], - "discovery": true, + "discoveryCommand": { + "arguments": [ + "-I", + "-B", + "${pluginDir}/scripts/discover_tests.py", + "${outputFile}", + "${root}", + "${optionArguments}" + ], + "executesProjectCode": true, + "mayUseNetwork": false + }, "arguments": [], "results": { "decoder": "junitXml", diff --git a/io.github.lithe-idea.python-support/scripts/build_model.py b/io.github.lithe-idea.python-support/scripts/build_model.py index 418fa9e..98737c0 100644 --- a/io.github.lithe-idea.python-support/scripts/build_model.py +++ b/io.github.lithe-idea.python-support/scripts/build_model.py @@ -406,6 +406,18 @@ def _module_name_for_file(rel_posix: str, has_src_dir: bool): return ".".join(parts), app_dir +def project_name_for_dir(instance_dir: Path) -> str: + for filename, parse in ( + ("pyproject.toml", _parse_pyproject), + ("setup.cfg", _parse_setup_cfg), + ("setup.py", _parse_setup_py), + ): + name = parse(instance_dir / filename)["name"] + if name: + return name + return instance_dir.name or "python-project" + + def build_model_with_diagnostics(root_dir: Path) -> tuple[dict, list[str]]: root_real = root_dir.resolve() py_meta = _parse_pyproject(root_dir / "pyproject.toml") diff --git a/io.github.lithe-idea.python-support/scripts/build_provider.py b/io.github.lithe-idea.python-support/scripts/build_provider.py index 8c78d4c..c8574d1 100644 --- a/io.github.lithe-idea.python-support/scripts/build_provider.py +++ b/io.github.lithe-idea.python-support/scripts/build_provider.py @@ -5,11 +5,7 @@ sys.dont_write_bytecode = True os.environ["PYTHONDONTWRITEBYTECODE"] = "1" -import argparse -import json from pathlib import Path -import shutil -import tempfile import threading from typing import Any, Optional from urllib.parse import unquote, urlparse @@ -20,120 +16,20 @@ sys.path.insert(0, _SCRIPTS_DIR) from build_model import ( # noqa: E402 - _parse_pyproject, - _parse_setup_cfg, - _parse_setup_py, _safe_within, build_model_with_diagnostics, inspect_file_entrypoints, + project_name_for_dir, ) from lithe_rpc import ( # noqa: E402 CallContext, JsonRpcServer, - MAX_BUILD_RESULT_BYTES, PluginError, run_bounded_process, ) -_MAX_DISCOVERED_TESTS = 10_000 -_MAX_TEST_SELECTOR_BYTES = 1024 _JUNIT_REPORT_REL = ".pytest_cache/lithe-junit.xml" -_PYTEST_COLLECTOR_SNIPPET = """ -import json, os, pathlib, sys -sys.dont_write_bytecode = True -os.environ["PYTHONDONTWRITEBYTECODE"] = "1" - -out_path = pathlib.Path(sys.argv[1]) -cache_dir = sys.argv[2] -project = json.loads(sys.argv[3]) -max_items, max_bytes, max_selector_bytes = map(int, sys.argv[4:7]) -extra_args = sys.argv[7:] - -try: - import pytest -except ModuleNotFoundError: - sys.exit(197) - -cwd_real = pathlib.Path.cwd().resolve() - -def valid_selector(text): - try: - return (text.strip() and not text.lstrip().startswith("-") - and len(text.encode("utf-8")) <= max_selector_bytes - and not any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in text)) - except UnicodeEncodeError: - return False - -class _LitheTestCollector: - def __init__(self): - self.items = [] - self.omitted = 0 - - def pytest_collection_finish(self, session): - root_real = pathlib.Path(str(session.config.rootpath)).resolve() - # Reserve room for JSON keys, counters and the provider response envelope. - remaining_bytes = max_bytes - 128 - for item in session.items: - nodeid = getattr(item, "nodeid", "") - if not isinstance(nodeid, str) or not nodeid: - continue - if "::" in nodeid: - fpart, cpart = nodeid.split("::", 1) - else: - fpart, cpart = nodeid, getattr(item, "name", "") or nodeid - item_path = getattr(item, "path", None) - resolved_suite = None - if item_path is not None: - try: - resolved_suite = pathlib.Path(item_path).resolve().relative_to(cwd_real).as_posix() - except Exception: - resolved_suite = None - if resolved_suite is None: - try: - resolved_suite = (root_real / fpart).resolve().relative_to(cwd_real).as_posix() - except Exception: - resolved_suite = None - if ( - resolved_suite - and valid_selector(resolved_suite) - and valid_selector(cpart) - and ":" not in resolved_suite and "\\\\" not in resolved_suite - and all(seg not in ("", ".", "..") and not seg.startswith("-") for seg in resolved_suite.split("/")) - ): - if len(self.items) < max_items: - selector = {"suite": resolved_suite, "case": cpart, "project": project} - size = len(json.dumps(selector, ensure_ascii=False).encode("utf-8")) + 2 - if size <= remaining_bytes: - self.items.append(selector) - remaining_bytes -= size - continue - self.omitted += 1 - -args = [ - "--collect-only", - "-q", - "--color=no", - "-o", - "addopts=", - "-o", - f"cache_dir={cache_dir}", - *extra_args, -] -collector = _LitheTestCollector() -raw_code = pytest.main(args, plugins=[collector]) -try: - exit_code = int(raw_code) -except Exception: - exit_code = 1 -out_path.write_text( - json.dumps({"items": collector.items, "omitted": collector.omitted}, ensure_ascii=False), - encoding="utf-8", -) -sys.exit(exit_code) -""".strip() - - def file_uri_to_path(uri: str) -> Optional[Path]: parsed = urlparse(uri) if parsed.scheme != "file": @@ -208,19 +104,6 @@ def _verify_contained_path(instance_dir: Path, instance_real: Path, rel_posix: s return cur -def _project_name_for_dir(instance_dir: Path) -> str: - py_meta = _parse_pyproject(instance_dir / "pyproject.toml") - if py_meta.get("name"): - return py_meta["name"] - cfg_meta = _parse_setup_cfg(instance_dir / "setup.cfg") - if cfg_meta.get("name"): - return cfg_meta["name"] - setup_meta = _parse_setup_py(instance_dir / "setup.py") - if setup_meta.get("name"): - return setup_meta["name"] - return instance_dir.name or "python-project" - - def _resolve_pytest_selector_args( instance_dir: Path, suite: Any, @@ -294,16 +177,9 @@ def _resolve_pytest_selector_args( return [target_dir] if target_dir else [] -def create_build_provider_server(*, cache_dir: Optional[str] = None) -> JsonRpcServer: +def create_build_provider_server() -> JsonRpcServer: server = JsonRpcServer(name="python-build-provider", version="0.2.0") workspace_root_holder: dict[str, Path] = {"root": Path.cwd().resolve()} - owned_temp_dir: Optional[str] = None - if cache_dir: - cache_root = Path(cache_dir) - else: - owned_temp_dir = tempfile.mkdtemp(prefix="lithe-python-build-") - cache_root = Path(owned_temp_dir) - degraded_model_roots: set[str] = set() state_lock = threading.Lock() @@ -328,10 +204,6 @@ def _on_init(params: dict[str, Any]) -> None: if cand.is_dir(): workspace_root_holder["root"] = cand.resolve() - def _on_shutdown() -> None: - if owned_temp_dir and os.path.isdir(owned_temp_dir): - shutil.rmtree(owned_temp_dir, ignore_errors=True) - def _resolve_instance(params: dict[str, Any]) -> tuple[str, Path]: ws_root = workspace_root_holder["root"] norm_root = _normalize_rel_root(params.get("root")) @@ -387,105 +259,6 @@ def handle_model(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]: ctx.diagnostics.recovered("lithe/build/model", "pyproject_restored", 1) return model - def handle_discover_tests(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]: - ctx.raise_if_cancelled() - norm_root, instance_dir = _resolve_instance(params) - python_exec, child_env = _resolve_runtime_and_env(params) - project_selection = { - "name": _project_name_for_dir(instance_dir), - "path": norm_root, - } - - try: - cache_root.mkdir(parents=True, exist_ok=True) - pytest_cache_dir = cache_root / "pytest-collect-cache" - pytest_cache_dir.mkdir(parents=True, exist_ok=True) - except OSError as exc: - raise PluginError("python.cacheUnavailable", "Workspace state directory is not writable.") from exc - - timeout_ms = 45_000.0 - raw_env_timeout = os.environ.get("LITHE_PYTHON_DISCOVER_TIMEOUT_MS") - if raw_env_timeout: - try: - timeout_ms = max(200.0, float(raw_env_timeout)) - except ValueError: - pass - - option_args = _string_args(params.get("optionArguments")) - with tempfile.TemporaryDirectory(dir=str(cache_root), prefix="discover-") as run_tmp: - out_json_path = Path(run_tmp) / "collected.json" - argv = [ - python_exec, - "-B", - "-c", - _PYTEST_COLLECTOR_SNIPPET, - str(out_json_path), - str(pytest_cache_dir), - json.dumps(project_selection), - str(_MAX_DISCOVERED_TESTS), - str(MAX_BUILD_RESULT_BYTES), - str(_MAX_TEST_SELECTOR_BYTES), - *option_args, - ] - try: - exit_code, _output, timed_out = run_bounded_process( - argv, - cwd=str(instance_dir), - env=child_env, - cancel_token=ctx.cancel_token, - timeout_seconds=timeout_ms / 1000.0, - ) - except FileNotFoundError as exc: - raise PluginError( - "python.interpreterUnavailable", - "The selected Python interpreter could not be started.", - ) from exc - - if timed_out: - raise PluginError("python.pytestTimedOut", "pytest test discovery timed out.") - if exit_code == 197: - raise PluginError( - "python.pytestUnavailable", - "pytest is not installed in the selected Python environment.", - ) - if exit_code == 5: - return { - "format": "litheTestDiscovery", - "version": 0, - "tests": [], - } - if exit_code != 0 or not out_json_path.is_file(): - raise PluginError( - "python.pytestCollectionFailed", - "pytest failed to collect tests. Fix syntax or import errors and retry.", - ) - - try: - with out_json_path.open("rb") as collection: - data = collection.read(MAX_BUILD_RESULT_BYTES + 1) - if len(data) > MAX_BUILD_RESULT_BYTES: - raise ValueError("pytest collection report exceeds its byte budget") - payload = json.loads(data) - items = payload["items"] - omitted = payload["omitted"] - if (not isinstance(items, list) or len(items) > _MAX_DISCOVERED_TESTS - or type(omitted) is not int or omitted < 0): - raise ValueError("invalid pytest collection report") - except (OSError, ValueError, TypeError, KeyError) as exc: - raise PluginError( - "python.pytestCollectionFailed", - "pytest returned an unreadable test collection payload.", - ) from exc - - if omitted: - ctx.diagnostics.degraded("lithe/build/discoverTests", "test_discovery_truncated", omitted) - - return { - "format": "litheTestDiscovery", - "version": 0, - "tests": items, - } - def handle_test(params: dict[str, Any], ctx: CallContext) -> dict[str, Any]: ctx.raise_if_cancelled() _norm_root, instance_dir = _resolve_instance(params) @@ -587,7 +360,7 @@ def handle_run_entrypoints(params: dict[str, Any], ctx: CallContext) -> dict[str if not rel_file or any(p in ("", ".", "..") for p in rel_file.split("/")): return {"format": "litheRunEntrypoints", "version": 0, "entrypoints": []} project_selection = { - "name": _project_name_for_dir(instance_dir), + "name": project_name_for_dir(instance_dir), "path": norm_root, } entrypoints = inspect_file_entrypoints(instance_dir, rel_file, project_selection) @@ -598,22 +371,12 @@ def handle_run_entrypoints(params: dict[str, Any], ctx: CallContext) -> dict[str } server.on_initialize(_on_init) - server.on_shutdown(_on_shutdown) server.build_handler("lithe/build/model", handle_model) - server.build_handler("lithe/build/discoverTests", handle_discover_tests) server.build_handler("lithe/build/test", handle_test) server.build_handler("lithe/build/runEntrypoints", handle_run_entrypoints) server.suppress_success_diagnostics("lithe/build/runEntrypoints") return server -def main(argv: list[str]) -> int: - parser = argparse.ArgumentParser(add_help=False) - parser.add_argument("--cache", dest="cache_dir", default=None) - known, _ = parser.parse_known_args(argv[1:]) - server = create_build_provider_server(cache_dir=known.cache_dir) - return server.listen() - - if __name__ == "__main__": - raise SystemExit(main(sys.argv)) + raise SystemExit(create_build_provider_server().listen()) diff --git a/io.github.lithe-idea.python-support/scripts/discover_tests.py b/io.github.lithe-idea.python-support/scripts/discover_tests.py new file mode 100644 index 0000000..854b4d2 --- /dev/null +++ b/io.github.lithe-idea.python-support/scripts/discover_tests.py @@ -0,0 +1,129 @@ +"""Collect exact pytest selectors for the host-owned discovery report.""" + +import json +import os +from pathlib import Path +import subprocess +import sys + +sys.dont_write_bytecode = True +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from build_model import project_name_for_dir # noqa: E402 + + +_DISCOVERY_TIMEOUT_SECONDS = 45 +_PYTEST_COLLECTOR = r""" +import json +from pathlib import Path +import sys + +try: + import pytest +except ModuleNotFoundError: + print("pytest --collect-only: pytest unavailable (ModuleNotFoundError)", file=sys.stderr) + sys.exit(197) + +MAX_TESTS = 10_000 +MAX_REPORT_BYTES = 32 * 1024 * 1024 +MAX_SELECTOR_BYTES = 1024 +HEADER = b'{"format":"litheTestDiscovery","version":0,"tests":[' +FOOTER = b"]}\n" + +output_file = Path(sys.argv[1]) +project = json.loads(sys.argv[2]) +cwd = Path.cwd().resolve() + + +def valid_selector(text): + if not isinstance(text, str): + return False + try: + return (text.strip() and not text.lstrip().startswith("-") + and len(text.encode("utf-8")) <= MAX_SELECTOR_BYTES + and not any(ord(c) < 32 or 127 <= ord(c) <= 159 for c in text)) + except UnicodeEncodeError: + return False + + +class Collector: + def __init__(self): + self.tests = None + + def pytest_collection_finish(self, session): + if len(session.items) > MAX_TESTS: + return + root = Path(session.config.rootpath).resolve() + tests = [] + remaining_bytes = MAX_REPORT_BYTES - len(HEADER) - len(FOOTER) + for item in session.items: + nodeid = getattr(item, "nodeid", "") + if not isinstance(nodeid, str) or not nodeid: + return + filename, separator, case = nodeid.partition("::") + if not separator: + case = getattr(item, "name", "") or nodeid + suite = None + for path in (getattr(item, "path", None), root / filename): + if path is not None: + try: + suite = Path(path).resolve().relative_to(cwd).as_posix() + break + except (OSError, RuntimeError, ValueError): + continue + if (not suite or not valid_selector(suite) or not valid_selector(case) + or ":" in suite or "\\" in suite + or any(seg in ("", ".", "..") or seg.startswith("-") for seg in suite.split("/"))): + return + selector = {"suite": suite, "case": case, "project": project} + encoded = json.dumps(selector, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + remaining_bytes -= len(encoded) + bool(tests) + if remaining_bytes < 0: + return + tests.append(encoded) + self.tests = tests + + +collector = Collector() +exit_code = pytest.main([ + "--collect-only", "-q", "--color=no", + "-o", "addopts=", "-o", f"cache_dir={output_file.with_name('pytest-cache')}", + *sys.argv[3:], +], plugins=[collector]) +if exit_code not in (pytest.ExitCode.OK, pytest.ExitCode.NO_TESTS_COLLECTED): + sys.exit(exit_code) +if collector.tests is None: + print("litheTestDiscovery: invalid or oversized test selectors", file=sys.stderr) + sys.exit(1) + +with output_file.open("xb") as report: + report.write(HEADER) + for index, item in enumerate(collector.tests): + if index: + report.write(b",") + report.write(item) + report.write(FOOTER) +""" + + +def main() -> int: + output_file, root, *options = sys.argv[1:] + project = {"name": project_name_for_dir(Path.cwd().resolve()), "path": root} + # The isolated entry point only imports bundled helpers. The pytest child + # inherits the selected Python's user site and project imports, like pytest + # execution, and stays in the host-owned process group or Windows job. + try: + child = subprocess.run( + [sys.executable, "-B", "-c", _PYTEST_COLLECTOR, output_file, json.dumps(project), *options], + env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1", "PYTHONIOENCODING": "utf-8"}, + check=False, + timeout=_DISCOVERY_TIMEOUT_SECONDS, + ) + except subprocess.TimeoutExpired: + print(f"pytest --collect-only: ETIMEDOUT ({_DISCOVERY_TIMEOUT_SECONDS}s)", file=sys.stderr) + return 124 + return child.returncode + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/package/archives.test.mjs b/scripts/package/archives.test.mjs index e3a84b1..27a3380 100644 --- a/scripts/package/archives.test.mjs +++ b/scripts/package/archives.test.mjs @@ -101,6 +101,7 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla `${PACKAGE_ID}/scripts/windows_job.py`, `${PACKAGE_ID}/scripts/build_model.py`, `${PACKAGE_ID}/scripts/build_provider.py`, + `${PACKAGE_ID}/scripts/discover_tests.py`, `${PACKAGE_ID}/scripts/debugpy_adapter.py`, `${PACKAGE_ID}/vendor/debugpy/adapter/__main__.py`, `${PACKAGE_ID}/vendor/debugpy/ThirdPartyNotices.txt`, @@ -123,6 +124,10 @@ test("every built archive has safe paths, no bytecode or symlinks, and valid pla assert.deepEqual(manifest.backend, { launch: { kind: "packaged", path: backendPath(archive.platform) } }); assert.deepEqual(manifest.toolchainProviders, baseManifest.toolchainProviders); assert.equal(manifest.requires.toolchainProviders, 0); + assert.deepEqual( + manifest.buildSystems.find(({ id }) => id === "python").test, + baseManifest.buildSystems.find(({ id }) => id === "python").test, + ); const isWindows = archive.platform.startsWith("windows-"); const pyreflyServer = manifest.languageServers.find((s) => s.languageID === "python"); assert.deepEqual(pyreflyServer.launch, { diff --git a/scripts/test.mjs b/scripts/test.mjs index 851b761..37bd738 100644 --- a/scripts/test.mjs +++ b/scripts/test.mjs @@ -344,8 +344,8 @@ try { "toolDefinitions", "toolchainProviders", ]); - for (const ver of Object.values(variant.requires)) { - assert.equal(ver, 0); + for (const [capability, version] of Object.entries(variant.requires)) { + assert.equal(version, capability === "buildSystems" ? 1 : 0); } assert.deepEqual([...variant.permissions].sort(), [ "backend.launch", @@ -396,7 +396,12 @@ try { assert.equal(pyBuild.provider.mayUseNetwork, false); assert.deepEqual(pyBuild.model, { source: "provider" }); assert.equal(pyBuild.test.source, "provider"); - assert.equal(pyBuild.test.discovery, true); + assert.equal("discovery" in pyBuild.test, false); + assert.deepEqual(pyBuild.test.discoveryCommand, { + arguments: ["-I", "-B", "${pluginDir}/scripts/discover_tests.py", "${outputFile}", "${root}", "${optionArguments}"], + executesProjectCode: true, + mayUseNetwork: false, + }); assert.deepEqual(pyBuild.test.filters, ["suite", "case"]); assert.deepEqual(pyBuild.test.arguments, []); assert.deepEqual(pyBuild.test.results, { @@ -1150,7 +1155,7 @@ try { } }); - await check("build_provider.py executes model (with degraded/recovered), pytest --collect-only discovery, pytest JUnit XML test runs, runEntrypoints, and cancellation cleanup", async () => { + await check("The packaged discovery command collects pytest selectors and the provider runs them exactly, reports JUnit, and handles cancellation", async () => { const pytestExecutable = resolvePytestRuntime(); const noPytestExec = ensureNoPytestPython(scratch); @@ -1162,10 +1167,17 @@ try { // Start with an intentionally malformed pyproject.toml to verify degraded -> recovered! writeFileSync(join(wsDir, "pyproject.toml"), "[project\nname = 'broken'\n"); writeFileSync(join(wsDir, "worker.py"), 'if __name__ == "__main__":\n print("run worker")\n'); + writeFileSync(join(wsDir, "conftest.py"), [ + "def pytest_sessionstart(session):", + " if session.config.option.collectonly:", + " session.config.cache.set('lithe/discovery-test', True)", + "", + ].join("\n")); writeFileSync( join(wsDir, "tests", "test_calc.py"), [ "import pytest", + "import worker", "", "@pytest.mark.parametrize('x,expected', [(2, 6), (3, 9)])", "def test_scale(x, expected):", @@ -1177,7 +1189,26 @@ try { ].join("\n") + "\n", ); - const child = spawn(pythonCmd, ["-I", "-B", buildProviderScript, "--cache", cacheDir], { + const discoveryCommand = pluginManifest.buildSystems.find(({ id }) => id === "python").test.discoveryCommand; + assert.ok(discoveryCommand, "The installed plugin must declare a test discovery command"); + function discover(label, { cwd = wsDir, root = ".", executable = pytestExecutable, options = [] } = {}) { + const attemptDir = join(cacheDir, label); + mkdirSync(attemptDir); + const report = join(attemptDir, "tests.json"); + const args = discoveryCommand.arguments.flatMap((value) => value === "${optionArguments}" + ? options + : value.replace("${pluginDir}", unpackedPluginDir).replace("${outputFile}", report).replace("${root}", root)); + const result = spawnSync(executable, args, { + cwd, + encoding: "utf8", + timeout: COMMAND_TIMEOUT_MS, + windowsHide: true, + }); + if (result.error) throw result.error; + return { ...result, report }; + } + + const child = spawn(pythonCmd, ["-I", "-B", buildProviderScript], { cwd: wsDir, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, @@ -1267,63 +1298,52 @@ try { "Expected recovered pyproject_restored log", ); - // 2. lithe/build/discoverTests via pytest --collect-only. - peer.send({ - jsonrpc: "2.0", - id: 4, - method: "lithe/build/discoverTests", - params: { - operationID: "op-discover-1", - buildSystemID: "python", - root: ".", - tool: { executable: pytestExecutable }, - options: {}, - optionArguments: [], - environment: {}, - }, - }); - const discResp = await peer.waitFor((m) => m.id === 4, "discoverTests response"); - assert.equal(discResp.result.format, "litheTestDiscovery"); - assert.equal(discResp.result.version, 0); - assert.equal(existsSync(join(wsDir, ".pytest_cache")), false, "discoverTests must write cache to workspaceStateDir, not workspace"); + // 2. Run the packaged command with the host's output path and project cwd. + const discovered = discover("collected"); + assert.equal(discovered.status, 0, discovered.stdout + discovered.stderr); + const discovery = JSON.parse(readFileSync(discovered.report, "utf8")); + assert.equal(discovery.format, "litheTestDiscovery"); + assert.equal(discovery.version, 0); + assert.equal(existsSync(join(wsDir, ".pytest_cache")), false); + assert.equal(existsSync(join(dirname(discovered.report), "pytest-cache")), true); - const discoveredCases = discResp.result.tests.map((t) => `${t.suite}::${t.case}`).sort(); + const discoveredCases = discovery.tests.map((t) => `${t.suite}::${t.case}`).sort(); assert.deepEqual(discoveredCases, [ "tests/test_calc.py::TestCalc::test_add", "tests/test_calc.py::test_scale[2-6]", "tests/test_calc.py::test_scale[3-9]", ]); - for (const item of discResp.result.tests) { + for (const item of discovery.tests) { assert.deepEqual(item.project, { name: "calc-suite", path: "." }); } - // 3. Missing pytest returns controlled PluginError python.pytestUnavailable + operationFailed ERROR. - peer.send({ - jsonrpc: "2.0", - id: 5, - method: "lithe/build/discoverTests", - params: { - operationID: "op-discover-missing", - buildSystemID: "python", - root: ".", - tool: { executable: noPytestExec }, - options: {}, - optionArguments: [], - environment: {}, - }, + // 3. Empty projects complete, while missing pytest and failed collection publish no report. + const missingPytest = discover("missing-pytest", { executable: noPytestExec }); + assert.equal(missingPytest.status, 197); + assert.match(missingPytest.stderr, /pytest unavailable/); + assert.equal(existsSync(missingPytest.report), false); + + const nested = join(wsDir, "nested project"); + mkdirSync(nested); + const empty = discover("empty", { cwd: nested, root: "nested project" }); + assert.equal(empty.status, 0, empty.stdout + empty.stderr); + assert.deepEqual(JSON.parse(readFileSync(empty.report, "utf8")), { + format: "litheTestDiscovery", version: 0, tests: [], }); - const missingPytest = await peer.waitFor((m) => m.id === 5, "missing pytest error"); - assert.equal(missingPytest.error?.code, -32000); - assert.equal(missingPytest.error?.data?.code, "python.pytestUnavailable"); - assert.ok( - peer.allReceived.some( - (m) => - m.method === "lithe/log" && - m.params?.operationId === "op-discover-missing" && - m.params?.kind === "operationFailed" && - m.params?.code === "python.pytestUnavailable", - ), - ); + writeFileSync(join(nested, "test_nested.py"), "def test_nested():\n assert True\n"); + const nestedDiscovery = discover("nested", { cwd: nested, root: "nested project" }); + assert.equal(nestedDiscovery.status, 0, nestedDiscovery.stdout + nestedDiscovery.stderr); + assert.deepEqual(JSON.parse(readFileSync(nestedDiscovery.report, "utf8")).tests, [{ + suite: "test_nested.py", case: "test_nested", project: { name: "nested project", path: "nested project" }, + }]); + rmSync(nested, { recursive: true }); + + const brokenTest = join(wsDir, "tests", "test_collection_error.py"); + writeFileSync(brokenTest, "def test_broken():\n assert (\n"); + const collectionError = discover("collection-error"); + assert.equal(collectionError.status, 2); + assert.equal(existsSync(collectionError.report), false); + rmSync(brokenTest); // 4. Execute a single discovered parameterized test via lithe/build/test and verify progress + JUnit XML. peer.send({ @@ -1359,11 +1379,15 @@ try { assert.match(junitXml, /test_scale\[2-6\]/); writeFileSync(join(wsDir, "tests", "test_names.py"), [ - "import pytest", "def test_add():", " assert True", "def test_additional():", " assert True", + "", + ].join("\n")); + const oversizedTest = join(wsDir, "tests", "test_long_id.py"); + writeFileSync(oversizedTest, [ + "import pytest", "@pytest.mark.parametrize('value', [pytest.param(1, id='é' * 600)])", "def test_long_id(value):", " assert value == 1", @@ -1382,22 +1406,19 @@ try { assert.equal(caseOnly.error?.data?.code, "python.invalidTestSelector"); assert.equal(readFileSync(junitXmlPath, "utf8"), junitXml); - peer.send({ - jsonrpc: "2.0", id: 69, method: "lithe/build/discoverTests", - params: { - operationID: "op-discover-long-id", - buildSystemID: "python", root: ".", tool: { executable: pytestExecutable }, - options: {}, optionArguments: [], environment: {}, - }, - }); - const withLongId = await peer.waitFor((m) => m.id === 69, "discover with oversized UTF-8 test ID"); + const withLongId = discover("oversized-id"); + assert.notEqual(withLongId.status, 0); + assert.match(withLongId.stderr, /invalid or oversized test selectors/); + assert.equal(existsSync(withLongId.report), false, "An oversized UTF-8 ID must fail the whole discovery"); + rmSync(oversizedTest); + const withDoctest = discover("doctest", { options: ["--doctest-glob=test_notes.txt"] }); + assert.equal(withDoctest.status, 0, withDoctest.stdout + withDoctest.stderr); + const tests = JSON.parse(readFileSync(withDoctest.report, "utf8")).tests; assert.deepEqual( - withLongId.result.tests.filter(({ suite }) => suite === "tests/test_names.py").map(({ case: name }) => name).sort(), + tests.filter(({ suite }) => suite === "tests/test_names.py").map(({ case: name }) => name).sort(), ["test_add", "test_additional"], ); - assert.ok(peer.allReceived.some((m) => m.method === "lithe/log" - && m.params?.operationId === "op-discover-long-id" && m.params?.code === "test_discovery_truncated")); - const doctest = withLongId.result.tests.find(({ suite }) => suite === "test_notes.txt"); + const doctest = tests.find(({ suite }) => suite === "test_notes.txt"); assert.ok(doctest, "pytest must discover a root-level doctest"); peer.send({ jsonrpc: "2.0", id: 70, method: "lithe/build/test", @@ -1538,7 +1559,7 @@ try { ); // 6. $/cancelRequest terminates active pytest subprocess tree cleanly with zero orphan processes! - const pidFile = join(scratch, "slow-collect.pid"); + const pidFile = join(scratch, "slow-test.pid"); writeFileSync( join(wsDir, "tests", "test_blocking.py"), [ @@ -1553,12 +1574,13 @@ try { peer.send({ jsonrpc: "2.0", id: 8, - method: "lithe/build/discoverTests", + method: "lithe/build/test", params: { - operationID: "op-discover-cancel", + operationID: "op-test-cancel", buildSystemID: "python", root: ".", tool: { executable: pytestExecutable }, + suite: "tests/test_blocking.py", options: {}, optionArguments: [], environment: {}, @@ -1574,10 +1596,10 @@ try { assert.ok(Number.isInteger(childPid) && childPid > 0); peer.send({ jsonrpc: "2.0", method: "$/cancelRequest", params: { id: 8 } }); - const cancelResp = await peer.waitFor((m) => m.id === 8, "cancelled discoverTests response", 10_000); + const cancelResp = await peer.waitFor((m) => m.id === 8, "cancelled test response", 10_000); assert.equal(cancelResp.error?.code, -32800); assert.equal( - peer.allReceived.some((m) => m.method === "lithe/log" && m.params?.operationId === "op-discover-cancel"), + peer.allReceived.some((m) => m.method === "lithe/log" && m.params?.operationId === "op-test-cancel"), false, "Cancelled requests must NOT emit operationFinished or operationFailed logs", );