fix: make the test suite pass on Windows (#4260)

Refuse a read-only destination in _atomic_replace on Windows (nt-only guard;
os.replace there raises PermissionError and the fallback would silently clobber
it), plus test-only guards: utf-8 encoding kwargs, posix-shape path assertions,
FIFO/AF_UNIX/symlink skips, and a replace-retry for AV/indexer locks. No POSIX
behavior change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
SoloDrex52andClaude Opus 4.8 authored and safishamsi committed 2026-10-09 19:18:06 +01:00
1 parent 68e0e9bbac
commit f949947003
17 files changed
+133 -18

No files matched your search

+7
View File
@@ -16,6 +16,7 @@ flow) and every reader honours it.
from __future__ import annotations
import errno
import functools
import json
import os
@@ -136,6 +137,12 @@ def _atomic_replace(path: "str | Path", write_fn) -> None:
os.chmod(tmp, mode)
except OSError:
pass
# On Windows os.replace refuses a read-only destination and the fallback
# would rename it aside and clobber it. Refuse here instead, for this
# generic write path only: install/cache callers of the fallback must
# still be able to replace their own (possibly read-only) copies.
if os.name == "nt" and real.is_file() and not os.access(real, os.W_OK):
raise PermissionError(errno.EACCES, "destination is read-only", str(real))
os_replace_with_fallback(tmp, str(real))
except BaseException:
try:
+19 -1
View File
@@ -10,7 +10,7 @@ import sys
import pytest
from graphify.paths import write_text_atomic
from graphify.paths import os_replace_with_fallback, write_text_atomic
def test_write_text_atomic_writes_and_leaves_no_tmp(tmp_path):
@@ -350,3 +350,21 @@ def test_write_text_atomic_succeeds_near_windows_max_path(tmp_path):
write_text_atomic(target, "content-at-max-path")
assert target.read_text(encoding="utf-8") == "content-at-max-path"
assert not any(p.name.endswith(".tmp") for p in tmp_path.iterdir())
def test_os_replace_with_fallback_still_replaces_a_readonly_destination(tmp_path):
"""Install/cache callers replace their own copies, which can be read-only
(e.g. a skill copied from a read-only package): only the generic atomic write
path refuses a read-only destination, never this shared helper."""
import stat as _stat
dst = tmp_path / "SKILL.md"
dst.write_text("old", encoding="utf-8")
os.chmod(dst, _stat.S_IREAD)
src = tmp_path / "SKILL.md.tmp"
src.write_text("new", encoding="utf-8")
try:
os_replace_with_fallback(src, dst)
assert dst.read_text(encoding="utf-8") == "new"
finally:
os.chmod(dst, _stat.S_IWRITE)
+17 -3
View File
@@ -8,6 +8,7 @@ import json
import os
import subprocess
import sys
import time
from pathlib import Path
import pytest
@@ -16,6 +17,19 @@ PYTHON = sys.executable
FIXTURES = Path(__file__).parent / "fixtures"
def _rename(src: Path, dst: Path) -> None:
"""Rename a directory, retrying briefly: on Windows a virus scanner or indexer
can hold a just-written file open and fail the rename with PermissionError."""
for attempt in range(20):
try:
src.rename(dst)
return
except PermissionError:
if attempt == 19:
raise
time.sleep(0.25)
def _run(args: list[str], cwd: Path, env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
return subprocess.run(
[PYTHON, "-m", "graphify"] + args,
@@ -224,7 +238,7 @@ def test_query_missing_graph_fails(tmp_path):
def test_query_uses_graphify_out_env(tmp_path):
out = _make_graph(tmp_path)
custom_out = tmp_path / "custom-graph"
out.rename(custom_out)
_rename(out, custom_out)
env = os.environ.copy()
env["GRAPHIFY_OUT"] = custom_out.name
@@ -271,7 +285,7 @@ def test_path_missing_graph_fails(tmp_path):
def test_path_uses_graphify_out_env(tmp_path):
out = _make_graph(tmp_path)
custom_out = tmp_path / "custom-graph"
out.rename(custom_out)
_rename(out, custom_out)
env = os.environ.copy()
env["GRAPHIFY_OUT"] = custom_out.name
@@ -405,7 +419,7 @@ def test_explain_missing_graph_fails(tmp_path):
def test_explain_uses_graphify_out_env(tmp_path):
out = _make_graph(tmp_path)
custom_out = tmp_path / "custom-graph"
out.rename(custom_out)
_rename(out, custom_out)
env = os.environ.copy()
env["GRAPHIFY_OUT"] = custom_out.name
+3 -2
View File
@@ -1661,7 +1661,8 @@ def test_c_include_out_of_root_target_id_is_deterministic_across_checkout_paths(
return [e["target"] for e in result["edges"] if e["relation"] == "imports"][0]
target_a = _build("checkout_alice")
target_b = _build("checkout_bob_at_a_totally_different_nesting_depth")
# Short enough to keep the cache path under Windows' 260-char MAX_PATH.
target_b = _build("checkout_bob_other_depth")
assert target_a == target_b == "ext_lib_foo_h"
@@ -5670,7 +5671,7 @@ def test_python_external_calls_survive_real_incremental_context(tmp_path):
(tmp_path / "helper.py").write_text("def other():\n return 1\n")
(tmp_path / "local_caller.py").write_text("import helper\n\ndef fetch_local():\n return helper.get()\n")
env = {k: v for k, v in os.environ.items()
if k in {"PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "PYTHONDONTWRITEBYTECODE"}}
if k in {"PATH", "HOME", "USERPROFILE", "SYSTEMROOT", "TMPDIR", "LANG", "LC_ALL", "PYTHONDONTWRITEBYTECODE"}}
env["PYTHONPATH"] = str(Path(__file__).resolve().parents[1])
def run():
+6 -3
View File
@@ -769,8 +769,10 @@ def test_uv_tool_env_rescues_hook_when_pin_and_launcher_fail(tmp_path):
mine = _tool_venv(home, "graphifyy", "bin/python", ok=True)
res = _detect_run(tmp_path, home, stub_bin)
assert res.returncode == 0, res.stderr
assert f"RESOLVED={mine}" in res.stdout, res.stdout + res.stderr
assert f"RESOLVED={other}" not in res.stdout
# sh may print an MSYS-style path on Windows, so compare the home-relative tail
resolved = [ln for ln in res.stdout.splitlines() if ln.startswith("RESOLVED=")]
assert [ln.endswith(mine.relative_to(home).as_posix()) for ln in resolved] == [True], res.stdout + res.stderr
assert other.relative_to(home).as_posix() not in res.stdout
assert "could not locate" not in res.stderr
@@ -823,7 +825,8 @@ def test_shebang_parse_requires_leading_hash_bang(tmp_path):
launcher.chmod(0o755)
res = _detect_run(tmp_path, home, stub_bin)
assert res.returncode == 0, res.stderr
assert f"RESOLVED={mine}" in res.stdout, res.stdout + res.stderr
resolved = [ln for ln in res.stdout.splitlines() if ln.startswith("RESOLVED=")]
assert [ln.endswith(mine.relative_to(home).as_posix()) for ln in resolved] == [True], res.stdout + res.stderr
assert "fakepy" not in res.stdout
@@ -44,6 +44,13 @@ def test_same_size_rewrite_in_one_tick_is_requeued(corpus):
src, manifest = corpus
det.save_manifest(det.detect(src)["files"], manifest, root=src, kind="semantic")
# The gate only distrusts an mtime stamped within a tick of the row's `seen`.
# How long save_manifest took is machine-dependent, so stamp the same tick
# explicitly instead of relying on a fast disk.
rows = json.loads(Path(manifest).read_text(encoding="utf-8"))
for row in rows.values():
row["seen"] = row["mtime"]
Path(manifest).write_text(json.dumps(rows), encoding="utf-8")
target = src / "f1.md"
stat_before = target.stat()
+2 -2
View File
@@ -515,7 +515,7 @@ def test_codex_skill_uses_graphify_with_existing_graph():
fast-path block, which jumps straight to the query flow when a graph exists.
"""
import graphify
skill = (Path(graphify.__file__).parent / "skill-codex.md").read_text()
skill = (Path(graphify.__file__).parent / "skill-codex.md").read_text(encoding="utf-8")
assert "Fast path — existing graph" in skill
assert "skip Steps 1–5 entirely and jump straight to `## For /graphify query`" in skill
assert "graphify query" in skill
@@ -1435,7 +1435,7 @@ def test_hermes_skill_destination_posix_uses_home():
from graphify.__main__ import _platform_skill_destination
with patch("graphify.__main__.platform.system", return_value="Linux"):
dst = _platform_skill_destination("hermes", project=False)
assert str(dst).endswith(".hermes/skills/graphify/SKILL.md"), dst
assert dst.as_posix().endswith(".hermes/skills/graphify/SKILL.md"), dst
def _cli_dispatched_commands() -> set[str]:
+10
View File
@@ -546,3 +546,13 @@ def test_install_from_read_only_package_dir(tmp_path, fake_bundle):
# The installed sidecar must stay writable, or the next install cannot
# rmtree it to swap in a new one.
assert os.access(refs, os.W_OK)
import pytest as _pytest_posix
@_pytest_posix.fixture(autouse=True)
def _posix_skill_layout(monkeypatch):
"""gemini and hermes install to different directories on Windows; these tests
assert the POSIX layout, so pin it."""
monkeypatch.setattr("platform.system", lambda: "Linux")
+2
View File
@@ -57,6 +57,8 @@ def test_skill_roundtrip_at_real_destination(platform, project, tmp_path, monkey
home.mkdir()
project_dir.mkdir()
monkeypatch.chdir(project_dir)
# hermes user scope lands under %LOCALAPPDATA% on Windows; keep it inside tmp
monkeypatch.setenv("LOCALAPPDATA", str(home / "AppData" / "Local"))
with patch("graphify.__main__.Path.home", return_value=home):
dst = mainmod._platform_skill_destination(
+2 -2
View File
@@ -3621,9 +3621,9 @@ def test_markdown_wikilink_fallback_unicode_normalization(tmp_path):
vault = tmp_path / "vault"
(vault / "log").mkdir(parents=True)
name_nfc = unicodedata.normalize("NFC", "어휘 노트")
(vault / f"{name_nfc}.md").write_text("# Term\n")
(vault / f"{name_nfc}.md").write_text("# Term\n", encoding="utf-8")
name_nfd = unicodedata.normalize("NFD", name_nfc)
(vault / "log" / "entry.md").write_text(f"See [[{name_nfd}]].\n")
(vault / "log" / "entry.md").write_text(f"See [[{name_nfd}]].\n", encoding="utf-8")
_, refs, page_id = _vault_extract(
vault, [vault / f"{name_nfc}.md", vault / "log" / "entry.md"])
entry_id = page_id(vault / "log" / "entry.md")
+1 -1
View File
@@ -114,7 +114,7 @@ def test_merge_chunks_accepts_unicode_id(tmp_path, monkeypatch):
"edges": [], "hyperedges": []})
out = tmp_path / "merged.json"
_run_merge(monkeypatch, ["graphify", "merge-chunks", str(c), "--out", str(out)])
merged = json.loads(out.read_text())
merged = json.loads(out.read_text(encoding="utf-8"))
assert {n["id"] for n in merged["nodes"]} == {"mod_处理数据"}
+16 -3
View File
@@ -34,6 +34,17 @@ def test_regular_source_file_is_accepted(tree):
assert _is_regular_file(tree / "src" / "module.py") is True
needs_fifo = pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="no named pipes on this platform")
def _symlink(link, target):
try:
link.symlink_to(target)
except OSError as exc: # Windows without Developer Mode / admin
pytest.skip(f"cannot create symlinks here: {exc}")
@needs_fifo
def test_fifo_is_rejected(tree):
"""The shape that hangs the whole run."""
fifo = tree / "src" / "pipe.py"
@@ -42,6 +53,7 @@ def test_fifo_is_rejected(tree):
assert _is_regular_file(fifo) is False
@pytest.mark.skipif(not hasattr(socket, "AF_UNIX"), reason="no unix sockets on this platform")
def test_unix_socket_is_rejected(tree):
sock_path = tree / "src" / "sock.py"
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
@@ -61,22 +73,23 @@ def test_directory_named_like_a_source_file_is_rejected(tree):
def test_symlink_to_a_regular_file_is_accepted(tree):
target = tree / "src" / "module.py"
link = tree / "src" / "alias.py"
link.symlink_to(target)
_symlink(link, target)
assert _is_regular_file(link) is True
@needs_fifo
def test_symlink_pointing_at_a_fifo_is_rejected(tree):
"""A link to a FIFO blocks exactly like the FIFO, so stat must follow it."""
fifo = tree / "src" / "real.py"
os.mkfifo(fifo)
link = tree / "src" / "link.py"
link.symlink_to(fifo)
_symlink(link, fifo)
assert _is_regular_file(link) is False
def test_broken_symlink_is_rejected_without_raising(tree):
link = tree / "src" / "dangling.py"
link.symlink_to(tree / "src" / "does-not-exist.py")
_symlink(link, tree / "src" / "does-not-exist.py")
assert _is_regular_file(link) is False
+10
View File
@@ -525,3 +525,13 @@ def test_install_and_hook_commands_skip_the_refresh(monkeypatch, cmd):
except (_Stop, SystemExit):
pass
assert calls == []
import pytest as _pytest_posix
@_pytest_posix.fixture(autouse=True)
def _posix_skill_layout(monkeypatch):
"""gemini and hermes install to different directories on Windows; these tests
assert the POSIX layout, so pin it."""
monkeypatch.setattr("platform.system", lambda: "Linux")
@@ -84,6 +84,23 @@ def _run_step1(script: str, input_path_value: str, cwd: Path) -> subprocess.Comp
)
def _skip_unless_bash_python_has_graphify() -> None:
"""On Windows, Step 1 only works when `bash` has a POSIX `python3` that can import
graphify (e.g. WSL). Git Bash + a Windows Python gets the Store `python3` stub
and `/mnt/c/...` paths it cannot open, so there is nothing meaningful to assert."""
if sys.platform != "win32":
return
try:
probe = subprocess.run(
["bash", "-c", "python3 -c 'import graphify'"],
capture_output=True, text=True, timeout=60,
)
except (OSError, subprocess.TimeoutExpired):
pytest.skip("bash is not available")
if probe.returncode != 0:
pytest.skip("bash has no python3 that can import graphify (WSL needed on Windows)")
# --- #3844: Monolith --watch contract tests ----------------------------------
@@ -180,6 +197,7 @@ def test_step1_does_not_execute_a_semicolon_separated_command_in_input_path(tmp_
@pytest.mark.parametrize("skill_file", ALL_TESTED_SKILL_FILES)
def test_step1_still_resolves_a_legitimate_path(tmp_path: Path, skill_file: str):
"""The fix must not break ordinary paths, including paths with spaces."""
_skip_unless_bash_python_has_graphify()
script = _extract_step1_bash_block(skill_file)
project = tmp_path / "my project with spaces"
project.mkdir()
+1 -1
View File
@@ -75,7 +75,7 @@ def test_same_named_directories_and_cross_file_references_stay_separate(tmp_path
variables = [n for n in result["nodes"] if n["label"] == "var.name"]
assert len({n["id"] for n in variables}) == 4
for variable in variables:
source = str(Path(variable["source_file"]).parent / "use.tf")
source = (Path(variable["source_file"]).parent / "use.tf").as_posix()
output = _node(result, "output.name", source)
assert any(e["source"] == output["id"] and e["target"] == variable["id"]
for e in result["edges"])
+10
View File
@@ -111,3 +111,13 @@ def test_project_uninstall_codebuddy_spares_global(tmp_path):
assert (global_tree / ".graphify_version").exists()
assert not (project_tree / "SKILL.md").exists()
assert not project_tree.exists()
import pytest as _pytest_posix
@_pytest_posix.fixture(autouse=True)
def _posix_skill_layout(monkeypatch):
"""gemini and hermes install to different directories on Windows; these tests
assert the POSIX layout, so pin it."""
monkeypatch.setattr("platform.system", lambda: "Linux")
+2
View File
@@ -807,6 +807,7 @@ def test_graphify_root_preserves_absolute_when_user_supplied(tmp_path):
)
@pytest.mark.skipif(sys.platform == "win32", reason="Windows cannot delete the current working directory")
def test_rebuild_code_deleted_cwd_without_repo_root_returns_false(tmp_path, monkeypatch, capsys):
"""Detached hooks can inherit a CWD that no longer exists.
@@ -831,6 +832,7 @@ def test_rebuild_code_deleted_cwd_without_repo_root_returns_false(tmp_path, monk
assert "current working directory no longer exists" in out
@pytest.mark.skipif(sys.platform == "win32", reason="Windows cannot delete the current working directory")
def test_rebuild_code_deleted_cwd_uses_graphify_repo_root(tmp_path, monkeypatch):
"""GRAPHIFY_REPO_ROOT lets detached hook rebuilds recover from a deleted CWD."""
from graphify.watch import _rebuild_code