"""Tests for the m2pack binary discovery helper.""" from __future__ import annotations import os import stat from pathlib import Path import pytest from metin_release.errors import ValidationError from metin_release.m2pack_binary import ENV_VAR, resolve_m2pack_binary def _make_stub(tmp_path: Path, name: str = "m2pack") -> Path: stub = tmp_path / name stub.write_text("#!/bin/sh\necho '{}'\n") stub.chmod(stub.stat().st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH) return stub def test_env_var_override_wins(tmp_path: Path, monkeypatch): stub = _make_stub(tmp_path) # Scrub PATH so shutil.which can't resolve m2pack monkeypatch.setenv("PATH", "/nonexistent") monkeypatch.setenv(ENV_VAR, str(stub)) resolved = resolve_m2pack_binary() assert resolved == stub.resolve() def test_env_var_empty_falls_through_to_path(tmp_path: Path, monkeypatch): stub = _make_stub(tmp_path) monkeypatch.setenv(ENV_VAR, " ") # blank-ish monkeypatch.setenv("PATH", str(tmp_path)) resolved = resolve_m2pack_binary() assert resolved == stub.resolve() def test_env_var_pointing_nowhere_raises(tmp_path: Path, monkeypatch): monkeypatch.setenv(ENV_VAR, str(tmp_path / "does-not-exist")) monkeypatch.setenv("PATH", "/nonexistent") with pytest.raises(ValidationError) as exc: resolve_m2pack_binary() assert exc.value.error_code == "m2pack_not_found" def test_path_fallback_used_when_env_unset(tmp_path: Path, monkeypatch): stub = _make_stub(tmp_path) monkeypatch.delenv(ENV_VAR, raising=False) monkeypatch.setenv("PATH", str(tmp_path)) resolved = resolve_m2pack_binary() assert resolved == stub.resolve() def test_missing_binary_raises_validation_error(monkeypatch): monkeypatch.delenv(ENV_VAR, raising=False) monkeypatch.setenv("PATH", "/nonexistent") with pytest.raises(ValidationError) as exc: resolve_m2pack_binary() assert exc.value.error_code == "m2pack_not_found" assert "M2PACK_BINARY" in str(exc.value) def test_custom_env_mapping_parameter(tmp_path: Path): stub = _make_stub(tmp_path) fake_env = {ENV_VAR: str(stub)} resolved = resolve_m2pack_binary(env=fake_env) assert resolved == stub.resolve()