modify framework

This commit is contained in:
김경종
2026-06-02 09:51:30 +09:00
parent 88d8613847
commit a292238675
13 changed files with 602 additions and 169 deletions
+41
View File
@@ -0,0 +1,41 @@
import importlib.util
import sys
import tempfile
import unittest
from pathlib import Path
def load_pre_commit_checks():
module_path = Path(__file__).resolve().parent.parent / ".codex" / "hooks" / "pre_commit_checks.py"
spec = importlib.util.spec_from_file_location("pre_commit_checks", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class PreCommitChecksTests(unittest.TestCase):
def test_git_commit_runs_python_self_tests_and_workspace_validation(self):
pre_commit_checks = load_pre_commit_checks()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
commands = pre_commit_checks._build_pre_commit_commands(root)
self.assertEqual(
commands,
[
[sys.executable, "-m", "unittest", "discover", "-s", "scripts", "-p", "test_*.py"],
[sys.executable, "scripts/validate_workspace.py"],
],
)
self.assertFalse(any("npm" in part.lower() for command in commands for part in command))
def test_only_git_commit_commands_trigger_checks(self):
pre_commit_checks = load_pre_commit_checks()
self.assertTrue(pre_commit_checks._is_git_commit('git commit -m "change"'))
self.assertTrue(pre_commit_checks._is_git_commit('git -c core.editor=true commit -m "change"'))
self.assertFalse(pre_commit_checks._is_git_commit("git status --short"))
self.assertFalse(pre_commit_checks._is_git_commit("echo git commit"))
if __name__ == "__main__":
unittest.main()
+61
View File
@@ -0,0 +1,61 @@
import importlib.util
import tempfile
import unittest
from pathlib import Path
def load_tdd_guard():
module_path = Path(__file__).resolve().parent.parent / ".codex" / "hooks" / "tdd-guard.py"
spec = importlib.util.spec_from_file_location("tdd_guard", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class CppTddGuardTests(unittest.TestCase):
def test_cpp_production_file_without_related_test_is_blocked(self):
tdd_guard = load_tdd_guard()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source = root / "include" / "fesa" / "Core" / "DofManager.hpp"
source.parent.mkdir(parents=True)
source.write_text("#pragma once\n", encoding="utf-8")
self.assertEqual(tdd_guard._guarded_paths([str(source)], root, root), ["DofManager"])
def test_cpp_production_file_with_module_test_is_allowed(self):
tdd_guard = load_tdd_guard()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source = root / "include" / "fesa" / "Core" / "DofManager.hpp"
source.parent.mkdir(parents=True)
source.write_text("#pragma once\n", encoding="utf-8")
tests_dir = root / "tests"
tests_dir.mkdir()
(tests_dir / "test_core_module_includes.cpp").write_text("int main() { return 0; }\n", encoding="utf-8")
self.assertEqual(tdd_guard._guarded_paths([str(source)], root, root), [])
def test_cpp_production_file_with_basename_test_in_same_patch_is_allowed(self):
tdd_guard = load_tdd_guard()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source = root / "src" / "Math" / "DenseMatrix.cpp"
source.parent.mkdir(parents=True)
source.write_text("void f() {}\n", encoding="utf-8")
test_path = root / "tests" / "test_dense_matrix.cpp"
self.assertEqual(tdd_guard._guarded_paths([str(source), str(test_path)], root, root), [])
def test_cmake_and_docs_are_exempt(self):
tdd_guard = load_tdd_guard()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
self.assertEqual(
tdd_guard._guarded_paths(["CMakeLists.txt", "docs/ARCHITECTURE.md", "cmake/toolchain.cmake"], root, root),
[],
)
if __name__ == "__main__":
unittest.main()
+94
View File
@@ -0,0 +1,94 @@
import importlib.util
import os
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
def load_validate_workspace():
module_path = Path(__file__).resolve().parent / "validate_workspace.py"
spec = importlib.util.spec_from_file_location("validate_workspace", module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class ValidateWorkspaceTests(unittest.TestCase):
def test_env_commands_override_cmake_detection(self):
validate_workspace = load_validate_workspace()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "CMakeLists.txt").write_text("cmake_minimum_required(VERSION 3.20)\n", encoding="utf-8")
with patch.dict(os.environ, {"HARNESS_VALIDATION_COMMANDS": "echo first\n echo second \n"}, clear=True):
self.assertEqual(validate_workspace.discover_commands(root), ["echo first", "echo second"])
def test_msvc_debug_cmake_commands_are_default_for_cmake_project(self):
validate_workspace = load_validate_workspace()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "CMakeLists.txt").write_text("cmake_minimum_required(VERSION 3.20)\n", encoding="utf-8")
build_dir = root / "build" / "msvc-debug"
with patch.dict(os.environ, {}, clear=True):
self.assertEqual(
validate_workspace.discover_commands(root),
[
f'cmake -S "{root}" -B "{build_dir}" -G "Visual Studio 17 2022" -A x64',
f'cmake --build "{build_dir}" --config Debug',
f'ctest --test-dir "{build_dir}" --output-on-failure -C Debug',
],
)
def test_msvc_debug_configure_preset_is_preferred_when_present(self):
validate_workspace = load_validate_workspace()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "CMakeLists.txt").write_text("cmake_minimum_required(VERSION 3.20)\n", encoding="utf-8")
(root / "CMakePresets.json").write_text(
"""
{
"version": 3,
"configurePresets": [
{
"name": "msvc-debug",
"generator": "Visual Studio 17 2022",
"binaryDir": "${sourceDir}/out/msvc-debug"
}
]
}
""",
encoding="utf-8",
)
with patch.dict(os.environ, {}, clear=True):
self.assertEqual(
validate_workspace.discover_commands(root),
[
"cmake --preset msvc-debug",
f'cmake --build "{root / "out" / "msvc-debug"}" --config Debug',
f'ctest --test-dir "{root / "out" / "msvc-debug"}" --output-on-failure -C Debug',
],
)
def test_no_cmake_project_has_no_validation_commands(self):
validate_workspace = load_validate_workspace()
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
with patch.dict(os.environ, {}, clear=True):
self.assertEqual(validate_workspace.discover_commands(root), [])
def test_common_cmake_install_path_is_prepended_when_cmake_is_not_on_path(self):
validate_workspace = load_validate_workspace()
with tempfile.TemporaryDirectory() as tmp:
common_bin = Path(tmp) / "CMake" / "bin"
common_bin.mkdir(parents=True)
(common_bin / "cmake.exe").write_text("", encoding="utf-8")
(common_bin / "ctest.exe").write_text("", encoding="utf-8")
with patch.object(validate_workspace, "COMMON_CMAKE_BIN", common_bin):
with patch.object(validate_workspace.shutil, "which", return_value=None):
env = validate_workspace.validation_environment({"PATH": "C:\\Windows\\System32"})
self.assertTrue(env["PATH"].startswith(str(common_bin)))
if __name__ == "__main__":
unittest.main()
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
"""Run C++/MSVC Harness validation commands."""
from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
from pathlib import Path
DEFAULT_GENERATOR = "Visual Studio 17 2022"
DEFAULT_PLATFORM = "x64"
DEFAULT_CONFIG = "Debug"
DEFAULT_BUILD_DIR = "build/msvc-debug"
PRESET_NAME = "msvc-debug"
COMMON_CMAKE_BIN = Path(r"C:\Program Files\CMake\bin")
def load_env_commands() -> list[str]:
raw = os.environ.get("HARNESS_VALIDATION_COMMANDS", "")
return [line.strip() for line in raw.splitlines() if line.strip()]
def _cmake_config() -> tuple[str, str, str, Path]:
generator = os.environ.get("HARNESS_CMAKE_GENERATOR", DEFAULT_GENERATOR)
platform = os.environ.get("HARNESS_CMAKE_PLATFORM", DEFAULT_PLATFORM)
config = os.environ.get("HARNESS_CMAKE_CONFIG", DEFAULT_CONFIG)
build_dir = Path(os.environ.get("HARNESS_BUILD_DIR", DEFAULT_BUILD_DIR))
return generator, platform, config, build_dir
def _read_presets(root: Path) -> dict:
presets_file = root / "CMakePresets.json"
if not presets_file.exists():
return {}
try:
return json.loads(presets_file.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return {}
def _preset_binary_dir(root: Path, preset: dict) -> Path:
binary_dir = str(preset.get("binaryDir") or DEFAULT_BUILD_DIR)
binary_dir = binary_dir.replace("${sourceDir}", str(root))
binary_dir = binary_dir.replace("$sourceDir", str(root))
path = Path(binary_dir)
return path if path.is_absolute() else root / path
def load_preset_commands(root: Path) -> list[str]:
payload = _read_presets(root)
config = os.environ.get("HARNESS_CMAKE_CONFIG", DEFAULT_CONFIG)
for preset in payload.get("configurePresets", []):
if isinstance(preset, dict) and preset.get("name") == PRESET_NAME:
build_dir = _preset_binary_dir(root, preset)
return [
f"cmake --preset {PRESET_NAME}",
f'cmake --build "{build_dir}" --config {config}',
f'ctest --test-dir "{build_dir}" --output-on-failure -C {config}',
]
return []
def load_cmake_commands(root: Path) -> list[str]:
if not (root / "CMakeLists.txt").exists():
return []
generator, platform, config, build_dir = _cmake_config()
if not build_dir.is_absolute():
build_dir = root / build_dir
return [
f'cmake -S "{root}" -B "{build_dir}" -G "{generator}" -A {platform}',
f'cmake --build "{build_dir}" --config {config}',
f'ctest --test-dir "{build_dir}" --output-on-failure -C {config}',
]
def discover_commands(root: Path) -> list[str]:
env_commands = load_env_commands()
if env_commands:
return env_commands
preset_commands = load_preset_commands(root)
if preset_commands:
return preset_commands
return load_cmake_commands(root)
def run_command(command: str, root: Path) -> subprocess.CompletedProcess:
return subprocess.run(
command,
cwd=root,
shell=True,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
env=validation_environment(os.environ),
)
def validation_environment(base_env: os._Environ | dict[str, str]) -> dict[str, str]:
env = dict(base_env)
if shutil.which("cmake") is not None:
return env
cmake_exe = COMMON_CMAKE_BIN / "cmake.exe"
if not cmake_exe.exists():
return env
current_path = env.get("PATH", "")
paths = [part for part in current_path.split(os.pathsep) if part]
common_bin_text = str(COMMON_CMAKE_BIN)
if not any(part.lower() == common_bin_text.lower() for part in paths):
env["PATH"] = common_bin_text + (os.pathsep + current_path if current_path else "")
return env
def emit_stream(prefix: str, content: str, *, stream) -> None:
text = (content or "").strip()
if not text:
return
print(prefix, file=stream)
print(text, file=stream)
def main() -> int:
root = Path(__file__).resolve().parent.parent
commands = discover_commands(root)
if not commands:
print("No C++ validation commands configured.")
print("Add CMakeLists.txt or set HARNESS_VALIDATION_COMMANDS.")
return 0
for command in commands:
print(f"$ {command}")
result = run_command(command, root)
emit_stream("[stdout]", result.stdout, stream=sys.stdout)
emit_stream("[stderr]", result.stderr, stream=sys.stderr)
if result.returncode != 0:
print(f"Validation failed: {command}", file=sys.stderr)
return result.returncode
print("Validation succeeded.")
return 0
if __name__ == "__main__":
raise SystemExit(main())