Files
flow/tests/test_domain_dotfiles_resolution.py
Tomas Mirchev 6b7a48bb20 refactor: post-review hardening pass
Independent re-audit surfaced 11 follow-ups across two layers of review
(my fresh-eyes read + a parallel agent pass). Bundled into a single
commit because changes are small and intertwined.

Symlink / state consistency:
- FileSystem.same_symlink now uses raw readlink() instead of resolve().
  Aligns the three sites that ask "is this our link?" (_load_state,
  _check_overwrite_safe, remove_symlink) on a single rule: exact-readlink
  match. Following symlink chains would let externally-modified links
  pass as ours and be silently overwritten.
- LinkedState.from_dict raises ConfigError on missing required fields
  instead of .get(..., False) silent defaults. Matches InstalledState.
- LinkOp.source is now consistently None for remove_link ops; the
  service derives expected_source from current.links. Removes the
  asymmetry between in-state and orphan-broken removal ops.
- _apply_plan: rename shadowing local from link_target to spec.

Fail loud:
- _xdg() now treats XDG_CONFIG_HOME="" the same as unset. Previously
  an empty env var produced Path("") and state files were written to
  $PWD instead of ~/.local/state/flow.
- _resolve_target raises PlanConflict when a package contains a bare
  _root entry (no path components) instead of silently dropping it.
- _strip_prefix raises FlowError when a declared install path does not
  start with its section's expected prefix (e.g. etc/foo under install.bin).

Speculative abstraction removed (CLAUDE.md):
- core.template.substitute (the $VAR form) had no production callers --
  deleted along with its tests; only the {{var}} form remains.
- SetupModule base class -- five subclasses, no shared behaviour, no
  polymorphic call site. Deleted.
- Profile.arch -- parsed but never read. Deleted.
- PackagePlan.pm_command -- set but never read. Deleted (service
  recomputes pm_install_command at the call site).
- FileSystem.ensure_dir(mode=...), .copy_file(sudo=...), .read_text(
  default=...) -- no callers. Deleted along with their test.
- bootstrap _execute_action: the upfront `phase not in VALID_PHASES`
  check duplicated the trailing exhaustive raise. Kept the trailing
  raise as the single source of truth; phase set still documented in
  VALID_PHASES.

Completion ctx threading:
- Removed _config()/_manifest() helpers that re-loaded from disk on
  every completion call. _list_targets, _list_namespaces, _list_platforms,
  _list_bootstrap_profiles, _list_manifest_packages now take ctx and
  read from ctx.config / ctx.manifest.

Test coverage and e2e:
- e2e container test exercises a real `flow dotfiles link` (no dry-run)
  and asserts the resulting symlinks point into the dotfiles dir;
  reruns to verify idempotency.
- New tests: LinkedState corrupt-state ConfigError, LinkedState bad-version
  ConfigError, bare-_root PlanConflict, service-level _root path routing
  + skip semantics.
- 11 stale test imports removed (pyflakes clean across src/ + tests/).

357 unit tests + 1 e2e (gated) all pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 00:23:06 +03:00

154 lines
6.0 KiB
Python

