Skip to content

fix: 修复验证test的 Windows 兼容性问题#8562

Open
lingyun14beta wants to merge 12 commits into
AstrBotDevs:masterfrom
lingyun14beta:test-windows
Open

fix: 修复验证test的 Windows 兼容性问题#8562
lingyun14beta wants to merge 12 commits into
AstrBotDevs:masterfrom
lingyun14beta:test-windows

Conversation

@lingyun14beta
Copy link
Copy Markdown
Contributor

@lingyun14beta lingyun14beta commented Jun 3, 2026

修复 AstrBot 在 Windows 上运行 uv run pytest tests/ 时出现的测试失败,均为 Windows 兼容性问题。

Modifications / 改动点

源码

  • computer_client.pystr(remote_zip) 改为 remote_zip.as_posix()
  • openai_source.py_file_uri_to_path 两处 str(Path(...)) 改为 .as_posix(),修复 file URI 解析错误
  • whisper_api_source.pyopen() 改为 with open(),修复 Windows 文件锁导致临时文件无法删除
  • skill_manager.pyos.path.normpath 改为 path.replace(chr(92), "/"),修复 type 命令路径格式错误
  • utils/__init__.py — 新建空文件,修复 Windows 上子模块无法导入

测试

  • 文件读取/子进程输出断言加 .replace("\r\n", "\n")
  • localhost URI 构造补前导 /,修复 file://localhostC:/... 格式错误
  • 两处测试加 monkeypatch.setattr("sys.platform", "linux"),确保 marker 过滤行为一致
  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

d5f4bb91cfef730c11079e61d3ee9a91 这些warning都是我插件依赖的缺失,实际上全过)

Checklist / 检查清单

  • 😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
    / 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。

  • 👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
    / 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”

  • 🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
    / 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到 requirements.txtpyproject.toml 文件相应位置。

  • 😮 My changes do not introduce malicious code.
    / 我的更改没有引入恶意代码。

Summary by Sourcery

Improve Windows compatibility for file handling and testing across core components and test suite.

Bug Fixes:

  • Normalize file URI and path handling to use POSIX-style paths, preventing incorrect resolution on Windows.
  • Fix Windows file locking issues when using temporary files by ensuring files are opened with context managers.
  • Correct Windows command path formatting for skill reading to avoid malformed paths passed to the shell.
  • Ensure sandbox skill bundle upload uses a POSIX-style remote path for better cross-platform compatibility.

Tests:

  • Relax test assertions to be agnostic to Windows CRLF line endings when checking file reads and subprocess output.
  • Adjust localhost file URI construction in tests to produce valid paths on Windows and Unix-like systems.
  • Stabilize marker-related requirements tests by forcing a consistent sys.platform value during test execution.

@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. area:core The bug / feature is about astrbot's core, backend labels Jun 3, 2026
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request focuses on improving cross-platform compatibility, particularly for Windows environments, by normalizing file paths to POSIX format (using forward slashes) and handling Windows line endings (\r\n) in test assertions. It also mocks the platform in pip-related tests. Feedback is provided regarding the use of chr(92) in skill_manager.py, suggesting the use of a standard escaped backslash string literal "\\" instead to improve readability.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread astrbot/core/skills/skill_manager.py
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 4 issues, and left some high level feedback:

  • In _build_skill_read_command_example, consider using Path(path).as_posix() (or path.replace("\\", "/") without chr(92)) instead of a magic chr(92) literal to improve readability and reduce the chance of subtle escaping bugs.
  • The repeated .replace("\r\n", "\n") normalization in multiple tests could be factored into a small helper function (e.g., normalize_newlines(text)) to make the intent clearer and avoid duplication.
  • For the tests that depend on a particular platform, using monkeypatch.setattr(sys, "platform", "linux") (with a direct module reference) instead of the string form may be slightly clearer and avoids issues if the import path changes.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `_build_skill_read_command_example`, consider using `Path(path).as_posix()` (or `path.replace("\\", "/")` without `chr(92)`) instead of a magic `chr(92)` literal to improve readability and reduce the chance of subtle escaping bugs.
- The repeated `.replace("\r\n", "\n")` normalization in multiple tests could be factored into a small helper function (e.g., `normalize_newlines(text)`) to make the intent clearer and avoid duplication.
- For the tests that depend on a particular platform, using `monkeypatch.setattr(sys, "platform", "linux")` (with a direct module reference) instead of the string form may be slightly clearer and avoids issues if the import path changes.

## Individual Comments

