Files
clean-architecture-backend-…/scripts/tests/test_check_docs.py
T
DongHyeonka 80e7ef12a2 ci(docs): FROZEN에 목록에 없는 지문이 남으면 문서 검사가 실패한다
예외 목록은 줄기만 해야 하는데 빈틈이 있다. check-docs.py는 목록의
줄이 FROZEN에 있는지만 보고, FROZEN의 지문이 목록에 있는지는 보지
않는다. 그래서 번역해서 지운 줄의 지문이 FROZEN에 남고, 같은 줄을 다시
더해도 검사가 통과한다. 기준 커밋 03a313ed에서 이미 FROZEN 217개 중
9개가 목록에 줄이 없었다(앞 단계의 이름 바꾸기에서 남은 것).

- run()이 FROZEN - (목록 줄의 지문)을 실패로 낸다. --only와 상관없이
  돈다(목록의 줄이 FROZEN에 있는지 보는 검사와 같다).
- 합친 트리의 목록이 비었으므로 FROZEN에서 217개를 모두 뺐다. 이제
  목록에 어떤 줄을 더해도 실패한다.
- 설명(스크립트 머리, 예외 목록 머리 주석, docs/README.md 「문서
  검사」)에 「줄을 지우면 FROZEN에서 그 지문도 뺀다」를 더했다.
  스크립트 머리의 「넷 모두」를 지금의 여섯 검사로 고쳤다.

버린 대안: FROZEN을 그대로 두고 자기 시험만 더하기. 실제 검사(PR
workflow)는 자기 시험과 따로 돌므로, 목록과 FROZEN이 어긋난 트리가
check-docs.py만으로는 통과한다. 검사 자신이 막아야 한다.

자기 시험(scripts/tests/test_check_docs.py)에 셋을 더했다.
- test_a_frozen_fingerprint_whose_line_was_removed_fails: 고장 낸 입력
  (빈 목록 + 지문 하나)이 language·head 어느 검사로 돌려도 실패한다.
- test_a_removed_line_added_back_fails_once_its_fingerprint_is_gone:
  지문을 뺀 뒤 줄을 다시 더하면 「기준선에 없는 예외다」로 실패하고,
  남은 줄에는 고아 지문 오류가 나지 않는다.
- test_every_frozen_fingerprint_has_its_line_in_the_real_exception_list:
  실제 FROZEN과 실제 목록이 맞는다.

조건을 끈 변이 시험(사본에 문자열 치환, 자기 시험 실행):
- 고아 지문 검사를 지움 → rc=1, 첫째 시험 실패
- FROZEN을 03a313ed의 217개로 되돌림 → rc=1, 셋째 시험 실패.
  실제 트리의 check-docs.py도 고아 지문 217건으로 실패한다.
- 둘 다(바꾸기 전 코드) → rc=1, 첫째·셋째 시험 실패

검증(노트북): check-docs.py OK(여섯 검사 걸림 0), 자기 시험 68 OK,
check-work-docs.py OK.
2026-11-07 18:15:29 +09:00

399 lines
20 KiB
Python

"""scripts/check-docs.py의 시험. 고장 낸 입력에서 실패하고, 맞는 입력에서 통과하는지 본다.
python3 -m unittest discover -s scripts/tests
"""
from __future__ import annotations
import importlib.util
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
SCRIPTS = Path(__file__).resolve().parent.parent
_spec = importlib.util.spec_from_file_location("check_docs", SCRIPTS / "check-docs.py")
check_docs = importlib.util.module_from_spec(_spec)
sys.modules["check_docs"] = check_docs
_spec.loader.exec_module(check_docs)
KOREAN = "이 문서는 한국어로 쓴 살아 있는 문서다. 코드와 같은 변경에서 고친다.\n"
ENGLISH = "This document is written in English and explains how the module works in detail.\n"
def head(kind: str = "설계서", status: str = "구현됨", written: str = "2026-08-11",
summary: str = "한국어로 쓴 요약 한 문장이다.", canonical: str = "`docs/live.md`",
extra: str = "", label: str | None = None) -> str:
if label is None:
label = check_docs.DECISION_LABEL if kind == "결정 기록" else check_docs.RECORD_LABEL.format(kind=kind)
lines = [check_docs.HEAD_START, label, "", f"- 상태: {status}", f"- 작성일: {written}",
f"- 요약: {summary}", f"- 현재 정본: {canonical}"]
if extra:
lines.append(extra)
lines += [check_docs.HEAD_END, ""]
return "\n".join(lines) + "\n"
class Repository:
"""A throwaway git working tree with a registry, so the checker sees what git sees."""
def __init__(self) -> None:
self._directory = tempfile.TemporaryDirectory()
self.root = Path(self._directory.name)
subprocess.run(["git", "init", "-q", str(self.root)], check=True)
self.write("docs/live.md", KOREAN)
self.write(check_docs.REGISTRY_FILE, json.dumps({"modules": [
{"id": "app", "gradle_path": ":app", "source_path": "src/app"},
{"id": "adapter-web", "gradle_path": ":adapter:inbound:web", "source_path": "src/adapter/inbound/web"},
]}))
def write(self, path: str, text: str) -> None:
target = self.root / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding="utf-8")
def run(self, only: tuple[str, ...] = check_docs.CHECKS, exceptions: str = "",
frozen: frozenset[str] | None = None) -> list[str]:
if frozen is None:
frozen = frozenset(check_docs.fingerprint(line) for line in check_docs.read_exceptions(exceptions))
errors, _ = check_docs.run(self.root, only, exceptions=exceptions, frozen=frozen)
return errors
def close(self) -> None:
self._directory.cleanup()
class RepositoryTestCase(unittest.TestCase):
def setUp(self) -> None:
self.repo = Repository()
self.addCleanup(self.repo.close)
def assertFailsWith(self, errors: list[str], fragment: str) -> None:
self.assertTrue(any(fragment in error for error in errors), f"no error with {fragment!r}: {errors}")
class LanguageTest(RepositoryTestCase):
def test_an_english_living_document_fails(self) -> None:
self.repo.write("docs/guide.md", "# Guide\n\n" + ENGLISH * 3)
self.assertFailsWith(self.repo.run(("language",)), "docs/guide.md: 영어 문서다")
def test_a_korean_living_document_passes(self) -> None:
self.repo.write("src/app/README.md", "# 앱\n\n" + KOREAN * 3)
self.assertEqual(self.repo.run(("language",)), [])
def test_code_commands_and_paths_do_not_make_a_korean_document_english(self) -> None:
code = "```bash\n" + "./gradlew :app:test --console=plain and many more english words here\n" * 20 + "```\n"
self.repo.write("docs/guide.md", "# 안내\n\n" + KOREAN + code + "`src/app/Foo.java`를 본다.\n")
self.assertEqual(self.repo.run(("language",)), [])
def test_a_record_body_keeps_its_original_language(self) -> None:
self.repo.write("docs/design/2026-08-11-x-design.md", head() + "# Design\n\n" + ENGLISH * 3)
self.assertEqual(self.repo.run(("language",)), [])
def test_an_english_decision_record_body_fails(self) -> None:
self.repo.write("docs/adr/ADR-X-001.md", head(kind="결정 기록", status="채택") + "# ADR\n\n" + ENGLISH * 3)
self.assertFailsWith(self.repo.run(("language",)), "docs/adr/ADR-X-001.md: 영어 문서다")
class ExceptionListTest(RepositoryTestCase):
LINE = "language\tdocs/guide.md"
def test_a_frozen_exception_excuses_its_document(self) -> None:
self.repo.write("docs/guide.md", ENGLISH * 3)
self.assertEqual(self.repo.run(("language",), exceptions=self.LINE + "\n"), [])
def test_adding_a_line_to_the_exception_list_fails(self) -> None:
self.repo.write("docs/guide.md", ENGLISH * 3)
errors = self.repo.run(("language",), exceptions=self.LINE + "\n", frozen=frozenset())
self.assertFailsWith(errors, "기준선에 없는 예외다")
def test_a_frozen_fingerprint_whose_line_was_removed_fails(self) -> None:
# The line was deleted from the list but its fingerprint stayed: the same line could come back.
orphan = frozenset({check_docs.fingerprint(self.LINE)})
for only in (("language",), ("head",)):
errors = self.repo.run(only, exceptions="", frozen=orphan)
self.assertFailsWith(errors, "예외 목록에 그 줄이 없는 지문이다")
def test_a_removed_line_added_back_fails_once_its_fingerprint_is_gone(self) -> None:
self.repo.write("docs/guide.md", ENGLISH * 3)
remaining = "language\tdocs/other.md"
self.repo.write("docs/other.md", ENGLISH * 3)
exceptions = remaining + "\n" + self.LINE + "\n"
errors = self.repo.run(("language",), exceptions=exceptions,
frozen=frozenset({check_docs.fingerprint(remaining)}))
self.assertFailsWith(errors, "기준선에 없는 예외다")
self.assertFalse(any("예외 목록에 그 줄이 없는 지문이다" in error for error in errors), errors)
def test_an_exception_that_no_longer_fails_must_be_removed(self) -> None:
self.repo.write("docs/guide.md", KOREAN * 3)
self.assertFailsWith(self.repo.run(("language",), exceptions=self.LINE + "\n"), "더는 걸리지 않는다")
def test_an_exception_for_one_check_does_not_excuse_another(self) -> None:
self.repo.write("docs/guide.md", "`docs/gone.md`를 본다. " + KOREAN)
errors = self.repo.run(("reference",), exceptions="number\tdocs/guide.md\tdocs/gone.md\n")
self.assertFailsWith(errors, "없는 경로다: docs/gone.md")
def test_every_line_of_the_real_exception_list_is_in_the_frozen_baseline(self) -> None:
text = (SCRIPTS.parent / check_docs.EXCEPTIONS_FILE).read_text(encoding="utf-8")
outside = [line for line in check_docs.read_exceptions(text)
if check_docs.fingerprint(line) not in check_docs.FROZEN]
self.assertEqual(outside, [])
def test_every_frozen_fingerprint_has_its_line_in_the_real_exception_list(self) -> None:
text = (SCRIPTS.parent / check_docs.EXCEPTIONS_FILE).read_text(encoding="utf-8")
listed = {check_docs.fingerprint(line) for line in check_docs.read_exceptions(text)}
self.assertEqual(sorted(check_docs.FROZEN - listed), [])
def test_a_new_line_in_the_real_exception_list_is_not_in_the_frozen_baseline(self) -> None:
self.assertNotIn(check_docs.fingerprint("language\tdocs/brand-new-english.md"), check_docs.FROZEN)
class HeadBlockTest(RepositoryTestCase):
PATH = "docs/design/2026-08-11-x-design.md"
def errors_for(self, text: str) -> list[str]:
self.repo.write(self.PATH, text + "# Original\n\nbody\n")
return self.repo.run(("head",))
def test_a_complete_head_block_passes(self) -> None:
self.assertEqual(self.errors_for(head()), [])
def test_canonical_none_with_a_reason_passes(self) -> None:
self.assertEqual(self.errors_for(head(canonical="없음 — 지운 기능이다")), [])
def test_a_record_without_a_head_block_fails(self) -> None:
self.assertFailsWith(self.errors_for(""), "맨 위에 머리 블록이 없다")
def test_a_status_outside_the_vocabulary_fails(self) -> None:
self.assertFailsWith(self.errors_for(head(status="Accepted")), "설계서의 상태는")
def test_a_plan_status_on_a_decision_record_fails(self) -> None:
self.repo.write("docs/adr/ADR-X-001.md", head(kind="결정 기록", status="끝남") + "# ADR\n")
self.assertFailsWith(self.repo.run(("head",)), "결정 기록의 상태는")
def test_a_malformed_date_fails(self) -> None:
self.assertFailsWith(self.errors_for(head(written="2026-13-01")), "작성일은 YYYY-MM-DD다")
def test_an_english_summary_fails(self) -> None:
self.assertFailsWith(self.errors_for(head(summary="A design for the module boundary.")), "요약은 한국어")
def test_a_canonical_path_that_does_not_exist_fails(self) -> None:
self.assertFailsWith(self.errors_for(head(canonical="`docs/missing.md`")), "현재 정본 경로가 없다")
def test_a_canonical_value_without_a_path_fails(self) -> None:
self.assertFailsWith(self.errors_for(head(canonical="jpa 문서")), "현재 정본은")
def test_superseded_without_its_replacement_fails(self) -> None:
self.assertFailsWith(self.errors_for(head(status="대체됨")), "「대체됨」 칸에 대체한 문서")
def test_superseded_with_its_replacement_passes(self) -> None:
self.assertEqual(self.errors_for(head(status="대체됨", extra="- 대체됨: `docs/live.md`")), [])
def test_a_wrong_kind_label_fails(self) -> None:
self.assertFailsWith(self.errors_for(head(label="> **기록 · 계획서** 다른 종류다.")), "머리 블록 둘째 줄은")
def test_an_unknown_field_fails(self) -> None:
self.assertFailsWith(self.errors_for(head(extra="- 담당: 누군가")), "머리 블록에 없는 칸이다")
def test_the_kind_follows_the_folder(self) -> None:
self.repo.write("docs/history/plans/evidence/x.md", head(kind="증거", status="보관") + "# Evidence\n")
self.assertEqual(self.repo.run(("head",)), [])
class ReferenceTest(RepositoryTestCase):
def errors_for(self, text: str, path: str = "docs/guide.md") -> list[str]:
self.repo.write(path, KOREAN + text)
return self.repo.run(("reference",))
def test_a_missing_repository_path_fails(self) -> None:
self.assertFailsWith(self.errors_for("`docs/gone.md`를 읽는다.\n"), "없는 경로다: docs/gone.md")
def test_an_existing_path_with_a_line_number_passes(self) -> None:
self.assertEqual(self.errors_for("`docs/live.md:12`를 읽는다.\n"), [])
def test_a_missing_path_under_the_root_compose_folder_fails(self) -> None:
self.assertFailsWith(self.errors_for("`compose/gone/README.md`를 읽는다.\n"), "없는 경로다: compose/gone/README.md")
def test_a_path_inside_a_command_is_checked(self) -> None:
self.assertFailsWith(self.errors_for("`python3 scripts/gone.py --all`을 돌린다.\n"), "scripts/gone.py")
def test_fenced_code_is_skipped(self) -> None:
self.assertEqual(self.errors_for("```text\n`docs/gone.md`\n```\n"), [])
def test_a_history_quote_is_skipped(self) -> None:
self.assertEqual(self.errors_for("> 이력: `docs/gone.md`는 2026-09-25에 지웠다.\n> `src/gone/` 도.\n"), [])
def test_a_placeholder_path_is_skipped(self) -> None:
self.assertEqual(self.errors_for("`docs/reviews/<폴더>`와 `src/**/CLAUDE.md`를 본다.\n"), [])
def test_a_leaf_relative_source_path_resolves_through_some_leaf(self) -> None:
self.repo.write("src/app/src/test/resources/contracts/x.sha256", "x")
self.assertEqual(self.errors_for("각 leaf의 `src/test/resources/contracts/x.sha256`을 본다.\n"), [])
def test_a_source_set_name_every_leaf_has_is_skipped(self) -> None:
self.assertEqual(self.errors_for("테스트는 각 leaf의 `src/test`와 `src/main/java/` 옆에 둔다.\n"), [])
def test_a_gradle_path_outside_the_registry_fails(self) -> None:
self.assertFailsWith(self.errors_for("`./gradlew :sample:check`를 돌린다.\n"), "registry에 없는 Gradle 경로다: :sample:check")
def test_a_task_of_a_registered_project_passes(self) -> None:
self.assertEqual(self.errors_for("`./gradlew :adapter:inbound:web:test`와 `:app:check`를 돌린다.\n"), [])
def test_the_removal_table_is_not_checked(self) -> None:
self.assertEqual(self.errors_for("`src/gone/Old.java`를 지웠다.\n", path="docs/capability-status.md"), [])
def test_a_record_is_not_checked(self) -> None:
self.repo.write("docs/design/2026-08-11-x-design.md", head() + "`docs/gone.md`\n")
self.assertEqual(self.repo.run(("reference",)), [])
class NumberTest(RepositoryTestCase):
def errors_for(self, text: str) -> list[str]:
self.repo.write("src/app/CLAUDE.md", KOREAN + text)
return self.repo.run(("number",))
def test_a_copied_spring_boot_version_fails(self) -> None:
self.assertFailsWith(self.errors_for("Runtime baseline: Spring Boot 4.0.8.\n"), "'Spring Boot 4.0.8'")
def test_a_major_version_passes(self) -> None:
self.assertEqual(self.errors_for("Spring Boot 4 위에서 돈다.\n"), [])
def test_a_copied_leaf_count_fails(self) -> None:
self.assertFailsWith(self.errors_for("registry는 leaf 65개를 가진다.\n"), "leaf 개수")
self.assertFailsWith(self.errors_for("declares exactly 19 leaf identities.\n"), "leaf 개수")
def test_a_word_count_of_leaves_passes(self) -> None:
self.assertEqual(self.errors_for("leaf 하나를 고른다.\n"), [])
class ScopeTest(RepositoryTestCase):
def test_markdown_under_a_source_set_resources_folder_is_not_a_document(self) -> None:
self.repo.write("src/app/src/test/resources/fixtures/broken-readme.md", "# Broken\n\n" + ENGLISH * 3)
self.assertEqual(self.repo.run(("language",)), [])
def test_markdown_beside_a_source_set_is_still_a_document(self) -> None:
self.repo.write("src/app/src/test/README.md", "# Tests\n\n" + ENGLISH * 3)
self.assertFailsWith(self.repo.run(("language",)), "src/app/src/test/README.md: 영어 문서다")
def table(*rows: str) -> str:
return "| 폴더 | 무엇 |\n| --- | --- |\n" + "".join(f"| {row} | 설명 |\n" for row in rows)
class MapTest(RepositoryTestCase):
def errors_for(self, text: str) -> list[str]:
self.repo.write(check_docs.MAP_FILE, "# docs\n\n" + KOREAN + text)
return self.repo.run(("map",))
def test_a_map_that_names_every_folder_passes(self) -> None:
self.repo.write("docs/jpa/guide.md", KOREAN)
self.repo.write("docs/history/plans/2026-08-11-x-plan.md", KOREAN)
checks = "| 검사 | 보는 것 |\n| --- | --- |\n| `language` | 언어 |\n"
self.assertEqual(self.errors_for(table("`jpa/`", "`history/plans/`") + "\n" + checks), [])
def test_a_folder_missing_from_the_map_fails(self) -> None:
self.repo.write("docs/redis/operations.md", KOREAN)
self.assertFailsWith(self.errors_for(table()), "지도에 없는 문서 폴더다: docs/redis/")
def test_a_folder_without_markdown_must_be_mapped_too(self) -> None:
self.repo.write("docs/security/public-paths-snapshot.txt", "/api/healthcheck\n")
self.assertFailsWith(self.errors_for(table()), "지도에 없는 문서 폴더다: docs/security/")
def test_a_folder_that_only_holds_folders_is_covered_by_its_subfolders(self) -> None:
self.repo.write("docs/history/plans/2026-08-11-x-plan.md", KOREAN)
self.repo.write("docs/history/study/x.md", KOREAN)
errors = self.errors_for(table("`history/`", "`history/plans/`"))
self.assertFailsWith(errors, "지도에 없는 문서 폴더다: docs/history/study/")
self.assertFalse(any("docs/history/plans/" in error for error in errors), errors)
def test_folders_below_the_mapped_level_need_no_row(self) -> None:
self.repo.write("docs/history/packages/jpa/README.md", KOREAN)
self.repo.write("docs/mongodb/advanced/sharding.md", KOREAN)
self.repo.write("docs/mongodb/guide.md", KOREAN)
self.assertEqual(self.errors_for(table("`history/packages/`", "`mongodb/`")), [])
def test_a_mapped_folder_that_does_not_exist_fails(self) -> None:
self.assertFailsWith(self.errors_for(table("`gone/`")), "지도의 폴더가 없다: docs/gone/")
def test_a_folder_named_outside_the_first_cell_does_not_count(self) -> None:
self.repo.write("docs/redis/operations.md", KOREAN)
self.assertFailsWith(self.errors_for(table("운영") + "| 캐시 | `redis/` |\n"),
"지도에 없는 문서 폴더다: docs/redis/")
def test_a_folder_inside_a_code_block_does_not_count(self) -> None:
self.repo.write("docs/redis/operations.md", KOREAN)
self.assertFailsWith(self.errors_for("```text\n" + table("`redis/`") + "```\n"),
"지도에 없는 문서 폴더다: docs/redis/")
def test_a_folder_may_be_written_from_the_repository_root(self) -> None:
self.repo.write("docs/redis/operations.md", KOREAN)
self.assertEqual(self.errors_for(table("`docs/redis/`")), [])
def test_a_placeholder_folder_is_not_an_entry(self) -> None:
self.assertEqual(self.errors_for(table("`history/packages/<어댑터>/`")), [])
def test_a_repository_without_the_map_fails(self) -> None:
self.assertFailsWith(self.repo.run(("map",)), "문서 지도가 없다")
def readme(sections: tuple[str, ...] = check_docs.README_SECTIONS, title: str = "# 템플릿",
intro: str = "이 저장소가 무엇이고 누가 쓰는지 쓴 한 문단이다.") -> str:
parts = [title, "", intro, ""] if intro else [title, ""]
for section in sections:
parts += [section if section.startswith("#") else f"## {section}", "", KOREAN]
return "\n".join(parts)
class ReadmeTest(RepositoryTestCase):
def errors_for(self, text: str) -> list[str]:
self.repo.write(check_docs.README_FILE, text)
return self.repo.run(("readme",))
def test_every_section_in_order_passes(self) -> None:
self.assertEqual(self.errors_for(readme()), [])
def test_other_sections_between_the_required_ones_pass(self) -> None:
sections = check_docs.README_SECTIONS[:2] + ("부록",) + check_docs.README_SECTIONS[2:]
self.assertEqual(self.errors_for(readme(sections)), [])
def test_each_missing_section_fails(self) -> None:
for missing in check_docs.README_SECTIONS:
with self.subTest(missing=missing):
sections = tuple(section for section in check_docs.README_SECTIONS if section != missing)
self.assertFailsWith(self.errors_for(readme(sections)), f"「## {missing}」 절이 없다")
def test_sections_out_of_order_fail(self) -> None:
sections = ("시작하기", "프로젝트 구조") + check_docs.README_SECTIONS[2:]
self.assertFailsWith(self.errors_for(readme(sections)), "「## 시작하기」 절은 「## 프로젝트 구조」 절 뒤에 온다")
def test_a_readme_that_does_not_start_with_a_title_fails(self) -> None:
self.assertFailsWith(self.errors_for(readme(title="템플릿 소개")), "첫 줄은 `# 제목`이다")
self.assertFailsWith(self.errors_for("소개 한 줄\n\n" + readme()), "첫 줄은 `# 제목`이다")
def test_a_readme_without_an_introduction_fails(self) -> None:
self.assertFailsWith(self.errors_for(readme(intro="")), "한 문단을 둔다")
def test_a_section_heading_at_another_level_does_not_count(self) -> None:
sections = tuple("### 문서 지도" if section == "문서 지도" else section
for section in check_docs.README_SECTIONS)
self.assertFailsWith(self.errors_for(readme(sections)), "「## 문서 지도」 절이 없다")
def test_a_section_heading_inside_a_code_block_does_not_count(self) -> None:
sections = tuple(section for section in check_docs.README_SECTIONS if section != "검증")
text = readme(sections) + "\n```markdown\n## 검증\n```\n"
self.assertFailsWith(self.errors_for(text), "「## 검증」 절이 없다")
def test_a_repository_without_a_readme_fails(self) -> None:
self.assertFailsWith(self.repo.run(("readme",)), "루트 README가 없다")
class CommandLineTest(unittest.TestCase):
def test_an_unknown_check_is_a_usage_error(self) -> None:
self.assertEqual(check_docs.main(["--only", "spelling"]), 2)
if __name__ == "__main__":
unittest.main()