"""Tests for dotfiles path resolution."""
from pathlib import Path
import pytest
from flow.core.errors import PlanConflict
from flow.domain.dotfiles.models import ModuleRef, Package
from flow.domain.dotfiles.resolution import resolve_all_targets, resolve_package_targets
RESERVED_ROOT = "_root"
HOME = Path("/home/testuser")
def _pkg(name, layer="_shared", files=(), module=None):
return Package(
name=name,
layer=layer,
package_id=f"{layer}/{name}",
source_dir=Path(f"/dots/{layer}/{name}"),
module=module,
local_files=tuple(files),
)
class TestResolvePackageTargets:
def test_simple_file(self):
pkg = _pkg("zsh", files=[
(Path("/dots/_shared/zsh/.zshrc"), Path(".zshrc")),
])
targets = resolve_package_targets(pkg, HOME, set())
assert len(targets) == 1
assert targets[0].target == HOME / ".zshrc"
assert targets[0].source == Path("/dots/_shared/zsh/.zshrc")
assert targets[0].from_module is False
def test_nested_config(self):
pkg = _pkg("git", files=[
(Path("/dots/_shared/git/.config/git/config"), Path(".config/git/config")),
])
targets = resolve_package_targets(pkg, HOME, set())
assert targets[0].target == HOME / ".config" / "git" / "config"
def test_root_marker(self):
pkg = _pkg("dns", files=[
(Path("/dots/_shared/dns/_root/etc/hosts"), Path("_root/etc/hosts")),
])
targets = resolve_package_targets(pkg, HOME, set())
assert targets[0].target == Path("/etc/hosts")
assert targets[0].needs_sudo is True
def test_root_marker_skipped_when_in_skip_set(self):
pkg = _pkg("dns", files=[
(Path("/dots/_shared/dns/_root/etc/hosts"), Path("_root/etc/hosts")),
])
targets = resolve_package_targets(pkg, HOME, {"_root"})
assert len(targets) == 0
def test_bare_root_marker_raises(self):
"""A package containing a file literally named `_root` (no children)
should be rejected, not silently dropped."""
pkg = _pkg("bad", files=[
(Path("/dots/_shared/bad/_root"), Path("_root")),
])
with pytest.raises(PlanConflict, match="_root"):
resolve_package_targets(pkg, HOME, set())
def test_skip_package_by_name(self):
pkg = _pkg("nvim", files=[
(Path("/dots/_shared/nvim/.config/nvim/init.lua"), Path(".config/nvim/init.lua")),
])
targets = resolve_package_targets(pkg, HOME, {"nvim"})
assert len(targets) == 0
def test_module_files_linked_under_mount_path(self):
module = ModuleRef(
source="https://github.com/org/nvim-config.git",
ref_type="branch",
ref_value="main",
mount_path=Path(".config/nvim"),
cache_dir=Path("/modules/_shared--nvim"),
module_files=(
(Path("/modules/_shared--nvim/init.lua"), Path("init.lua")),
(Path("/modules/_shared--nvim/lua/plugins.lua"), Path("lua/plugins.lua")),
),
)
pkg = _pkg("nvim", files=[
(Path("/dots/_shared/nvim/.local/bin/nvim-wrapper"), Path(".local/bin/nvim-wrapper")),
], module=module)
targets = resolve_package_targets(pkg, HOME, set())
# Local file outside mount_path
local_targets = [t for t in targets if not t.from_module]
assert len(local_targets) == 1
assert local_targets[0].target == HOME / ".local" / "bin" / "nvim-wrapper"
# Module files under mount_path
module_targets = [t for t in targets if t.from_module]
assert len(module_targets) == 2
module_target_paths = {t.target for t in module_targets}
assert HOME / ".config" / "nvim" / "init.lua" in module_target_paths
assert HOME / ".config" / "nvim" / "lua" / "plugins.lua" in module_target_paths
def test_module_yaml_file_not_linked(self):
"""The _module.yaml marker itself should never be linked."""
pkg = _pkg("nvim", files=[
(Path("/dots/_shared/nvim/.config/nvim/_module.yaml"), Path(".config/nvim/_module.yaml")),
], module=ModuleRef(
source="x", ref_type="branch", ref_value="main",
mount_path=Path(".config/nvim"),
cache_dir=Path("/m"), module_files=(),
))
targets = resolve_package_targets(pkg, HOME, set())
assert not any(t.target.name == "_module.yaml" for t in targets)
def test_root_level_module_skips_all_local_files(self):
"""When mount_path is '.', all local files are from the module, not dotfiles repo."""
module = ModuleRef(
source="x", ref_type="branch", ref_value="main",
mount_path=Path("."),
cache_dir=Path("/m"),
module_files=(
(Path("/m/init.lua"), Path("init.lua")),
),
)
pkg = _pkg("nvim", files=[
(Path("/dots/_shared/nvim/_module.yaml"), Path("_module.yaml")),
(Path("/dots/_shared/nvim/stale-file.txt"), Path("stale-file.txt")),
], module=module)
targets = resolve_package_targets(pkg, HOME, set())
# Only module files should appear, local files skipped
assert len(targets) == 1
assert targets[0].from_module is True
assert targets[0].target == HOME / "init.lua"
class TestResolveAllTargets:
def test_no_conflicts(self):
pkgs = [
_pkg("zsh", files=[(Path("/a/.zshrc"), Path(".zshrc"))]),
_pkg("git", files=[(Path("/a/.gitconfig"), Path(".gitconfig"))]),
]
targets = resolve_all_targets(pkgs, HOME, set())
assert len(targets) == 2
def test_duplicate_target_raises(self):
pkgs = [
_pkg("zsh", layer="_shared", files=[(Path("/a/.zshrc"), Path(".zshrc"))]),
_pkg("zsh", layer="work", files=[(Path("/b/.zshrc"), Path(".zshrc"))]),
]
with pytest.raises(PlanConflict):
resolve_all_targets(pkgs, HOME, set())