### Comment 1
<location path="astrbot/core/skills/skill_manager.py" line_range="199" />
<code_context>
     if _is_windows_prompt_path(path):
         command = "type"
-        path_arg = f'"{os.path.normpath(path)}"'
+        path_arg = f'"{path.replace(chr(92), "/")}"'
     else:
         command = "cat"
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Consider preserving Windows path normalization while converting separators.

The previous use of `os.path.normpath(path)` also cleaned up redundant separators and `..` segments. The new version only swaps backslashes for `/`, so we lose that normalization. To keep normalized paths while still avoiding backslashes in the rendered command, consider `PureWindowsPath(path).as_posix()` or `os.path.normpath(path).replace("\\", "/")`.
</issue_to_address>

### Comment 2
<location path="astrbot/core/provider/sources/openai_source.py" line_range="273-278" />
<code_context>
         path = unquote(parsed.path or "")
         if re.fullmatch(r"[A-Za-z]:", netloc):
-            return str(Path(f"{netloc}{path}"))
+            return Path(f"{netloc}{path}").as_posix()
         if re.match(r"^/[A-Za-z]:/", path):
             path = path[1:]
         if netloc and netloc != "localhost":
             path = f"//{netloc}{path}"
-        return str(Path(path))
+        return Path(path).as_posix()

     async def _image_ref_to_data_url(
</code_context>
<issue_to_address>
**question (bug_risk):** Clarify intent of always returning POSIX-style paths from `_file_uri_to_path`.

Using `.as_posix()` changes this function to always return forward-slash paths, even on Windows. That’s fine for most Python file operations, but could break callers that expect OS-native paths (e.g., for Windows UIs or external tools that require `\`). If this normalization is intentional, consider making that explicit at call sites or in variable names so it’s clear these are logical/normalized paths rather than native OS paths.
</issue_to_address>

### Comment 3
<location path="tests/test_openai_source.py" line_range="1066-1069" />
<code_context>
         PILImage.new("RGBA", (1, 1), (255, 0, 0, 255)).save(image_path)

-        localhost_uri = f"file://localhost{image_path.as_posix()}"
+        posix_path = image_path.as_posix()
+        if not posix_path.startswith("/"):
+            posix_path = "/" + posix_path
+        localhost_uri = f"file://localhost{posix_path}"
         payloads, _ = await provider._prepare_chat_payload(
             prompt=None,
</code_context>
<issue_to_address>
**suggestion (testing):** Add explicit test coverage for Windows-style paths where `as_posix()` lacks a leading slash

This branch is intended for Windows-style paths where `image_path.as_posix()` yields `C:/path/to/file` (no leading slash), but this test may not hit that case on the current platform. To properly exercise it, parameterize (or add) a test that builds `posix_path` explicitly in both forms (with and without a leading `/`) and asserts the resulting `localhost_uri`. You can use a fake path or a monkeypatched `Path`-like object to deterministically check `file://localhost/C:/...` vs `file://localhost/...` formats.
</issue_to_address>

### Comment 4
<location path="tests/test_pip_helper_modules.py" line_range="445-446" />
<code_context>


-def test_iter_requirements_supports_direct_line_input():
+def test_iter_requirements_supports_direct_line_input(monkeypatch):
+    monkeypatch.setattr("sys.platform", "linux")
     parsed = list(
         requirements_utils.iter_requirements(
</code_context>
<issue_to_address>
**suggestion (testing):** Clarify platform-dependent expectations and consider adding a complementary Windows-case test

Since `sys.platform` is forced to `"linux"` here for determinism, please also add a test that sets `sys.platform` to `"win32"` and asserts the expected inclusion/exclusion of the Windows-only requirement. This will exercise both branches of the marker logic independent of the CI OS.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread astrbot/core/skills/skill_manager.py
Comment thread astrbot/core/provider/sources/openai_source.py
Comment thread tests/test_openai_source.py
Comment on lines +445 to +446
def test_iter_requirements_supports_direct_line_input(monkeypatch):
monkeypatch.setattr("sys.platform", "linux")
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Clarify platform-dependent expectations and consider adding a complementary Windows-case test

Since sys.platform is forced to "linux" here for determinism, please also add a test that sets sys.platform to "win32" and asserts the expected inclusion/exclusion of the Windows-only requirement. This will exercise both branches of the marker logic independent of the CI OS.

lingyun14beta and others added 2 commits June 3, 2026 23:23
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core The bug / feature is about astrbot's core, backend size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant