diff --git a/.claude/agents/wss-pr-reviewer.md b/.claude/agents/wss-pr-reviewer.md index f3f226c7d..24a669189 100644 --- a/.claude/agents/wss-pr-reviewer.md +++ b/.claude/agents/wss-pr-reviewer.md @@ -31,7 +31,7 @@ tools: Bash, Read, Grep, Glob - `docs/ARCHITECTURE.md` — 레이어·의존성 방향·데이터 흐름(cross-layer 판단의 정본) - `docs/CONVENTIONS.md` — 네이밍·import 순서·접근제어·비동기·에러 규약 - 변경된 각 `Projects/<레이어>/CLAUDE.md` + `Projects/<레이어>/<모듈>/CLAUDE.md` — 레이어/모듈 규칙·함정 -- 변경에 따라: `docs/TESTING.md`(Domain 테스트·Mock·커버리지 4종), `docs/DEFINITION_OF_DONE.md`(완료 점검) +- 변경에 따라: `docs/TESTING.md`(Domain 테스트 5원칙·Stub/Mock·사람이 판단할 곳), `docs/DEFINITION_OF_DONE.md`(완료 점검) - `Plugins/DependencyPlugin/ProjectDescriptionHelpers/ModuleType.swift` — 모듈 식별·등록 단일 진실 소스 - **Feature 변경이 있으면**: `Projects/Feature/CLAUDE.md` + `Projects/Feature/Docs/VIEWMODEL_TEMPLATE.md`·`VIEW_TEMPLATE.md` - 정본 레퍼런스(패턴 비교용): Domain `Projects/Domain/{BaseDomain,NovelDomain}/`, Data `Projects/Data/{BaseData,NovelData}/`, Feature `Projects/Feature/NovelReviewFeature/` @@ -58,7 +58,7 @@ tools: Bash, Read, Grep, Glob - **UI / Feature**: `@Observable`. `ObservableObject`/`@Published`/`@StateObject` ❌. ### D. 레이어별 핵심 계약 (변경된 레이어만) -- **Domain**: 비즈니스 정책은 Entity/정책 타입에 위임(UseCase는 조합만). **새/변경 UseCase·Entity·정책에 테스트가 없으면 🔴** — 커버리지 4종(정상/경계값/정책위반/상태변화), "읽히는 명세"(`docs/TESTING.md`). 프로토콜 변경 시 Mock 동기화. +- **Domain**: 비즈니스 정책은 Entity/정책 타입에 위임(UseCase는 조합만). **분기·검증·계산이 있는 새/변경 Entity·정책·UseCase에 테스트가 없으면 🔴**(넘기기만 하는 UseCase는 테스트가 없는 게 맞다). 테스트 이름이 말한 것을 본문이 실제로 확인하는지, 경계값("딱 그 값"·"하나 넘는 값")이 있는지 본다 — 형식은 ArchLint가 검사하니 의미를 본다(`docs/TESTING.md`). 프로토콜 변경 시 Mock 동기화. - **Data**: 네트워킹·디코딩·시스템 에러를 **`RepositoryError`로 변환**해 던지는가(원시 에러 누출 = 🔴, 정본 `docs/CONVENTIONS.md`·BaseData). Repository 구현은 internal + **Factory(public) 경유 노출**. DTO↔Entity는 Mapper에서(DTO 누출 금지). - **Feature**: View↔VM 계약(`@MainActor @Observable`, 단일 `private(set) var state`, View→VM 입력은 `handle(.action)`), `await` 이후 `state` 변경 전 취소/닫힘 재확인(경합), 생명주기 1회 가드, 강제 언래핑/폰트 등록 누락(SIGTRAP)·탭 트랩(`contentShape`)·디자인시스템 우회. ※ 화면 단위 미세 규칙을 끝까지 파야 하면 `wss-feature-reviewer`를 권고로 언급. - **Core / UI / App**: Core 인프라 재진입 함정(예: 토큰 갱신이 다시 토큰 갱신을 부르는 무한루프 가드), UI 디자인 토큰 단일 소스·도메인 의존 유입 금지, App은 레이어 규칙 지키며 Factory로 조립(여기서만 Data 조립 허용). @@ -86,5 +86,5 @@ tools: Bash, Read, Grep, Glob ``` - 위반이 없는 항목/카테고리는 통과로 명시한다("A. Cross-layer 정합성: 위반 없음"). -- 맨 끝에 **한 줄 총평**과, 필요하면 **검증 권고** 한 줄(예: "`/domain-test`로 새 UseCase 테스트 통과 확인, 시뮬레이터로 해당 화면 동작 확인 권장"). +- 맨 끝에 **한 줄 총평**과, 필요하면 **검증 권고** 한 줄(예: "`Mutate <모듈>`로 새 규칙의 테스트가 버그를 잡는지 확인, 시뮬레이터로 해당 화면 동작 확인 권장"). - 코드를 수정하지 않는다. 수정은 사용자/메인 에이전트 몫이다. diff --git a/.claude/skills/new-module/SKILL.md b/.claude/skills/new-module/SKILL.md index dcde4d7a4..ec98ca282 100644 --- a/.claude/skills/new-module/SKILL.md +++ b/.claude/skills/new-module/SKILL.md @@ -38,14 +38,14 @@ metadata: ### 4. Project.swift 생성 `Projects///Project.swift` 생성. **같은 레이어 기존 모듈을 복제**해 `createModule(...)` 형태/`targets`/`internalDependencies`를 맞춘다. -- targets 기본: domain `[.sources, .testing, .tests]`, data/core `[.sources, .demo, .testing, .tests]`, ui `[.sources, .demo]`, feature `[.sources, .demo, .tests]`. +- targets 기본: domain `[.sources, .tests]`(가짜 객체가 필요해지면 `.testing` 추가 — 넘기기만 하는 UseCase는 테스트하지 않아 Stub/Mock이 필요 없을 수 있다), data/core `[.sources, .demo, .testing, .tests]`, ui `[.sources, .demo]`, feature `[.sources, .demo, .tests]`. ### 5. 소스 디렉토리 - `Sources/` 생성. 레이어 표준 하위 폴더를 만든다(빈 폴더 대신 최소 placeholder 또는 첫 타입): - domain: `Entity/`, `UseCase/`, `Repository/` - data: `DTO/`, `Service/`, `Mapper/`, `Repository/`, `Factory/`, `Endpoint/`, `Logger/` - feature: `Factory/` + 화면별 폴더(`/` — 타입별 분리 ❌), 별도로 `Demo/`(Demo 앱). 골격은 `new-feature` 스킬이 담당. -- domain이면 `Testing/`, `Tests/{Entity,UseCase}/`도. +- domain이면 `Tests/{Entity,UseCase}/`도(`Testing/`은 `.testing`을 넣을 때만). ### 6. 프로젝트 생성 - `tuist generate` 실행. 실패하면 출력 그대로 보고 (에셋/Derived 문제면 안내). @@ -55,5 +55,5 @@ metadata: ### 8. 마무리 보고 - 등록한 case, 생성 파일, **선택한 의존성과 근거**를 요약. -- domain이면: "테스트 필수 — `docs/TESTING.md`, CI는 `/domain-test`로 폴더 자동 인식" 안내. +- domain이면: "판단하는 코드는 테스트 필수 — `docs/TESTING.md`(목록 먼저 합의). 이 기준으로 테스트를 다 쓰면 `TestSpecScope.modules`(`Tooling/ArchLint/Sources/ArchLintCore/TestSpecSupport.swift`)에 모듈을 추가해 ArchLint 테스트 규칙을 켜고, `--write-test-specs`로 `TEST_SPEC.md`를 만든다" 안내. - 커밋은 사용자가 지시할 때만. ([Type] #이슈 규약은 docs/WORKFLOW.md) diff --git a/.claude/skills/rewrite-domain-tests/SKILL.md b/.claude/skills/rewrite-domain-tests/SKILL.md new file mode 100644 index 000000000..e51fad611 --- /dev/null +++ b/.claude/skills/rewrite-domain-tests/SKILL.md @@ -0,0 +1,92 @@ +--- +name: rewrite-domain-tests +description: WSS-iOS-V2에서 아직 "테스트=기능 명세" 기준으로 안 바뀐 Domain 모듈의 테스트를 다시 쓸 때 사용한다(#293에서 Auth·NovelReview·Base·Collection에 한 과정 그대로). 모듈명을 받아 ① 현재 소스와 기존 테스트 읽기(기존 테스트는 실제 사고 기록만 추림) → ② 기준 모듈(NovelReviewDomain)을 본떠 테스트 목록 초안 → ③ 사람이 목록 승인 → ④ 테스트 재작성·넘기기 테스트 정리 → ⑤ ArchLint 적용 범위에 추가·검사 통과·TEST_SPEC.md 생성 → ⑥ 사람이 본문 훑기 → ⑦ 뮤테이션 도구 실행·살아남은 버그를 사람이 판단, 까지 단계별 게이트로 진행한다. "도메인 테스트 다시 쓰자", "이 모듈 테스트 명세로 바꾸자", 또는 "/rewrite-domain-tests " 같은 요청에 트리거. 새 코드를 TDD로 쓰는 일이나 Feature/Data 테스트는 범위 밖. +metadata: + short-description: Domain 모듈 테스트를 기능 명세로 재작성 (목록 합의 → 재작성 → ArchLint → 본문 확인 → 뮤테이션), 단계별 게이트 +--- + +# Rewrite Domain Tests — Domain 테스트를 기능 명세로 재작성 (WSS-iOS-V2) + +인자: `` (예: `Feed` → `FeedDomain`). 비면 묻는다. +**AI가 테스트 코드를 쓰고, 무엇을 확인할지는 사람이 정한다.** 이 스킬은 그 결정 지점(🚦)을 빼먹지 않게 하는 순서다. + +> ⚠️ **규칙은 여기 없다 — 정본을 먼저 읽는다.** 5원칙·Stub/Mock·쓰는 법·사람이 보는 곳은 +> [docs/TESTING.md](../../../docs/TESTING.md), 기계가 검사하는 규칙 id는 +> [Tooling/ArchLint/README.md](../../../Tooling/ArchLint/README.md)의 "테스트 명세 규칙"이 정본이다. +> 이 스킬은 **순서와 사람 게이트만** 적는다. 규칙을 여기 복사하지 않는다(어긋난다). +> +> ⚠️ **기준 모듈(이렇게 쓰면 된다는 본보기)** — 지어내지 말고 읽고 따른다. +> - **NovelReviewDomain** — 주 기준. Entity(Draft) 테스트·하위 Suite·`TEST_SPEC.md` 모양: +> `Projects/Domain/NovelReviewDomain/Tests/Entity/NovelReviewDraftTests.swift`, `TEST_SPEC.md` +> - **BaseDomain `Tests/UseCase/`** — UseCase 테스트와 Stub/Mock(NovelReview엔 UseCase 테스트가 없다): +> `AppReviewRequestUseCaseTests.swift`, `Testing/Mock/MockKeywordRepository.swift` +> - **CollectionDomain** — 하위 Suite를 개념으로 나눈 예, `ValidationError` case별 `#expect(throws:)` +> +> ⚠️ **게이트 승인 = 커밋 지시.** 게이트에서 진행을 물을 때 *무엇을 몇 개의 커밋으로, 어떤 메시지로* +> 할지 같이 보여준다. 커밋은 `commit` 스킬 규약(`[Type] #이슈 - 한글`, 이슈번호는 브랜치명에서, +> 명시적 경로로만 스테이징). **push는 안 한다.** + +## 절차 + +### 0. 준비 +- `ModuleType.swift`에서 `Domain`이 정식 모듈인지 확인한다(폴더 `ls`로 판단 ❌ — 유령 폴더). +- `TestSpecSupport.swift`의 `TestSpecScope.modules`에 이미 있으면 → 이미 끝난 모듈이라고 알리고 멈춘다. +- 모듈 `Sources`·`Tests`에 커밋 안 한 변경이 있으면 먼저 정리한다(뮤테이션 도구가 시작을 거부한다). + +### 1. 재료 읽기 +- **현재 소스가 기준이다.** `Sources/` 전부를 읽고 타입·메서드마다 분류한다: + 판단(분기·검증·계산·정규화·상태 변화) / 담기(규칙 있는 타입이 값을 담음 — **테스트 대상**) / 넘기기(저장소 호출 그대로) / 값만 담는 타입. + ⚠️ "담는 것은 넘기는 것이 아니다" — NovelReview에서 setter를 '판단 없음'으로 뺐다가 뮤테이션에서 걸렸다(TESTING.md). +- **기존 테스트는 가볍게만 본다.** 옛 방식이라 구조는 본뜨지 않는다. 대신 **실제 사고·버그 이력이 적힌 테스트·주석** + (이슈 번호, "실측", "버그" 같은 말)만 추려서, 목록에 살릴 후보로 들고 간다. +- 이 모듈의 `Testing/Mock`을 누가 쓰는지 `Projects/` 전체에서 grep 해 둔다(다른 모듈·Feature 테스트가 쓰면 지울 수 없다). + +### 2. 테스트 목록 초안 +- 기준 모듈의 `TEST_SPEC.md` 모양 그대로 쓴다: Suite 이름 → (하위 Suite) → 테스트 이름(한국어 문장). +- 같이 적는다: + - **넣지 않는 것과 이유** — 넘기기 UseCase, 값만 담는 타입 등. 빠뜨린 것과 뺀 것을 구분하기 위해서다. + - **지울 것** — 넘기기 UseCase 테스트, 그래서 안 쓰게 되는 Mock·`Testing` 타깃(1단계 grep 결과 근거). + - **1단계에서 추린 사고 이력**을 어느 테스트가 이어받는지. + - 판단이 필요한 곳(경계값, 순서가 명세인지, 시각·달력 의존을 인자로 뺄지 등)은 **질문으로** 따로 뽑는다. +- 하위 Suite 묶음은 **개념** 기준(개수 ❌). 묶음도 사람이 정할 몫이라 초안은 제안일 뿐이다. +- **판단 코드가 하나도 없으면**(전부 넘기기·값만 담는 타입 — SocialDomain 시험 실행에서 나옴) 목록은 "테스트 0개"다. + 이때 초안에 TESTING.md "적용 범위"의 테스트 없는 모듈 처리(타깃 빼기·적용 범위엔 넣기)를 그대로 제안한다. + +### 🚦 3. 사람이 목록 승인 +- 목록과 질문을 보여주고 **승인 전에는 테스트 코드를 쓰지 않는다.** +- 소스를 바꿔야 하는 결정(예: `calendar` 인자 추가, 중복 거부 추가)이 나오면 여기서 확정한다 — 소스 변경도 승인 범위다. +- 커밋할 것 없음(목록은 대화에만). 승인되면 4단계로. + +### 4. 테스트 재작성 +- 승인된 목록대로 `Tests/{Entity,UseCase}/`를 다시 쓴다. 쓰는 법은 TESTING.md "쓰는 법"·"가짜 객체" 그대로. +- 지우기로 한 테스트·Mock을 지우고, Mock이 전부 사라지면 `Project.swift`의 `.testing` 타깃도 뺀다. + 테스트가 0개가 되면 `.tests` 타깃도 빼고 `tuist generate` 후 모듈 스킴 **빌드**로 확인한다(돌릴 테스트가 없다). +- 모듈 스킴으로 테스트를 돌려 통과시킨다(XcodeBuildMCP `test_sim`, scheme `Domain` — `…Tests` 스킴은 없다). + ⚠️ `Executed 0 tests`는 실패가 아니다(TESTING.md 주의사항). + +### 5. ArchLint 켜기 +- `TestSpecScope.modules`에 `Domain`을 추가한다(빼먹으면 규칙이 이 모듈엔 아예 안 돈다). +- `swift run --package-path Tooling/ArchLint ArchLint --write-test-specs .` → `TEST_SPEC.md` 생성. +- `swift run --package-path Tooling/ArchLint ArchLint .` error 0이 될 때까지 고친다. + - **규칙 오탐이면 allow 주석으로 덮지 말고 사용자에게 알린다.** 규칙을 고칠지(별도 `[Fix]` 커밋 + 규칙 자체 테스트), 이유 단 allow로 둘지 사람이 정한다. + - `test-aaa-act` warning(실행 여러 문장)은 설계 점검 질문으로 사용자에게 넘긴다. +- **커밋 제안**: 재작성 + 적용 범위 추가 + `TEST_SPEC.md`를 `[Test] #이슈 - Domain 테스트를 기능 명세로 재작성` 하나로 + (`TEST_SPEC.md`는 적용 범위가 있어야 검사되므로 같이 간다). 소스 변경이 있었으면 관심사별로 나눠 제안한다. + +### 🚦 6. 사람이 본문 훑기 +- 사람에게 볼 곳을 짚어준다: 이름이 말한 것을 본문이 실제로 확인하는지, `arguments` 이유 주석, allow 주석. +- 고칠 게 나오면 고치고 4~5단계 검사를 다시 통과시킨 뒤 넘어간다. + +### 7. 뮤테이션 → 🚦 살아남은 버그 판단 +- `tuist generate` 후 `swift run --package-path Tooling/ArchLint Mutate Domain` (모듈 전체 — 테스트를 바꿨으므로 `--changed-since` ❌). + 오래 걸리니 백그라운드로 돌린다. + 테스트가 0개인 모듈은 도구가 "테스트가 없다"로 멈춘다 — 6·7단계는 건너뛰고 그 사실을 보고한다. +- 결과를 **있는 그대로** 보고한다: 잡힘 / 살아남음 / 컴파일 불가. +- **살아남은 버그마다** 무엇이 바뀌었고 사용자에게 어떤 결과가 나는지 한 줄로 설명하고 사람이 고른다: + 테스트 추가 / 결과가 같아 의미 없는 변이 / 규칙 없는 값이라 테스트 안 함. 이유는 PR 본문 재료로 남긴다. +- 테스트를 추가했으면 5단계 검사(`--write-test-specs` 포함)를 다시 통과시키고 `[Test] #이슈 - <무엇을> 확인` 으로 따로 커밋 제안. + +### 8. 마무리 보고 +- 테스트 수 전후, 지운 넘기기 테스트 수, 뮤테이션 잡힘/생존, allow 주석 수, 발견한 규칙 오탐. +- 함정을 새로 알았으면 모듈 `CLAUDE.md`(또는 TESTING.md 주의사항)에 한 줄 누적한다. +- 다음 단계로 `make-PR`을 제안한다(자동 실행 ❌). diff --git a/CLAUDE.md b/CLAUDE.md index f49b319f0..4a6f683fe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -21,8 +21,8 @@ [`Plugins/DependencyPlugin/ProjectDescriptionHelpers/ModuleType.swift`](Plugins/DependencyPlugin/ProjectDescriptionHelpers/ModuleType.swift) 문서/디스크보다 이 파일이 우선. 새 모듈은 여기 먼저 등록한다. - **유령 폴더 주의**: 디스크엔 레지스트리에 없는 폴더(rename·브랜치 전환이 남긴 gitignore된 `.xcodeproj`/`Derived` 잔재)가 남을 수 있다. **레포에 없고 삭제해도 재발**하니 청소 대상이 아니다. **모듈 목록을 `ls`로 추론하지 말고 ModuleType.swift로만 판단**한다(정식은 `XxxDomain`/`XxxData` 형태만). -4. **테스트는 필수**(현재 Domain 레이어 한정). 새 UseCase·Entity·정책은 **테스트 없이 머지하지 않는다.** - 테스트는 "읽히는 기능 명세"로 작성 → 작성 전 [docs/TESTING.md](docs/TESTING.md) 필독. 모듈이 `Project.swift`에 `.tests` 타깃을 선언하면(레이어 무관) develop 대상 PR마다 CI가 자동으로 그 모듈 테스트를 돌린다. +4. **판단하는 코드는 테스트 필수**(현재 Domain 레이어 한정). 분기·검증·계산이 있는 Entity·정책·UseCase는 **테스트 없이 머지하지 않는다.** 저장소 호출을 넘기기만 하는 UseCase는 테스트하지 않는다. + 테스트는 "읽히는 기능 명세"로 작성하고 ArchLint 테스트 규칙(아직 일부 모듈만 — TESTING.md "적용 범위")·뮤테이션 도구로 검증한다 → 작성 전 [docs/TESTING.md](docs/TESTING.md) 필독. 모듈이 `Project.swift`에 `.tests` 타깃을 선언하면(레이어 무관) develop 대상 PR마다 CI가 자동으로 그 모듈 테스트를 돌린다. 5. **외부 의존성 없음 원칙** — 서드파티 라이브러리를 함부로 추가하지 않는다. (예외: `fastlane`(`Gemfile`) — 앱 바이너리에 링크되는 게 아니라 서명·아카이브·배포를 자동화하는 빌드 툴링(Ruby gem)이라 이 원칙이 겨냥하는 "앱 런타임 의존성"과 다른 범주. #231에서 의도적으로 diff --git a/Projects/Domain/AuthDomain/CLAUDE.md b/Projects/Domain/AuthDomain/CLAUDE.md index 8a237f509..c120d3246 100644 --- a/Projects/Domain/AuthDomain/CLAUDE.md +++ b/Projects/Domain/AuthDomain/CLAUDE.md @@ -14,3 +14,4 @@ - ⚠️ **`login`만 `throws(AuthError)`** 를 쓴다 (다른 레이어 표준인 `RepositoryError`가 아님). `AuthError`: `networkUnavailable / invalidCredential / providerUnavailable / invalidData / unknown`. 로그인 외(logout/withdraw/sync)는 `RepositoryError`. - `logout`/`withdraw`는 서버 호출뿐 아니라 **로컬 토큰·개인정보 삭제까지** 책임 (프로토콜 주석 명시). +- UseCase 4개(로그인·로그아웃·탈퇴·Apple 동기화)는 **일부러 테스트가 없다**(#293). 저장소에 넘기기만 해서 이 모듈에서 지킬 규칙이 없고, 토큰 저장·삭제 같은 실제 동작은 AuthData의 몫이다. 테스트를 다시 넣으면 ArchLint `test-passthrough`가 막는다. 그래서 `.testing` 타깃(Mock)도 없앴다 — UseCase에 분기나 조합이 생기면 그때 테스트와 Stub/Mock을 만든다. diff --git a/Projects/Domain/AuthDomain/Project.swift b/Projects/Domain/AuthDomain/Project.swift index 63105b2bf..f455089de 100644 --- a/Projects/Domain/AuthDomain/Project.swift +++ b/Projects/Domain/AuthDomain/Project.swift @@ -11,6 +11,6 @@ import DependencyPlugin let project = Project.createDomainModule( name: ModuleType.domain(.auth).name, - targets: [.sources, .testing, .tests], + targets: [.sources, .tests], internalDependencies: [.module(.domain(.base))] ) diff --git a/Projects/Domain/AuthDomain/TEST_SPEC.md b/Projects/Domain/AuthDomain/TEST_SPEC.md new file mode 100644 index 000000000..e7daa92dd --- /dev/null +++ b/Projects/Domain/AuthDomain/TEST_SPEC.md @@ -0,0 +1,50 @@ +# AuthDomain 테스트 명세 + + + +## 탈퇴 사유 작성 + +`Tests/Entity/WithdrawalReasonDraftTests.swift` + +- 처음에는 '자주 사용하지 않아서' 항목이 골라져 있고, 탈퇴 이유는 비어 있고, 정책에 동의하지 않은 상태다 + +### 항목 고르기 + +- 항목을 고르면 그 항목이 골라진다 + - `WithdrawalReasonOption.inconvenientAndBuggy` + - `.wantToDeleteContent` + - `.noDesiredContent` + - `.custom` + +### 탈퇴 이유 작성 + +- '직접입력' 항목을 고르면 탈퇴 이유를 작성할 수 있다 +- '직접입력'이 아닌 항목에서는 탈퇴 이유를 작성해도 저장되지 않는다 + - `WithdrawalReasonOption.notFrequentlyUsed` + - `.inconvenientAndBuggy` + - `.wantToDeleteContent` + - `.noDesiredContent` +- 탈퇴 이유는 80자까지 그대로 저장된다 +- 탈퇴 이유가 80자를 넘으면 앞 80자만 남는다 +- '직접입력'에서 다른 항목으로 바꾸면 작성한 탈퇴 이유가 지워진다 + - `WithdrawalReasonOption.notFrequentlyUsed` + - `.inconvenientAndBuggy` + - `.wantToDeleteContent` + - `.noDesiredContent` +- '직접입력'을 다시 골라도 작성한 탈퇴 이유는 그대로다 + +### 제출 + +- 정책에 동의하지 않으면 어떤 항목을 골라도 제출할 수 없다 + - `WithdrawalReasonOption.allCases` +- 정책에 동의하면 '직접입력'이 아닌 항목은 바로 제출할 수 있다 + - `WithdrawalReasonOption.notFrequentlyUsed` + - `.inconvenientAndBuggy` + - `.wantToDeleteContent` + - `.noDesiredContent` +- '직접입력'은 탈퇴 이유를 작성하고 정책에 동의하면 제출할 수 있다 +- '직접입력'은 탈퇴 이유가 비었거나 공백뿐이면 정책에 동의해도 제출할 수 없다 + - `""` — 아무것도 쓰지 않음 + - `" "` — 스페이스만 + - `"\n\t "` — 줄바꿈·탭도 공백으로 본다 +- 정책 동의를 취소하면 다시 제출할 수 없다 diff --git a/Projects/Domain/AuthDomain/Testing/Mock/MockAuthRepository.swift b/Projects/Domain/AuthDomain/Testing/Mock/MockAuthRepository.swift deleted file mode 100644 index aa65a17f0..000000000 --- a/Projects/Domain/AuthDomain/Testing/Mock/MockAuthRepository.swift +++ /dev/null @@ -1,59 +0,0 @@ -// -// MockAuthRepository.swift -// AuthDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation - -import AuthDomain -import BaseDomain - -public final class MockAuthRepository: AuthRepository { - - public init() {} - - // login - public var loginResult: Result = .failure(.unknown) - public private(set) var loginCallCount: Int = 0 - public private(set) var loginReceivedCredential: SocialLoginCredential? - - public func login(with credential: SocialLoginCredential) async throws(AuthError) -> NeedOnboarding { - loginCallCount += 1 - loginReceivedCredential = credential - return try loginResult.get() - } - - // logout - public var logoutResult: Result = .success(()) - public private(set) var logoutCallCount: Int = 0 - - public func logout() async throws(RepositoryError) { - logoutCallCount += 1 - _ = try logoutResult.get() - } - - // withdraw - public var withdrawResult: Result = .success(()) - public private(set) var withdrawCallCount: Int = 0 - public private(set) var withdrawReceivedDraft: WithdrawalReasonDraft? - - public func withdraw(draft: WithdrawalReasonDraft) async throws(RepositoryError) { - withdrawCallCount += 1 - withdrawReceivedDraft = draft - _ = try withdrawResult.get() - } - - // syncAppleCredential - public var syncResult: Result = .success(()) - public private(set) var syncCallCount: Int = 0 - public private(set) var syncReceivedCredential: AppleSyncCredential? - - public func syncAppleCredential(_ credential: AppleSyncCredential) async throws(RepositoryError) { - syncCallCount += 1 - syncReceivedCredential = credential - _ = try syncResult.get() - } -} diff --git a/Projects/Domain/AuthDomain/Tests/Entity/WithdrawalReasonDraftTests.swift b/Projects/Domain/AuthDomain/Tests/Entity/WithdrawalReasonDraftTests.swift index 245fd63a0..d80a6fd4d 100644 --- a/Projects/Domain/AuthDomain/Tests/Entity/WithdrawalReasonDraftTests.swift +++ b/Projects/Domain/AuthDomain/Tests/Entity/WithdrawalReasonDraftTests.swift @@ -7,149 +7,200 @@ // import Testing -@testable import AuthDomain -@Suite("WithdrawalReasonDraft") -struct WithdrawalReasonDraftTests { +import AuthDomain - // MARK: - Init +@Suite("탈퇴 사유 작성") +struct WithdrawalReasonDraftTests { - @Test("초안은 기본 옵션과 빈 텍스트로 생성된다") - func initializesWithDefaults() { + @Test("처음에는 '자주 사용하지 않아서' 항목이 골라져 있고, 탈퇴 이유는 비어 있고, 정책에 동의하지 않은 상태다") + func startsWithFirstOptionAndNothingFilled() { let draft = WithdrawalReasonDraft() - #expect(draft.option == (WithdrawalReasonOption.allCases.first ?? .notFrequentlyUsed)) + #expect(draft.option == .notFrequentlyUsed) #expect(draft.customReasonText == "") #expect(draft.policyAgreed == false) - #expect(draft.isSubmittable == false) } - - // MARK: - setOption - - @Test("탈퇴 사유 옵션을 변경 가능하며, 직접 입력 옵션의 경우 이유를 작성할 수 있다") - func canChangeWithdrawalReasonOptionAndEditCustomReasonWhenSelected() { - var draft = WithdrawalReasonDraft() - - for option in WithdrawalReasonOption.allCases { + + @Suite("항목 고르기") + struct SelectingOption { + + @Test( + "항목을 고르면 그 항목이 골라진다", + arguments: [ + WithdrawalReasonOption.inconvenientAndBuggy, + .wantToDeleteContent, + .noDesiredContent, + .custom + ] + ) + func selectingOptionSelectsIt(option: WithdrawalReasonOption) { + var draft = WithdrawalReasonDraft() + draft.setOption(option) + #expect(draft.option == option) } - - draft.setOption(.custom) - draft.setCustomReasonText("어떤 이유") - #expect(draft.customReasonText == "어떤 이유") } - - @Test("직접 입력이 아닌 옵션으로 바꾸면 입력 텍스트는 초기화된다") - func setOptionClearsCustomTextWhenSwitchingToNonCustom() { - var draft = WithdrawalReasonDraft() - let reason = "어떤 이유" - - for option in WithdrawalReasonOption.allCases { + + @Suite("탈퇴 이유 작성") + struct WritingReason { + + @Test("'직접입력' 항목을 고르면 탈퇴 이유를 작성할 수 있다") + func customOptionAcceptsReason() { + var draft = WithdrawalReasonDraft() + draft.setOption(.custom) + + draft.setCustomReasonText("읽을 작품이 줄었어요") + + #expect(draft.customReasonText == "읽을 작품이 줄었어요") + } + + @Test( + "'직접입력'이 아닌 항목에서는 탈퇴 이유를 작성해도 저장되지 않는다", + arguments: [ + WithdrawalReasonOption.notFrequentlyUsed, + .inconvenientAndBuggy, + .wantToDeleteContent, + .noDesiredContent + ] + ) + func nonCustomOptionIgnoresReason(option: WithdrawalReasonOption) { + var draft = WithdrawalReasonDraft() + draft.setOption(option) + + draft.setCustomReasonText("읽을 작품이 줄었어요") + + #expect(draft.customReasonText == "") + } + + @Test("탈퇴 이유는 80자까지 그대로 저장된다") + func keepsReasonUpTo80Characters() { + var draft = WithdrawalReasonDraft() draft.setOption(.custom) + let reason = String(repeating: "가", count: 80) + draft.setCustomReasonText(reason) + #expect(draft.customReasonText == reason) - - draft.setOption(option) - - if case .custom = option { - #expect(draft.customReasonText == reason) - } else { - #expect(draft.customReasonText == "") - } } - } - @Test("직접 입력이 아닌 옵션에서는 이유 작성 함수가 아무 일도 하지 않는다") - func setOtherTextIsNoOpWhenOptionDoesNotRequireText() { - var draft = WithdrawalReasonDraft() - let reason = "저장되면 안 됨" - - for option in WithdrawalReasonOption.allCases { - draft.setOption(option) + @Test("탈퇴 이유가 80자를 넘으면 앞 80자만 남는다") + func cutsReasonOver80Characters() { + var draft = WithdrawalReasonDraft() + draft.setOption(.custom) + // 81번째 글자만 다르게 둬서, 잘려 나간 쪽이 뒤인지 확인한다. + let reason = String(repeating: "가", count: 80) + "나" + draft.setCustomReasonText(reason) - - if case .custom = option { - #expect(draft.customReasonText == reason) - } else { - #expect(draft.customReasonText == "") - } + + #expect(draft.customReasonText == String(repeating: "가", count: 80)) } - } - @Test("직접 입력 옵션의 입력 텍스트가 최대 80자로 잘린다") - func setOtherTextClipsToMaxLengthWhenCustom() { - var draft = WithdrawalReasonDraft() - draft.setOption(.custom) + @Test( + "'직접입력'에서 다른 항목으로 바꾸면 작성한 탈퇴 이유가 지워진다", + arguments: [ + WithdrawalReasonOption.notFrequentlyUsed, + .inconvenientAndBuggy, + .wantToDeleteContent, + .noDesiredContent + ] + ) + func switchingAwayFromCustomClearsReason(option: WithdrawalReasonOption) { + var draft = WithdrawalReasonDraft() + draft.setOption(.custom) + draft.setCustomReasonText("읽을 작품이 줄었어요") - let long = String(repeating: "a", count: WithdrawalReasonDraft.maxCustomReasonLength + 10) - draft.setCustomReasonText(long) + draft.setOption(option) - #expect(draft.customReasonText.count == WithdrawalReasonDraft.maxCustomReasonLength) - } + #expect(draft.customReasonText == "") + } - @Test("직접 입력 옵션에서는 80자 이하면 그대로 저장된다") - func setOtherTextStoresWhenWithinMaxLengthWhenCustom() { - var draft = WithdrawalReasonDraft() - draft.setOption(.custom) + @Test("'직접입력'을 다시 골라도 작성한 탈퇴 이유는 그대로다") + func reselectingCustomKeepsReason() { + var draft = WithdrawalReasonDraft() + draft.setOption(.custom) + draft.setCustomReasonText("읽을 작품이 줄었어요") - let text = "짧은 텍스트" - draft.setCustomReasonText(text) + draft.setOption(.custom) - #expect(draft.customReasonText == text) + #expect(draft.customReasonText == "읽을 작품이 줄었어요") + } } - // MARK: - isSubmittable - - @Test("탈퇴 정책 동의를 하지 않으면 제출 불가능하다") - func isSubmittableIsFalseWhenPolicyDoesNotRequireText() { - var draft = WithdrawalReasonDraft() - draft.setPolicyAgreed(false) - - for option in WithdrawalReasonOption.allCases { + @Suite("제출") + struct Submission { + + @Test( + "정책에 동의하지 않으면 어떤 항목을 골라도 제출할 수 없다", + arguments: WithdrawalReasonOption.allCases + ) + func cannotSubmitWithoutPolicyAgreement(option: WithdrawalReasonOption) { + var draft = WithdrawalReasonDraft() draft.setOption(option) - draft.setCustomReasonText("그냥 이유") - #expect(draft.isSubmittable == false) - } - } + // '직접입력'이 아닌 항목에선 무시된다. 항목마다 정책 동의 말고는 다 채운 상태로 맞추려는 것. + draft.setCustomReasonText("읽을 작품이 줄었어요") + let isSubmittable = draft.isSubmittable + + #expect(isSubmittable == false) + } - @Test("탈퇴 정책 동의를 한 경우, 직접 입력이 아닌 옵션은 텍스트가 없어도 제출 가능하다") - func isSubmittableIsTrueWhenOptionDoesNotRequireText() { - var draft = WithdrawalReasonDraft() - draft.setPolicyAgreed(true) - - for option in WithdrawalReasonOption.allCases { - if case .custom = option { continue } + @Test( + "정책에 동의하면 '직접입력'이 아닌 항목은 바로 제출할 수 있다", + arguments: [ + WithdrawalReasonOption.notFrequentlyUsed, + .inconvenientAndBuggy, + .wantToDeleteContent, + .noDesiredContent + ] + ) + func nonCustomOptionSubmitsWithPolicyAgreement(option: WithdrawalReasonOption) { + var draft = WithdrawalReasonDraft() draft.setOption(option) - draft.setCustomReasonText("") + + draft.setPolicyAgreed(true) + #expect(draft.isSubmittable == true) } - } - @Test("탈퇴 정책 동의를 한 경우, 직접 입력 옵션은 텍스트가 비어있으면 제출할 수 없다") - func isSubmittableIsFalseWhenCustomTextIsEmptyOrWhitespace() { - var draft = WithdrawalReasonDraft() - draft.setPolicyAgreed(true) - draft.setOption(.custom) + @Test("'직접입력'은 탈퇴 이유를 작성하고 정책에 동의하면 제출할 수 있다") + func customOptionSubmitsWithReasonAndPolicyAgreement() { + var draft = WithdrawalReasonDraft() + draft.setOption(.custom) + draft.setCustomReasonText("읽을 작품이 줄었어요") - draft.setCustomReasonText("") - #expect(draft.isSubmittable == false) + draft.setPolicyAgreed(true) - draft.setCustomReasonText(" ") - #expect(draft.isSubmittable == false) + #expect(draft.isSubmittable == true) + } - draft.setCustomReasonText("\n\t ") - #expect(draft.isSubmittable == false) - } + @Test( + "'직접입력'은 탈퇴 이유가 비었거나 공백뿐이면 정책에 동의해도 제출할 수 없다", + arguments: [ + "", // 아무것도 쓰지 않음 + " ", // 스페이스만 + "\n\t " // 줄바꿈·탭도 공백으로 본다 + ] + ) + func customOptionCannotSubmitWithBlankReason(reason: String) { + var draft = WithdrawalReasonDraft() + draft.setOption(.custom) + draft.setCustomReasonText(reason) - @Test("탈퇴 정책 동의를 한 경우, 직접 입력 옵션은 텍스트가 있으면 제출할 수 있다") - func isSubmittableIsTrueWhenCustomTextIsNotEmpty() { - var draft = WithdrawalReasonDraft() - draft.setPolicyAgreed(true) - draft.setOption(.custom) + draft.setPolicyAgreed(true) - draft.setCustomReasonText("원하는 이유를 적었습니다") - #expect(draft.isSubmittable == true) + #expect(draft.isSubmittable == false) + } + + @Test("정책 동의를 취소하면 다시 제출할 수 없다") + func withdrawingPolicyAgreementBlocksSubmit() { + var draft = WithdrawalReasonDraft() + draft.setPolicyAgreed(true) + + draft.setPolicyAgreed(false) + + #expect(draft.isSubmittable == false) + } } } diff --git a/Projects/Domain/AuthDomain/Tests/UseCase/LogoutUseCaseTests.swift b/Projects/Domain/AuthDomain/Tests/UseCase/LogoutUseCaseTests.swift deleted file mode 100644 index 647dc0098..000000000 --- a/Projects/Domain/AuthDomain/Tests/UseCase/LogoutUseCaseTests.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// LogoutUseCaseTests.swift -// AuthDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import AuthDomain -import AuthDomainTesting -import BaseDomain - -@Suite("LogoutUseCase") -struct LogoutUseCaseTests { - - @Test("로그아웃 성공 시 서버 로그아웃 요청 후 로컬 토큰과 사용자 데이터를 제거한다") - func clearsLocalDataAfterLogout() async throws { - let repo = MockAuthRepository() - - repo.logoutResult = .success(()) - - let sut = DefaultLogoutUseCase(authRepository: repo) - - try await sut.execute() - - #expect(repo.logoutCallCount == 1) - } - - @Test("로그아웃 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func doesNotClearLocalDataWhenRepositoryFails() async { - let repo = MockAuthRepository() - - repo.logoutResult = .failure(.serverUnavailable) - - let sut = DefaultLogoutUseCase(authRepository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - try await sut.execute() - } - - #expect(repo.logoutCallCount == 1) - } -} diff --git a/Projects/Domain/AuthDomain/Tests/UseCase/SocialLoginUseCaseTests.swift b/Projects/Domain/AuthDomain/Tests/UseCase/SocialLoginUseCaseTests.swift deleted file mode 100644 index 74435f1ae..000000000 --- a/Projects/Domain/AuthDomain/Tests/UseCase/SocialLoginUseCaseTests.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// SocialLoginUseCaseTests.swift -// AuthDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import AuthDomain -import AuthDomainTesting - -@Suite("SocialLoginUseCase") -struct SocialLoginUseCaseTests { - - @Test("소셜 로그인 성공 시 토큰을 저장하고 온보딩 필요 여부를 반환한다") - func savesSessionAndReturnsNeedOnboarding() async throws { - let repo = MockAuthRepository() - - let session = NeedOnboarding(value: true) - repo.loginResult = .success(session) - - let sut = DefaultSocialLoginUseCase(authRepository: repo) - - let needOnboarding = try await sut.execute(credential: .kakao(accessToken: "kakao_token")) - - #expect(repo.loginCallCount == 1) - #expect(needOnboarding.value == true) - } - - @Test("소셜 로그인 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryErrorForApple() async { - let repo = MockAuthRepository() - - repo.loginResult = .failure(.networkUnavailable) - - let sut = DefaultSocialLoginUseCase(authRepository: repo) - - await #expect(throws: AuthError.networkUnavailable) { - _ = try await sut.execute( - credential: .apple( - authorizationCode: "apple_code", - idToken: "apple_id_token" - ) - ) - } - - #expect(repo.loginCallCount == 1) - } -} diff --git a/Projects/Domain/AuthDomain/Tests/UseCase/SyncAppleCredentialUseCaseTests.swift b/Projects/Domain/AuthDomain/Tests/UseCase/SyncAppleCredentialUseCaseTests.swift deleted file mode 100644 index e7440ca87..000000000 --- a/Projects/Domain/AuthDomain/Tests/UseCase/SyncAppleCredentialUseCaseTests.swift +++ /dev/null @@ -1,47 +0,0 @@ -// -// SyncAppleCredentialUseCaseTests.swift -// AuthDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import AuthDomain -import AuthDomainTesting -import BaseDomain - -@Suite("SyncAppleCredentialUseCase") -struct SyncAppleCredentialUseCaseTests { - - @Test("애플 인증 정보 동기화 요청을 수행한다") - func syncsAppleCredential() async throws { - let repo = MockAuthRepository() - repo.syncResult = .success(()) - - let sut = DefaultSyncAppleCredentialUseCase(repository: repo) - - let cred = AppleSyncCredential(authorizationCode: "code", idToken: "token") - try await sut.execute(credential: cred) - - #expect(repo.syncCallCount == 1) - #expect(repo.syncReceivedCredential == cred) - } - - @Test("애플 인증 정보 동기화 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockAuthRepository() - repo.syncResult = .failure(.invalidData) - - let sut = DefaultSyncAppleCredentialUseCase(repository: repo) - - await #expect(throws: RepositoryError.invalidData) { - try await sut.execute( - credential: AppleSyncCredential(authorizationCode: "bad", idToken: "bad") - ) - } - - #expect(repo.syncCallCount == 1) - } -} diff --git a/Projects/Domain/AuthDomain/Tests/UseCase/WithdrawUseCaseTests.swift b/Projects/Domain/AuthDomain/Tests/UseCase/WithdrawUseCaseTests.swift deleted file mode 100644 index 80ea14bb9..000000000 --- a/Projects/Domain/AuthDomain/Tests/UseCase/WithdrawUseCaseTests.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// WithdrawUseCaseTests.swift -// AuthDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import AuthDomain -import AuthDomainTesting -import BaseDomain - -@Suite("WithdrawUseCase") -struct WithdrawUseCaseTests { - - @Test("회원 탈퇴 시 초안을 전달하여 탈퇴 요청을 수행한다") - func withdrawsWithDraft() async throws { - let repo = MockAuthRepository() - repo.withdrawResult = .success(()) - - let sut = DefaultWithdrawUseCase(repository: repo) - - let draft = WithdrawalReasonDraft() - try await sut.execute(draft: draft) - - #expect(repo.withdrawCallCount == 1) - #expect(repo.withdrawReceivedDraft == draft) - } - - @Test("회원 탈퇴 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockAuthRepository() - repo.withdrawResult = .failure(.networkUnavailable) - - let sut = DefaultWithdrawUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - try await sut.execute(draft: WithdrawalReasonDraft()) - } - - #expect(repo.withdrawCallCount == 1) - } -} diff --git a/Projects/Domain/BaseDomain/CLAUDE.md b/Projects/Domain/BaseDomain/CLAUDE.md index 588601baf..187e127cc 100644 --- a/Projects/Domain/BaseDomain/CLAUDE.md +++ b/Projects/Domain/BaseDomain/CLAUDE.md @@ -68,3 +68,6 @@ fetchKeywords()`를 직접 부르지 말고 이 UseCase를 재사용할 것(재사용하지 않으면 캐시 미스 시 그 UseCase만 재시도 없이 조용히 빈 값으로 폴백한다 — 앱 첫 설치 직후처럼 `syncKeywords()`(fire-and-forget, `App/CLAUDE.md`)가 아직 안 끝난 시점에 실제로 겪은 증상). +- **테스트가 일부러 없는 UseCase**(#293): `LoadPopularKeywordsUseCase`·`OnboardingHintUseCase`는 저장소에 넘기기만 해서 지킬 규칙이 없다 — 다시 넣으면 ArchLint `test-passthrough`가 막는다. 그 테스트만 쓰던 `MockOnboardingHintRepository`도 지웠다. +- **`MockKeywordRepository`는 "동기화했는지"로 답을 바꾼다**(#293) — 조회(`fetchKeywords`·`searchKeywords`)는 호출을 기록하지 않고, 동기화 전엔 `…Result`, 동기화 뒤엔 `…ResultAfterSync`를 돌려준다. 검색은 **검색어마다** 답을 정해 두고(`searchKeywordsResults["회귀"]`), 정해 두지 않은 검색어엔 빈 목록을 준다 — 검색어를 저장소에 제대로 넘기는지가 결과로 드러난다. "캐시 실패 → 동기화 → 다시 조회"는 몇 번 불렀는지가 아니라 **동기화 뒤 값을 받았는지**로 확인한다. 조회 호출 횟수를 다시 세게 만들지 말 것(`test-double-query`). 동기화는 명령이라 `syncKeywordsCallCount`를 센다(BaseDomain·NovelDomain·SplashData 테스트가 쓴다). +- **`ReadingPeriod.init`의 `calendar`**(#293)는 테스트용이다 — 미래 날짜 판정이 일 단위라 기기 시간대에 따라 결과가 갈린다. 앱 코드는 기본값(`.current`)을 쓰고, 테스트는 서울 달력을 넘긴다. diff --git a/Projects/Domain/BaseDomain/Sources/ReadingPeriod.swift b/Projects/Domain/BaseDomain/Sources/ReadingPeriod.swift index 436a1695c..a2f44cfb3 100644 --- a/Projects/Domain/BaseDomain/Sources/ReadingPeriod.swift +++ b/Projects/Domain/BaseDomain/Sources/ReadingPeriod.swift @@ -20,8 +20,13 @@ public struct ReadingPeriod: Equatable, Sendable { /// - 적어도 한쪽은 존재. /// /// `notAfter` 비교는 **일(day) 단위**다. 순간 단위로 비교하면 자정 근처에서 같은 날 날짜가 미래로 오판된다. - public init(start: Date?, end: Date?, notAfter limit: Date = Date()) throws { - let calendar = Calendar.current + /// 날짜를 가르는 기준은 `calendar`(기본 기기 달력)다. 테스트는 시간대를 고정한 달력을 넘긴다. + public init( + start: Date?, + end: Date?, + notAfter limit: Date = Date(), + calendar: Calendar = .current + ) throws { func isAfterLimit(_ date: Date) -> Bool { calendar.compare(date, to: limit, toGranularity: .day) == .orderedDescending } diff --git a/Projects/Domain/BaseDomain/TEST_SPEC.md b/Projects/Domain/BaseDomain/TEST_SPEC.md new file mode 100644 index 000000000..7a77b3a38 --- /dev/null +++ b/Projects/Domain/BaseDomain/TEST_SPEC.md @@ -0,0 +1,164 @@ +# BaseDomain 테스트 명세 + + + +## 매력 포인트 + +`Tests/Entity/AttractivePointTests.swift` + +- 매력 포인트는 디자인이 정한 순서대로 보인다 + +## 작성자 프로필 이동 + +`Tests/Entity/AuthorTests.swift` + +- 작성자를 알면 그 작성자의 프로필로 이동할 수 있다 +- 탈퇴한 작성자의 프로필로는 이동할 수 없다 +- 작성자를 모르면 프로필로 이동할 수 없다 + +## 딥링크 + +`Tests/Entity/DeepLinkTests.swift` + +### 링크 만들기 + +- 컬렉션 상세 링크는 websoso 스킴, collections 주소, id 하나로 만든다 +- 작품·피드·알림 상세는 링크를 만들지 않는다 + - `DeepLink.novelDetail(NovelID(7))` — 푸시로 받기만 한다 + - `.feedDetail(FeedID(7))` — 푸시로 받기만 한다 + - `.notificationDetail(NotificationID(7))` — 푸시로 받기만 한다 +- 컬렉션 상세의 카카오 공유 값에는 컬렉션 id 하나만 담는다 +- 작품·피드·알림 상세는 카카오 공유 값이 비어 있다 + - `DeepLink.novelDetail(NovelID(7))` — 푸시로 받기만 한다 + - `.feedDetail(FeedID(7))` — 푸시로 받기만 한다 + - `.notificationDetail(NotificationID(7))` — 푸시로 받기만 한다 + +### 링크 읽기 + +- 주소가 화면 종류를, 경로의 숫자가 id를 정한다 + - `("websoso://collections/1", DeepLink.collectionDetail(CollectionID(1)))` — 컬렉션 상세. 가장 작은 id도 읽는다 + - `("websoso://novels/22", .novelDetail(NovelID(22)))` — 작품 상세 + - `("websoso://feeds/22", .feedDetail(FeedID(22)))` — 피드 상세 + - `("websoso://notifications/22", .notificationDetail(NotificationID(22)))` — 알림 상세 +- 스킴과 주소는 대소문자를 가리지 않는다 +- websoso가 아닌 스킴은 읽지 않는다 +- 모르는 주소나 주소가 없는 링크는 읽지 않는다 + - `"websoso://comments/22"` — 모르는 주소 + - `"websoso:///22"` — 주소가 없다 +- id가 양의 정수가 아니면 읽지 않는다 + - `"abc"` — 숫자가 아니다 + - `"0"` — 서버가 주는 id는 1부터다 + - `"-1"` — 음수다 +- id가 없거나 경로가 더 붙어 있으면 읽지 않는다 + - `"websoso://collections"` — id가 없다 + - `"websoso://collections/22/extra"` — id 뒤에 경로가 더 있다 + +### 카카오톡 링크 읽기 + +- 카카오톡 링크의 컬렉션 id를 읽어 컬렉션 상세로 간다 +- 카카오톡 링크는 스킴이 무엇이든 읽는다 +- 카카오톡 링크에 컬렉션 id가 없거나 양의 정수가 아니면 읽지 않는다 + - `"kakao1234abcd://kakaolink"` — 컬렉션 id가 없다 + - `"kakao1234abcd://kakaolink?collectionId=abc"` — 숫자가 아니다 + - `"kakao1234abcd://kakaolink?collectionId=0"` — 서버가 주는 id는 1부터다 + - `"kakao1234abcd://kakaolink?collectionId=-1"` — 음수다 + +### 푸시 알림 읽기 + +- 푸시의 화면 종류에 맞는 id로 상세를 연다 + - `(["view": "novelDetail", "novelId": "12345", "feedId": ""], DeepLink.novelDetail(NovelID(12345)))` — 작품 상세. 서버는 다른 id를 빈 값으로 함께 보내기도 한다. + - `(["view": "feedDetail", "feedId": "42", "novelId": ""], .feedDetail(FeedID(42)))` — 피드 상세 + - `(["view": "notificationDetail", "notificationId": "3853"], .notificationDetail(NotificationID(3853)))` — 알림 상세(공지). 실제 공지 푸시는 알림 id만 있고 작품 id 키는 없다(#243). +- 모르는 화면 종류이거나 화면 종류가 없으면 읽지 않는다 + - `["view": "commentDetail", "novelId": "7"]` — 모르는 화면 종류 + - `["novelId": "7"]` — 화면 종류가 없다 +- 화면 종류에 맞는 id가 없거나 양의 정수가 아니면 읽지 않는다 + - `["view": "notificationDetail", "novelId": "7"]` — 화면 종류와 다른 id만 있다 + - `["view": "novelDetail", "novelId": ""]` — id가 비었다 + - `["view": "novelDetail", "novelId": "abc"]` — 숫자가 아니다 + - `["view": "novelDetail", "novelId": "0"]` — 서버가 주는 id는 1부터다 + - `["view": "novelDetail", "novelId": "-1"]` — 음수다 + +## 작품 관심 등록 + +`Tests/Entity/NovelTests.swift` + +- 관심 작품으로 등록하면 관심 수가 하나 늘어난다 +- 이미 관심 작품이면 다시 등록해도 그대로다 +- 관심 여부를 모르는 작품은 관심 작품으로 등록하지 않는다 +- 관심을 해제하면 관심 수가 하나 줄어든다 +- 관심 작품이 아니면 해제해도 그대로다 +- 관심 수가 0이면 해제해도 0 아래로 내려가지 않는다 +- 관심 작품에서 관심을 전환하면 해제된다 +- 관심 작품이 아닐 때 관심을 전환하면 등록된다 + +## 평점 + +`Tests/Entity/RatingTests.swift` + +- 0.5부터 5.0까지 0.5점 단위면 평점이 된다 + - `0.5` — 가장 낮은 평점 + - `2.5` — 0.5점이 붙은 평점 + - `3.0` — 중간의 정수 평점 + - `5.0` — 가장 높은 평점 +- 범위 밖이면 평점이 아니다 + - `0.0` — 가장 낮은 평점보다 0.5점 작다 + - `5.5` — 가장 높은 평점보다 0.5점 크다 +- 0.5점 단위가 아니면 평점이 아니다 + - `4.7` — 소수 첫째 자리가 0.5점 단위가 아니다 + - `1.25` — 0.5점보다 잘게 나눴다 + +## 독서 기간 + +`Tests/Entity/ReadingPeriodTests.swift` + +### 만들기 + +- 시작일이나 종료일 하나만 있어도 기간이 된다 + - `(yesterday, nil)` — 시작일만 있다 + - `(nil, yesterday)` — 종료일만 있다 +- 같은 날이어도 기간이 된다 +- 둘 다 없으면 기간이 아니다 +- 시작일이 종료일보다 늦으면 기간이 아니다 +- 오늘 이후 날짜는 넣을 수 없다 + - `(tomorrow, nil)` — 시작일이 내일이다 + - `(nil, tomorrow)` — 종료일이 내일이다 +- 오늘 날짜면 시각이 기준보다 늦어도 넣을 수 있다 + +### 독서 상태에 맞추기 + +- 읽는 중이면 시작일만 남긴다 +- 읽는 중인데 종료일만 있으면 그 날을 시작일로 옮긴다 +- 다 읽음이면 빈 쪽을 채운다 +- 다 읽음인데 종료일만 있으면 그 날로 시작일을 채운다 +- 하차면 종료일만 남긴다 +- 하차인데 시작일만 있으면 그 날을 종료일로 옮긴다 + +## 앱 리뷰 요청 + +`Tests/UseCase/AppReviewRequestUseCaseTests.swift` + +- 참여가 2번뿐이면 리뷰를 요청하지 않는다 +- 참여가 3번이 되면 리뷰를 요청한다 +- 이번 버전에 이미 리뷰를 요청했으면 다시 요청하지 않는다 +- 리뷰를 요청했다고 기록하면 이번 버전에서는 다시 요청하지 않는다 +- 버전이 바뀌면 지난 버전의 참여는 세지 않는다 +- 버전이 바뀐 뒤 참여를 기록하면 처음부터 다시 센다 +- 새 버전에서 다시 3번 참여하면 지난 버전에 요청했어도 다시 요청한다 + +## 전체 키워드 불러오기 + +`Tests/UseCase/LoadTotalKeywordsUseCaseTests.swift` + +- 처음 불러오기에 성공하면 동기화하지 않는다 +- 불러오기에 실패하면 동기화한 뒤 다시 불러온 결과를 준다 +- 동기화한 뒤에도 실패하면 그 에러를 전한다 + +## 키워드 검색 + +`Tests/UseCase/SearchKeywordsUseCaseTests.swift` + +- 처음 검색에 성공하면 동기화하지 않는다 +- 검색에 실패하면 동기화한 뒤 다시 검색한 결과를 준다 +- 동기화한 뒤에도 실패하면 그 에러를 전한다 +- 묶음별 검색 결과를 키워드 목록 하나로 펼친다 diff --git a/Projects/Domain/BaseDomain/Testing/Mock/MockKeywordRepository.swift b/Projects/Domain/BaseDomain/Testing/Mock/MockKeywordRepository.swift index 8c03b71ff..367562404 100644 --- a/Projects/Domain/BaseDomain/Testing/Mock/MockKeywordRepository.swift +++ b/Projects/Domain/BaseDomain/Testing/Mock/MockKeywordRepository.swift @@ -10,54 +10,31 @@ import Foundation import BaseDomain +/// 키워드 저장소 가짜 객체. +/// 조회(`fetchKeywords`·`searchKeywords`·`fetchPopularKeywords`)는 정해 둔 값만 돌려주고 호출을 기록하지 않는다(Stub). +/// 검색은 **검색어마다** 답을 정해 둔다 — 정해 두지 않은 검색어엔 빈 목록을 준다. 그래서 검색어를 잘못 넘기면 결과가 달라진다. +/// 실제 저장소처럼 **동기화했는지에 따라** 답이 바뀐다 — 동기화 전엔 `…Result`, 동기화 뒤엔 `…ResultAfterSync`(없으면 `…Result`). +/// 동기화(`syncKeywords`)는 명령이라 호출 횟수를 기록한다(Mock). public final class MockKeywordRepository: KeywordRepository { public var fetchKeywordsResult: Result<[KeywordGroup], RepositoryError> = .success([]) - /// 설정하면 `fetchKeywords()` 호출마다 순서대로 하나씩 소비한다(마지막 값은 이후 호출에 계속 반환). - /// 캐시 미스 → 동기화 → 재조회처럼 호출마다 결과가 달라야 하는 시나리오 검증용. 미설정 시 `fetchKeywordsResult`를 매번 사용. - public var fetchKeywordsResults: [Result<[KeywordGroup], RepositoryError>]? - public var searchKeywordsResult: Result<[KeywordGroup], RepositoryError> = .success([]) - /// 설정하면 `searchKeywords(_:)` 호출마다 순서대로 하나씩 소비한다(마지막 값은 이후 호출에 계속 반환). - /// 캐시 미스 → 동기화 → 재조회처럼 호출마다 결과가 달라야 하는 시나리오 검증용. 미설정 시 `searchKeywordsResult`를 매번 사용. - public var searchKeywordsResults: [Result<[KeywordGroup], RepositoryError>]? + public var fetchKeywordsResultAfterSync: Result<[KeywordGroup], RepositoryError>? + public var searchKeywordsResults: [String: Result<[KeywordGroup], RepositoryError>] = [:] + public var searchKeywordsResultsAfterSync: [String: Result<[KeywordGroup], RepositoryError>] = [:] public var fetchPopularKeywordsResult: Result = .success(PopularKeywords(keywords: [])) - public private(set) var fetchKeywordsCallCount = 0 public private(set) var syncKeywordsCallCount = 0 - public private(set) var searchKeywordsCallCount = 0 - public private(set) var searchedQueries: [String] = [] - public private(set) var fetchPopularKeywordsCallCount = 0 public init() {} public func fetchKeywords() async throws(RepositoryError) -> [KeywordGroup] { - fetchKeywordsCallCount += 1 - let result: Result<[KeywordGroup], RepositoryError> - if let sequence = fetchKeywordsResults, !sequence.isEmpty { - let index = min(fetchKeywordsCallCount, sequence.count) - 1 - result = sequence[index] - } else { - result = fetchKeywordsResult - } - switch result { - case .success(let value): return value - case .failure(let error): throw error - } + try Self.value(of: currentResult(before: fetchKeywordsResult, after: fetchKeywordsResultAfterSync)) } public func searchKeywords(_ query: String) async throws(RepositoryError) -> [KeywordGroup] { - searchedQueries.append(query) - searchKeywordsCallCount += 1 - let result: Result<[KeywordGroup], RepositoryError> - if let sequence = searchKeywordsResults, !sequence.isEmpty { - let index = min(searchKeywordsCallCount, sequence.count) - 1 - result = sequence[index] - } else { - result = searchKeywordsResult - } - switch result { - case .success(let value): return value - case .failure(let error): throw error - } + try Self.value(of: currentResult( + before: searchKeywordsResults[query] ?? .success([]), + after: searchKeywordsResultsAfterSync[query] + )) } public func syncKeywords() async { @@ -65,8 +42,19 @@ public final class MockKeywordRepository: KeywordRepository { } public func fetchPopularKeywords() async throws(RepositoryError) -> PopularKeywords { - fetchPopularKeywordsCallCount += 1 - switch fetchPopularKeywordsResult { + try Self.value(of: fetchPopularKeywordsResult) + } + + private func currentResult( + before: Result, + after: Result? + ) -> Result { + guard syncKeywordsCallCount > 0, let after else { return before } + return after + } + + private static func value(of result: Result) throws(RepositoryError) -> Value { + switch result { case .success(let value): return value case .failure(let error): throw error } diff --git a/Projects/Domain/BaseDomain/Testing/Mock/MockOnboardingHintRepository.swift b/Projects/Domain/BaseDomain/Testing/Mock/MockOnboardingHintRepository.swift deleted file mode 100644 index b7199013f..000000000 --- a/Projects/Domain/BaseDomain/Testing/Mock/MockOnboardingHintRepository.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// MockOnboardingHintRepository.swift -// BaseDomain -// -// Created by YunhakLee on 8/31/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation - -import BaseDomain - -/// 테스트용 인메모리 온보딩 힌트 저장소. 초기 "봤음" 집합을 주입할 수 있고, `markSeen` 호출 이력을 노출한다. -public final class MockOnboardingHintRepository: OnboardingHintRepository { - - public var seenHints: Set - public private(set) var markSeenCalls: [OnboardingHint] = [] - - public init(seenHints: Set = []) { - self.seenHints = seenHints - } - - public func hasSeen(_ hint: OnboardingHint) -> Bool { - seenHints.contains(hint) - } - - public func markSeen(_ hint: OnboardingHint) { - markSeenCalls.append(hint) - seenHints.insert(hint) - } -} diff --git a/Projects/Domain/BaseDomain/Tests/Entity/AttractivePointTests.swift b/Projects/Domain/BaseDomain/Tests/Entity/AttractivePointTests.swift index 8f3fc0a08..f1483fe49 100644 --- a/Projects/Domain/BaseDomain/Tests/Entity/AttractivePointTests.swift +++ b/Projects/Domain/BaseDomain/Tests/Entity/AttractivePointTests.swift @@ -8,20 +8,18 @@ import Testing -@testable import BaseDomain +import BaseDomain -@Suite +@Suite("매력 포인트") struct AttractivePointTests { - // MARK: - 표시 순서 계약 + @Test("매력 포인트는 디자인이 정한 순서대로 보인다") + func followsDesignOrder() { + // 작품 평가·서재 필터·서재 목록 셀이 따로 정한 순서 없이 선언 순서를 그대로 쓴다(#256). + // 선언 순서를 바꾸면 컴파일도 다른 테스트도 통과한 채 세 화면의 순서가 한꺼번에 바뀐다. + let order = AttractivePoint.allCases - @Test("케이스 선언 순서가 곧 화면 표시 순서다 — 필력이 3번째(디자인 정본, #256)") - func allCasesFollowDesignOrder() { - // 작품 평가·서재 필터·서재 리스트 셀이 별도 순서 배열 없이 allCases 순서를 그대로 공유한다 - // (#256에서 WSSComponent의 displayOrder 배열을 지우고 enum 선언 순서를 유일한 정본으로 승격). - // 케이스를 재정렬하거나 추가하면 컴파일·기존 테스트 모두 초록인 채 세 화면의 순서가 통째로 - // 바뀌므로, 이 테스트가 그 계약을 고정한다 — 순서를 바꾸려면 디자인 확정과 함께 여기도 갱신할 것. - #expect(AttractivePoint.allCases == [ + #expect(order == [ .worldview, .material, .writingSkill, diff --git a/Projects/Domain/BaseDomain/Tests/Entity/AuthorTests.swift b/Projects/Domain/BaseDomain/Tests/Entity/AuthorTests.swift index a62194875..7835ff22d 100644 --- a/Projects/Domain/BaseDomain/Tests/Entity/AuthorTests.swift +++ b/Projects/Domain/BaseDomain/Tests/Entity/AuthorTests.swift @@ -5,39 +5,39 @@ // Copyright © 2026 kr.websoso.app. All rights reserved. // +import Foundation import Testing -@testable import BaseDomain +import BaseDomain -@Suite +@Suite("작성자 프로필 이동") struct AuthorTests { - // MARK: - accessibleUserId + @Test("작성자를 알면 그 작성자의 프로필로 이동할 수 있다") + func knownAuthorIsReachable() { + let author = makeAuthor(userId: UserID(1003)) - @Test("userId가 정상 값이면 accessibleUserId가 그 값을 그대로 반환한다") - func accessibleUserIdReturnsValue() { - let author = makeAuthor(userId: UserID(42)) - - #expect(author.accessibleUserId == UserID(42)) + #expect(author.accessibleUserId == UserID(1003)) } - @Test("userId가 탈퇴 유저 센티널(-1)이면 accessibleUserId가 nil이다") - func accessibleUserIdNilWhenWithdrawn() { + @Test("탈퇴한 작성자의 프로필로는 이동할 수 없다") + func withdrawnAuthorIsNotReachable() { + // 서버는 탈퇴한 작성자를 -1로 보낸다. let author = makeAuthor(userId: UserID(-1)) #expect(author.accessibleUserId == nil) } - @Test("userId가 nil이면 accessibleUserId가 nil이다") - func accessibleUserIdNilWhenMissing() { + @Test("작성자를 모르면 프로필로 이동할 수 없다") + func unknownAuthorIsNotReachable() { let author = makeAuthor(userId: nil) #expect(author.accessibleUserId == nil) } -} -private extension AuthorTests { - func makeAuthor(userId: UserID?) -> Author { - Author(userId: userId, nickname: "닉네임", profileImage: nil) + // MARK: - Helpers + + private func makeAuthor(userId: UserID?) -> Author { + Author(userId: userId, nickname: "소소", profileImage: nil) } } diff --git a/Projects/Domain/BaseDomain/Tests/Entity/DeepLinkTests.swift b/Projects/Domain/BaseDomain/Tests/Entity/DeepLinkTests.swift index 28e6fb447..c8e859446 100644 --- a/Projects/Domain/BaseDomain/Tests/Entity/DeepLinkTests.swift +++ b/Projects/Domain/BaseDomain/Tests/Entity/DeepLinkTests.swift @@ -8,242 +8,217 @@ import Foundation import Testing -@testable import BaseDomain +import BaseDomain -@Suite +@Suite("딥링크") struct DeepLinkTests { - // MARK: - url - - // ⚠️ 설명에 `://`·`/`를 넣지 않는다 — 테스트 리포터가 `/`를 스위트 구분자로 오인해 이름이 쪼개진다(실측). - @Test("컬렉션 상세 딥링크의 url은 websoso 스킴, collections host, 그 뒤 id 하나로 이뤄진다") - func collectionDetailURLFormat() { - let deepLink = DeepLink.collectionDetail(CollectionID(31)) - - #expect(deepLink.url?.absoluteString == "websoso://collections/31") - } - - // MARK: - init(url:) - - @Test("websoso 스킴에 collections host와 정수 id가 붙은 URL을 파싱하면 그 id의 컬렉션 상세 딥링크가 된다") - func parseCollectionDetail() { - let url = makeURL("websoso://collections/31") - - #expect(DeepLink(url: url) == .collectionDetail(CollectionID(31))) - } - - @Test("딥링크가 만든 url을 다시 파싱하면 원래 딥링크와 같다") - func roundTrip() throws { - let original = DeepLink.collectionDetail(CollectionID(7)) - - let url = try #require(original.url) - - #expect(DeepLink(url: url) == original) - } - - @Test("스킴과 host는 대소문자를 가리지 않는다") - func parseIsCaseInsensitive() { - let url = makeURL("WEBSOSO://Collections/31") - - #expect(DeepLink(url: url) == .collectionDetail(CollectionID(31))) - } - - @Test("websoso 스킴이 아니면 nil이다") - func nilWhenSchemeDiffers() { - let url = makeURL("https://collections/31") - - #expect(DeepLink(url: url) == nil) - } - - @Test("모르는 host면 nil이다") - func nilWhenHostUnknown() { - let url = makeURL("websoso://comments/31") - - #expect(DeepLink(url: url) == nil) - } - - @Test("id가 정수가 아니면 nil이다") - func nilWhenIDNotInteger() { - let url = makeURL("websoso://collections/abc") - - #expect(DeepLink(url: url) == nil) - } - - @Test("id가 없으면 nil이다") - func nilWhenIDMissing() { - let url = makeURL("websoso://collections") - - #expect(DeepLink(url: url) == nil) - } - - @Test("id 뒤에 경로가 더 붙어 있으면 nil이다") - func nilWhenExtraPath() { - let url = makeURL("websoso://collections/31/extra") - - #expect(DeepLink(url: url) == nil) - } - - @Test("id가 0이거나 음수면 nil이다 — 서버 발급 ID는 양수뿐이다", arguments: ["0", "-1"]) - func nilWhenIDNotPositive(rawID: String) { - let url = makeURL("websoso://collections/\(rawID)") - - #expect(DeepLink(url: url) == nil) - } - - @Test("host가 없으면 nil이다") - func nilWhenHostEmpty() { - let url = makeURL("websoso:///31") - - #expect(DeepLink(url: url) == nil) - } - - // MARK: - kakaoExecutionParameters (카카오톡 공유 카드) - - @Test("컬렉션 상세 딥링크의 카카오 execution params는 collectionId 키에 id 문자열 하나다") - func kakaoExecutionParametersFormat() { - let deepLink = DeepLink.collectionDetail(CollectionID(31)) - - #expect(deepLink.kakaoExecutionParameters == ["collectionId": "31"]) - } - - @Test("카카오톡이 여는 kakaolink host URL의 collectionId 쿼리를 파싱하면 그 id의 컬렉션 상세 딥링크가 된다") - func parseKakaoLink() { - let url = makeURL("kakaoabc123://kakaolink?collectionId=31") - - #expect(DeepLink(url: url) == .collectionDetail(CollectionID(31))) - } - - @Test("카카오 execution params를 kakaolink URL 쿼리로 되돌려 파싱하면 원래 딥링크와 같다") - func kakaoRoundTrip() throws { - let original = DeepLink.collectionDetail(CollectionID(7)) - var components = try #require(URLComponents(string: "kakaoabc123://kakaolink")) - components.queryItems = original.kakaoExecutionParameters.map { URLQueryItem(name: $0.key, value: $0.value) } - - let url = try #require(components.url) - - #expect(DeepLink(url: url) == original) - } - - @Test("kakaolink host는 스킴이 무엇이든 파싱한다") - func parseKakaoLinkIgnoresScheme() { - let url = makeURL("KAKAOXYZ://KakaoLink?collectionId=31") - - #expect(DeepLink(url: url) == .collectionDetail(CollectionID(31))) - } - - @Test("kakaolink host인데 collectionId 쿼리가 없으면 nil이다") - func nilWhenKakaoLinkMissingCollectionID() { - let url = makeURL("kakaoabc123://kakaolink?novelId=31") - - #expect(DeepLink(url: url) == nil) - } - - @Test("kakaolink host의 collectionId가 정수가 아니면 nil이다") - func nilWhenKakaoLinkCollectionIDNotInteger() { - let url = makeURL("kakaoabc123://kakaolink?collectionId=abc") - - #expect(DeepLink(url: url) == nil) - } - - @Test("kakaolink host의 collectionId가 0이거나 음수면 nil이다", arguments: ["0", "-1"]) - func nilWhenKakaoLinkCollectionIDNotPositive(rawID: String) { - let url = makeURL("kakaoabc123://kakaolink?collectionId=\(rawID)") - - #expect(DeepLink(url: url) == nil) - } - - // MARK: - 작품·피드 상세 딥링크 init(url:) (#243) - - @Test("websoso 스킴에 novels host와 정수 id가 붙은 URL을 파싱하면 그 id의 작품 상세 딥링크가 된다") - func parseNovelDetail() { - let url = makeURL("websoso://novels/12345") - - #expect(DeepLink(url: url) == .novelDetail(NovelID(12345))) - } - - @Test("websoso 스킴에 feeds host와 정수 id가 붙은 URL을 파싱하면 그 id의 피드 상세 딥링크가 된다") - func parseFeedDetail() { - let url = makeURL("websoso://feeds/67890") - - #expect(DeepLink(url: url) == .feedDetail(FeedID(67890))) - } - - @Test("novels host의 id가 0이거나 음수면 nil이다", arguments: ["0", "-1"]) - func nilWhenNovelIDNotPositive(rawID: String) { - let url = makeURL("websoso://novels/\(rawID)") - - #expect(DeepLink(url: url) == nil) - } - - @Test("websoso 스킴에 notifications host와 정수 id가 붙은 URL을 파싱하면 그 id의 알림 상세 딥링크가 된다") - func parseNotificationDetail() { - let url = makeURL("websoso://notifications/3853") - - #expect(DeepLink(url: url) == .notificationDetail(NotificationID(3853))) - } - - @Test("notifications host의 id가 0이거나 음수면 nil이다", arguments: ["0", "-1"]) - func nilWhenNotificationIDNotPositive(rawID: String) { - let url = makeURL("websoso://notifications/\(rawID)") - - #expect(DeepLink(url: url) == nil) - } - - @Test("작품·피드·알림 상세 딥링크는 outbound url을 만들지 않는다 — 푸시로 받기만 한다") - func novelAndFeedHaveNoOutboundURL() { - #expect(DeepLink.novelDetail(NovelID(1)).url == nil) - #expect(DeepLink.feedDetail(FeedID(1)).url == nil) - #expect(DeepLink.notificationDetail(NotificationID(1)).url == nil) - } - - // MARK: - 푸시 payload 파싱 fromNotificationPayload (#243) - - @Test("view가 novelDetail이고 novelId가 있으면 그 작품 상세 딥링크가 된다") - func parsePayloadNovelDetail() { - let payload = ["view": "novelDetail", "novelId": "12345", "feedId": "", "notificationId": "67890"] - - #expect(DeepLink.fromNotificationPayload(payload) == .novelDetail(NovelID(12345))) - } - - @Test("view가 feedDetail이고 feedId가 있으면 그 피드 상세 딥링크가 된다") - func parsePayloadFeedDetail() { - let payload = ["view": "feedDetail", "feedId": "42", "novelId": ""] - - #expect(DeepLink.fromNotificationPayload(payload) == .feedDetail(FeedID(42))) - } - - // 공지 push 실측 형태(#243): view=notificationDetail + notificationId만 채워지고 novelId 키는 없다. - @Test("view가 notificationDetail이고 notificationId가 있으면 그 알림 상세 딥링크가 된다") - func parsePayloadNotificationDetail() { - let payload = ["view": "notificationDetail", "notificationId": "3853", "feedId": ""] - - #expect(DeepLink.fromNotificationPayload(payload) == .notificationDetail(NotificationID(3853))) - } - - @Test("모르는 view면 nil이다") - func nilWhenPayloadViewUnknown() { - let payload = ["view": "commentDetail", "notificationId": "1"] - - #expect(DeepLink.fromNotificationPayload(payload) == nil) - } - - @Test("view는 맞지만 해당 id가 비었거나 정수가 아니면 nil이다", arguments: ["", "abc", "0", "-1"]) - func nilWhenPayloadIDInvalid(rawID: String) { - let payload = ["view": "novelDetail", "novelId": rawID] - - #expect(DeepLink.fromNotificationPayload(payload) == nil) - } - - @Test("view 키가 없으면 nil이다") - func nilWhenPayloadViewMissing() { - let payload = ["novelId": "12345"] - - #expect(DeepLink.fromNotificationPayload(payload) == nil) + @Suite("링크 만들기") + struct MakingLink { + + @Test("컬렉션 상세 링크는 websoso 스킴, collections 주소, id 하나로 만든다") + func collectionDetailMakesURL() { + let link = DeepLink.collectionDetail(CollectionID(22)) + + #expect(link.url == URL(string: "websoso://collections/22")) + } + + @Test( + "작품·피드·알림 상세는 링크를 만들지 않는다", + arguments: [ + DeepLink.novelDetail(NovelID(7)), // 푸시로 받기만 한다 + .feedDetail(FeedID(7)), // 푸시로 받기만 한다 + .notificationDetail(NotificationID(7)) // 푸시로 받기만 한다 + ] + ) + func pushOnlyLinksMakeNoURL(link: DeepLink) { + let url = link.url + + #expect(url == nil) + } + + @Test("컬렉션 상세의 카카오 공유 값에는 컬렉션 id 하나만 담는다") + func collectionDetailMakesKakaoParameters() { + let link = DeepLink.collectionDetail(CollectionID(22)) + + #expect(link.kakaoExecutionParameters == ["collectionId": "22"]) + } + + @Test( + "작품·피드·알림 상세는 카카오 공유 값이 비어 있다", + arguments: [ + DeepLink.novelDetail(NovelID(7)), // 푸시로 받기만 한다 + .feedDetail(FeedID(7)), // 푸시로 받기만 한다 + .notificationDetail(NotificationID(7)) // 푸시로 받기만 한다 + ] + ) + func pushOnlyLinksMakeNoKakaoParameters(link: DeepLink) { + let parameters = link.kakaoExecutionParameters + + #expect(parameters.isEmpty) + } + } + + @Suite("링크 읽기") + struct ReadingURL { + + @Test( + "주소가 화면 종류를, 경로의 숫자가 id를 정한다", + arguments: [ + ("websoso://collections/1", DeepLink.collectionDetail(CollectionID(1))), // 컬렉션 상세. 가장 작은 id도 읽는다 + ("websoso://novels/22", .novelDetail(NovelID(22))), // 작품 상세 + ("websoso://feeds/22", .feedDetail(FeedID(22))), // 피드 상세 + ("websoso://notifications/22", .notificationDetail(NotificationID(22))) // 알림 상세 + ] + ) + func hostAndPathDecideLink(rawURL: String, expected: DeepLink) { + let link = DeepLink(url: makeURL(rawURL)) + + #expect(link == expected) + } + + @Test("스킴과 주소는 대소문자를 가리지 않는다") + func schemeAndHostIgnoreCase() { + let link = DeepLink(url: makeURL("WEBSOSO://Collections/22")) + + #expect(link == .collectionDetail(CollectionID(22))) + } + + @Test("websoso가 아닌 스킴은 읽지 않는다") + func otherSchemeIsIgnored() { + let link = DeepLink(url: makeURL("https://collections/22")) + + #expect(link == nil) + } + + @Test( + "모르는 주소나 주소가 없는 링크는 읽지 않는다", + arguments: [ + "websoso://comments/22", // 모르는 주소 + "websoso:///22" // 주소가 없다 + ] + ) + func unknownOrMissingHostIsIgnored(rawURL: String) { + let link = DeepLink(url: makeURL(rawURL)) + + #expect(link == nil) + } + + @Test( + "id가 양의 정수가 아니면 읽지 않는다", + arguments: [ + "abc", // 숫자가 아니다 + "0", // 서버가 주는 id는 1부터다 + "-1" // 음수다 + ] + ) + func nonPositiveIDIsIgnored(rawID: String) { + let link = DeepLink(url: makeURL("websoso://collections/\(rawID)")) + + #expect(link == nil) + } + + @Test( + "id가 없거나 경로가 더 붙어 있으면 읽지 않는다", + arguments: [ + "websoso://collections", // id가 없다 + "websoso://collections/22/extra" // id 뒤에 경로가 더 있다 + ] + ) + func missingIDOrExtraPathIsIgnored(rawURL: String) { + let link = DeepLink(url: makeURL(rawURL)) + + #expect(link == nil) + } + } + + @Suite("카카오톡 링크 읽기") + struct ReadingKakaoLink { + + @Test("카카오톡 링크의 컬렉션 id를 읽어 컬렉션 상세로 간다") + func kakaoLinkOpensCollection() { + let link = DeepLink(url: makeURL("kakao1234abcd://kakaolink?collectionId=22")) + + #expect(link == .collectionDetail(CollectionID(22))) + } + + @Test("카카오톡 링크는 스킴이 무엇이든 읽는다") + func kakaoLinkIgnoresScheme() { + // 스킴의 앱 키는 앱 설정에만 있어 이 모듈은 모른다. 등록된 스킴만 앱에 오므로 검사하지 않는다. + let link = DeepLink(url: makeURL("anything://kakaolink?collectionId=22")) + + #expect(link == .collectionDetail(CollectionID(22))) + } + + @Test( + "카카오톡 링크에 컬렉션 id가 없거나 양의 정수가 아니면 읽지 않는다", + arguments: [ + "kakao1234abcd://kakaolink", // 컬렉션 id가 없다 + "kakao1234abcd://kakaolink?collectionId=abc", // 숫자가 아니다 + "kakao1234abcd://kakaolink?collectionId=0", // 서버가 주는 id는 1부터다 + "kakao1234abcd://kakaolink?collectionId=-1" // 음수다 + ] + ) + func kakaoLinkWithoutValidIDIsIgnored(rawURL: String) { + let link = DeepLink(url: makeURL(rawURL)) + + #expect(link == nil) + } + } + + @Suite("푸시 알림 읽기") + struct ReadingPush { + + @Test( + "푸시의 화면 종류에 맞는 id로 상세를 연다", + arguments: [ + // 작품 상세. 서버는 다른 id를 빈 값으로 함께 보내기도 한다. + (["view": "novelDetail", "novelId": "12345", "feedId": ""], DeepLink.novelDetail(NovelID(12345))), + // 피드 상세 + (["view": "feedDetail", "feedId": "42", "novelId": ""], .feedDetail(FeedID(42))), + // 알림 상세(공지). 실제 공지 푸시는 알림 id만 있고 작품 id 키는 없다(#243). + (["view": "notificationDetail", "notificationId": "3853"], .notificationDetail(NotificationID(3853))) + ] + ) + func pushOpensDetailForView(payload: [String: String], expected: DeepLink) { + let link = DeepLink.fromNotificationPayload(payload) + + #expect(link == expected) + } + + @Test( + "모르는 화면 종류이거나 화면 종류가 없으면 읽지 않는다", + arguments: [ + ["view": "commentDetail", "novelId": "7"], // 모르는 화면 종류 + ["novelId": "7"] // 화면 종류가 없다 + ] + ) + func unknownOrMissingViewIsIgnored(payload: [String: String]) { + let link = DeepLink.fromNotificationPayload(payload) + + #expect(link == nil) + } + + @Test( + "화면 종류에 맞는 id가 없거나 양의 정수가 아니면 읽지 않는다", + arguments: [ + ["view": "notificationDetail", "novelId": "7"], // 화면 종류와 다른 id만 있다 + ["view": "novelDetail", "novelId": ""], // id가 비었다 + ["view": "novelDetail", "novelId": "abc"], // 숫자가 아니다 + ["view": "novelDetail", "novelId": "0"], // 서버가 주는 id는 1부터다 + ["view": "novelDetail", "novelId": "-1"] // 음수다 + ] + ) + func pushWithoutValidIDIsIgnored(payload: [String: String]) { + let link = DeepLink.fromNotificationPayload(payload) + + #expect(link == nil) + } } } -private extension DeepLinkTests { - func makeURL(_ string: String) -> URL { - URL(string: string)! - } +// MARK: - Helpers + +private func makeURL(_ raw: String) -> URL { + URL(string: raw)! } diff --git a/Projects/Domain/BaseDomain/Tests/Entity/NovelTests.swift b/Projects/Domain/BaseDomain/Tests/Entity/NovelTests.swift index dab488ede..d6dc9662d 100644 --- a/Projects/Domain/BaseDomain/Tests/Entity/NovelTests.swift +++ b/Projects/Domain/BaseDomain/Tests/Entity/NovelTests.swift @@ -6,17 +6,18 @@ // Copyright © 2026 kr.websoso.app. All rights reserved. // +import Foundation import Testing -@testable import BaseDomain +import BaseDomain -@Suite +@Suite("작품 관심 등록") struct NovelTests { - // MARK: - markAsInterested + // MARK: - 등록 - @Test("관심 없는 작품을 관심 작품으로 등록하면 isInterested가 true가 되고 관심 수가 증가한다") - func markAsInterestedFromFalse() { + @Test("관심 작품으로 등록하면 관심 수가 하나 늘어난다") + func markingAddsInterest() { var novel = makeNovel(isInterested: false, interestCount: 10) novel.markAsInterested() @@ -25,8 +26,8 @@ struct NovelTests { #expect(novel.interestCount == 11) } - @Test("이미 관심 등록된 작품에 markAsInterested를 호출하면 상태가 변하지 않는다") - func markAsInterestedWhenAlreadyInterested() { + @Test("이미 관심 작품이면 다시 등록해도 그대로다") + func markingAgainChangesNothing() { var novel = makeNovel(isInterested: true, interestCount: 10) novel.markAsInterested() @@ -35,8 +36,8 @@ struct NovelTests { #expect(novel.interestCount == 10) } - @Test("isInterested가 nil인 작품에 markAsInterested를 호출하면 상태가 변하지 않는다") - func markAsInterestedWhenNil() { + @Test("관심 여부를 모르는 작품은 관심 작품으로 등록하지 않는다") + func markingUnknownChangesNothing() { var novel = makeNovel(isInterested: nil, interestCount: 10) novel.markAsInterested() @@ -45,10 +46,10 @@ struct NovelTests { #expect(novel.interestCount == 10) } - // MARK: - unmarkAsInterested + // MARK: - 해제 - @Test("관심 등록된 작품의 관심을 해제하면 isInterested가 false가 되고 관심 수가 감소한다") - func unmarkAsInterestedFromTrue() { + @Test("관심을 해제하면 관심 수가 하나 줄어든다") + func unmarkingRemovesInterest() { var novel = makeNovel(isInterested: true, interestCount: 10) novel.unmarkAsInterested() @@ -57,8 +58,8 @@ struct NovelTests { #expect(novel.interestCount == 9) } - @Test("관심 없는 작품에 unmarkAsInterested를 호출하면 상태가 변하지 않는다") - func unmarkAsInterestedWhenAlreadyFalse() { + @Test("관심 작품이 아니면 해제해도 그대로다") + func unmarkingNonInterestChangesNothing() { var novel = makeNovel(isInterested: false, interestCount: 10) novel.unmarkAsInterested() @@ -67,8 +68,8 @@ struct NovelTests { #expect(novel.interestCount == 10) } - @Test("관심 수가 0일 때 unmarkAsInterested를 호출하면 관심 수가 0 이하로 내려가지 않는다") - func unmarkAsInterestedDoesNotGoBelowZero() { + @Test("관심 수가 0이면 해제해도 0 아래로 내려가지 않는다") + func unmarkingNeverGoesBelowZero() { var novel = makeNovel(isInterested: true, interestCount: 0) novel.unmarkAsInterested() @@ -77,10 +78,10 @@ struct NovelTests { #expect(novel.interestCount == 0) } - // MARK: - toggleInterest + // MARK: - 전환 - @Test("관심 등록된 작품을 토글하면 관심이 해제된다") - func toggleInterestFromTrue() { + @Test("관심 작품에서 관심을 전환하면 해제된다") + func togglingInterestRemovesIt() { var novel = makeNovel(isInterested: true, interestCount: 10) novel.toggleInterest() @@ -89,8 +90,8 @@ struct NovelTests { #expect(novel.interestCount == 9) } - @Test("관심 없는 작품을 토글하면 관심이 등록된다") - func toggleInterestFromFalse() { + @Test("관심 작품이 아닐 때 관심을 전환하면 등록된다") + func togglingNonInterestAddsIt() { var novel = makeNovel(isInterested: false, interestCount: 10) novel.toggleInterest() @@ -98,22 +99,19 @@ struct NovelTests { #expect(novel.isInterested == true) #expect(novel.interestCount == 11) } -} -extension NovelTests { - private func makeNovel( - isInterested: Bool? = nil, - interestCount: Int = 0 - ) -> Novel { + // MARK: - Helpers + + private func makeNovel(isInterested: Bool?, interestCount: Int) -> Novel { Novel( id: NovelID(1), thumbnailImage: nil, - title: "전지적 독자 시점", - authors: ["싱숑"], - genres: [.fantasy], + title: "작품", + authors: ["작가"], + genres: [], interestCount: interestCount, rating: 4.5, - ratingCount: 50, + ratingCount: 10, isInterested: isInterested ) } diff --git a/Projects/Domain/BaseDomain/Tests/Entity/RatingTests.swift b/Projects/Domain/BaseDomain/Tests/Entity/RatingTests.swift new file mode 100644 index 000000000..6d2bd1d41 --- /dev/null +++ b/Projects/Domain/BaseDomain/Tests/Entity/RatingTests.swift @@ -0,0 +1,57 @@ +// +// RatingTests.swift +// BaseDomain +// +// Created by YunhakLee on 2/6/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Testing + +import BaseDomain + +@Suite("평점") +struct RatingTests { + + @Test( + "0.5부터 5.0까지 0.5점 단위면 평점이 된다", + arguments: [ + 0.5, // 가장 낮은 평점 + 2.5, // 0.5점이 붙은 평점 + 3.0, // 중간의 정수 평점 + 5.0 // 가장 높은 평점 + ] + ) + func halfStepsWithinRangeAreRatings(value: Double) throws { + let rating = try Rating(value) + + #expect(rating.value == value) + } + + @Test( + "범위 밖이면 평점이 아니다", + arguments: [ + 0.0, // 가장 낮은 평점보다 0.5점 작다 + 5.5 // 가장 높은 평점보다 0.5점 크다 + ] + ) + func outOfRangeIsNotRating(value: Double) { + #expect(throws: Rating.ValidationError.outOfRange) { + try Rating(value) + } + } + + // archlint:allow test-name-number — 0.5는 단위를 말한다(넣는 값이 아니다) + @Test( + "0.5점 단위가 아니면 평점이 아니다", + arguments: [ + 4.7, // 소수 첫째 자리가 0.5점 단위가 아니다 + 1.25 // 0.5점보다 잘게 나눴다 + ] + ) + func nonHalfStepIsNotRating(value: Double) { + #expect(throws: Rating.ValidationError.invalidStep) { + try Rating(value) + } + } +} diff --git a/Projects/Domain/BaseDomain/Tests/Entity/ReadingPeriodTests.swift b/Projects/Domain/BaseDomain/Tests/Entity/ReadingPeriodTests.swift new file mode 100644 index 000000000..3cf2da48f --- /dev/null +++ b/Projects/Domain/BaseDomain/Tests/Entity/ReadingPeriodTests.swift @@ -0,0 +1,162 @@ +// +// ReadingPeriodTests.swift +// BaseDomain +// +// Created by YunhakLee on 2/6/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation +import Testing + +import BaseDomain + +// 고정 날짜. 기준일(today)은 서울 시각 2023-11-15 07:13이다. +private let threeDaysAgo = Date(timeIntervalSince1970: 1_699_740_800) +private let yesterday = Date(timeIntervalSince1970: 1_699_913_600) +private let today = Date(timeIntervalSince1970: 1_700_000_000) +private let tomorrow = Date(timeIntervalSince1970: 1_700_086_400) + +// 날짜는 서울 달력으로 가른다 — 기기 시간대에 따라 결과가 달라지지 않게 고정한다. +private let seoul: Calendar = { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "Asia/Seoul")! + return calendar +}() + +@Suite("독서 기간") +struct ReadingPeriodTests { + + @Suite("만들기") + struct Creating { + + @Test( + "시작일이나 종료일 하나만 있어도 기간이 된다", + arguments: [ + (yesterday, nil), // 시작일만 있다 + (nil, yesterday) // 종료일만 있다 + ] as [(Date?, Date?)] + ) + func oneDateIsEnough(start: Date?, end: Date?) throws { + let period = try makePeriod(start: start, end: end) + + #expect(period.start == start) + #expect(period.end == end) + } + + @Test("같은 날이어도 기간이 된다") + func sameDayIsPeriod() throws { + let period = try makePeriod(start: yesterday, end: yesterday) + + #expect(period.start == yesterday) + #expect(period.end == yesterday) + } + + @Test("둘 다 없으면 기간이 아니다") + func noDatesIsNotPeriod() { + #expect(throws: ReadingPeriod.ValidationError.invalidPeriod) { + try makePeriod(start: nil, end: nil) + } + } + + @Test("시작일이 종료일보다 늦으면 기간이 아니다") + func startAfterEndIsNotPeriod() { + #expect(throws: ReadingPeriod.ValidationError.startAfterEnd) { + try makePeriod(start: yesterday, end: threeDaysAgo) + } + } + + @Test( + "오늘 이후 날짜는 넣을 수 없다", + arguments: [ + (tomorrow, nil), // 시작일이 내일이다 + (nil, tomorrow) // 종료일이 내일이다 + ] as [(Date?, Date?)] + ) + func futureDateIsRejected(start: Date?, end: Date?) { + #expect(throws: ReadingPeriod.ValidationError.futureDate) { + try makePeriod(start: start, end: end) + } + } + + @Test("오늘 날짜면 시각이 기준보다 늦어도 넣을 수 있다") + func laterTimeTodayIsAllowed() throws { + // 서울 시각 19:13. UTC로 보면 기준일 다음 날이라, 시각으로 비교하면 막힌다. + let laterToday = Date(timeIntervalSince1970: 1_700_043_200) + + let period = try makePeriod(start: nil, end: laterToday) + + #expect(period.end == laterToday) + } + } + + @Suite("독서 상태에 맞추기") + struct Normalizing { + + @Test("읽는 중이면 시작일만 남긴다") + func watchingKeepsOnlyStart() throws { + let period = try makePeriod(start: threeDaysAgo, end: yesterday) + + let normalized = period.normalized(for: .watching) + + #expect(normalized?.start == threeDaysAgo) + #expect(normalized?.end == nil) + } + + @Test("읽는 중인데 종료일만 있으면 그 날을 시작일로 옮긴다") + func watchingMovesEndToStart() throws { + let period = try makePeriod(start: nil, end: yesterday) + + let normalized = period.normalized(for: .watching) + + #expect(normalized?.start == yesterday) + #expect(normalized?.end == nil) + } + + @Test("다 읽음이면 빈 쪽을 채운다") + func watchedFillsMissingSide() throws { + let period = try makePeriod(start: threeDaysAgo, end: nil) + + let normalized = period.normalized(for: .watched) + + #expect(normalized?.start == threeDaysAgo) + #expect(normalized?.end == threeDaysAgo) + } + + @Test("다 읽음인데 종료일만 있으면 그 날로 시작일을 채운다") + func watchedFillsStartFromEnd() throws { + let period = try makePeriod(start: nil, end: yesterday) + + let normalized = period.normalized(for: .watched) + + #expect(normalized?.start == yesterday) + #expect(normalized?.end == yesterday) + } + + @Test("하차면 종료일만 남긴다") + func quitKeepsOnlyEnd() throws { + let period = try makePeriod(start: threeDaysAgo, end: yesterday) + + let normalized = period.normalized(for: .quit) + + #expect(normalized?.start == nil) + #expect(normalized?.end == yesterday) + } + + @Test("하차인데 시작일만 있으면 그 날을 종료일로 옮긴다") + func quitMovesStartToEnd() throws { + let period = try makePeriod(start: threeDaysAgo, end: nil) + + let normalized = period.normalized(for: .quit) + + #expect(normalized?.start == nil) + #expect(normalized?.end == threeDaysAgo) + } + } +} + +// MARK: - Helpers + +private func makePeriod(start: Date?, end: Date?) throws -> ReadingPeriod { + try ReadingPeriod(start: start, end: end, notAfter: today, calendar: seoul) +} diff --git a/Projects/Domain/BaseDomain/Tests/UseCase/AppReviewRequestUseCaseTests.swift b/Projects/Domain/BaseDomain/Tests/UseCase/AppReviewRequestUseCaseTests.swift index 94614180d..8e69890e4 100644 --- a/Projects/Domain/BaseDomain/Tests/UseCase/AppReviewRequestUseCaseTests.swift +++ b/Projects/Domain/BaseDomain/Tests/UseCase/AppReviewRequestUseCaseTests.swift @@ -9,90 +9,87 @@ import Foundation import Testing -@testable import BaseDomain +import BaseDomain import BaseDomainTesting -@Suite("앱 리뷰 요청 게이팅 UseCase") +@Suite("앱 리뷰 요청") struct AppReviewRequestUseCaseTests { - @Test("누적 참여가 임계치 미만이면 요청하지 않는다.") - func belowThreshold_returnsFalse() { - let mock = MockAppReviewRequestRepository(engagementCount: 2, currentAppVersion: "1.0.0") - let usecase = DefaultAppReviewRequestUseCase(repository: mock, threshold: 3) + @Test("참여가 2번뿐이면 리뷰를 요청하지 않는다") + func twoEngagementsAreNotEnough() { + let useCase = makeUseCase(MockAppReviewRequestRepository(engagementCount: 2)) - #expect(usecase.shouldRequestReview() == false) + #expect(useCase.shouldRequestReview() == false) } - @Test("임계치를 채웠어도 이번 버전에서 이미 요청했으면 다시 요청하지 않는다.") - func atThreshold_sameVersion_returnsFalse() { - let mock = MockAppReviewRequestRepository( - engagementCount: 3, - lastRequestedVersion: "1.0.0", - currentAppVersion: "1.0.0" - ) - let usecase = DefaultAppReviewRequestUseCase(repository: mock, threshold: 3) + @Test("참여가 3번이 되면 리뷰를 요청한다") + func threeEngagementsRequestReview() { + let useCase = makeUseCase(MockAppReviewRequestRepository(engagementCount: 3)) - #expect(usecase.shouldRequestReview() == false) + #expect(useCase.shouldRequestReview() == true) } - @Test("임계치를 채웠고 이번 버전에서 아직 요청 전이면 요청한다.") - func atThreshold_newVersion_returnsTrue() { - let mock = MockAppReviewRequestRepository( - engagementCount: 3, - lastRequestedVersion: "0.9.0", - currentAppVersion: "1.0.0" - ) - let usecase = DefaultAppReviewRequestUseCase(repository: mock, threshold: 3) + @Test("이번 버전에 이미 리뷰를 요청했으면 다시 요청하지 않는다") + func alreadyRequestedThisVersion() { + let repository = MockAppReviewRequestRepository(engagementCount: 3, lastRequestedVersion: "1.0.0") + + let useCase = makeUseCase(repository) - #expect(usecase.shouldRequestReview() == true) + #expect(useCase.shouldRequestReview() == false) } - @Test("recordEngagement는 누적 참여 수를 1씩 올린다.") - func recordEngagement_increments() { - let mock = MockAppReviewRequestRepository(engagementCount: 0) - let usecase = DefaultAppReviewRequestUseCase(repository: mock) + @Test("리뷰를 요청했다고 기록하면 이번 버전에서는 다시 요청하지 않는다") + func markingRequestStopsFurtherRequests() { + let useCase = makeUseCase(MockAppReviewRequestRepository(engagementCount: 3)) + + useCase.markReviewRequested() + + #expect(useCase.shouldRequestReview() == false) + } - usecase.recordEngagement() - usecase.recordEngagement() + @Test("버전이 바뀌면 지난 버전의 참여는 세지 않는다") + func previousVersionEngagementsDoNotCount() { + let useCase = makeUseCase(previousVersionRepository(lastRequestedVersion: nil)) - #expect(mock.engagementCount == 2) + #expect(useCase.shouldRequestReview() == false) } - @Test("markReviewRequested는 현재 앱 버전을 마지막 요청 버전으로 각인한다.") - func markReviewRequested_persistsCurrentVersion() { - let mock = MockAppReviewRequestRepository(currentAppVersion: "2.1.0") - let usecase = DefaultAppReviewRequestUseCase(repository: mock) + @Test("버전이 바뀐 뒤 참여를 기록하면 처음부터 다시 센다") + func newVersionCountsFromStart() { + let useCase = makeUseCase(previousVersionRepository(lastRequestedVersion: nil)) - usecase.markReviewRequested() + record(useCase, times: 2) - #expect(mock.lastRequestedVersion == "2.1.0") + #expect(useCase.shouldRequestReview() == false) } - @Test("앱 버전이 바뀐 뒤 recordEngagement는 이전 버전 카운트를 버리고 1부터 다시 센다.") - func recordEngagement_onNewVersion_resetsCount() { - let mock = MockAppReviewRequestRepository( - engagementCount: 5, - engagementCountVersion: "0.9.0", - currentAppVersion: "1.0.0" - ) - let usecase = DefaultAppReviewRequestUseCase(repository: mock) + @Test("새 버전에서 다시 3번 참여하면 지난 버전에 요청했어도 다시 요청한다") + func newVersionCanRequestAgain() { + let useCase = makeUseCase(previousVersionRepository(lastRequestedVersion: "1.0.0")) + + record(useCase, times: 3) - usecase.recordEngagement() + #expect(useCase.shouldRequestReview() == true) + } + + // MARK: - Helpers - #expect(mock.engagementCount == 1) - #expect(mock.engagementCountVersion == "1.0.0") + /// 기준 횟수는 기본값(3번)을 그대로 쓴다 — 기본값도 명세다. + private func makeUseCase(_ repository: MockAppReviewRequestRepository) -> DefaultAppReviewRequestUseCase { + DefaultAppReviewRequestUseCase(repository: repository) } - @Test("이전 버전에서 쌓인 카운트는 임계치 판정에서 무효다(버전이 바뀌면 0으로 본다).") - func shouldRequestReview_ignoresOldVersionCount() { - let mock = MockAppReviewRequestRepository( + /// 지난 버전(1.0.0)에서 참여를 5번 쌓고, 지금은 1.1.0인 저장소. + private func previousVersionRepository(lastRequestedVersion: String?) -> MockAppReviewRequestRepository { + MockAppReviewRequestRepository( engagementCount: 5, - engagementCountVersion: "0.9.0", - lastRequestedVersion: nil, - currentAppVersion: "1.0.0" + engagementCountVersion: "1.0.0", + lastRequestedVersion: lastRequestedVersion, + currentAppVersion: "1.1.0" ) - let usecase = DefaultAppReviewRequestUseCase(repository: mock, threshold: 3) + } - #expect(usecase.shouldRequestReview() == false) + private func record(_ useCase: DefaultAppReviewRequestUseCase, times: Int) { + for _ in 0.. PopularKeywords { - PopularKeywords( - keywords: names.enumerated().map { index, name in - Keyword(id: KeywordID(index + 1), name: name) - } - ) - } -} diff --git a/Projects/Domain/BaseDomain/Tests/UseCase/LoadTotalKeywordsUseCaseTests.swift b/Projects/Domain/BaseDomain/Tests/UseCase/LoadTotalKeywordsUseCaseTests.swift index b6416dbdd..35511a542 100644 --- a/Projects/Domain/BaseDomain/Tests/UseCase/LoadTotalKeywordsUseCaseTests.swift +++ b/Projects/Domain/BaseDomain/Tests/UseCase/LoadTotalKeywordsUseCaseTests.swift @@ -9,95 +9,45 @@ import Foundation import Testing -@testable import BaseDomain +import BaseDomain import BaseDomainTesting -@Suite +@Suite("전체 키워드 불러오기") struct LoadTotalKeywordsUseCaseTests { - @Test("전체 키워드 목록을 성공적으로 불러온다.") - func loadTotalKeywordsSuccess() async throws { - let mock = MockKeywordRepository() - mock.fetchKeywordsResult = .success([makeKeywordGroup()]) + private let regression = Keyword(id: KeywordID(11), name: "회귀") - let usecase = DefaultLoadTotalKeywordsUseCase(keywordRepository: mock) - let result = try await usecase.execute() + @Test("처음 불러오기에 성공하면 동기화하지 않는다") + func firstLoadSucceedsWithoutSync() async throws { + let repository = MockKeywordRepository() + repository.fetchKeywordsResult = .success([KeywordGroup(category: .material, keywords: [regression])]) - #expect(result.count == 1) - #expect(result.first?.category == .worldview) - #expect(mock.fetchKeywordsCallCount == 1) - } - - @Test("여러 그룹의 키워드를 모두 반환한다.") - func loadMultipleKeywordGroupsSuccess() async throws { - let mock = MockKeywordRepository() - mock.fetchKeywordsResult = .success([ - makeKeywordGroup(category: .worldview), - makeKeywordGroup(category: .material), - makeKeywordGroup(category: .character) - ]) - - let usecase = DefaultLoadTotalKeywordsUseCase(keywordRepository: mock) - let result = try await usecase.execute() + let groups = try await DefaultLoadTotalKeywordsUseCase(keywordRepository: repository).execute() - #expect(result.count == 3) - #expect(mock.fetchKeywordsCallCount == 1) + #expect(groups.flatMap(\.keywords) == [regression]) + #expect(repository.syncKeywordsCallCount == 0) } - @Test("전체 키워드 목록이 비어있어도 빈 배열을 반환한다.") - func loadEmptyKeywordsSuccess() async throws { - let mock = MockKeywordRepository() - mock.fetchKeywordsResult = .success([]) + @Test("불러오기에 실패하면 동기화한 뒤 다시 불러온 결과를 준다") + func failedLoadSyncsAndLoadsAgain() async throws { + let repository = MockKeywordRepository() + repository.fetchKeywordsResult = .failure(.notFound) + repository.fetchKeywordsResultAfterSync = .success([KeywordGroup(category: .material, keywords: [regression])]) - let usecase = DefaultLoadTotalKeywordsUseCase(keywordRepository: mock) - let result = try await usecase.execute() + let groups = try await DefaultLoadTotalKeywordsUseCase(keywordRepository: repository).execute() - #expect(result.isEmpty) - #expect(mock.fetchKeywordsCallCount == 1) + #expect(groups.flatMap(\.keywords) == [regression]) } - @Test("전체 키워드 조회가 동기화 후 재조회에도 계속 실패하면 에러를 던진다.") - func loadTotalKeywordsFailureThrows() async { - let mock = MockKeywordRepository() - mock.fetchKeywordsResult = .failure(RepositoryError.unknown) + @Test("동기화한 뒤에도 실패하면 그 에러를 전한다") + func failedAfterSyncPassesError() async { + let repository = MockKeywordRepository() + repository.fetchKeywordsResult = .failure(.notFound) + repository.fetchKeywordsResultAfterSync = .failure(.networkUnavailable) + let useCase = DefaultLoadTotalKeywordsUseCase(keywordRepository: repository) - let usecase = DefaultLoadTotalKeywordsUseCase(keywordRepository: mock) - - await #expect(throws: RepositoryError.unknown) { - try await usecase.execute() + await #expect(throws: RepositoryError.networkUnavailable) { + try await useCase.execute() } - - // 최초 조회 실패 → 동기화 1회 → 재조회까지 시도한 뒤에도 실패하면 그 에러를 던진다. - #expect(mock.fetchKeywordsCallCount == 2) - #expect(mock.syncKeywordsCallCount == 1) - } - - @Test("로컬 캐시가 비어있으면 동기화 후 재조회로 복구한다.") - func loadTotalKeywordsRecoversAfterSyncOnCacheMiss() async throws { - let mock = MockKeywordRepository() - mock.fetchKeywordsResults = [ - .failure(.unknown), - .success([makeKeywordGroup(category: .vibe)]) - ] - - let usecase = DefaultLoadTotalKeywordsUseCase(keywordRepository: mock) - let result = try await usecase.execute() - - #expect(result.count == 1) - #expect(result.first?.category == .vibe) - #expect(mock.fetchKeywordsCallCount == 2) - #expect(mock.syncKeywordsCallCount == 1) - } -} - -extension LoadTotalKeywordsUseCaseTests { - private func makeKeywordGroup(category: KeywordCategory = .worldview) -> KeywordGroup { - KeywordGroup( - category: category, - keywords: [ - Keyword(id: KeywordID(1), name: "이세계"), - Keyword(id: KeywordID(2), name: "웹툰화") - ] - ) } } diff --git a/Projects/Domain/BaseDomain/Tests/UseCase/OnboardingHintUseCaseTests.swift b/Projects/Domain/BaseDomain/Tests/UseCase/OnboardingHintUseCaseTests.swift deleted file mode 100644 index 9d640b328..000000000 --- a/Projects/Domain/BaseDomain/Tests/UseCase/OnboardingHintUseCaseTests.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// OnboardingHintUseCaseTests.swift -// BaseDomain -// -// Created by YunhakLee on 8/31/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import BaseDomain -import BaseDomainTesting - -@Suite("온보딩 힌트 UseCase") -struct OnboardingHintUseCaseTests { - - @Test("이미 본 힌트는 hasSeen이 true다.") - func returnsTrueWhenSeen() { - let mock = MockOnboardingHintRepository(seenHints: [.novelDetailReview]) - let usecase = DefaultOnboardingHintUseCase(repository: mock) - - #expect(usecase.hasSeen(.novelDetailReview) == true) - } - - @Test("아직 안 본 힌트는 hasSeen이 false다.") - func returnsFalseWhenUnseen() { - let mock = MockOnboardingHintRepository() - let usecase = DefaultOnboardingHintUseCase(repository: mock) - - #expect(usecase.hasSeen(.novelDetailReview) == false) - } - - @Test("markSeen은 저장소에 그 힌트를 봤음으로 위임하고, 이후 hasSeen이 true가 된다.") - func markSeenDelegatesAndPersists() { - let mock = MockOnboardingHintRepository() - let usecase = DefaultOnboardingHintUseCase(repository: mock) - - usecase.markSeen(.novelDetailReview) - - #expect(mock.markSeenCalls == [.novelDetailReview]) - #expect(usecase.hasSeen(.novelDetailReview) == true) - } - - @Test("한 힌트를 봤음 처리해도 다른 힌트는 여전히 안 본 상태다.") - func markSeenDoesNotAffectOtherHints() { - let mock = MockOnboardingHintRepository() - let usecase = DefaultOnboardingHintUseCase(repository: mock) - - usecase.markSeen(.myPageCollectionTooltip) - - #expect(usecase.hasSeen(.myPageCollectionTooltip) == true) - #expect(usecase.hasSeen(.novelDetailReview) == false) - } -} diff --git a/Projects/Domain/BaseDomain/Tests/UseCase/SearchKeywordsUseCaseTests.swift b/Projects/Domain/BaseDomain/Tests/UseCase/SearchKeywordsUseCaseTests.swift index 31366edcd..83c0e9ca9 100644 --- a/Projects/Domain/BaseDomain/Tests/UseCase/SearchKeywordsUseCaseTests.swift +++ b/Projects/Domain/BaseDomain/Tests/UseCase/SearchKeywordsUseCaseTests.swift @@ -9,94 +9,59 @@ import Foundation import Testing -@testable import BaseDomain +import BaseDomain import BaseDomainTesting -@Suite +@Suite("키워드 검색") struct SearchKeywordsUseCaseTests { - @Test("키워드 검색 시 결과를 성공적으로 반환한다.") - func searchKeywordsSuccess() async throws { - let mock = MockKeywordRepository() - mock.searchKeywordsResult = .success([ - KeywordGroup(category: .worldview, keywords: [ - makeKeyword(id: 1, name: "삼국지"), - makeKeyword(id: 2, name: "성장") - ]) - ]) - - let usecase = DefaultSearchKeywordUseCase(keywordRepository: mock) - let result = try await usecase.execute(searchText: "삼국지") - - #expect(result.count == 2) - #expect(result.first?.name == "삼국지") - #expect(mock.searchedQueries.contains("삼국지")) - } + private let regression = Keyword(id: KeywordID(11), name: "회귀") + private let academy = Keyword(id: KeywordID(12), name: "아카데미") - @Test("검색 결과가 없어도 빈 배열을 반환한다.") - func searchKeywordsEmptyResult() async throws { - let mock = MockKeywordRepository() - mock.searchKeywordsResult = .success([]) + @Test("처음 검색에 성공하면 동기화하지 않는다") + func firstSearchSucceedsWithoutSync() async throws { + let repository = MockKeywordRepository() + repository.searchKeywordsResults["회귀"] = .success([KeywordGroup(category: .material, keywords: [regression])]) - let usecase = DefaultSearchKeywordUseCase(keywordRepository: mock) - let result = try await usecase.execute(searchText: "존재하지않는키워드") + let keywords = try await DefaultSearchKeywordUseCase(keywordRepository: repository).execute(searchText: "회귀") - #expect(result.isEmpty) - #expect(mock.searchedQueries.contains("존재하지않는키워드")) + #expect(keywords == [regression]) + #expect(repository.syncKeywordsCallCount == 0) } - @Test("검색어가 레포지토리로 정확히 전달된다.") - func searchQueryIsPassedToRepository() async throws { - let mock = MockKeywordRepository() - mock.searchKeywordsResult = .success([]) - - let usecase = DefaultSearchKeywordUseCase(keywordRepository: mock) - let query = "판타지" + @Test("검색에 실패하면 동기화한 뒤 다시 검색한 결과를 준다") + func failedSearchSyncsAndSearchesAgain() async throws { + let repository = MockKeywordRepository() + repository.searchKeywordsResults["회귀"] = .failure(.notFound) + repository.searchKeywordsResultsAfterSync["회귀"] = .success([KeywordGroup(category: .material, keywords: [regression])]) - _ = try await usecase.execute(searchText: query) + let keywords = try await DefaultSearchKeywordUseCase(keywordRepository: repository).execute(searchText: "회귀") - #expect(mock.searchedQueries.last == query) + #expect(keywords == [regression]) } - @Test("키워드 검색이 동기화 후 재조회에도 계속 실패하면 에러를 던진다.") - func searchKeywordsFailureThrows() async { - let mock = MockKeywordRepository() - mock.searchKeywordsResult = .failure(RepositoryError.unknown) - - let usecase = DefaultSearchKeywordUseCase(keywordRepository: mock) + @Test("동기화한 뒤에도 실패하면 그 에러를 전한다") + func failedAfterSyncPassesError() async { + let repository = MockKeywordRepository() + repository.searchKeywordsResults["회귀"] = .failure(.notFound) + repository.searchKeywordsResultsAfterSync["회귀"] = .failure(.networkUnavailable) + let useCase = DefaultSearchKeywordUseCase(keywordRepository: repository) - await #expect(throws: RepositoryError.unknown) { - try await usecase.execute(searchText: "집착") + await #expect(throws: RepositoryError.networkUnavailable) { + try await useCase.execute(searchText: "회귀") } - - #expect(mock.searchedQueries.contains("집착")) - // 최초 조회 실패 → 동기화 1회 → 재조회까지 시도한 뒤에도 실패하면 그 에러를 던진다. - #expect(mock.searchKeywordsCallCount == 2) - #expect(mock.syncKeywordsCallCount == 1) } - @Test("로컬 캐시가 비어있으면 동기화 후 재조회로 복구한다.") - func searchKeywordsRecoversAfterSyncOnCacheMiss() async throws { - let mock = MockKeywordRepository() - mock.searchKeywordsResults = [ - .failure(.unknown), - .success([ - KeywordGroup(category: .worldview, keywords: [makeKeyword(id: 1, name: "삼국지")]) - ]) - ] - - let usecase = DefaultSearchKeywordUseCase(keywordRepository: mock) - let result = try await usecase.execute(searchText: "삼국지") + @Test("묶음별 검색 결과를 키워드 목록 하나로 펼친다") + func flattensGroupsIntoOneList() async throws { + let repository = MockKeywordRepository() + repository.searchKeywordsResults["아"] = .success([ + KeywordGroup(category: .material, keywords: [regression]), + KeywordGroup(category: .worldview, keywords: [academy]) + ]) - #expect(result.count == 1) - #expect(result.first?.name == "삼국지") - #expect(mock.searchKeywordsCallCount == 2) - #expect(mock.syncKeywordsCallCount == 1) - } -} + let keywords = try await DefaultSearchKeywordUseCase(keywordRepository: repository).execute(searchText: "아") -extension SearchKeywordsUseCaseTests { - private func makeKeyword(id: Int, name: String) -> Keyword { - Keyword(id: KeywordID(id), name: name) + #expect(keywords == [regression, academy]) } } diff --git a/Projects/Domain/CLAUDE.md b/Projects/Domain/CLAUDE.md index 89fbf61a7..f09cd929c 100644 --- a/Projects/Domain/CLAUDE.md +++ b/Projects/Domain/CLAUDE.md @@ -22,10 +22,11 @@ Projects/Domain/Domain/ │ ├── Entity/ # 도메인 모델 (struct, 정책 메서드 포함) │ ├── UseCase/ # 비즈니스 흐름 (프로토콜 + Default 구현) │ └── Repository/ # 데이터 접근 계약 (프로토콜만) -├── Testing/ # Mock[Repository].swift +├── TEST_SPEC.md # 자동 생성 테스트 목록(ArchLint --write-test-specs, 손으로 고치지 않음) — 테스트 규칙이 켜진 모듈만 +├── Testing/ # Mock[Repository].swift — 가짜 객체가 필요한 모듈만 └── Tests/ ├── Entity/ - └── Usecase/ + └── UseCase/ ``` ## 코드 규칙 @@ -93,15 +94,16 @@ public final class DefaultLoadNovelUseCase: LoadNovelUseCase { ## 테스트 (필수 — 이 레이어 한정) -새 UseCase·Entity·정책 메서드는 **테스트 없이 머지 금지**. +분기·검증·계산이 있는 Entity·정책·UseCase는 **테스트 없이 머지 금지**. 저장소 호출을 넘기기만 하는 UseCase는 테스트하지 않는다. > 📖 **테스트를 작성/수정하기 전에 [docs/TESTING.md](../../docs/TESTING.md)를 먼저 읽어라.** -> (철학 "테스트=읽히는 명세", 명세형 네이밍, Mock 패턴, 예시 전부 거기에 있음) +> (5원칙과 그 이유, 작업 순서, 사람이 판단할 곳, Stub/Mock, 예시가 거기 있음. 검사 규칙 목록은 `Tooling/ArchLint/README.md`) 빠른 요약: -- **Swift Testing** (`@Test`/`#expect`/`@Suite`), XCTest 금지. Mock은 `Testing/`(`DomainTesting` 타깃). -- `@Test("한글 명세 문장") func englishName()` — 이름이 곧 명세. -- CI: PR에 `/domain-test` 댓글 → `Projects/Domain` 폴더 자동 스캔. ⚠️ 빈/잔재 폴더는 매트릭스를 깨뜨림. +- **Swift Testing** (`@Test`/`#expect`/`@Suite`), XCTest·`@testable import` 금지. 가짜 객체는 `Testing/`(`DomainTesting` 타깃) — 조회는 Stub, 명령은 Mock. +- `@Suite("기능")` 안에 `@Test("~다")` — 이름이 곧 명세. 테스트 목록은 모듈 루트 `TEST_SPEC.md`로 PR에 보인다. +- ArchLint 테스트 규칙과 `TEST_SPEC.md`는 아직 **일부 모듈에만** 켜져 있다(`TestSpecScope.modules`, TESTING.md "적용 범위"). 안 켜진 모듈도 새 테스트는 같은 기준으로 쓴다. +- CI: develop 대상 PR마다 자동 실행(`Project.swift`에 `.tests` 선언한 정식 모듈만 — 유령 폴더는 자동 제외). ## 주의사항 (작업 중 발견 시 누적) diff --git a/Projects/Domain/CollectionDomain/CLAUDE.md b/Projects/Domain/CollectionDomain/CLAUDE.md index fbb7efea6..0ff7412ad 100644 --- a/Projects/Domain/CollectionDomain/CLAUDE.md +++ b/Projects/Domain/CollectionDomain/CLAUDE.md @@ -57,7 +57,8 @@ 반영할 땐 편도 append 여러 번이 아니라 한 번에 전체를 새 목록으로 바꾸는 게 계약에 맞는다. count 상한은 `addNovel`과 같은 `novelOverLimit` throw(선택 화면이 UI에서 이미 100개로 막아두므로 실사용 경로는 아니지만, "사용자 입력은 거부"라는 `updateName` 방침과 일관되게 clamp 대신 throw를 골랐다). - 대표 작품이 새 목록에서 빠지면 `removeNovel`과 동일하게 대표 지정도 함께 풀린다. + 대표 작품이 새 목록에서 빠지면 `removeNovel`과 동일하게 대표 지정도 함께 풀린다. 같은 작품이 두 번 들어오면 + `addNovel`과 같은 `duplicatedNovel`로 거부한다(#293 — 전엔 통째 교체만 중복을 통과시켜 들어오는 길마다 규칙이 갈렸다). - **목록 카드는 `CollectionCard` 하나다**(#283 회의 결정) — 사용자별·좋아요·공개 목록이 이름·설명·작품 수·미리보기·공개 여부·소유자를 겹쳐 다뤄, 한때 따로 뒀던 공개 목록용 `PublicCollectionCard`를 합쳤다. 목록마다 서버가 주는 값이 달라 아래처럼 채운다 (판정은 `CollectionMapper` 한 곳, 로그인 사용자 ID는 Repository가 `AppStorage .userID`로 읽는다): @@ -72,3 +73,6 @@ 서버에 owner를 요청할 것. `owner` 옵셔널도 같은 응답 빈틈 때문에 둔 임시 형태라 서버가 owner를 주면 함께 리팩터링한다. - `isPrivate`은 세 목록 모두 서버 값을 그대로 쓴다 — 남의 나만 보는 컬렉션은 서버가 애초에 내려주지 않는다. - `fetchPublicCollections`는 서버(`GET /collections`)가 전체 개수를 주지 않아 다른 목록과 달리 `(페이지, 개수)` 튜플이 아니라 페이지만 돌려준다. +- UseCase 9개(조회 5·생성·수정·삭제·좋아요)는 **일부러 테스트가 없다**(#293). 저장소에 넘기기만 해서 이 모듈에서 지킬 규칙이 없다 — + 다시 넣으면 ArchLint `test-passthrough`가 막는다. 그래서 `.testing` 타깃(`MockCollectionRepository`)도 없앴다. + UseCase에 분기나 조합이 생기면 그때 테스트와 Stub/Mock을 만든다. diff --git a/Projects/Domain/CollectionDomain/Project.swift b/Projects/Domain/CollectionDomain/Project.swift index 55aa03b84..92a8f8fe8 100644 --- a/Projects/Domain/CollectionDomain/Project.swift +++ b/Projects/Domain/CollectionDomain/Project.swift @@ -11,6 +11,6 @@ import DependencyPlugin let project = Project.createDomainModule( name: ModuleType.domain(.collection).name, - targets: [.sources, .testing, .tests], + targets: [.sources, .tests], internalDependencies: [.module(.domain(.base))] ) diff --git a/Projects/Domain/CollectionDomain/Sources/Entity/CollectionDraft.swift b/Projects/Domain/CollectionDomain/Sources/Entity/CollectionDraft.swift index 27edfc7d9..8d39123b6 100644 --- a/Projects/Domain/CollectionDomain/Sources/Entity/CollectionDraft.swift +++ b/Projects/Domain/CollectionDomain/Sources/Entity/CollectionDraft.swift @@ -121,7 +121,9 @@ public struct CollectionDraft: Equatable, Sendable { /// count 상한은 `addNovel`과 동일하게 throw — 선택 화면이 UI에서 이미 100개로 막아두므로 실사용에서는 /// 도달하지 않지만, "사용자 입력 검증은 거부"(clamp 아님) 방침을 `updateName`과 동일하게 지킨다. /// 대표 작품이 새 목록에 더 이상 없으면 대표 지정도 함께 풀린다(`removeNovel`과 같은 이유). + /// 중복은 `addNovel`과 같은 `duplicatedNovel`로 막는다 — 들어오는 길에 따라 규칙이 갈리지 않게. public mutating func setNovels(_ ids: [NovelID]) throws(ValidationError) { + guard Set(ids).count == ids.count else { throw .duplicatedNovel } guard ids.count <= Self.maxNovelCount else { throw .novelOverLimit(max: Self.maxNovelCount) } diff --git a/Projects/Domain/CollectionDomain/TEST_SPEC.md b/Projects/Domain/CollectionDomain/TEST_SPEC.md new file mode 100644 index 000000000..e80e2077b --- /dev/null +++ b/Projects/Domain/CollectionDomain/TEST_SPEC.md @@ -0,0 +1,80 @@ +# CollectionDomain 테스트 명세 + + + +## 컬렉션 좋아요 + +`Tests/Entity/CollectionDetailTests.swift` + +- 좋아요하면 좋아요 수가 하나 는다 +- 이미 좋아요했으면 다시 좋아요해도 그대로다 +- 좋아요를 취소하면 좋아요 수가 하나 준다 +- 좋아요하지 않았으면 취소해도 그대로다 +- 좋아요 수가 0이면 취소해도 0 아래로 내려가지 않는다 +- 좋아요한 컬렉션에서 좋아요를 전환하면 취소된다 +- 좋아요하지 않은 컬렉션에서 좋아요를 전환하면 좋아요가 된다 + +## 컬렉션 만들기·수정하기 + +`Tests/Entity/CollectionDraftTests.swift` + +### 제출 + +- 이름이 있고 작품이 하나 이상이면 설명이 없어도 제출할 수 있다 +- 이름이 비었거나 공백뿐이면 제출할 수 없다 + - `""` — 아무것도 쓰지 않음 + - `" "` — 스페이스만 + - `"\n\t "` — 줄바꿈·탭도 공백으로 본다 +- 작품이 하나도 없으면 제출할 수 없다 + +### 이름 + +- 이름은 20자까지 입력할 수 있다 +- 이름이 20자를 넘으면 거부하고 이전 이름을 지킨다 +- 남은 이름 글자 수는 20에서 지금 길이를 뺀 값이다 + +### 설명 + +- 설명은 60자까지 입력할 수 있다 +- 설명이 60자를 넘으면 거부하고 이전 설명을 지킨다 +- 남은 설명 글자 수는 60에서 지금 길이를 뺀 값이다 + +### 수정하기 + +- 수정하기를 열면 저장된 컬렉션 내용이 그대로 채워진다 +- 설명이 없던 컬렉션은 수정하기를 열면 설명이 비어 있다 +- 저장된 컬렉션이 제한을 넘으면 넘는 부분을 잘라 채운다 + +### 작품 추가·빼기 + +- 작품을 추가하면 목록 끝에 붙는다 +- 이미 담긴 작품은 다시 추가할 수 없다 +- 작품이 100개면 더 추가할 수 없다 +- 작품을 빼면 목록에서 사라진다 + +### 작품 목록 통째로 바꾸기 + +- 작품 목록을 새 목록으로 통째로 바꿀 수 있다 +- 새 목록이 100개여도 통째로 바꿀 수 있다 +- 새 목록이 100개를 넘으면 바꿀 수 없다 +- 새 목록에 같은 작품이 두 번 있으면 바꿀 수 없다 + +### 대표 작품 고르기 + +- 담긴 작품을 대표로 고를 수 있다 +- 담기지 않은 작품은 대표로 고를 수 없다 +- 대표를 고르지 않았으면 첫 작품이 대표다 +- 대표를 골랐으면 고른 작품이 대표다 +- 작품이 없으면 대표도 없다 + +### 작품이 빠질 때 대표 작품 + +- 대표로 고른 작품을 빼면 대표 선택도 풀린다 +- 대표로 고르지 않은 작품을 빼면 대표 선택은 그대로다 +- 대표로 고른 작품이 새 목록에 없으면 대표 선택도 풀린다 +- 대표로 고른 작품이 새 목록에도 있으면 대표 선택은 그대로다 + +### 나만 보기 + +- 컬렉션을 새로 만들 때 나만 보기는 꺼져 있다 +- 꺼진 나만 보기를 누르면 켜진다 diff --git a/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift b/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift deleted file mode 100644 index 9851be9b6..000000000 --- a/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift +++ /dev/null @@ -1,111 +0,0 @@ -// -// MockCollectionRepository.swift -// CollectionDomainTesting -// -// Created by YunhakLee on 8/18/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation - -import BaseDomain -import CollectionDomain - -public final class MockCollectionRepository: CollectionRepository { - - // MARK: - 주입할 결과 - - public var fetchCollectionPreviewsResult: Result<([CollectionPreview], Int), RepositoryError>! - public var fetchCollectionsResult: Result<(CursorPaginated, Int), RepositoryError>! - public var fetchLikedCollectionsResult: Result<(CursorPaginated, Int), RepositoryError>! - public var fetchPublicCollectionsResult: Result, RepositoryError>! - public var fetchCollectionDetailResult: Result! - public var createCollectionResult: Result! - public var updateCollectionResult: Result = .success(()) - public var deleteCollectionResult: Result = .success(()) - public var likeCollectionResult: Result = .success(()) - public var unlikeCollectionResult: Result = .success(()) - - // MARK: - 호출 기록 - - public private(set) var fetchedPreviewRequests: [(userID: UserID, size: Int)] = [] - public private(set) var fetchedCollectionRequests: [(userID: UserID, cursor: String?, size: Int)] = [] - public private(set) var fetchedLikedRequests: [(cursor: String?, size: Int)] = [] - public private(set) var fetchedPublicRequests: [(cursor: String?, size: Int)] = [] - public private(set) var fetchedDetailRequests: [(id: CollectionID, sortType: SortType)] = [] - public private(set) var createdDrafts: [CollectionDraft] = [] - public private(set) var updatedRequests: [(id: CollectionID, draft: CollectionDraft)] = [] - public private(set) var deletedIDs: [CollectionID] = [] - public private(set) var likedIDs: [CollectionID] = [] - public private(set) var unlikedIDs: [CollectionID] = [] - - public init() {} - - // MARK: - CollectionRepository - - public func fetchCollectionPreviews( - userID: UserID, - size: Int - ) async throws(RepositoryError) -> ([CollectionPreview], Int) { - fetchedPreviewRequests.append((userID, size)) - return try fetchCollectionPreviewsResult.get() - } - - public func fetchCollections( - userID: UserID, - cursor: String?, - size: Int - ) async throws(RepositoryError) -> (CursorPaginated, Int) { - fetchedCollectionRequests.append((userID, cursor, size)) - return try fetchCollectionsResult.get() - } - - public func fetchLikedCollections( - cursor: String?, - size: Int - ) async throws(RepositoryError) -> (CursorPaginated, Int) { - fetchedLikedRequests.append((cursor, size)) - return try fetchLikedCollectionsResult.get() - } - - public func fetchPublicCollections( - cursor: String?, - size: Int - ) async throws(RepositoryError) -> CursorPaginated { - fetchedPublicRequests.append((cursor, size)) - return try fetchPublicCollectionsResult.get() - } - - public func fetchCollectionDetail( - id: CollectionID, - sortType: SortType - ) async throws(RepositoryError) -> CollectionDetail { - fetchedDetailRequests.append((id, sortType)) - return try fetchCollectionDetailResult.get() - } - - public func createCollection(_ draft: CollectionDraft) async throws(RepositoryError) -> CollectionID { - createdDrafts.append(draft) - return try createCollectionResult.get() - } - - public func updateCollection(id: CollectionID, draft: CollectionDraft) async throws(RepositoryError) { - updatedRequests.append((id, draft)) - try updateCollectionResult.get() - } - - public func deleteCollection(id: CollectionID) async throws(RepositoryError) { - deletedIDs.append(id) - try deleteCollectionResult.get() - } - - public func likeCollection(id: CollectionID) async throws(RepositoryError) { - likedIDs.append(id) - try likeCollectionResult.get() - } - - public func unlikeCollection(id: CollectionID) async throws(RepositoryError) { - unlikedIDs.append(id) - try unlikeCollectionResult.get() - } -} diff --git a/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDetailTests.swift b/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDetailTests.swift index 0207a3504..4a506167d 100644 --- a/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDetailTests.swift +++ b/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDetailTests.swift @@ -6,42 +6,42 @@ // Copyright © 2026 kr.websoso.app. All rights reserved. // -import Testing import Foundation +import Testing -@testable import CollectionDomain import BaseDomain +import CollectionDomain -@Suite("CollectionDetail") +@Suite("컬렉션 좋아요") struct CollectionDetailTests { - // MARK: - markAsLiked + // MARK: - 좋아요 - @Test("좋아요하지 않은 컬렉션을 좋아요하면 상태가 켜지고 좋아요 수가 늘어난다") - func markAsLiked() { - var detail = makeDetail(likeCount: 10, isLiked: false) + @Test("좋아요하면 좋아요 수가 하나 는다") + func likingAddsLike() { + var detail = makeDetail(isLiked: false, likeCount: 10) detail.markAsLiked() - #expect(detail.isLiked) + #expect(detail.isLiked == true) #expect(detail.likeCount == 11) } - @Test("이미 좋아요한 컬렉션에 markAsLiked를 호출하면 좋아요 수가 중복으로 늘지 않는다") - func markAsLikedTwice() { - var detail = makeDetail(likeCount: 10, isLiked: true) + @Test("이미 좋아요했으면 다시 좋아요해도 그대로다") + func likingAgainChangesNothing() { + var detail = makeDetail(isLiked: true, likeCount: 10) detail.markAsLiked() - #expect(detail.isLiked) + #expect(detail.isLiked == true) #expect(detail.likeCount == 10) } - // MARK: - unmarkAsLiked + // MARK: - 취소 - @Test("좋아요한 컬렉션을 취소하면 상태가 꺼지고 좋아요 수가 줄어든다") - func unmarkAsLiked() { - var detail = makeDetail(likeCount: 10, isLiked: true) + @Test("좋아요를 취소하면 좋아요 수가 하나 준다") + func unlikingRemovesLike() { + var detail = makeDetail(isLiked: true, likeCount: 10) detail.unmarkAsLiked() @@ -49,9 +49,9 @@ struct CollectionDetailTests { #expect(detail.likeCount == 9) } - @Test("좋아요하지 않은 컬렉션에 unmarkAsLiked를 호출하면 좋아요 수가 줄지 않는다") - func unmarkAsLikedWhenNotLiked() { - var detail = makeDetail(likeCount: 10, isLiked: false) + @Test("좋아요하지 않았으면 취소해도 그대로다") + func unlikingWithoutLikeChangesNothing() { + var detail = makeDetail(isLiked: false, likeCount: 10) detail.unmarkAsLiked() @@ -59,67 +59,50 @@ struct CollectionDetailTests { #expect(detail.likeCount == 10) } - @Test("좋아요 수가 0인 상태에서 취소해도 좋아요 수가 음수로 내려가지 않는다") - func unmarkAsLikedAtZero() { - var detail = makeDetail(likeCount: 0, isLiked: true) + @Test("좋아요 수가 0이면 취소해도 0 아래로 내려가지 않는다") + func unlikingNeverGoesBelowZero() { + var detail = makeDetail(isLiked: true, likeCount: 0) detail.unmarkAsLiked() + #expect(detail.isLiked == false) #expect(detail.likeCount == 0) } - // MARK: - toggleLike + // MARK: - 전환 - @Test("좋아요하지 않은 컬렉션을 토글하면 좋아요 상태가 된다") - func toggleLikeOn() { - var detail = makeDetail(likeCount: 3, isLiked: false) - - detail.toggleLike() - - #expect(detail.isLiked) - #expect(detail.likeCount == 4) - } - - @Test("좋아요한 컬렉션을 토글하면 좋아요가 취소된다") - func toggleLikeOff() { - var detail = makeDetail(likeCount: 3, isLiked: true) + @Test("좋아요한 컬렉션에서 좋아요를 전환하면 취소된다") + func togglingLikeRemovesIt() { + var detail = makeDetail(isLiked: true, likeCount: 10) detail.toggleLike() #expect(detail.isLiked == false) - #expect(detail.likeCount == 2) + #expect(detail.likeCount == 9) } - // MARK: - novelCount + @Test("좋아요하지 않은 컬렉션에서 좋아요를 전환하면 좋아요가 된다") + func togglingWithoutLikeAddsIt() { + var detail = makeDetail(isLiked: false, likeCount: 10) - @Test("작품 수는 담긴 작품 목록의 길이와 같다") - func novelCountMatchesNovels() { - let detail = makeDetail(novelCount: 3) + detail.toggleLike() - #expect(detail.novelCount == 3) + #expect(detail.isLiked == true) + #expect(detail.likeCount == 11) } -} - -// MARK: - Helper -private extension CollectionDetailTests { + // MARK: - Helpers - func makeDetail( - novelCount: Int = 1, - likeCount: Int = 0, - isLiked: Bool = false - ) -> CollectionDetail { + private func makeDetail(isLiked: Bool, likeCount: Int) -> CollectionDetail { CollectionDetail( id: CollectionID(1), - name: "취향 저격 로판", + name: "컬렉션", description: nil, owner: Author(userId: UserID(1), nickname: "웹소소", profileImage: nil), isMine: false, isPrivate: false, representativeNovelID: NovelID(1), - novels: (1...max(1, novelCount)).map { - CollectionNovel(id: NovelID($0), title: "작품", author: "작가", thumbnailImage: nil) - }, + novels: [CollectionNovel(id: NovelID(1), title: "작품", author: "작가", thumbnailImage: nil)], likeCount: likeCount, isLiked: isLiked ) diff --git a/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDraftTests.swift b/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDraftTests.swift index 3ee3f9833..8a27b799b 100644 --- a/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDraftTests.swift +++ b/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDraftTests.swift @@ -6,345 +6,395 @@ // Copyright © 2026 kr.websoso.app. All rights reserved. // -import Testing import Foundation +import Testing -@testable import CollectionDomain import BaseDomain +import CollectionDomain -@Suite("CollectionDraft") +@Suite("컬렉션 만들기·수정하기") struct CollectionDraftTests { - // MARK: - isSubmittable + @Suite("제출") + struct Submission { - @Test("이름이 있고 작품이 하나 이상이면 제출할 수 있다") - func submittableWithNameAndNovel() { - let draft = makeDraft(name: "취향 저격 로판", novelIDs: [NovelID(1)]) + @Test("이름이 있고 작품이 하나 이상이면 설명이 없어도 제출할 수 있다") + func submittableWithNameAndNovel() { + let draft = makeDraft(name: "취향 저격 로판", description: "", novelIDs: [NovelID(1)]) - #expect(draft.isSubmittable) - } + #expect(draft.isSubmittable == true) + } - @Test("설명은 선택 항목이라 비어 있어도 제출할 수 있다") - func submittableWithoutDescription() { - let draft = makeDraft(name: "취향 저격 로판", description: "", novelIDs: [NovelID(1)]) + @Test( + "이름이 비었거나 공백뿐이면 제출할 수 없다", + arguments: [ + "", // 아무것도 쓰지 않음 + " ", // 스페이스만 + "\n\t " // 줄바꿈·탭도 공백으로 본다 + ] + ) + func notSubmittableWithBlankName(name: String) { + let draft = makeDraft(name: name, novelIDs: [NovelID(1)]) - #expect(draft.isSubmittable) - } + #expect(draft.isSubmittable == false) + } - @Test("이름이 비어 있으면 제출할 수 없다") - func notSubmittableWithoutName() { - let draft = makeDraft(name: "", novelIDs: [NovelID(1)]) + @Test("작품이 하나도 없으면 제출할 수 없다") + func notSubmittableWithoutNovel() { + let draft = makeDraft(name: "취향 저격 로판", novelIDs: []) - #expect(draft.isSubmittable == false) + #expect(draft.isSubmittable == false) + } } - @Test("이름이 공백 문자뿐이면 제출할 수 없다") - func notSubmittableWithBlankName() { - let draft = makeDraft(name: " ", novelIDs: [NovelID(1)]) + @Suite("이름") + struct Name { - #expect(draft.isSubmittable == false) - } + @Test("이름은 20자까지 입력할 수 있다") + func nameAcceptsUpToTwenty() throws { + var draft = makeDraft() + let name = String(repeating: "가", count: 20) - @Test("작품이 하나도 없으면 제출할 수 없다") - func notSubmittableWithoutNovel() { - let draft = makeDraft(name: "취향 저격 로판", novelIDs: []) + try draft.updateName(name) - #expect(draft.isSubmittable == false) - } - - // MARK: - updateName + #expect(draft.name == name) + } - @Test("이름을 20자까지는 입력할 수 있다") - func updateNameAtLimit() throws { - var draft = makeDraft() + @Test("이름이 20자를 넘으면 거부하고 이전 이름을 지킨다") + func nameOverTwentyIsRejected() { + var draft = makeDraft(name: "원래 이름") - try draft.updateName(String(repeating: "가", count: 20)) + #expect(throws: CollectionDraft.ValidationError.nameOverLimit(max: 20)) { + try draft.updateName(String(repeating: "가", count: 21)) + } + #expect(draft.name == "원래 이름") + } - #expect(draft.name.count == 20) - } + @Test("남은 이름 글자 수는 20에서 지금 길이를 뺀 값이다") + func remainingNameCount() { + let draft = makeDraft(name: "다섯글자야") - @Test("이름이 20자를 넘으면 입력이 거부되고 이전 값이 남는다") - func updateNameOverLimit() { - var draft = makeDraft(name: "원래 이름") + let remains = draft.remainsNameCount() - #expect(throws: CollectionDraft.ValidationError.nameOverLimit(max: 20)) { - try draft.updateName(String(repeating: "가", count: 21)) + #expect(remains == 20 - 5) } - #expect(draft.name == "원래 이름") } - @Test("이름 남은 글자 수는 20에서 현재 길이를 뺀 값이다") - func remainsNameCount() throws { - var draft = makeDraft() + @Suite("설명") + struct Description { - try draft.updateName("다섯글자야") + @Test("설명은 60자까지 입력할 수 있다") + func descriptionAcceptsUpToSixty() throws { + var draft = makeDraft() + let description = String(repeating: "가", count: 60) - #expect(draft.remainsNameCount() == 15) - } + try draft.updateDescription(description) - // MARK: - updateDescription + #expect(draft.description == description) + } - @Test("설명을 60자까지는 입력할 수 있다") - func updateDescriptionAtLimit() throws { - var draft = makeDraft() + @Test("설명이 60자를 넘으면 거부하고 이전 설명을 지킨다") + func descriptionOverSixtyIsRejected() { + var draft = makeDraft(description: "원래 설명") - try draft.updateDescription(String(repeating: "가", count: 60)) + #expect(throws: CollectionDraft.ValidationError.descriptionOverLimit(max: 60)) { + try draft.updateDescription(String(repeating: "가", count: 61)) + } + #expect(draft.description == "원래 설명") + } - #expect(draft.description.count == 60) - } + @Test("남은 설명 글자 수는 60에서 지금 길이를 뺀 값이다") + func remainingDescriptionCount() { + let draft = makeDraft(description: "다섯글자야") - @Test("설명이 60자를 넘으면 입력이 거부된다") - func updateDescriptionOverLimit() { - var draft = makeDraft() + let remains = draft.remainsDescriptionCount() - #expect(throws: CollectionDraft.ValidationError.descriptionOverLimit(max: 60)) { - try draft.updateDescription(String(repeating: "가", count: 61)) + #expect(remains == 60 - 5) } } - // MARK: - init + @Suite("수정하기") + struct Editing { - @Test("저장된 값으로 초안을 만들 때 제한을 넘는 이름은 잘려서 들어온다") - func initTruncatesOverLimitName() { - let draft = makeDraft(name: String(repeating: "가", count: 25)) + @Test("수정하기를 열면 저장된 컬렉션 내용이 그대로 채워진다") + func editingFillsSavedCollection() { + let detail = makeDetail( + name: "취향 저격 로판", + description: "여주가 강한 로맨스 판타지", + isPrivate: true, + novelIDs: [NovelID(9), NovelID(5)], + representativeNovelID: NovelID(5) + ) - #expect(draft.name.count == 20) - } + let draft = CollectionDraft(from: detail) - @Test("수정하기 화면은 기존 컬렉션을 그대로 편집 가능한 초안으로 되돌린다") - func initFromDetail() { - let detail = makeDetail( - name: "취향 저격 로판", - description: "여주가 강한 로맨스 판타지", - isPrivate: true, - novelIDs: [NovelID(9), NovelID(5)], - representativeNovelID: NovelID(5) - ) + #expect(draft.name == "취향 저격 로판") + #expect(draft.description == "여주가 강한 로맨스 판타지") + #expect(draft.isPrivate == true) + #expect(draft.novelIDs == [NovelID(9), NovelID(5)]) + #expect(draft.representativeNovelID == NovelID(5)) + } - let draft = CollectionDraft(from: detail) + @Test("설명이 없던 컬렉션은 수정하기를 열면 설명이 비어 있다") + func editingCollectionWithoutDescription() { + let detail = makeDetail(description: nil) - #expect(draft.name == "취향 저격 로판") - #expect(draft.description == "여주가 강한 로맨스 판타지") - #expect(draft.isPrivate) - #expect(draft.novelIDs == [NovelID(9), NovelID(5)]) - #expect(draft.representativeNovelID == NovelID(5)) - } + let draft = CollectionDraft(from: detail) + + #expect(draft.description == "") + } - @Test("설명이 없던 컬렉션을 초안으로 되돌리면 설명은 빈 문자열이 된다") - func initFromDetailWithoutDescription() { - let detail = makeDetail(description: nil) + @Test("저장된 컬렉션이 제한을 넘으면 넘는 부분을 잘라 채운다") + func editingCutsOverLimitValues() { + // 넘치는 마지막 글자만 다르게 둬서, 잘려 나간 쪽이 뒤인지 확인한다. + let detail = makeDetail( + name: String(repeating: "가", count: 20) + "나", + description: String(repeating: "가", count: 60) + "나", + novelIDs: (1...101).map { NovelID($0) } + ) - let draft = CollectionDraft(from: detail) + let draft = CollectionDraft(from: detail) - #expect(draft.description.isEmpty) + #expect(draft.name == String(repeating: "가", count: 20)) + #expect(draft.description == String(repeating: "가", count: 60)) + #expect(draft.novelIDs == (1...100).map { NovelID($0) }) + } } - // MARK: - addNovel + @Suite("작품 추가·빼기") + struct AddingAndRemovingNovels { - @Test("작품을 추가하면 표시 순서 끝에 붙는다") - func addNovelAppends() throws { - var draft = makeDraft(novelIDs: [NovelID(1)]) + @Test("작품을 추가하면 목록 끝에 붙는다") + func addingNovelAppends() throws { + var draft = makeDraft(novelIDs: [NovelID(1)]) - try draft.addNovel(NovelID(2)) + try draft.addNovel(NovelID(2)) - #expect(draft.novelIDs == [NovelID(1), NovelID(2)]) - } + #expect(draft.novelIDs == [NovelID(1), NovelID(2)]) + } - @Test("이미 담긴 작품은 다시 추가할 수 없다") - func addDuplicatedNovel() { - var draft = makeDraft(novelIDs: [NovelID(1)]) + @Test("이미 담긴 작품은 다시 추가할 수 없다") + func addingDuplicatedNovelIsRejected() { + var draft = makeDraft(novelIDs: [NovelID(1)]) - #expect(throws: CollectionDraft.ValidationError.duplicatedNovel) { - try draft.addNovel(NovelID(1)) + #expect(throws: CollectionDraft.ValidationError.duplicatedNovel) { + try draft.addNovel(NovelID(1)) + } + #expect(draft.novelIDs == [NovelID(1)]) } - #expect(draft.novelIDs.count == 1) - } - @Test("작품이 100개면 더 추가할 수 없다") - func addNovelOverLimit() { - var draft = makeDraft(novelIDs: (1...100).map { NovelID($0) }) + @Test("작품이 100개면 더 추가할 수 없다") + func addingOverHundredIsRejected() { + let novelIDs = (1...100).map { NovelID($0) } + var draft = makeDraft(novelIDs: novelIDs) - #expect(throws: CollectionDraft.ValidationError.novelOverLimit(max: 100)) { - try draft.addNovel(NovelID(101)) + #expect(throws: CollectionDraft.ValidationError.novelOverLimit(max: 100)) { + try draft.addNovel(NovelID(101)) + } + #expect(draft.novelIDs == novelIDs) } - } - // MARK: - removeNovel + @Test("작품을 빼면 목록에서 사라진다") + func removingNovelDropsIt() { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - @Test("작품을 빼면 목록에서 사라진다") - func removeNovel() { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) + draft.removeNovel(NovelID(1)) - draft.removeNovel(NovelID(1)) - - #expect(draft.novelIDs == [NovelID(2)]) + #expect(draft.novelIDs == [NovelID(2)]) + } } - @Test("대표로 지정한 작품을 빼면 대표 지정도 함께 풀린다") - func removeRepresentativeNovel() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - try draft.setRepresentativeNovel(NovelID(1)) + @Suite("작품 목록 통째로 바꾸기") + struct SettingNovels { - draft.removeNovel(NovelID(1)) + @Test("작품 목록을 새 목록으로 통째로 바꿀 수 있다") + func settingNovelsReplacesAll() throws { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - #expect(draft.representativeNovelID == nil) - } + try draft.setNovels([NovelID(3), NovelID(4), NovelID(5)]) - @Test("대표가 아닌 작품을 빼면 대표 지정은 그대로 남는다") - func removeNonRepresentativeNovel() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - try draft.setRepresentativeNovel(NovelID(1)) + #expect(draft.novelIDs == [NovelID(3), NovelID(4), NovelID(5)]) + } - draft.removeNovel(NovelID(2)) + @Test("새 목록이 100개여도 통째로 바꿀 수 있다") + func settingNovelsAcceptsUpToHundred() throws { + var draft = makeDraft(novelIDs: [NovelID(1)]) + let novelIDs = (1...100).map { NovelID($0) } - #expect(draft.representativeNovelID == NovelID(1)) - } + try draft.setNovels(novelIDs) + + #expect(draft.novelIDs == novelIDs) + } - // MARK: - setNovels + @Test("새 목록이 100개를 넘으면 바꿀 수 없다") + func settingOverHundredNovelsIsRejected() { + var draft = makeDraft(novelIDs: [NovelID(1)]) - @Test("작품 리스트 전체를 새 선택 결과로 교체한다") - func setNovelsReplacesAll() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) + #expect(throws: CollectionDraft.ValidationError.novelOverLimit(max: 100)) { + try draft.setNovels((1...101).map { NovelID($0) }) + } + #expect(draft.novelIDs == [NovelID(1)]) + } - try draft.setNovels([NovelID(3), NovelID(4), NovelID(5)]) + @Test("새 목록에 같은 작품이 두 번 있으면 바꿀 수 없다") + func settingDuplicatedNovelsIsRejected() { + var draft = makeDraft(novelIDs: [NovelID(1)]) - #expect(draft.novelIDs == [NovelID(3), NovelID(4), NovelID(5)]) + #expect(throws: CollectionDraft.ValidationError.duplicatedNovel) { + try draft.setNovels([NovelID(2), NovelID(3), NovelID(2)]) + } + #expect(draft.novelIDs == [NovelID(1)]) + } } - @Test("작품이 100개를 넘으면 교체할 수 없다") - func setNovelsOverLimit() { - var draft = makeDraft(novelIDs: [NovelID(1)]) + @Suite("대표 작품 고르기") + struct Representative { + + @Test("담긴 작품을 대표로 고를 수 있다") + func choosingIncludedNovelAsRepresentative() throws { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - #expect(throws: CollectionDraft.ValidationError.novelOverLimit(max: 100)) { - try draft.setNovels((1...101).map { NovelID($0) }) + try draft.setRepresentativeNovel(NovelID(2)) + + #expect(draft.representativeNovelID == NovelID(2)) } - #expect(draft.novelIDs == [NovelID(1)]) - } - @Test("대표 작품이 새 목록에 없으면 대표 지정도 함께 풀린다") - func setNovelsDropsRepresentativeWhenExcluded() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - try draft.setRepresentativeNovel(NovelID(1)) + @Test("담기지 않은 작품은 대표로 고를 수 없다") + func choosingMissingNovelAsRepresentativeIsRejected() { + var draft = makeDraft(novelIDs: [NovelID(1)]) - try draft.setNovels([NovelID(2), NovelID(3)]) + #expect(throws: CollectionDraft.ValidationError.representativeNovelNotIncluded) { + try draft.setRepresentativeNovel(NovelID(99)) + } + #expect(draft.representativeNovelID == nil) + } - #expect(draft.representativeNovelID == nil) - } + @Test("대표를 고르지 않았으면 첫 작품이 대표다") + func firstNovelIsRepresentativeByDefault() { + let draft = makeDraft(novelIDs: [NovelID(7), NovelID(3)]) - @Test("대표 작품이 새 목록에도 있으면 대표 지정이 유지된다") - func setNovelsKeepsRepresentativeWhenIncluded() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - try draft.setRepresentativeNovel(NovelID(1)) + let representative = draft.effectiveRepresentativeNovelID - try draft.setNovels([NovelID(1), NovelID(3)]) + #expect(representative == NovelID(7)) + } - #expect(draft.representativeNovelID == NovelID(1)) - } + @Test("대표를 골랐으면 고른 작품이 대표다") + func chosenNovelIsRepresentative() { + let draft = makeDraft(novelIDs: [NovelID(7), NovelID(3)], representativeNovelID: NovelID(3)) - // MARK: - setRepresentativeNovel + let representative = draft.effectiveRepresentativeNovelID - @Test("담긴 작품 중 하나를 대표로 지정할 수 있다") - func setRepresentativeNovel() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) + #expect(representative == NovelID(3)) + } + + @Test("작품이 없으면 대표도 없다") + func noRepresentativeWithoutNovel() { + let draft = makeDraft(novelIDs: []) - try draft.setRepresentativeNovel(NovelID(2)) + let representative = draft.effectiveRepresentativeNovelID - #expect(draft.representativeNovelID == NovelID(2)) + #expect(representative == nil) + } } - @Test("담기지 않은 작품은 대표로 지정할 수 없다") - func setRepresentativeNovelNotIncluded() { - var draft = makeDraft(novelIDs: [NovelID(1)]) + @Suite("작품이 빠질 때 대표 작품") + struct RepresentativeAfterNovelChange { + + @Test("대표로 고른 작품을 빼면 대표 선택도 풀린다") + func removingRepresentativeClearsIt() { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)], representativeNovelID: NovelID(1)) - #expect(throws: CollectionDraft.ValidationError.representativeNovelNotIncluded) { - try draft.setRepresentativeNovel(NovelID(99)) + draft.removeNovel(NovelID(1)) + + #expect(draft.representativeNovelID == nil) } - } - // MARK: - effectiveRepresentativeNovelID + @Test("대표로 고르지 않은 작품을 빼면 대표 선택은 그대로다") + func removingOtherNovelKeepsRepresentative() { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)], representativeNovelID: NovelID(1)) - @Test("대표를 고르지 않았으면 표시 순서 첫 작품이 대표가 된다") - func effectiveRepresentativeFallsBackToFirst() { - let draft = makeDraft(novelIDs: [NovelID(7), NovelID(3)]) + draft.removeNovel(NovelID(2)) - #expect(draft.effectiveRepresentativeNovelID == NovelID(7)) - } + #expect(draft.representativeNovelID == NovelID(1)) + } - @Test("대표를 골랐으면 첫 작품이 아니라 고른 작품이 대표가 된다") - func effectiveRepresentativeUsesChosen() throws { - var draft = makeDraft(novelIDs: [NovelID(7), NovelID(3)]) + @Test("대표로 고른 작품이 새 목록에 없으면 대표 선택도 풀린다") + func settingNovelsWithoutRepresentativeClearsIt() throws { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)], representativeNovelID: NovelID(1)) - try draft.setRepresentativeNovel(NovelID(3)) + try draft.setNovels([NovelID(2), NovelID(3)]) - #expect(draft.effectiveRepresentativeNovelID == NovelID(3)) - } + #expect(draft.representativeNovelID == nil) + } - @Test("작품이 하나도 없으면 대표도 없다") - func effectiveRepresentativeWithoutNovel() { - let draft = makeDraft(novelIDs: []) + @Test("대표로 고른 작품이 새 목록에도 있으면 대표 선택은 그대로다") + func settingNovelsWithRepresentativeKeepsIt() throws { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)], representativeNovelID: NovelID(1)) - #expect(draft.effectiveRepresentativeNovelID == nil) + try draft.setNovels([NovelID(3), NovelID(1)]) + + #expect(draft.representativeNovelID == NovelID(1)) + } } - // MARK: - togglePrivate + @Suite("나만 보기") + struct Private { - @Test("나만 보는 컬렉션은 기본적으로 꺼져 있다") - func privateIsOffByDefault() { - let draft = CollectionDraft() + @Test("컬렉션을 새로 만들 때 나만 보기는 꺼져 있다") + func privateIsOffForNewCollection() { + let draft = CollectionDraft() - #expect(draft.isPrivate == false) - } + #expect(draft.isPrivate == false) + } - @Test("나만 보기를 토글하면 상태가 뒤집힌다") - func togglePrivate() { - var draft = makeDraft() + @Test("꺼진 나만 보기를 누르면 켜진다") + func togglingPrivateTurnsItOn() { + var draft = makeDraft(isPrivate: false) - draft.togglePrivate() + draft.togglePrivate() - #expect(draft.isPrivate) + #expect(draft.isPrivate == true) + } } } -// MARK: - Helper - -private extension CollectionDraftTests { - - func makeDraft( - name: String = "컬렉션", - description: String = "설명", - isPrivate: Bool = false, - novelIDs: [NovelID] = [NovelID(1)], - representativeNovelID: NovelID? = nil - ) -> CollectionDraft { - CollectionDraft( - name: name, - description: description, - isPrivate: isPrivate, - novelIDs: novelIDs, - representativeNovelID: representativeNovelID - ) - } +// MARK: - Helpers + +private func makeDraft( + name: String = "컬렉션", + description: String = "설명", + isPrivate: Bool = false, + novelIDs: [NovelID] = [NovelID(1)], + representativeNovelID: NovelID? = nil +) -> CollectionDraft { + CollectionDraft( + name: name, + description: description, + isPrivate: isPrivate, + novelIDs: novelIDs, + representativeNovelID: representativeNovelID + ) +} - func makeDetail( - name: String = "컬렉션", - description: String? = "설명", - isPrivate: Bool = false, - novelIDs: [NovelID] = [NovelID(1)], - representativeNovelID: NovelID = NovelID(1) - ) -> CollectionDetail { - CollectionDetail( - id: CollectionID(1), - name: name, - description: description, - owner: Author(userId: UserID(1), nickname: "웹소소", profileImage: nil), - isMine: true, - isPrivate: isPrivate, - representativeNovelID: representativeNovelID, - novels: novelIDs.map { - CollectionNovel(id: $0, title: "작품", author: "작가", thumbnailImage: nil) - }, - likeCount: 0, - isLiked: false - ) - } +private func makeDetail( + name: String = "컬렉션", + description: String? = "설명", + isPrivate: Bool = false, + novelIDs: [NovelID] = [NovelID(1)], + representativeNovelID: NovelID = NovelID(1) +) -> CollectionDetail { + CollectionDetail( + id: CollectionID(1), + name: name, + description: description, + owner: Author(userId: UserID(1), nickname: "웹소소", profileImage: nil), + isMine: true, + isPrivate: isPrivate, + representativeNovelID: representativeNovelID, + novels: novelIDs.map { + CollectionNovel(id: $0, title: "작품", author: "작가", thumbnailImage: nil) + }, + likeCount: 0, + isLiked: false + ) } diff --git a/Projects/Domain/CollectionDomain/Tests/UseCase/CollectionLikeUseCaseTests.swift b/Projects/Domain/CollectionDomain/Tests/UseCase/CollectionLikeUseCaseTests.swift deleted file mode 100644 index a43759fbe..000000000 --- a/Projects/Domain/CollectionDomain/Tests/UseCase/CollectionLikeUseCaseTests.swift +++ /dev/null @@ -1,73 +0,0 @@ -// -// CollectionLikeUseCaseTests.swift -// CollectionDomainTests -// -// Created by YunhakLee on 8/18/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing -import Foundation - -@testable import CollectionDomain -import CollectionDomainTesting -import BaseDomain - -@Suite("CollectionLikeUseCase") -struct CollectionLikeUseCaseTests { - - @Test("좋아요를 누르면 해당 컬렉션 ID로 등록을 요청한다") - func likeSuccess() async throws { - let mock = MockCollectionRepository() - let useCase = DefaultCollectionLikeUseCase(collectionRepository: mock) - - try await useCase.like(id: CollectionID(31)) - - #expect(mock.likedIDs == [CollectionID(31)]) - #expect(mock.unlikedIDs.isEmpty) - } - - @Test("좋아요를 취소하면 해당 컬렉션 ID로 취소를 요청한다") - func unlikeSuccess() async throws { - let mock = MockCollectionRepository() - let useCase = DefaultCollectionLikeUseCase(collectionRepository: mock) - - try await useCase.unlike(id: CollectionID(31)) - - #expect(mock.unlikedIDs == [CollectionID(31)]) - #expect(mock.likedIDs.isEmpty) - } - - @Test("서버가 멱등이라 같은 좋아요를 두 번 보내도 그대로 두 번 요청한다") - func likeIsIdempotentOnServer() async throws { - let mock = MockCollectionRepository() - let useCase = DefaultCollectionLikeUseCase(collectionRepository: mock) - - try await useCase.like(id: CollectionID(31)) - try await useCase.like(id: CollectionID(31)) - - #expect(mock.likedIDs == [CollectionID(31), CollectionID(31)]) - } - - @Test("볼 수 없는 컬렉션에 좋아요를 누르면 forbidden을 전달한다") - func likeForbidden() async { - let mock = MockCollectionRepository() - mock.likeCollectionResult = .failure(.forbidden) - let useCase = DefaultCollectionLikeUseCase(collectionRepository: mock) - - await #expect(throws: RepositoryError.forbidden) { - try await useCase.like(id: CollectionID(31)) - } - } - - @Test("좋아요 취소에 실패하면 에러를 그대로 전달한다") - func unlikeFailure() async { - let mock = MockCollectionRepository() - mock.unlikeCollectionResult = .failure(.networkUnavailable) - let useCase = DefaultCollectionLikeUseCase(collectionRepository: mock) - - await #expect(throws: RepositoryError.networkUnavailable) { - try await useCase.unlike(id: CollectionID(31)) - } - } -} diff --git a/Projects/Domain/CollectionDomain/Tests/UseCase/CreateCollectionUseCaseTests.swift b/Projects/Domain/CollectionDomain/Tests/UseCase/CreateCollectionUseCaseTests.swift deleted file mode 100644 index 70b4980ea..000000000 --- a/Projects/Domain/CollectionDomain/Tests/UseCase/CreateCollectionUseCaseTests.swift +++ /dev/null @@ -1,77 +0,0 @@ -// -// CreateCollectionUseCaseTests.swift -// CollectionDomainTests -// -// Created by YunhakLee on 8/18/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing -import Foundation - -@testable import CollectionDomain -import CollectionDomainTesting -import BaseDomain - -@Suite("CreateCollectionUseCase") -struct CreateCollectionUseCaseTests { - - @Test("컬렉션을 만들면 생성된 컬렉션 ID를 돌려준다") - func createSuccess() async throws { - let mock = MockCollectionRepository() - mock.createCollectionResult = .success(CollectionID(12)) - let useCase = DefaultCreateCollectionUseCase(collectionRepository: mock) - - let id = try await useCase.execute(makeDraft()) - - #expect(id == CollectionID(12)) - #expect(mock.createdDrafts.count == 1) - } - - @Test("작품의 표시 순서가 초안 그대로 전달된다") - func preservesNovelOrder() async throws { - let mock = MockCollectionRepository() - mock.createCollectionResult = .success(CollectionID(1)) - let useCase = DefaultCreateCollectionUseCase(collectionRepository: mock) - - _ = try await useCase.execute(makeDraft(novelIDs: [NovelID(9), NovelID(5), NovelID(3)])) - - #expect(mock.createdDrafts.last?.novelIDs == [NovelID(9), NovelID(5), NovelID(3)]) - } - - @Test("나만 보는 설정이 초안 그대로 전달된다") - func passesPrivacy() async throws { - let mock = MockCollectionRepository() - mock.createCollectionResult = .success(CollectionID(1)) - let useCase = DefaultCreateCollectionUseCase(collectionRepository: mock) - - _ = try await useCase.execute(makeDraft(isPrivate: true)) - - #expect(mock.createdDrafts.last?.isPrivate == true) - } - - @Test("생성에 실패하면 에러를 그대로 전달한다") - func createFailure() async { - let mock = MockCollectionRepository() - mock.createCollectionResult = .failure(.invalidData) - let useCase = DefaultCreateCollectionUseCase(collectionRepository: mock) - - await #expect(throws: RepositoryError.invalidData) { - try await useCase.execute(makeDraft()) - } - } -} - -private extension CreateCollectionUseCaseTests { - func makeDraft( - isPrivate: Bool = false, - novelIDs: [NovelID] = [NovelID(1)] - ) -> CollectionDraft { - CollectionDraft( - name: "취향 저격 로판", - description: "여주가 강한 로맨스 판타지", - isPrivate: isPrivate, - novelIDs: novelIDs - ) - } -} diff --git a/Projects/Domain/CollectionDomain/Tests/UseCase/DeleteCollectionUseCaseTests.swift b/Projects/Domain/CollectionDomain/Tests/UseCase/DeleteCollectionUseCaseTests.swift deleted file mode 100644 index 1f8d15ab5..000000000 --- a/Projects/Domain/CollectionDomain/Tests/UseCase/DeleteCollectionUseCaseTests.swift +++ /dev/null @@ -1,39 +0,0 @@ -// -// DeleteCollectionUseCaseTests.swift -// CollectionDomainTests -// -// Created by YunhakLee on 8/18/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing -import Foundation - -@testable import CollectionDomain -import CollectionDomainTesting -import BaseDomain - -@Suite("DeleteCollectionUseCase") -struct DeleteCollectionUseCaseTests { - - @Test("삭제하려는 컬렉션 ID가 전달된다") - func deleteSuccess() async throws { - let mock = MockCollectionRepository() - let useCase = DefaultDeleteCollectionUseCase(collectionRepository: mock) - - try await useCase.execute(id: CollectionID(31)) - - #expect(mock.deletedIDs == [CollectionID(31)]) - } - - @Test("삭제에 실패하면 에러를 그대로 전달한다") - func deleteFailure() async { - let mock = MockCollectionRepository() - mock.deleteCollectionResult = .failure(.notFound) - let useCase = DefaultDeleteCollectionUseCase(collectionRepository: mock) - - await #expect(throws: RepositoryError.notFound) { - try await useCase.execute(id: CollectionID(31)) - } - } -} diff --git a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadCollectionDetailUseCaseTests.swift b/Projects/Domain/CollectionDomain/Tests/UseCase/LoadCollectionDetailUseCaseTests.swift deleted file mode 100644 index ebef8de2a..000000000 --- a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadCollectionDetailUseCaseTests.swift +++ /dev/null @@ -1,80 +0,0 @@ -// -// LoadCollectionDetailUseCaseTests.swift -// CollectionDomainTests -// -// Created by YunhakLee on 8/18/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing -import Foundation - -@testable import CollectionDomain -import CollectionDomainTesting -import BaseDomain - -@Suite("LoadCollectionDetailUseCase") -struct LoadCollectionDetailUseCaseTests { - - @Test("컬렉션 상세를 불러온다") - func loadSuccess() async throws { - let mock = MockCollectionRepository() - mock.fetchCollectionDetailResult = .success(makeDetail(name: "취향 저격 로판")) - let useCase = DefaultLoadCollectionDetailUseCase(collectionRepository: mock) - - let detail = try await useCase.execute(id: CollectionID(31), sortType: .recent) - - #expect(detail.name == "취향 저격 로판") - } - - @Test("화면이 고른 정렬 기준이 그대로 전달된다") - func passesSortType() async throws { - let mock = MockCollectionRepository() - mock.fetchCollectionDetailResult = .success(makeDetail()) - let useCase = DefaultLoadCollectionDetailUseCase(collectionRepository: mock) - - _ = try await useCase.execute(id: CollectionID(31), sortType: .old) - - #expect(mock.fetchedDetailRequests.last?.sortType == .old) - #expect(mock.fetchedDetailRequests.last?.id == CollectionID(31)) - } - - @Test("없는 컬렉션을 조회하면 notFound를 전달한다") - func loadNotFound() async { - let mock = MockCollectionRepository() - mock.fetchCollectionDetailResult = .failure(.notFound) - let useCase = DefaultLoadCollectionDetailUseCase(collectionRepository: mock) - - await #expect(throws: RepositoryError.notFound) { - try await useCase.execute(id: CollectionID(99), sortType: .recent) - } - } - - @Test("남의 나만 보는 컬렉션을 조회하면 forbidden을 전달한다") - func loadForbidden() async { - let mock = MockCollectionRepository() - mock.fetchCollectionDetailResult = .failure(.forbidden) - let useCase = DefaultLoadCollectionDetailUseCase(collectionRepository: mock) - - await #expect(throws: RepositoryError.forbidden) { - try await useCase.execute(id: CollectionID(31), sortType: .recent) - } - } -} - -private extension LoadCollectionDetailUseCaseTests { - func makeDetail(name: String = "컬렉션") -> CollectionDetail { - CollectionDetail( - id: CollectionID(31), - name: name, - description: nil, - owner: Author(userId: UserID(7), nickname: "웹소소", profileImage: nil), - isMine: true, - isPrivate: false, - representativeNovelID: NovelID(1), - novels: [CollectionNovel(id: NovelID(1), title: "작품", author: "작가", thumbnailImage: nil)], - likeCount: 0, - isLiked: false - ) - } -} diff --git a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadCollectionPreviewsUseCaseTests.swift b/Projects/Domain/CollectionDomain/Tests/UseCase/LoadCollectionPreviewsUseCaseTests.swift deleted file mode 100644 index 5b17b7aa7..000000000 --- a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadCollectionPreviewsUseCaseTests.swift +++ /dev/null @@ -1,76 +0,0 @@ -// -// LoadCollectionPreviewsUseCaseTests.swift -// CollectionDomainTests -// -// Created by YunhakLee on 8/18/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing -import Foundation - -@testable import CollectionDomain -import CollectionDomainTesting -import BaseDomain - -@Suite("LoadCollectionPreviewsUseCase") -struct LoadCollectionPreviewsUseCaseTests { - - @Test("마이페이지 미리보기와 전체 컬렉션 수를 함께 불러온다") - func loadSuccess() async throws { - let mock = MockCollectionRepository() - mock.fetchCollectionPreviewsResult = .success(([makePreview(), makePreview()], 7)) - let useCase = DefaultLoadCollectionPreviewsUseCase(collectionRepository: mock) - - let (previews, totalCount) = try await useCase.execute(userID: UserID(1), size: 3) - - #expect(previews.count == 2) - #expect(totalCount == 7) - } - - @Test("전체 개수는 이번에 받아온 미리보기 개수와 별개다") - func totalCountIsIndependentFromPageSize() async throws { - let mock = MockCollectionRepository() - mock.fetchCollectionPreviewsResult = .success(([makePreview(), makePreview(), makePreview()], 21)) - let useCase = DefaultLoadCollectionPreviewsUseCase(collectionRepository: mock) - - let (previews, totalCount) = try await useCase.execute(userID: UserID(1), size: 3) - - #expect(previews.count == 3) - #expect(totalCount == 21) - } - - @Test("화면이 정한 조회 개수가 그대로 전달된다") - func passesRequestedSize() async throws { - let mock = MockCollectionRepository() - mock.fetchCollectionPreviewsResult = .success(([], 0)) - let useCase = DefaultLoadCollectionPreviewsUseCase(collectionRepository: mock) - - _ = try await useCase.execute(userID: UserID(42), size: 3) - - #expect(mock.fetchedPreviewRequests.last?.size == 3) - #expect(mock.fetchedPreviewRequests.last?.userID == UserID(42)) - #expect(mock.fetchedPreviewRequests.count == 1) - } - - @Test("조회에 실패하면 에러를 그대로 전달한다") - func loadFailure() async { - let mock = MockCollectionRepository() - mock.fetchCollectionPreviewsResult = .failure(.networkUnavailable) - let useCase = DefaultLoadCollectionPreviewsUseCase(collectionRepository: mock) - - await #expect(throws: RepositoryError.networkUnavailable) { - try await useCase.execute(userID: UserID(1), size: 3) - } - } -} - -private extension LoadCollectionPreviewsUseCaseTests { - func makePreview() -> CollectionPreview { - CollectionPreview( - id: CollectionID(1), - name: "취향 저격 로판", - representativeNovel: CollectionNovel(id: NovelID(1), title: "작품", author: "작가", thumbnailImage: nil) - ) - } -} diff --git a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadCollectionsUseCaseTests.swift b/Projects/Domain/CollectionDomain/Tests/UseCase/LoadCollectionsUseCaseTests.swift deleted file mode 100644 index 5b942d466..000000000 --- a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadCollectionsUseCaseTests.swift +++ /dev/null @@ -1,100 +0,0 @@ -// -// LoadCollectionsUseCaseTests.swift -// CollectionDomainTests -// -// Created by YunhakLee on 8/18/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing -import Foundation - -@testable import CollectionDomain -import CollectionDomainTesting -import BaseDomain - -@Suite("LoadCollectionsUseCase") -struct LoadCollectionsUseCaseTests { - - @Test("컬렉션 목록과 전체 개수를 함께 불러온다") - func loadSuccess() async throws { - let mock = MockCollectionRepository() - mock.fetchCollectionsResult = .success((makePage(cardCount: 2, hasNext: true, nextCursor: "c1"), 12)) - let useCase = DefaultLoadCollectionsUseCase(collectionRepository: mock) - - let (page, totalCount) = try await useCase.execute(userID: UserID(1), cursor: nil, size: 10) - - #expect(page.items.count == 2) - #expect(page.hasNext) - #expect(page.nextCursor == "c1") - #expect(totalCount == 12) - } - - @Test("첫 페이지는 커서 없이 요청한다") - func firstPageHasNoCursor() async throws { - let mock = MockCollectionRepository() - mock.fetchCollectionsResult = .success((makePage(), 0)) - let useCase = DefaultLoadCollectionsUseCase(collectionRepository: mock) - - _ = try await useCase.execute(userID: UserID(1), cursor: nil, size: 10) - - #expect(mock.fetchedCollectionRequests.last?.cursor == nil) - } - - @Test("다음 페이지는 직전 응답이 준 커서를 그대로 넘긴다") - func nextPagePassesCursorAsIs() async throws { - let mock = MockCollectionRepository() - mock.fetchCollectionsResult = .success((makePage(), 0)) - let useCase = DefaultLoadCollectionsUseCase(collectionRepository: mock) - - _ = try await useCase.execute(userID: UserID(1), cursor: "server-issued-cursor", size: 10) - - #expect(mock.fetchedCollectionRequests.last?.cursor == "server-issued-cursor") - } - - @Test("마지막 페이지에는 다음 커서가 없다") - func lastPageHasNoNextCursor() async throws { - let mock = MockCollectionRepository() - mock.fetchCollectionsResult = .success((makePage(hasNext: false, nextCursor: nil), 2)) - let useCase = DefaultLoadCollectionsUseCase(collectionRepository: mock) - - let (page, _) = try await useCase.execute(userID: UserID(1), cursor: "c1", size: 10) - - #expect(page.hasNext == false) - #expect(page.nextCursor == nil) - } - - @Test("조회에 실패하면 에러를 그대로 전달한다") - func loadFailure() async { - let mock = MockCollectionRepository() - mock.fetchCollectionsResult = .failure(.forbidden) - let useCase = DefaultLoadCollectionsUseCase(collectionRepository: mock) - - await #expect(throws: RepositoryError.forbidden) { - try await useCase.execute(userID: UserID(1), cursor: nil, size: 10) - } - } -} - -private extension LoadCollectionsUseCaseTests { - func makePage( - cardCount: Int = 1, - hasNext: Bool = false, - nextCursor: String? = nil - ) -> CursorPaginated { - CursorPaginated( - items: (0.. CursorPaginated { - CursorPaginated( - items: (0.. CursorPaginated { - CursorPaginated( - items: (0.. CollectionDraft { - CollectionDraft(name: name, novelIDs: novelIDs) - } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryUseCaseTests.swift index 62916507f..c4a1dd6e9 100644 --- a/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryUseCaseTests.swift +++ b/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryUseCaseTests.swift @@ -113,7 +113,6 @@ struct LoadMyLibraryUseCaseTests { _ = try await usecase.execute(filter: MyLibraryFilter(), cursor: nil, size: 20) #expect(novelRepository.lastMyLibraryCachedKeywords == [keyword]) - #expect(keywordRepository.fetchKeywordsCallCount == 1) } @Test("키워드 캐시 조회에 실패해도 서재 목록은 빈 캐시로 정상 조회된다") @@ -132,8 +131,7 @@ struct LoadMyLibraryUseCaseTests { #expect(result.0.items.count == expected.items.count) #expect(novelRepository.lastMyLibraryCachedKeywords == []) - // LoadTotalKeywordsUseCase가 캐시 미스 시 서버 동기화 후 1회 재조회하므로 2번 호출된다. - #expect(keywordRepository.fetchKeywordsCallCount == 2) + // 캐시 조회가 실패하면 LoadTotalKeywordsUseCase가 서버와 한 번 동기화한 뒤 다시 읽는다. #expect(keywordRepository.syncKeywordsCallCount == 1) } diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserLibraryUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserLibraryUseCaseTests.swift index 507ebec0f..da542747a 100644 --- a/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserLibraryUseCaseTests.swift +++ b/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserLibraryUseCaseTests.swift @@ -100,7 +100,6 @@ struct LoadUserLibraryUseCaseTests { _ = try await usecase.execute(id: UserID(1003), filter: LibraryFilter(), cursor: nil) #expect(novelRepository.lastUserLibraryCachedKeywords == [keyword]) - #expect(keywordRepository.fetchKeywordsCallCount == 1) } @Test("키워드 캐시 조회에 실패해도 서재 목록은 빈 캐시로 정상 조회된다") @@ -119,8 +118,7 @@ struct LoadUserLibraryUseCaseTests { #expect(result.0.items.count == expected.items.count) #expect(novelRepository.lastUserLibraryCachedKeywords == []) - // LoadTotalKeywordsUseCase가 캐시 미스 시 서버 동기화 후 1회 재조회하므로 2번 호출된다. - #expect(keywordRepository.fetchKeywordsCallCount == 2) + // 캐시 조회가 실패하면 LoadTotalKeywordsUseCase가 서버와 한 번 동기화한 뒤 다시 읽는다. #expect(keywordRepository.syncKeywordsCallCount == 1) } diff --git a/Projects/Domain/NovelReviewDomain/CLAUDE.md b/Projects/Domain/NovelReviewDomain/CLAUDE.md index a73549958..4090ae5ff 100644 --- a/Projects/Domain/NovelReviewDomain/CLAUDE.md +++ b/Projects/Domain/NovelReviewDomain/CLAUDE.md @@ -13,3 +13,6 @@ ## 주의사항 (작업 중 발견 시 누적) - 조회 결과가 옵셔널이므로 "초안 없음(nil)"과 "에러(throw)"를 구분해 처리할 것. +- UseCase 3개(조회·저장·삭제)는 **일부러 테스트가 없다**(#293). 저장소에 넘기기만 해서 지킬 규칙이 없다 — 다시 넣으면 ArchLint `test-passthrough`가 막는다. `MockNovelReviewRepository`도 그 테스트만 써서 지웠다. `.testing` 타깃의 UseCase Mock 2개는 **NovelReviewFeature 테스트가 쓰므로 남겼다**(조회용 `MockLoadNovelReviewDraftUseCase`는 용어상 Stub이지만 Feature 테스트를 건드려야 해 이름은 그대로). +- 기간 정규화(`ReadingPeriod.normalized(for:)`)와 평점 검증은 **BaseDomain 코드**라 그 테스트도 BaseDomain에 있다. 여기선 초안이 정규화를 "적용하는지"만 본다. +- `setKeywords`는 `Set`을 거쳐 담아 **순서가 보존되지 않는다** — 명세가 아니라 테스트도 순서를 보지 않는다. diff --git a/Projects/Domain/NovelReviewDomain/TEST_SPEC.md b/Projects/Domain/NovelReviewDomain/TEST_SPEC.md new file mode 100644 index 000000000..061bdbc94 --- /dev/null +++ b/Projects/Domain/NovelReviewDomain/TEST_SPEC.md @@ -0,0 +1,34 @@ +# NovelReviewDomain 테스트 명세 + + + +## 리뷰 초안 작성 + +`Tests/Entity/NovelReviewDraftTests.swift` + +### 기간 + +- 독서 상태에 맞게 기간을 고쳐서 담는다 +- 독서 상태를 바꾸면 기간도 새 상태에 맞게 고친다 +- 기간을 넣으면 지금 독서 상태에 맞게 고친다 +- 기간을 지우면 기간이 비어 있다 + +### 평점 + +- 저장된 평점으로 초안을 만들면 그 평점이 담겨 있다 +- 평점을 바꾸면 새 평점이 담긴다 +- 평점을 지우면 평점이 비어 있다 + +### 매력 포인트 + +- 매력 포인트를 3개까지 고를 수 있다 +- 매력 포인트를 3개 고른 뒤에는 더 고를 수 없다 +- 이미 고른 매력 포인트를 또 고르면 아무 일도 없다 +- 고른 매력 포인트를 빼면 목록에서 사라진다 + +### 키워드 + +- 키워드는 20개까지 담을 수 있다 +- 키워드가 20개를 넘으면 담을 수 없다 +- 같은 키워드가 두 번 들어오면 담을 수 없다 +- 담긴 키워드를 빼면 목록에서 사라진다 diff --git a/Projects/Domain/NovelReviewDomain/Testing/Mock/MockNovelReviewRepository.swift b/Projects/Domain/NovelReviewDomain/Testing/Mock/MockNovelReviewRepository.swift deleted file mode 100644 index 75c289ae9..000000000 --- a/Projects/Domain/NovelReviewDomain/Testing/Mock/MockNovelReviewRepository.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// MockNovelReviewRepository.swift -// NovelReviewDomain -// -// Created by YunhakLee on 2/5/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation - -import NovelReviewDomain -import BaseDomain - -public final class MockNovelReviewRepository: NovelReviewRepository { - public var loadedNovelID: NovelID? - public var savedDrafts: [NovelReviewDraft] = [] - public var deletedNovelIDs: [NovelID] = [] - - public var loadResult: Result = .success(nil) - public var saveResult: Result = .success(()) - public var deleteResult: Result = .success(()) - - public init() {} - - public func loadNovelReviewDraft(novelID: NovelID) async throws(RepositoryError) -> NovelReviewDraft? { - loadedNovelID = novelID - switch loadResult { - case .success(let value): - return value - case .failure(let error): - throw error - } - } - - public func save(draft: NovelReviewDraft) async throws(RepositoryError) { - savedDrafts.append(draft) - switch saveResult { - case .success: - return - case .failure(let error): - throw error - } - } - - public func deleteNovelReview(novelID: NovelID) async throws(RepositoryError) { - deletedNovelIDs.append(novelID) - switch deleteResult { - case .success: - return - case .failure(let error): - throw error - } - } -} diff --git a/Projects/Domain/NovelReviewDomain/Tests/Entity/NovelReviewDraftTests.swift b/Projects/Domain/NovelReviewDomain/Tests/Entity/NovelReviewDraftTests.swift index b8a55c4ab..2fc6c5447 100644 --- a/Projects/Domain/NovelReviewDomain/Tests/Entity/NovelReviewDraftTests.swift +++ b/Projects/Domain/NovelReviewDomain/Tests/Entity/NovelReviewDraftTests.swift @@ -1,5 +1,5 @@ // -// NovelReviewDraftTests 2.swift +// NovelReviewDraftTests.swift // NovelReviewDomain // // Created by YunhakLee on 2/6/26. @@ -9,262 +9,207 @@ import Foundation import Testing -@testable import NovelReviewDomain -import NovelReviewDomainTesting import BaseDomain +import NovelReviewDomain -@Suite("NovelReviewDraft") +@Suite("리뷰 초안 작성") struct NovelReviewDraftTests { - // MARK: - Helpers + @Suite("기간") + struct Period { - private func makeKeyword(_ id: Int) -> Keyword { - Keyword(id: KeywordID(id), name: "K\(id)") - } + // 고정 날짜. 둘 다 기준일(today)보다 앞이라 '미래 날짜'에 걸리지 않는다. + private let firstDay = Date(timeIntervalSince1970: 1_700_000_000) + private let lastDay = Date(timeIntervalSince1970: 1_700_259_200) // firstDay + 3일 + private let today = Date(timeIntervalSince1970: 1_701_000_000) - private func makeDraft( - status: ReadingStatus = .watching, - period: ReadingPeriod? = nil, - rating: Rating? = nil, - attractivePoints: [AttractivePoint] = [], - keywords: [Keyword] = [] - ) -> NovelReviewDraft { - NovelReviewDraft( - novelID: NovelID(42), - status: status, - period: period, - rating: rating, - attractivePoints: attractivePoints, - keywords: keywords - ) - } + @Test("독서 상태에 맞게 기간을 고쳐서 담는다") + func normalizesPeriodOnCreation() throws { + let period = try ReadingPeriod(start: firstDay, end: nil, notAfter: today) - // MARK: - Init rules + let draft = makeDraft(status: .watched, period: period) - @Test("초기화 시 읽기 상태에 따라 기간이 정규화된다") - func initNormalizesPeriodByStatus() throws { - let d = Date(timeIntervalSince1970: 1_700_000_000) + #expect(draft.period?.start == firstDay) + #expect(draft.period?.end == firstDay) + } - // watched인데 end만 들어온 period → normalized가 start/end를 채우는 정책이라고 가정 - // (ReadingPeriod.normalized(for:) 내부 정책에 맞춰 draft가 그 결과를 채택하는지만 검증) - let p = try ReadingPeriod(start: nil, end: d) + @Test("독서 상태를 바꾸면 기간도 새 상태에 맞게 고친다") + func changingStatusNormalizesPeriod() throws { + let period = try ReadingPeriod(start: firstDay, end: lastDay, notAfter: today) + var draft = makeDraft(status: .watched, period: period) - let draft = makeDraft(status: .watched, period: p) + draft.changeStatus(.quit) - let out = try #require(draft.period) - // "normalized(for: .watched)"의 결과를 기대해야 하므로, - // 여기서는 최소한 'draft.period가 nil이 아니며, status에 의해 변경될 수 있다' 정도만 확인 - // 정책이 "watched이면 start/end가 둘 다 있어야 한다"라면 아래처럼 강하게 체크 가능: - #expect(out.start != nil) - #expect(out.end != nil) - } + #expect(draft.status == .quit) + #expect(draft.period?.start == nil) + #expect(draft.period?.end == lastDay) + } - // MARK: - Status/period editing + @Test("기간을 넣으면 지금 독서 상태에 맞게 고친다") + func settingPeriodNormalizesForCurrentStatus() throws { + var draft = makeDraft(status: .watching) + let period = try ReadingPeriod(start: firstDay, end: lastDay, notAfter: today) - - @Test("기간이 nil일 때 상태를 변경해도 기간은 그대로 nil을 유지한다") - func changeStatusKeepsNilPeriodAcrossStatuses() { - var draft = makeDraft(status: .watching, period: nil) + draft.setPeriod(period) - draft.changeStatus(.watched) - #expect(draft.status == .watched) - #expect(draft.period == nil) + #expect(draft.period?.start == firstDay) + #expect(draft.period?.end == nil) + } - draft.changeStatus(.quit) - #expect(draft.status == .quit) - #expect(draft.period == nil) + @Test("기간을 지우면 기간이 비어 있다") + func clearingPeriodEmptiesIt() throws { + let period = try ReadingPeriod(start: firstDay, end: lastDay, notAfter: today) + var draft = makeDraft(status: .watched, period: period) - draft.changeStatus(.watching) - #expect(draft.status == .watching) - #expect(draft.period == nil) + draft.setPeriod(nil) + + #expect(draft.period == nil) + } } - @Test("상태를 변경하면 기존 기간은 새로운 상태 기준으로 정규화된다") - func changeStatusNormalizesPeriodForAllTransitions() throws { - let start = Date(timeIntervalSince1970: 1_700_000_000) - let end = Date(timeIntervalSince1970: 1_700_000_100) + @Suite("평점") + struct RatingChange { - // From .watched (start+end) - do { - var draft = makeDraft(status: .watched, period: try ReadingPeriod(start: start, end: end)) + @Test("저장된 평점으로 초안을 만들면 그 평점이 담겨 있다") + func keepsRatingOnCreation() throws { + let rating = try Rating(4.0) - draft.changeStatus(.watching) - let p1 = try #require(draft.period) - #expect(draft.status == .watching) - #expect(p1.start != nil) - #expect(p1.end == nil) + let draft = makeDraft(rating: rating) - draft = makeDraft(status: .watched, period: try ReadingPeriod(start: start, end: end)) - draft.changeStatus(.quit) - let p2 = try #require(draft.period) - #expect(draft.status == .quit) - #expect(p2.start == nil) - #expect(p2.end != nil) + #expect(draft.rating == rating) } - // From .watching (start only) - do { - var draft = makeDraft(status: .watching, period: try ReadingPeriod(start: start, end: nil)) + @Test("평점을 바꾸면 새 평점이 담긴다") + func changingRatingReplacesIt() throws { + // 비어 있지 않은 평점에서 시작한다 — 처음 넣기가 아니라 바꾸기를 본다. + var draft = makeDraft(rating: try Rating(4.0)) + let newRating = try Rating(2.5) - draft.changeStatus(.watched) - let p1 = try #require(draft.period) - #expect(draft.status == .watched) - #expect(p1.start != nil) - #expect(p1.end != nil) // normalized should fill end + draft.setRating(newRating) - draft = makeDraft(status: .watching, period: try ReadingPeriod(start: start, end: nil)) - draft.changeStatus(.quit) - let p2 = try #require(draft.period) - #expect(draft.status == .quit) - #expect(p2.start == nil) - #expect(p2.end != nil) // quit keeps only end + #expect(draft.rating == newRating) } - // From .quit (end only) - do { - var draft = makeDraft(status: .quit, period: try ReadingPeriod(start: nil, end: end)) - - draft.changeStatus(.watching) - let p1 = try #require(draft.period) - #expect(draft.status == .watching) - #expect(p1.start != nil) // watching keeps only start - #expect(p1.end == nil) - - draft = makeDraft(status: .quit, period: try ReadingPeriod(start: nil, end: end)) - draft.changeStatus(.watched) - let p2 = try #require(draft.period) - #expect(draft.status == .watched) - #expect(p2.start != nil) - #expect(p2.end != nil) // normalized should fill start + @Test("평점을 지우면 평점이 비어 있다") + func clearingRatingEmptiesIt() throws { + var draft = makeDraft(rating: try Rating(4.0)) + + draft.setRating(nil) + + #expect(draft.rating == nil) } } - @Test("setPeriod는 현재 상태에 맞게 기간을 정규화하여 저장한다") - func setPeriodNormalizesForEachStatus() throws { - let start = Date(timeIntervalSince1970: 1_700_000_000) - let end = Date(timeIntervalSince1970: 1_700_000_100) - - // status: watching -> should end up with start only - do { - var draft = makeDraft(status: .watching, period: nil) - draft.setPeriod(try ReadingPeriod(start: start, end: end)) - let p = try #require(draft.period) - #expect(p.start != nil) - #expect(p.end == nil) - } + @Suite("매력 포인트") + struct AttractivePoints { - // status: watched -> should end up with start+end (if one side missing, normalized fills) - do { - var draft = makeDraft(status: .watched, period: nil) - draft.setPeriod(try ReadingPeriod(start: start, end: nil)) - let p = try #require(draft.period) - #expect(p.start != nil) - #expect(p.end != nil) - } + @Test("매력 포인트를 3개까지 고를 수 있다") + func selectsUpToThreeAttractivePoints() throws { + var draft = makeDraft(attractivePoints: [.worldview, .material]) - // status: quit -> should end up with end only - do { - var draft = makeDraft(status: .quit, period: nil) - draft.setPeriod(try ReadingPeriod(start: start, end: end)) - let p = try #require(draft.period) - #expect(p.start == nil) - #expect(p.end != nil) + try draft.addAttractivePoint(.character) + + #expect(draft.attractivePoints.count == 3) + #expect(draft.attractivePoints == [.worldview, .material, .character]) } - // set nil clears - do { - var draft = makeDraft(status: .watched, period: try ReadingPeriod(start: start, end: end)) - draft.setPeriod(nil) - #expect(draft.period == nil) + @Test("매력 포인트를 3개 고른 뒤에는 더 고를 수 없다") + func cannotSelectMoreThanThreeAttractivePoints() { + var draft = makeDraft(attractivePoints: [.worldview, .material, .character]) + + #expect(throws: NovelReviewDraft.ValidationError.tooManyAttractivePoints(max: 3)) { + try draft.addAttractivePoint(.vibe) + } } - } - // MARK: - Rating + @Test("이미 고른 매력 포인트를 또 고르면 아무 일도 없다") + func reselectingAttractivePointChangesNothing() throws { + // 꽉 찬 상태에서 시작한다 — 개수를 따지기 전에 이미 고른 것인지부터 봐야 막히지 않는다. + var draft = makeDraft(attractivePoints: [.worldview, .material, .character]) + + try draft.addAttractivePoint(.worldview) + + #expect(draft.attractivePoints == [.worldview, .material, .character]) + } - @Test("평점은 설정 및 nil 초기화가 가능하다") - func setRatingUpdates() throws { - var draft = makeDraft(rating: nil) - let r = try Rating(4.5) + @Test("고른 매력 포인트를 빼면 목록에서 사라진다") + func removingAttractivePointDropsIt() { + var draft = makeDraft(attractivePoints: [.worldview, .material]) - draft.setRating(r) - #expect(draft.rating == r) + draft.removeAttractivePoint(.worldview) - draft.setRating(nil) - #expect(draft.rating == nil) + #expect(draft.attractivePoints == [.material]) + } } - // MARK: - Attractive points editing rules + @Suite("키워드") + struct Keywords { - @Test("이미 선택된 매력 포인트를 다시 추가해도 중복되지 않는다") - func addAttractivePointIgnoresDuplicates() throws { - var draft = makeDraft(attractivePoints: [.worldview]) + @Test("키워드는 20개까지 담을 수 있다") + func holdsUpToTwentyKeywords() throws { + var draft = makeDraft() + let keywords = makeKeywords(count: 20) - try draft.addAttractivePoint(.worldview) // duplicate - #expect(draft.attractivePoints == [.worldview]) - } + try draft.setKeywords(keywords) - @Test("매력 포인트가 3개를 초과하면 예외가 발생한다") - func addAttractivePointThrowsOnOverflow() throws { - var draft = makeDraft(attractivePoints: [.worldview, .material, .character]) + // 담는 순서는 지키지 않는다(명세 아님) — 무엇이 담겼는지만 본다. + #expect(Set(draft.keywords) == Set(keywords)) + } - #expect(throws: NovelReviewDraft.ValidationError.tooManyAttractivePoints(max: NovelReviewDraft.maxAttractivePoints)) { - try draft.addAttractivePoint(.relationship) + @Test("키워드가 20개를 넘으면 담을 수 없다") + func cannotHoldMoreThanTwentyKeywords() { + var draft = makeDraft() + let keywords = makeKeywords(count: 21) + + #expect(throws: NovelReviewDraft.ValidationError.tooManyKeywords(max: 20)) { + try draft.setKeywords(keywords) + } } - } - @Test("매력 포인트 삭제는 여러 번 호출해도 안전하다") - func removeAttractivePointIsIdempotent() { - var draft = makeDraft(attractivePoints: [.vibe, .material]) + @Test("같은 키워드가 두 번 들어오면 담을 수 없다") + func cannotHoldDuplicateKeyword() { + var draft = makeDraft() + let keyword = makeKeyword(1) - draft.removeAttractivePoint(.vibe) - #expect(draft.attractivePoints == [.material]) + #expect(throws: NovelReviewDraft.ValidationError.duplicateKeyword) { + try draft.setKeywords([keyword, keyword]) + } + } - // removing again should be no-op - draft.removeAttractivePoint(.vibe) - #expect(draft.attractivePoints == [.material]) - } + @Test("담긴 키워드를 빼면 목록에서 사라진다") + func removingKeywordDropsIt() { + var draft = makeDraft(keywords: [makeKeyword(1), makeKeyword(2)]) - // MARK: - Keywords editing rules + draft.removeKeyword(makeKeyword(1)) - @Test("키워드 설정은 중복된 키워드가 있는 값으로 설정하려는 경우 예외가 발생한다.") - func setKeywordsThrowsOnDuplicates() throws { - var draft = makeDraft() - var input = (1...19).map(makeKeyword) - input.append(makeKeyword(19)) - #expect(throws: NovelReviewDraft.ValidationError.duplicateKeyword) { - try draft.setKeywords(input) + #expect(draft.keywords == [makeKeyword(2)]) } } - - @Test("키워드 설정은 키워드가 20개를 초과한 값으로 설정하려는 경우 예외가 발생한다.") - func setKeywordsThrowsOnOverflow() throws { - var draft = makeDraft() - let input = (1...21).map(makeKeyword) - #expect(throws: NovelReviewDraft.ValidationError.tooManyKeywords(max: NovelReviewDraft.maxKeywords)) { - try draft.setKeywords(input) - } - } - - @Test("키워드 설정은 중복되지 않고, 20개 이하이면 설정 가능하다.") - func setKeywordsUpdates() throws { - var draft = makeDraft() - let input = (1...20).map(makeKeyword) - try draft.setKeywords(input) - #expect(draft.keywords.count == 20) - } - - @Test("키워드 삭제는 여러 번 호출해도 안전하다") - func removeKeywordIsIdempotent() { - let k1 = makeKeyword(1) - let k2 = makeKeyword(2) +} - var draft = makeDraft(keywords: [k1, k2]) +// MARK: - Helpers + +private func makeDraft( + status: ReadingStatus = .watching, + period: ReadingPeriod? = nil, + rating: Rating? = nil, + attractivePoints: [AttractivePoint] = [], + keywords: [Keyword] = [] +) -> NovelReviewDraft { + NovelReviewDraft( + novelID: NovelID(1), + status: status, + period: period, + rating: rating, + attractivePoints: attractivePoints, + keywords: keywords + ) +} - draft.removeKeyword(k1) - #expect(draft.keywords == [k2]) +private func makeKeyword(_ id: Int) -> Keyword { + Keyword(id: KeywordID(id), name: "키워드\(id)") +} - // removing again should be no-op - draft.removeKeyword(k1) - #expect(draft.keywords == [k2]) - } +private func makeKeywords(count: Int) -> [Keyword] { + (1...count).map(makeKeyword) } diff --git a/Projects/Domain/NovelReviewDomain/Tests/Entity/RatingTests.swift b/Projects/Domain/NovelReviewDomain/Tests/Entity/RatingTests.swift deleted file mode 100644 index b731cc9d0..000000000 --- a/Projects/Domain/NovelReviewDomain/Tests/Entity/RatingTests.swift +++ /dev/null @@ -1,72 +0,0 @@ -// -// RatingTests.swift -// NovelReviewDomain -// -// Created by YunhakLee on 2/6/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelReviewDomain -import NovelReviewDomainTesting -import BaseDomain - -@Suite("Rating") -struct RatingTests { - - @Test("평점은 0.5부터 5.0까지 0.5 단위로만 허용된다") - func acceptsValidValues() throws { - // 0.5, 1.0, 1.5, ..., 5.0 - let validValues = stride(from: 0.5, through: 5.0, by: 0.5) - for v in validValues { - let rating = try Rating(v) - #expect(rating.value == v) - } - } - - @Test("평점은 최소값 0.5와 최대값 5.0을 허용한다") - func acceptsBoundaries() throws { - let low = try Rating(0.5) - #expect(low.value == 0.5) - - let high = try Rating(5.0) - #expect(high.value == 5.0) - } - - @Test("평점이 허용 범위를 벗어나면 예외가 발생한다") - func rejectsOutOfRange() { - #expect(throws: Rating.ValidationError.outOfRange) { - _ = try Rating(0.0) - } - #expect(throws: Rating.ValidationError.outOfRange) { - _ = try Rating(5.5) - } - #expect(throws: Rating.ValidationError.outOfRange) { - _ = try Rating(-1.0) - } - #expect(throws: Rating.ValidationError.outOfRange) { - _ = try Rating(999.0) - } - } - - @Test("평점이 0.5 단위가 아니면 예외가 발생한다") - func rejectsInvalidStep() { - #expect(throws: Rating.ValidationError.invalidStep) { - _ = try Rating(4.7) - } - #expect(throws: Rating.ValidationError.invalidStep) { - _ = try Rating(1.25) - } - } - - @Test("같은 값의 평점은 서로 동등하다") - func equatableByValue() throws { - let a = try Rating(3.5) - let b = try Rating(3.5) - let c = try Rating(4.0) - - #expect(a == b) - #expect(a != c) - } -} diff --git a/Projects/Domain/NovelReviewDomain/Tests/Entity/ReadingPeriodTests.swift b/Projects/Domain/NovelReviewDomain/Tests/Entity/ReadingPeriodTests.swift deleted file mode 100644 index a7ad02876..000000000 --- a/Projects/Domain/NovelReviewDomain/Tests/Entity/ReadingPeriodTests.swift +++ /dev/null @@ -1,134 +0,0 @@ -// -// ReadingPeriodTests.swift -// NovelReviewDomain -// -// Created by YunhakLee on 2/6/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import NovelReviewDomain -import NovelReviewDomainTesting -import BaseDomain - -@Suite("ReadingPeriod") -struct ReadingPeriodTests { - - @Test("시작일이 종료일보다 이전이면 기간 생성이 가능하다") - func acceptsStartBeforeEnd() throws { - let start = Date(timeIntervalSince1970: 1_700_000_000) - let end = Date(timeIntervalSince1970: 1_700_000_100) - - let period = try ReadingPeriod(start: start, end: end) - - #expect(period.start == start) - #expect(period.end == end) - } - - @Test("시작일과 종료일이 같아도 기간 생성이 가능하다") - func acceptsStartEqualToEnd() throws { - let d = Date(timeIntervalSince1970: 1_700_000_000) - - let period = try ReadingPeriod(start: d, end: d) - - #expect(period.start == d) - #expect(period.end == d) - } - - @Test("시작일만 있어도 기간 생성이 가능하다") - func acceptsOnlyStart() throws { - let start = Date(timeIntervalSince1970: 1_700_000_000) - - let period = try ReadingPeriod(start: start, end: nil) - - #expect(period.start == start) - #expect(period.end == nil) - } - - @Test("종료일만 있어도 기간 생성이 가능하다") - func acceptsOnlyEnd() throws { - let end = Date(timeIntervalSince1970: 1_700_000_000) - - let period = try ReadingPeriod(start: nil, end: end) - - #expect(period.start == nil) - #expect(period.end == end) - } - - @Test("시작일과 종료일이 모두 없으면 기간 생성에 실패한다") - func rejectsBothNil() { - #expect(throws: ReadingPeriod.ValidationError.invalidPeriod) { - _ = try ReadingPeriod(start: nil, end: nil) - } - } - - @Test("시작일이 종료일보다 늦으면 기간 생성에 실패한다") - func rejectsStartAfterEnd() { - let start = Date(timeIntervalSince1970: 1_700_000_100) - let end = Date(timeIntervalSince1970: 1_700_000_000) - - #expect(throws: ReadingPeriod.ValidationError.startAfterEnd) { - _ = try ReadingPeriod(start: start, end: end) - } - } - - @Test("종료일이 기준일(오늘) 이후면 기간 생성에 실패한다") - func rejectsFutureEnd() { - let calendar = Calendar.current - let today = calendar.startOfDay(for: Date(timeIntervalSince1970: 1_700_000_000)) - let tomorrow = calendar.date(byAdding: .day, value: 1, to: today)! - - #expect(throws: ReadingPeriod.ValidationError.futureDate) { - _ = try ReadingPeriod(start: nil, end: tomorrow, notAfter: today) - } - } - - @Test("시작일이 기준일(오늘) 이후면 기간 생성에 실패한다") - func rejectsFutureStart() { - let calendar = Calendar.current - let today = calendar.startOfDay(for: Date(timeIntervalSince1970: 1_700_000_000)) - let tomorrow = calendar.date(byAdding: .day, value: 1, to: today)! - - #expect(throws: ReadingPeriod.ValidationError.futureDate) { - _ = try ReadingPeriod(start: tomorrow, end: tomorrow, notAfter: today) - } - } - - @Test("기준일과 같은 날이면(시각이 달라도) 기간 생성이 가능하다") - func acceptsSameDayAsLimit() throws { - let calendar = Calendar.current - let today = calendar.startOfDay(for: Date(timeIntervalSince1970: 1_700_000_000)) - let laterSameDay = today.addingTimeInterval(60 * 60) // 같은 날, 1시간 뒤 - - let period = try ReadingPeriod(start: nil, end: laterSameDay, notAfter: today) - - #expect(period.end == laterSameDay) - } - - @Test("기준일 이전 날짜는 기간 생성이 가능하다") - func acceptsPastDate() throws { - let calendar = Calendar.current - let today = calendar.startOfDay(for: Date(timeIntervalSince1970: 1_700_000_000)) - let yesterday = calendar.date(byAdding: .day, value: -1, to: today)! - - let period = try ReadingPeriod(start: yesterday, end: yesterday, notAfter: today) - - #expect(period.start == yesterday) - #expect(period.end == yesterday) - } - - @Test("같은 시작일과 종료일을 가지면 동일한 기간으로 비교된다") - func equatableByDates() throws { - let start = Date(timeIntervalSince1970: 1_700_000_000) - let end = Date(timeIntervalSince1970: 1_700_000_100) - - let a = try ReadingPeriod(start: start, end: end) - let b = try ReadingPeriod(start: start, end: end) - let c = try ReadingPeriod(start: start, end: nil) - - #expect(a == b) - #expect(a != c) - } -} diff --git a/Projects/Domain/NovelReviewDomain/Tests/UseCase/DeleteNovelReviewUseCaseTests.swift b/Projects/Domain/NovelReviewDomain/Tests/UseCase/DeleteNovelReviewUseCaseTests.swift deleted file mode 100644 index 117909ac6..000000000 --- a/Projects/Domain/NovelReviewDomain/Tests/UseCase/DeleteNovelReviewUseCaseTests.swift +++ /dev/null @@ -1,40 +0,0 @@ -// -// DeleteNovelReviewUseCaseTests.swift -// NovelReviewDomain -// -// Created by YunhakLee on 2/6/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelReviewDomain -import NovelReviewDomainTesting -import BaseDomain - -@Suite("DeleteNovelReviewUseCase") -struct DeleteNovelReviewUseCaseTests { - - @Test("주어진 작품 ID로 작품 평가를 삭제한다") - func deletesByID() async throws { - let repo = MockNovelReviewRepository() - let sut = DefaultDeleteNovelReviewUseCase(repository: repo) - - let novelID = NovelID(99) - try await sut.execute(novelID: novelID) - - #expect(repo.deletedNovelIDs == [novelID]) - } - - @Test("삭제 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func deletePropagatesError() async { - let repo = MockNovelReviewRepository() - repo.deleteResult = .failure(.networkUnavailable) - - let sut = DefaultDeleteNovelReviewUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - try await sut.execute(novelID: NovelID(100)) - } - } -} diff --git a/Projects/Domain/NovelReviewDomain/Tests/UseCase/LoadNovelReviewDraftUseCaseTests.swift b/Projects/Domain/NovelReviewDomain/Tests/UseCase/LoadNovelReviewDraftUseCaseTests.swift deleted file mode 100644 index 58b149221..000000000 --- a/Projects/Domain/NovelReviewDomain/Tests/UseCase/LoadNovelReviewDraftUseCaseTests.swift +++ /dev/null @@ -1,72 +0,0 @@ -// -// LoadNovelReviewDraftUseCaseTests.swift -// NovelReviewDomain -// -// Created by YunhakLee on 2/6/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelReviewDomain -import NovelReviewDomainTesting -import BaseDomain - -@Suite("LoadNovelReviewDraftUseCase") -struct LoadNovelReviewDraftUseCaseTests { - - private func makeDraft( - status: ReadingStatus = .watching, - period: ReadingPeriod? = nil, - rating: Rating? = nil, - attractivePoints: [AttractivePoint] = [], - keywords: [Keyword] = [] - ) -> NovelReviewDraft { - NovelReviewDraft( - novelID: NovelID(42), - status: status, - period: period, - rating: rating, - attractivePoints: attractivePoints, - keywords: keywords - ) - } - - @Test("주어진 작품 ID로 초안 데이터를 조회한다") - func loadsDraftSuccessfully() async throws { - let repo = MockNovelReviewRepository() - let expectedDraft = makeDraft() - repo.loadResult = .success(expectedDraft) - - let sut = DefaultLoadNovelReviewDraftUseCase(repository: repo) - - let result = try await sut.execute(novelID: expectedDraft.novelID) - - #expect(repo.loadedNovelID == expectedDraft.novelID) - #expect(result == expectedDraft) - } - - @Test("해당 작품의 초안이 없으면 nil을 반환한다") - func returnsNilWhenNoDraftExists() async throws { - let repo = MockNovelReviewRepository() - repo.loadResult = .success(nil) - - let sut = DefaultLoadNovelReviewDraftUseCase(repository: repo) - - let result = try await sut.execute(novelID: NovelID(1)) - - #expect(result == nil) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNovelReviewRepository() - repo.loadResult = .failure(.networkUnavailable) - - let sut = DefaultLoadNovelReviewDraftUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - try await sut.execute(novelID: NovelID(1)) - } - } -} diff --git a/Projects/Domain/NovelReviewDomain/Tests/UseCase/SaveNovelReviewUseCaseTests.swift b/Projects/Domain/NovelReviewDomain/Tests/UseCase/SaveNovelReviewUseCaseTests.swift deleted file mode 100644 index ac6109546..000000000 --- a/Projects/Domain/NovelReviewDomain/Tests/UseCase/SaveNovelReviewUseCaseTests.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// SaveNovelReviewUseCaseTests.swift -// NovelReviewDomain -// -// Created by YunhakLee on 2/6/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelReviewDomain -import NovelReviewDomainTesting -import BaseDomain - -@Suite("SaveNovelReviewUseCase") -struct SaveNovelReviewUseCaseTests { - - private func makeDraft( - status: ReadingStatus = .watching, - period: ReadingPeriod? = nil, - rating: Rating? = nil, - attractivePoints: [AttractivePoint] = [], - keywords: [Keyword] = [] - ) -> NovelReviewDraft { - NovelReviewDraft( - novelID: NovelID(42), - status: status, - period: period, - rating: rating, - attractivePoints: attractivePoints, - keywords: keywords - ) - } - - @Test("초안 데이터를 저장한다") - func savesDraftSuccessfully() async throws { - let repo = MockNovelReviewRepository() - let draft = makeDraft() - - let sut = DefaultSaveNovelReviewUseCase(repository: repo) - - try await sut.execute(draft: draft) - - #expect(repo.savedDrafts == [draft]) - } - - @Test("저장 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNovelReviewRepository() - repo.saveResult = .failure(.serverUnavailable) - - let sut = DefaultSaveNovelReviewUseCase(repository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - try await sut.execute(draft: makeDraft()) - } - } -} diff --git a/Tooling/ArchLint/Package.swift b/Tooling/ArchLint/Package.swift index 79576703d..a5055ecab 100644 --- a/Tooling/ArchLint/Package.swift +++ b/Tooling/ArchLint/Package.swift @@ -25,6 +25,24 @@ let package = Package( .testTarget( name: "ArchLintCoreTests", dependencies: ["ArchLintCore"] + ), + // 뮤테이션 도구(#293) — 소스에 버그를 하나씩 심어 테스트가 잡는지 본다. + // 넘기기만 하는 UseCase 판정을 ArchLintCore와 공유한다. + .target( + name: "MutationCore", + dependencies: [ + "ArchLintCore", + .product(name: "SwiftSyntax", package: "swift-syntax"), + .product(name: "SwiftParser", package: "swift-syntax") + ] + ), + .executableTarget( + name: "Mutate", + dependencies: ["MutationCore"] + ), + .testTarget( + name: "MutationCoreTests", + dependencies: ["MutationCore"] ) ] ) diff --git a/Tooling/ArchLint/README.md b/Tooling/ArchLint/README.md index 7cb00cc1e..42bfaf64f 100644 --- a/Tooling/ArchLint/README.md +++ b/Tooling/ArchLint/README.md @@ -9,9 +9,10 @@ ## 구조 -- `Sources/ArchLintCore/` — 규칙 12개(파일 단위 9 + 모듈 단위 3) + 스캔/파싱 로직(라이브러리) +- `Sources/ArchLintCore/` — 아키텍처 규칙 12개 + 테스트 명세 규칙 14개(`Test*Rule`, #293) + 스캔/파싱 로직(라이브러리) - `Sources/ArchLint/` — 얇은 실행 파일(`main.swift` → `runArchLint(...)` 호출) -- `Tests/ArchLintCoreTests/` — 규칙 자체 테스트 +- `Sources/MutationCore/` + `Sources/Mutate/` — 뮤테이션 도구(#293, 아래 "테스트 명세 규칙" 참고) +- `Tests/ArchLintCoreTests/`·`Tests/MutationCoreTests/` — 규칙·도구 자체 테스트 로직을 라이브러리로 뺀 이유: SwiftPM에서 **실행 타깃은 테스트가 import 못 하기** 때문(규칙을 테스트하려면 필수). @@ -21,6 +22,9 @@ swift run --package-path Tooling/ArchLint ArchLint . # 검사 실행 (인자: 레포 루트, 기본 ".") swift test --package-path Tooling/ArchLint # 규칙 자체 테스트 (회귀 그물) ARCHLINT_DEBUG=1 swift run ... # 스캔·매칭 진단을 stderr로 +swift run --package-path Tooling/ArchLint ArchLint --write-test-specs . # 테스트 목록 파일(TEST_SPEC.md) 갱신 +swift run --package-path Tooling/ArchLint Mutate AuthDomain # 뮤테이션(로컬·수동, tuist generate 후) +swift run --package-path Tooling/ArchLint Mutate AuthDomain --changed-since # origin/develop 이후 바뀐 소스에만(기준은 --changed-since=) ``` `/Projects` 아래 모든 `.swift`를 파싱해 규칙을 적용한다. @@ -48,6 +52,41 @@ CI(`GITHUB_ACTIONS=true`)에서는 `::error`/`::warning` 주석도 emit 해 위 | ⑬ Feature Factory 배타성 | `feature-exclusivity` | **error** | `Projects/Feature/` (모듈 단위) | ⑫를 Feature로 옮김 — Feature 모듈의 top-level public은 `*FeatureFactory`만(⑫의 `*DataFactory`와 대칭 · View·VM·상태는 internal, Factory는 `some View` 반환). Data와 달리 **조립 seam 예외**: `Sources/Navigation/`의 **계약 타입(typealias·protocol + `*Route` enum, #253)만** 허용(App이 Feature 간 직접 의존 없이 콘텐츠 주입/화면 전환 의도 수신 — 같은 폴더라도 구체 View/VM·Route 아닌 enum은 위반). 판정 로직은 ⑫와 `publicTopLevelOffense` 공유(접미사만 `Factory`). `extension`은 외부 public 타입에 public 멤버를 붙일 때만 노출로 본다(로컬 internal 타입 확장은 제외). | | ⑭ Feature 라우트 콜백 | `feature-route-callback` | warning | `Projects/{Feature}/**/Sources` | Feature **public 함수**(사실상 Factory 진입점 — ⑬이 그 외 public을 막음)의 `on…Tapped:`/`on…Selected:` 클로저 파라미터 금지 — 화면 전환 의도는 모듈 `*Route` enum + `onRoute:` 하나로(#253, 정본 `NovelDetailFeature/Sources/Navigation/NovelDetailRoute.swift`). 네이밍 관행 기반 프록시라 warning(비-라우팅 콜백 `onSubmitted`/`onSaved` 등 과거형 네이밍은 정상적으로 안 걸림). internal 서브뷰의 로컬 콜백은 대상 아님. | +## 테스트 명세 규칙 (#293) + +"AI가 코드를 쓰고, 사람은 테스트를 보고 믿는다"를 위한 규칙. 사람이 테스트 이름(목록)과 본문만 읽고 +믿을 수 있도록, 테스트가 **읽히고 · 규칙이 사는 곳을 직접 시험하고 · 버그면 실패하고 · 리팩터링엔 안 깨지고 · +늘 같은지**를 검사한다. **`TestSpecScope.modules`에 든 모듈에만** 적용한다 — 재작성을 마친 모듈만 넣는다. + +| id | 심각도 | 내용 | +|---|---|---| +| `test-name` | error | `@Suite`(한국어 이름) 안의 `@Test("~다")` 한국어 문장. 코드 식별자·`/`·모호어(성공적으로 등)·중복 금지 | +| `test-assert` | error | `#expect` 필수(`#require`만 ❌), `!= nil` 금지 | +| `test-name-number` | error | 이름의 숫자가 본문·arguments에 있어야 함. 숫자가 넣는 값이 아니라 단위를 말하면("0.5점 단위") allow 주석으로 뺀다 | +| `test-aaa` | error | 빈 줄로 준비/실행/확인 ≤3구역, 확인(`#expect`·`#require`)은 마지막 구역에만, `// Given` 라벨·for·if·switch·guard·삼항 금지 | +| `test-aaa-act` | warning | 실행 구역이 2문장 이상 — 설계 점검을 사람에게 묻는다 | +| `test-body-length` | warning | 본문 15줄 초과 | +| `test-arguments` | error | `arguments:` 배열은 항목마다 줄바꿈, 리터럴 항목엔 이유 주석(enum case는 면제) | +| `test-determinism` | error | `Date()`·`Date.now`·`Calendar/TimeZone/Locale.current`·`UUID()`·`.random`·`static var` 금지 | +| `test-result-only` | error | `@testable import` 금지, Entity 테스트(`Tests/Entity/`)에 Mock 금지 | +| `test-double-query` | error | `Testing/` 가짜 객체의 조회 메서드(`fetch…`·`load…`·`search…`)가 호출을 기록하면 위반(조회는 Stub, 명령만 Mock) | +| `test-passthrough` | error(모듈) | 저장소 호출을 넘기기만 하는 `Default…UseCase`를 테스트하면 위반. 결과를 거르거나 바꾸면(클로저·이어 부르기) 넘기기가 아니다 | +| `test-required` | error(모듈) | 분기·throw가 있는 타입이 테스트에 한 번도 안 나오면 위반 | +| `test-error-case` | error(모듈) | 에러 enum의 case마다 `#expect(throws: …case)` 필요(타입만 적으면 안 셈). 폴더·이름과 상관없이 찾고, 저장소 에러(`RepositoryError`·`Sources/Repository/`)는 대상이 아니다 | +| `test-source-constant` | error(모듈) | 테스트가 소스 `static let` 상수를 쓰면 위반 — 명세 값을 직접 쓴다 | +| `test-spec-file` | error | 모듈 루트 `TEST_SPEC.md`가 테스트와 다르면 위반(`--write-test-specs`로 갱신). 하위 `@Suite`는 부모 아래 한 단계 내린 제목으로 적는다 | + +- **예외**: 위반 줄이나 바로 윗줄에 `// archlint:allow — 이유`. **이유가 없으면 무시**된다(사람이 리뷰할 근거). + `test-`로 시작하는 테스트 명세 규칙에만 통한다 — 위 아키텍처 규칙은 주석으로 끄지 못한다. + 이 주석은 PR에서 사람이 확인할 목록이다. +- **뮤테이션 도구(`Mutate`)**: 모듈 Sources에 버그를 하나씩 심어(연산자 뒤집기·`!` 삭제·true↔false·정수+1·문장 삭제) + 그 모듈 테스트를 돌리고, **살아남은 버그**(테스트가 못 잡음)를 보고한다. 넘기기만 하는 UseCase는 뺀다. + 소스를 직접 고쳤다 되돌리므로 Sources가 깨끗할 때만 시작한다. Ctrl-C·kill(-9 제외)·터미널 닫기·실행 실패로 끝나도 돌던 xcodebuild를 멈추고 시작할 때 읽어 둔 원본으로 되돌린다. + 버그 하나가 5분을 넘기면(무한 루프) 끊고 "잡힘(시간 초과)"로 센다. + DerivedData를 Xcode와 나눠 임시 폴더(`$TMPDIR/wss-mutation-derived-data`)에 둔다 — 동시 빌드 충돌과 레포 안 빌드 폴더를 피한다. 로컬·수동 실행. + `--changed-since[=]`(기본 `origin/develop`)는 갈라진 지점 이후 바뀐 소스(작업 폴더·추적 안 된 파일 포함)에만 심어 시간을 줄인다. + 모듈의 `Tests/`·`Testing/`이 바뀌었으면 모듈 전체에 심는다 — 테스트가 약해지면 손대지 않은 소스의 버그도 새로 살아남기 때문(`ChangedScope`). + ## 규칙 추가하기 1. `Sources/ArchLintCore/`에 `Rule` 채택 struct + `SyntaxVisitor` 서브클래스를 만든다 diff --git a/Tooling/ArchLint/Sources/ArchLint/main.swift b/Tooling/ArchLint/Sources/ArchLint/main.swift index b7a740ac0..40a7363ef 100644 --- a/Tooling/ArchLint/Sources/ArchLint/main.swift +++ b/Tooling/ArchLint/Sources/ArchLint/main.swift @@ -1,12 +1,15 @@ import Foundation import ArchLintCore -// 얇은 실행 파일 — 로직은 ArchLintCore. 사용법: arch-lint [repoRoot] (기본 ".") +// 얇은 실행 파일 — 로직은 ArchLintCore. 사용법: arch-lint [--write-test-specs] [repoRoot] (기본 ".") +// --write-test-specs: 명세 모듈의 테스트 목록 파일(TEST_SPEC.md)을 새로 쓴다(없으면 최신인지 검사만). // ARCHLINT_DEBUG=1 이면 스캔·매칭 진단을 stderr로 출력. -let repoRoot = CommandLine.arguments.dropFirst().first ?? "." +let arguments = CommandLine.arguments.dropFirst() +let repoRoot = arguments.first { !$0.hasPrefix("--") } ?? "." let env = ProcessInfo.processInfo.environment exit(runArchLint( repoRoot: repoRoot, isGitHubActions: env["GITHUB_ACTIONS"] == "true", - debug: env["ARCHLINT_DEBUG"] == "1" + debug: env["ARCHLINT_DEBUG"] == "1", + writeTestSpecs: arguments.contains("--write-test-specs") )) diff --git a/Tooling/ArchLint/Sources/ArchLintCore/Linter.swift b/Tooling/ArchLint/Sources/ArchLintCore/Linter.swift index dd04639f7..5a7e03c9b 100644 --- a/Tooling/ArchLint/Sources/ArchLintCore/Linter.swift +++ b/Tooling/ArchLint/Sources/ArchLintCore/Linter.swift @@ -22,14 +22,30 @@ let allRules: [Rule] = [ folderName: "Repository", requiredSuffix: "Repository" ), - FeatureRouteCallbackRule() + FeatureRouteCallbackRule(), + // #293 테스트 = 기능 명세 (TestSpecScope.modules에 든 모듈만) + TestNamingRule(), + TestAssertionRule(), + TestNameNumberRule(), + TestStructureRule(), + TestActSizeRule(), + TestBodyLengthRule(), + TestArgumentsRule(), + TestDeterminismRule(), + TestResultOnlyRule(), + TestDoubleQueryRule() ] /// 등록된 모듈 단위 규칙 전체. 파일 하나가 아니라 모듈 전체를 봐야 하는 규칙(존재성 등)을 여기 둔다. let allModuleRules: [ModuleRule] = [ FactoryExistenceRule(), FactoryExclusivityRule(), - FeatureExclusivityRule() + FeatureExclusivityRule(), + // #293 테스트 = 기능 명세 (TestSpecScope.modules에 든 모듈만) + TestPassThroughRule(), + TestRequiredRule(), + TestErrorCaseRule(), + TestSourceConstantRule() ] /// 소스 문자열 하나에 규칙을 적용해 위반을 반환한다(테스트 진입점). @@ -41,7 +57,8 @@ func lint(source: String, path: String, rules: [Rule] = allRules) -> [Violation] for rule in rules where rule.applies(to: path) { result.append(contentsOf: rule.check(tree, path: path, converter: converter)) } - return result + let lines = source.components(separatedBy: "\n") + return AllowComment.filter(result) { $0 == path ? lines : nil } } /// 모듈 단위 규칙 테스트 진입점 — 여러 소스 문자열을 한 모듈로 묶어 규칙을 돌린다. @@ -50,7 +67,14 @@ func lintModule(sources: [(path: String, source: String)], moduleName: String, r let files: [ParsedFile] = sources .filter { rule.applies(to: $0.path) } .map { ParsedFile(path: $0.path, tree: Parser.parse(source: $0.source)) } - return rule.check(moduleName: moduleName, files: files) + let lines = Dictionary(sources.map { ($0.path, $0.source.components(separatedBy: "\n")) }) { first, _ in first } + return AllowComment.filter(rule.check(moduleName: moduleName, files: files)) { lines[$0] } +} + +/// 테스트 목록 파일 테스트 진입점 — 소스 문자열들을 한 모듈의 테스트 파일로 보고 목록을 만든다. +func renderTestSpec(sources: [(path: String, source: String)], moduleName: String) -> String { + let files = sources.map { ParsedFile(path: $0.path, tree: Parser.parse(source: $0.source)) } + return TestSpecDocument.render(module: moduleName, files: files) } /// /Projects 아래 모든 .swift 파일의 전체 경로. @@ -78,7 +102,8 @@ func repoRelative(_ path: String, repoRoot: String) -> String { /// 전체 실행: /Projects 스캔 → 규칙 적용 → 출력 → 종료코드(error>0 이면 1). /// GitHub Actions 환경이면 ::error/::warning 주석도 emit 한다. -public func runArchLint(repoRoot: String, isGitHubActions: Bool, debug: Bool) -> Int32 { +/// `writeTestSpecs`면 명세 모듈의 테스트 목록 파일을 새로 쓰고, 아니면 최신인지 검사한다. +public func runArchLint(repoRoot: String, isGitHubActions: Bool, debug: Bool, writeTestSpecs: Bool = false) -> Int32 { func debugLog(_ message: String) { guard debug else { return } FileHandle.standardError.write(Data(("DEBUG " + message + "\n").utf8)) @@ -136,6 +161,34 @@ public func runArchLint(repoRoot: String, isGitHubActions: Bool, debug: Bool) -> } } + // 3) 테스트 목록 파일(TEST_SPEC.md) — 명세 모듈마다 테스트 이름으로 만든 파일이 최신인지. + let specModuleDirs = scanned + .filter { $0.hasSuffix("/Project.swift") } + .map { String($0.dropLast("/Project.swift".count)) } + .filter { TestSpecScope.modules.contains(String($0.split(separator: "/").last ?? "")) } + for dir in specModuleDirs.sorted() { + let moduleName = String(dir.split(separator: "/").last ?? "") + let testFiles: [ParsedFile] = scanned + .filter { $0.hasPrefix(dir + "/Tests/") } + .compactMap { file in parse(file).map { ParsedFile(path: $0.relPath, tree: $0.tree) } } + let rendered = TestSpecDocument.render(module: moduleName, files: testFiles) + let specPath = dir + "/" + TestSpecDocument.fileName + if writeTestSpecs { + try? rendered.write(toFile: specPath, atomically: true, encoding: .utf8) + print("갱신: \(repoRelative(specPath, repoRoot: repoRoot))") + } else if (try? String(contentsOfFile: specPath, encoding: .utf8)) != rendered { + allViolations.append(Violation( + path: repoRelative(specPath, repoRoot: repoRoot), line: 1, ruleID: TestSpecDocument.ruleID, + message: "테스트 목록 파일이 테스트와 다르다 — `swift run --package-path Tooling/ArchLint ArchLint --write-test-specs .`로 갱신해 커밋한다", + severity: .error + )) + } + } + + // `// archlint:allow <규칙> — 이유`로 사람이 승인한 예외를 뺀다. + let linesByPath = Dictionary(parseCache.values.map { ($0.relPath, $0.tree.description.components(separatedBy: "\n")) }) { first, _ in first } + allViolations = AllowComment.filter(allViolations) { linesByPath[$0] } + allViolations.sort { ($0.path, $0.line) < ($1.path, $1.line) } for v in allViolations { print("\(v.severity.rawValue.uppercased()) \(v.path):\(v.line) [\(v.ruleID)] \(v.message)") diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestArgumentsRule.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestArgumentsRule.swift new file mode 100644 index 000000000..6ddb86b5c --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestArgumentsRule.swift @@ -0,0 +1,68 @@ +import Foundation +import SwiftSyntax + +/// `@Test(arguments: [...])`의 입력 목록이 읽힌다(#293 원칙 1 "읽힌다") — error. +/// - 항목마다 줄을 바꾼다 — 어떤 경우들을 확인하는지 목록으로 보인다. +/// - 리터럴(문자열·숫자 등) 항목에는 왜 그 값인지 주석을 단다. `""`·`" "`만으로는 의도가 안 보인다. +/// enum case처럼 이름이 곧 뜻인 항목은 주석이 없어도 된다. +/// 배열 리터럴이 아닌 인자(`Option.allCases` 등)는 대상이 아니다. 타입을 붙인 배열(`[…] as [T]`)은 대상이다. +struct TestArgumentsRule: Rule { + let id = "test-arguments" + let severity: Severity = .error + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Tests") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let collector = SpecTestCollector() + collector.walk(tree) + var violations: [Violation] = [] + func report(_ node: some SyntaxProtocol, _ message: String) { + violations.append(Violation( + path: path, line: SpecSyntax.line(of: node, converter), + ruleID: id, message: message, severity: severity + )) + } + + for test in collector.tests { + guard let array = SpecSyntax.argumentArray(test.arguments) else { continue } + var previousLine = SpecSyntax.line(of: array.leftSquare, converter) + var sharesLine = false + for element in array.elements { + let line = SpecSyntax.line(of: element, converter) + if line == previousLine { sharesLine = true } + previousLine = line + if Self.isLiteral(element), !Self.hasComment(element) { + report(element, "리터럴 항목 \(element.expression.trimmedDescription)에 이유 주석이 없다 — 왜 이 값을 넣는지 // 로 쓴다") + } + } + if sharesLine { + report(array, "arguments 항목은 한 줄에 하나씩 쓴다 — 어떤 경우들을 확인하는지 목록으로 보이게") + } + } + return violations + } + + private static func isLiteral(_ element: ArrayElementSyntax) -> Bool { + element.expression.tokens(viewMode: .sourceAccurate).contains { token in + switch token.tokenKind { + case .stringQuote, .multilineStringQuote, .stringSegment, .integerLiteral, .floatLiteral: + return true + case .keyword(let keyword): + return keyword == .true || keyword == .false || keyword == .nil + default: + return false + } + } + } + + private static func hasComment(_ element: ArrayElementSyntax) -> Bool { + let pieces = Array(element.leadingTrivia) + Array(element.trailingTrivia) + return pieces.contains { piece in + if case .lineComment = piece { return true } + if case .blockComment = piece { return true } + return false + } + } +} diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestAssertionRule.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestAssertionRule.swift new file mode 100644 index 000000000..10098e992 --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestAssertionRule.swift @@ -0,0 +1,129 @@ +import Foundation +import SwiftSyntax + +/// 테스트가 이름이 말한 것을 실제로 확인한다(#293 원칙 3 "버그면 실패") — error. +/// - 본문에 `#expect`가 하나 이상 있다(`#require`만 있으면 값이 맞는지는 안 본다). +/// - `!= nil`로 확인하지 않는다 — 값이 "있다"만 보고 무엇인지는 안 본다. 기대값을 `==`로 쓴다. +struct TestAssertionRule: Rule { + let id = "test-assert" + let severity: Severity = .error + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Tests") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let collector = SpecTestCollector() + collector.walk(tree) + var violations: [Violation] = [] + func report(_ node: some SyntaxProtocol, _ message: String) { + violations.append(Violation( + path: path, line: SpecSyntax.line(of: node, converter), + ruleID: id, message: message, severity: severity + )) + } + + for test in collector.tests { + guard let body = test.function.body else { continue } + + let macros = MacroCounter() + macros.walk(body) + if !macros.names.contains("expect") { + report(test.function, "#expect가 없다 — 이름이 말한 결과를 #expect로 확인한다(#require만으로는 값을 보지 않는다)") + } + + let nilChecks = NotNilFinder() + nilChecks.walk(body) + for node in nilChecks.found { + report(node, "`!= nil`은 값이 무엇인지 확인하지 않는다 — 기대값을 ==로 쓴다") + } + } + return violations + } +} + +/// 이름에 나온 숫자가 본문(arguments 포함)에 보인다(#293 원칙 3) — error. +/// "80자"라고 했으면 80을 실제로 넣어 본다. "0.5점 단위"처럼 숫자가 넣는 값이 아니라 단위를 말할 때는 +/// `// archlint:allow test-name-number — 이유`로 뺀다. `test-assert`에서 떼어 낸 이유는, 예외를 줘도 +/// 같은 테스트의 `!= nil` 검사까지 꺼지지 않게 하려는 것이다. +struct TestNameNumberRule: Rule { + let id = "test-name-number" + let severity: Severity = .error + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Tests") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let collector = SpecTestCollector() + collector.walk(tree) + var violations: [Violation] = [] + for test in collector.tests { + guard let body = test.function.body, let name = test.displayName else { continue } + // 이름 문자열 자체는 빼고, 본문과 arguments만 본다. + let literals = LiteralCollector() + literals.walk(body) + if let arguments = test.arguments { literals.walk(arguments) } + for number in Self.numbers(in: name) where !literals.contains(number) { + violations.append(Violation( + path: path, line: SpecSyntax.line(of: test.function, converter), + ruleID: id, + message: "이름의 숫자 \(number)이(가) 본문에 없다 — 이름이 말한 값을 실제로 넣어 확인한다", + severity: severity + )) + } + } + return violations + } + + static func numbers(in text: String) -> [String] { + let pattern = try! NSRegularExpression(pattern: "[0-9]+(\\.[0-9]+)?") + let range = NSRange(text.startIndex..., in: text) + return pattern.matches(in: text, range: range).compactMap { match in + Range(match.range, in: text).map { String(text[$0]) } + } + } +} + +/// `x != nil` 모양을 찾는다(연산자 폴딩 전 SequenceExpr 기준). +private final class NotNilFinder: SyntaxVisitor { + private(set) var found: [SequenceExprSyntax] = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: SequenceExprSyntax) -> SyntaxVisitorContinueKind { + let elements = Array(node.elements) + for (index, element) in elements.enumerated() { + guard element.as(BinaryOperatorExprSyntax.self)?.operator.text == "!=" else { continue } + let neighbors = [index - 1, index + 1].filter { elements.indices.contains($0) } + if neighbors.contains(where: { elements[$0].is(NilLiteralExprSyntax.self) }) { + found.append(node) + } + } + return .visitChildren + } +} + +/// 숫자 리터럴과 문자열 리터럴 내용을 모은다. +private final class LiteralCollector: SyntaxVisitor { + private var numbers: Set = [] + private var strings: [String] = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind { + switch token.tokenKind { + case .integerLiteral(let text), .floatLiteral(let text): + numbers.insert(text.replacingOccurrences(of: "_", with: "")) + case .stringSegment(let text): + strings.append(text) + default: + break + } + return .visitChildren + } + + func contains(_ number: String) -> Bool { + numbers.contains(number) || strings.contains { $0.contains(number) } + } +} diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestDeterminismRule.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestDeterminismRule.swift new file mode 100644 index 000000000..f9eeb3984 --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestDeterminismRule.swift @@ -0,0 +1,66 @@ +import Foundation +import SwiftSyntax + +/// 테스트는 언제 어디서 돌려도 같은 결과(#293 원칙 5 "늘 같다") — error. +/// 지금 시각·기기 설정·난수·테스트 간 공유 상태에 기대지 않는다: +/// `Date()`·`Date.now`·`Calendar.current`·`TimeZone.current`·`Locale.current`·`UUID()`· +/// `.random`·`.randomElement`·`.shuffled`·`static var`. +/// 날짜가 필요하면 고정 값을 만들고, 기준 시각은 인자로 넘긴다. +struct TestDeterminismRule: Rule { + let id = "test-determinism" + let severity: Severity = .error + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Tests") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let visitor = DeterminismVisitor() + visitor.walk(tree) + return visitor.found.map { node, what in + Violation( + path: path, line: SpecSyntax.line(of: node, converter), ruleID: id, + message: "\(what)는 돌릴 때마다 달라진다 — 고정 값을 만들어 쓴다", severity: severity + ) + } + } +} + +private final class DeterminismVisitor: SyntaxVisitor { + private(set) var found: [(Syntax, String)] = [] + + private static let deviceSettings: Set = ["Calendar", "TimeZone", "Locale"] + private static let randomMembers: Set = ["random", "randomElement", "shuffled"] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: FunctionCallExprSyntax) -> SyntaxVisitorContinueKind { + if let callee = node.calledExpression.as(DeclReferenceExprSyntax.self), + ["Date", "UUID"].contains(callee.baseName.text), + node.arguments.isEmpty, node.trailingClosure == nil { + found.append((Syntax(node), "\(callee.baseName.text)()")) + } + return .visitChildren + } + + override func visit(_ node: MemberAccessExprSyntax) -> SyntaxVisitorContinueKind { + let member = node.declName.baseName.text + let base = node.base?.as(DeclReferenceExprSyntax.self)?.baseName.text + if base == "Date", member == "now" { + found.append((Syntax(node), "Date.now")) + } else if let base, Self.deviceSettings.contains(base), member == "current" || member == "autoupdatingCurrent" { + found.append((Syntax(node), "\(base).\(member)")) + } else if Self.randomMembers.contains(member) { + found.append((Syntax(node), ".\(member)")) + } + return .visitChildren + } + + override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind { + let isStatic = node.modifiers.contains { $0.name.text == "static" || $0.name.text == "class" } + if isStatic, node.bindingSpecifier.text == "var" { + found.append((Syntax(node), "static var(테스트끼리 공유하는 상태)")) + } + return .visitChildren + } +} diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestDoubleQueryRule.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestDoubleQueryRule.swift new file mode 100644 index 000000000..41bfd8282 --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestDoubleQueryRule.swift @@ -0,0 +1,133 @@ +import Foundation +import SwiftSyntax + +/// 가짜 객체의 조회 메서드(`fetch…`·`load…`·`search…`)는 호출을 기록하지 않는다(#293 원칙 4) — error. +/// 조회는 Stub: 정해 둔 값을 돌려줄 뿐이다. "몇 번 불렀나"를 기록하면 테스트가 그걸 확인하게 되고, +/// 캐시를 넣거나 호출을 합치는 정상적인 리팩터링에도 테스트가 깨진다. 조회 입력이 맞는지는 +/// Stub이 입력마다 다른 값을 돌려주게 해서 결과로 확인한다. +/// 명령(저장·삭제·전송)은 Mock: 호출 기록이 곧 결과라 기록해도 된다. +/// 중복 요청 금지처럼 조회 횟수가 진짜 요구사항이면 `// archlint:allow test-double-query — 이유`. +struct TestDoubleQueryRule: Rule { + let id = "test-double-query" + let severity: Severity = .error + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Testing") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let visitor = QueryRecordingVisitor() + visitor.walk(tree) + return visitor.found.map { function in + Violation( + path: path, line: SpecSyntax.line(of: function, converter), ruleID: id, + message: "조회 메서드 \(function.name.text)가 호출을 기록한다 — 조회는 값만 돌려주고(Stub) 결과로 확인한다", + severity: severity + ) + } + } + + static func isQueryName(_ name: String) -> Bool { + for prefix in ["fetch", "load", "search"] where name.hasPrefix(prefix) { + guard let next = name.dropFirst(prefix.count).first else { return true } + return next.isUppercase + } + return false + } +} + +private final class QueryRecordingVisitor: SyntaxVisitor { + private(set) var found: [FunctionDeclSyntax] = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { + guard TestDoubleQueryRule.isQueryName(node.name.text), let body = node.body else { return .skipChildren } + let locals = LocalNameCollector() + locals.walk(body) + let finder = MutationFinder(locals: locals.names) + finder.walk(body) + if finder.mutates { found.append(node) } + return .skipChildren + } +} + +/// 메서드 안에서 선언한 지역 변수 이름 — 이것을 바꾸는 건 결과를 만드는 일이지 호출 기록이 아니다. +private final class LocalNameCollector: SyntaxVisitor { + private(set) var names: Set = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: IdentifierPatternSyntax) -> SyntaxVisitorContinueKind { + names.insert(node.identifier.text) + return .skipChildren + } + + // 클로저 매개변수(`{ result, item in … }`)도 그 클로저의 지역 값이다. + override func visit(_ node: ClosureShorthandParameterSyntax) -> SyntaxVisitorContinueKind { + names.insert(node.name.text) + return .skipChildren + } + + override func visit(_ node: ClosureParameterSyntax) -> SyntaxVisitorContinueKind { + names.insert((node.secondName ?? node.firstName).text) + return .skipChildren + } +} + +/// 저장 프로퍼티에 대입·`+=`·`append`/`insert` 같은 상태 변경을 하는가. 지역 변수를 바꾸는 것은 세지 않는다. +private final class MutationFinder: SyntaxVisitor { + private let locals: Set + private(set) var mutates = false + + init(locals: Set) { + self.locals = locals + super.init(viewMode: .sourceAccurate) + } + + override func visit(_ node: SequenceExprSyntax) -> SyntaxVisitorContinueKind { + let elements = Array(node.elements) + for (index, element) in elements.enumerated() where index > 0 && isMutatingOperator(element) { + if isStored(elements[index - 1]) { mutates = true } + } + return .visitChildren + } + + override func visit(_ node: InfixOperatorExprSyntax) -> SyntaxVisitorContinueKind { + if isMutatingOperator(node.operator), isStored(node.leftOperand) { mutates = true } + return .visitChildren + } + + override func visit(_ node: FunctionCallExprSyntax) -> SyntaxVisitorContinueKind { + if let member = node.calledExpression.as(MemberAccessExprSyntax.self), + ["append", "insert", "removeAll", "removeLast", "removeFirst"].contains(member.declName.baseName.text), + let base = member.base, isStored(base) { + mutates = true + } + return .visitChildren + } + + private func isMutatingOperator(_ expression: ExprSyntax) -> Bool { + if expression.is(AssignmentExprSyntax.self) { return true } + guard let binary = expression.as(BinaryOperatorExprSyntax.self) else { return false } + return ["+=", "-=", "*=", "/="].contains(binary.operator.text) + } + + /// 바꾸는 대상이 지역 변수가 아닌가(`self.x`, 또는 메서드 안에서 선언하지 않은 이름). + private func isStored(_ expression: ExprSyntax) -> Bool { + if let subscriptCall = expression.as(SubscriptCallExprSyntax.self) { return isStored(subscriptCall.calledExpression) } + if let member = expression.as(MemberAccessExprSyntax.self) { + guard let base = member.base else { return true } + if base.as(DeclReferenceExprSyntax.self)?.baseName.tokenKind == .keyword(.self) { return true } + return isStored(base) + } + if let reference = expression.as(DeclReferenceExprSyntax.self) { + // `$0`·`$1`은 클로저 매개변수다. + if case .dollarIdentifier = reference.baseName.tokenKind { return false } + return !locals.contains(reference.baseName.text) + } + // `_ = value`는 버리는 것이지 기록이 아니다. + if expression.is(DiscardAssignmentExprSyntax.self) { return false } + return true + } +} diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestLocationRules.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestLocationRules.swift new file mode 100644 index 000000000..bb304cb33 --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestLocationRules.swift @@ -0,0 +1,385 @@ +import Foundation +import SwiftSyntax + +// 규칙이 있는 코드를, 그 규칙이 사는 곳에서 직접 테스트한다(#293 원칙 2) — 모듈 단위, error. +// Sources와 Tests를 함께 봐야 해서 ModuleRule로 둔다. + +/// 명세 모듈의 Sources·Tests 파일을 나눈 것. +struct SpecModuleFiles { + let sources: [ParsedFile] + let tests: [ParsedFile] + + init?(moduleName: String, files: [ParsedFile]) { + guard TestSpecScope.modules.contains(moduleName) else { return nil } + sources = files.filter { TestSpecScope.locate($0.path)?.part == "Sources" } + tests = files.filter { TestSpecScope.locate($0.path)?.part == "Tests" } + } + + static func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Sources") || TestSpecScope.contains(path, part: "Tests") + } +} + +private func converter(_ file: ParsedFile) -> SourceLocationConverter { + SourceLocationConverter(fileName: file.path, tree: file.tree) +} + +// MARK: - 넘기기만 하는 코드는 테스트하지 않는다 + +/// `Default…UseCase`가 저장소 호출을 그대로 넘기기만 하면 그 테스트는 "Mock을 불렀다"만 확인한다. +/// 실제 동작(토큰 저장·삭제 등)은 구현 레이어(Data) 몫이라, 여기 테스트는 아무것도 지키지 못하면서 +/// 시그니처를 바꿀 때마다 깨진다. 로직이 생기면(분기·조합·변환) 그때 테스트를 쓴다. +struct TestPassThroughRule: ModuleRule { + let id = "test-passthrough" + let severity: Severity = .error + + func applies(to path: String) -> Bool { SpecModuleFiles.applies(to: path) } + + func check(moduleName: String, files: [ParsedFile]) -> [Violation] { + guard let module = SpecModuleFiles(moduleName: moduleName, files: files) else { return [] } + let passThrough = Set(module.sources.flatMap { PassThroughFinder.passThroughUseCases(in: $0.tree) }) + guard !passThrough.isEmpty else { return [] } + + var violations: [Violation] = [] + for file in module.tests { + let references = ReferenceCollector() + references.walk(file.tree) + let locations = converter(file) + for (name, node) in references.firstReference where passThrough.contains(name) { + violations.append(Violation( + path: file.path, line: SpecSyntax.line(of: node, locations), ruleID: id, + message: "\(name)는 저장소 호출을 넘기기만 한다 — 테스트하지 않는다(실제 동작은 구현 레이어에서 확인)", + severity: severity + )) + } + } + return violations + } +} + +public enum PassThroughFinder { + /// 모든 메서드가 "저장소 메서드 하나를 받은 인자 그대로 부르기"뿐인 `Default…UseCase` 이름. + /// 뮤테이션 도구도 이 판정으로 변이 대상에서 뺀다(테스트하지 않기로 한 코드라). + public static func passThroughUseCases(in tree: SourceFileSyntax) -> [String] { + tree.statements.compactMap { item in + guard let decl = item.item.as(ClassDeclSyntax.self), + decl.name.text.hasPrefix("Default"), decl.name.text.hasSuffix("UseCase") else { return nil } + let functions = decl.memberBlock.members.compactMap { $0.decl.as(FunctionDeclSyntax.self) } + guard !functions.isEmpty, functions.allSatisfy(isForwarding) else { return nil } + return decl.name.text + } + } + + private static func isForwarding(_ function: FunctionDeclSyntax) -> Bool { + guard let statements = function.body?.statements, statements.count == 1, + let call = forwardedCall(Syntax(statements.first!.item)), + // `repository.fetch().filter { … }`처럼 클로저를 넘기거나 결과에 이어 부르면 거르고 바꾸는 코드다. + call.trailingClosure == nil, call.additionalTrailingClosures.isEmpty, + let member = call.calledExpression.as(MemberAccessExprSyntax.self), + let base = member.base, isStoredReference(base) else { return false } + let parameters = Set(function.signature.parameterClause.parameters.map { + ($0.secondName ?? $0.firstName).text + }) + return call.arguments.allSatisfy { argument in + guard let reference = argument.expression.as(DeclReferenceExprSyntax.self) else { return false } + return parameters.contains(reference.baseName.text) + } + } + + /// 부르는 대상이 이름 하나(`repository`)나 `self.repository`인지 — 다른 호출의 결과면 넘기기가 아니다. + private static func isStoredReference(_ expression: ExprSyntax) -> Bool { + if expression.is(DeclReferenceExprSyntax.self) { return true } + guard let member = expression.as(MemberAccessExprSyntax.self), + let base = member.base?.as(DeclReferenceExprSyntax.self) else { return false } + return base.baseName.tokenKind == .keyword(.self) + } + + private static func forwardedCall(_ node: Syntax) -> FunctionCallExprSyntax? { + if let statement = node.as(ReturnStmtSyntax.self), let expression = statement.expression { + return forwardedCall(Syntax(expression)) + } + if let statement = node.as(ExpressionStmtSyntax.self) { return forwardedCall(Syntax(statement.expression)) } + if let expression = node.as(TryExprSyntax.self) { return forwardedCall(Syntax(expression.expression)) } + if let expression = node.as(AwaitExprSyntax.self) { return forwardedCall(Syntax(expression.expression)) } + return node.as(FunctionCallExprSyntax.self) + } +} + +// MARK: - 분기·throw가 있는 코드는 테스트가 있어야 한다 + +/// 분기(if·guard·switch·삼항)나 throw가 있는 타입은 규칙을 가진 타입이다 — 테스트에서 한 번은 불려야 한다. +struct TestRequiredRule: ModuleRule { + let id = "test-required" + let severity: Severity = .error + + func applies(to path: String) -> Bool { SpecModuleFiles.applies(to: path) } + + func check(moduleName: String, files: [ParsedFile]) -> [Violation] { + guard let module = SpecModuleFiles(moduleName: moduleName, files: files) else { return [] } + let passThrough = Set(module.sources.flatMap { PassThroughFinder.passThroughUseCases(in: $0.tree) }) + + var tested: Set = [] + for file in module.tests { + let references = ReferenceCollector() + references.walk(file.tree) + tested.formUnion(references.firstReference.keys) + } + + var violations: [Violation] = [] + var reported: Set = [] + for file in module.sources { + let locations = converter(file) + for item in file.tree.statements { + guard let (name, decl) = Self.typeDeclaration(item.item), + !passThrough.contains(name), !tested.contains(name), !reported.contains(name) else { continue } + let branches = RuleBranchFinder() + branches.walk(decl) + guard branches.found else { continue } + reported.insert(name) + violations.append(Violation( + path: file.path, line: SpecSyntax.line(of: decl, locations), ruleID: id, + message: "\(name)에 분기·throw가 있는데 테스트가 없다 — 이 규칙을 명세하는 테스트를 쓴다", + severity: severity + )) + } + } + return violations + } + + /// top-level 타입 선언·확장의 이름과 노드. + static func typeDeclaration(_ item: CodeBlockItemSyntax.Item) -> (String, Syntax)? { + if let decl = item.as(StructDeclSyntax.self) { return (decl.name.text, Syntax(decl)) } + if let decl = item.as(ClassDeclSyntax.self) { return (decl.name.text, Syntax(decl)) } + if let decl = item.as(EnumDeclSyntax.self) { return (decl.name.text, Syntax(decl)) } + if let decl = item.as(ActorDeclSyntax.self) { return (decl.name.text, Syntax(decl)) } + if let decl = item.as(ExtensionDeclSyntax.self) { return (decl.extendedType.trimmedDescription, Syntax(decl)) } + return nil + } +} + +private final class RuleBranchFinder: SyntaxVisitor { + private(set) var found = false + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: IfExprSyntax) -> SyntaxVisitorContinueKind { mark() } + override func visit(_ node: GuardStmtSyntax) -> SyntaxVisitorContinueKind { mark() } + override func visit(_ node: SwitchExprSyntax) -> SyntaxVisitorContinueKind { mark() } + override func visit(_ node: UnresolvedTernaryExprSyntax) -> SyntaxVisitorContinueKind { mark() } + override func visit(_ node: TernaryExprSyntax) -> SyntaxVisitorContinueKind { mark() } + override func visit(_ node: ThrowStmtSyntax) -> SyntaxVisitorContinueKind { mark() } + + private func mark() -> SyntaxVisitorContinueKind { + found = true + return .skipChildren + } +} + +// MARK: - 검증 에러 case마다 #expect(throws:) + +/// 판단 코드가 내는 에러 enum(`ValidationError`·`PolicyError` 등)은 case마다 그 에러가 나는 상황을 테스트한다. +/// 폴더나 이름으로 고르지 않는다 — BaseDomain처럼 `Entity/` 없이 `Sources/`에 바로 두는 모듈도 있다. +/// 저장소 에러(`RepositoryError`, `Repository/` 폴더의 `AuthError` 등)는 저장소가 내는 에러라 대상이 아니다. +/// `#expect(throws: X.self)`처럼 타입만 보면 다른 case가 나도 통과하므로 case를 직접 적어야 한다. +struct TestErrorCaseRule: ModuleRule { + let id = "test-error-case" + let severity: Severity = .error + + func applies(to path: String) -> Bool { SpecModuleFiles.applies(to: path) } + + func check(moduleName: String, files: [ParsedFile]) -> [Violation] { + guard let module = SpecModuleFiles(moduleName: moduleName, files: files) else { return [] } + + var expected: Set = [] + for file in module.tests { + let finder = ThrowsExpectationCaseFinder() + finder.walk(file.tree) + expected.formUnion(finder.names) + } + + var violations: [Violation] = [] + for file in module.sources where !file.path.contains("/Sources/Repository/") { + let finder = ErrorEnumFinder() + finder.walk(file.tree) + let locations = converter(file) + for (enumName, element) in finder.cases where !expected.contains(element.name.text) { + violations.append(Violation( + path: file.path, line: SpecSyntax.line(of: element, locations), ruleID: id, + message: "\(enumName).\(element.name.text)가 나는 상황을 #expect(throws:)로 확인하는 테스트가 없다", + severity: severity + )) + } + } + return violations + } +} + +private final class ErrorEnumFinder: SyntaxVisitor { + private(set) var cases: [(String, EnumCaseElementSyntax)] = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind { + let inherited = node.inheritanceClause?.inheritedTypes.map { $0.type.trimmedDescription } ?? [] + // `Error`·`LocalizedError`·`Error & Sendable`처럼 Error가 들어간 채택이면 에러 enum으로 본다. + guard inherited.contains(where: { $0.contains("Error") }), + node.name.text != "RepositoryError" else { return .visitChildren } + for member in node.memberBlock.members { + guard let caseDecl = member.decl.as(EnumCaseDeclSyntax.self) else { continue } + for element in caseDecl.elements { cases.append((node.name.text, element)) } + } + return .visitChildren + } +} + +/// `#expect(throws: …)`의 throws 인자에 적힌 case 이름들. +private final class ThrowsExpectationCaseFinder: SyntaxVisitor { + private(set) var names: Set = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: MacroExpansionExprSyntax) -> SyntaxVisitorContinueKind { + collect(node.macroName.text, node.arguments) + return .visitChildren + } + + override func visit(_ node: MacroExpansionDeclSyntax) -> SyntaxVisitorContinueKind { + collect(node.macroName.text, node.arguments) + return .visitChildren + } + + private func collect(_ name: String, _ arguments: LabeledExprListSyntax) { + guard name == "expect", let first = arguments.first, first.label?.text == "throws" else { return } + let members = MemberNameCollector() + members.walk(first.expression) + names.formUnion(members.names) + } +} + +private final class MemberNameCollector: SyntaxVisitor { + private(set) var names: Set = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: MemberAccessExprSyntax) -> SyntaxVisitorContinueKind { + names.insert(node.declName.baseName.text) + return .visitChildren + } +} + +// MARK: - 기대값에 소스 상수를 쓰지 않는다 + +/// `WithdrawalReasonDraft.maxCustomReasonLength`처럼 소스의 `static let`을 테스트에 쓰면, +/// 상수가 잘못 바뀌어도 테스트가 따라 바뀌어 통과한다. 명세의 값(80)을 직접 쓴다. +/// 타입 이름과 멤버 이름을 함께 본다 — 다른 타입의 같은 이름(enum case `DeepLink.novelDetail`과 +/// 내부 상수 `NotificationView.novelDetail`)을 상수로 오인하지 않게. +struct TestSourceConstantRule: ModuleRule { + let id = "test-source-constant" + let severity: Severity = .error + + func applies(to path: String) -> Bool { SpecModuleFiles.applies(to: path) } + + func check(moduleName: String, files: [ParsedFile]) -> [Violation] { + guard let module = SpecModuleFiles(moduleName: moduleName, files: files) else { return [] } + + var constants: Set = [] + for file in module.sources { + let finder = StaticConstantFinder() + finder.walk(file.tree) + constants.formUnion(finder.names) + } + guard !constants.isEmpty else { return [] } + + var violations: [Violation] = [] + for file in module.tests { + let finder = TypeMemberAccessFinder() + finder.walk(file.tree) + let locations = converter(file) + for node in finder.accesses where constants.contains(TypeMemberAccessFinder.key(of: node)) { + violations.append(Violation( + path: file.path, line: SpecSyntax.line(of: node, locations), ruleID: id, + message: "소스 상수 \(node.trimmedDescription)를 쓴다 — 상수가 틀려도 테스트가 따라간다. 명세의 값을 직접 쓴다", + severity: severity + )) + } + } + return violations + } +} + +/// `static let`을 `타입.이름`으로 모은다(타입은 가장 안쪽 선언). +private final class StaticConstantFinder: SyntaxVisitor { + private(set) var names: Set = [] + private var typeNames: [String] = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind { enter(node.name.text) } + override func visitPost(_ node: StructDeclSyntax) { typeNames.removeLast() } + override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind { enter(node.name.text) } + override func visitPost(_ node: EnumDeclSyntax) { typeNames.removeLast() } + override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind { enter(node.name.text) } + override func visitPost(_ node: ClassDeclSyntax) { typeNames.removeLast() } + override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { + enter(node.extendedType.trimmedDescription.components(separatedBy: ".").last ?? "") + } + override func visitPost(_ node: ExtensionDeclSyntax) { typeNames.removeLast() } + + private func enter(_ name: String) -> SyntaxVisitorContinueKind { + typeNames.append(name) + return .visitChildren + } + + override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind { + let isStatic = node.modifiers.contains { $0.name.text == "static" } + guard isStatic, node.bindingSpecifier.text == "let", let typeName = typeNames.last else { return .skipChildren } + for binding in node.bindings { + if let pattern = binding.pattern.as(IdentifierPatternSyntax.self) { + names.insert("\(typeName).\(pattern.identifier.text)") + } + } + return .skipChildren + } +} + +/// `Type.member` 모양(앞이 대문자 타입 이름)의 멤버 접근. +private final class TypeMemberAccessFinder: SyntaxVisitor { + private(set) var accesses: [MemberAccessExprSyntax] = [] + + init() { super.init(viewMode: .sourceAccurate) } + + /// `타입.이름` — `StaticConstantFinder`가 모은 이름과 맞춰 본다. + static func key(of node: MemberAccessExprSyntax) -> String { + "\(node.base?.trimmedDescription ?? "").\(node.declName.baseName.text)" + } + + override func visit(_ node: MemberAccessExprSyntax) -> SyntaxVisitorContinueKind { + if let base = node.base?.as(DeclReferenceExprSyntax.self), base.baseName.text.first?.isUppercase == true { + accesses.append(node) + } + return .visitChildren + } +} + +// MARK: - 공용 + +/// 파일에서 타입·값 이름이 처음 나온 곳. +final class ReferenceCollector: SyntaxVisitor { + private(set) var firstReference: [String: Syntax] = [:] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: DeclReferenceExprSyntax) -> SyntaxVisitorContinueKind { + record(node.baseName.text, Syntax(node)) + return .visitChildren + } + + override func visit(_ node: IdentifierTypeSyntax) -> SyntaxVisitorContinueKind { + record(node.name.text, Syntax(node)) + return .visitChildren + } + + private func record(_ name: String, _ node: Syntax) { + if firstReference[name] == nil { firstReference[name] = node } + } +} diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestNamingRule.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestNamingRule.swift new file mode 100644 index 000000000..e59222b08 --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestNamingRule.swift @@ -0,0 +1,97 @@ +import Foundation +import SwiftSyntax + +/// 테스트 이름 = 기능 명세 한 줄(#293 원칙 1 "읽힌다") — error. +/// - `@Test`는 `@Suite` 안에 있고, `@Suite`는 한국어 이름을 갖는다. +/// - `@Test("…")` 이름은 "~다"로 끝나는 한국어 문장이다. +/// - 이름에 코드 식별자(`draft.option`·`setOption(`·camelCase)를 쓰지 않는다 — 동작을 말로 쓴다. +/// - `/`를 쓰지 않는다(XcodeBuildMCP 리포터가 스위트 구분자로 읽어 이름을 쪼갠다). +/// - 모호한 말(성공적으로·정상적으로·올바르게·제대로)을 쓰지 않는다 — 무엇이 어떻게 되는지 쓴다. +/// - 한 스위트 안에서 이름이 겹치지 않는다. +struct TestNamingRule: Rule { + let id = "test-name" + let severity: Severity = .error + + static let vagueWords = ["성공적으로", "정상적으로", "올바르게", "제대로"] + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Tests") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let collector = SpecTestCollector() + collector.walk(tree) + var violations: [Violation] = [] + func report(_ node: some SyntaxProtocol, _ message: String) { + violations.append(Violation( + path: path, line: SpecSyntax.line(of: node, converter), + ruleID: id, message: message, severity: severity + )) + } + + for suite in collector.suites where !SpecSyntax.hasHangul(suite.displayName ?? "") { + report(suite.node, "@Suite에 한국어 이름이 없다 — 무엇의 명세인지 @Suite(\"…\")로 쓴다") + } + + var seen: [SyntaxIdentifier: Set] = [:] + for test in collector.tests { + if test.suiteID == nil { + report(test.function, "@Test가 @Suite 밖에 있다 — 기능 단위 @Suite 안에 둔다") + } + guard let name = test.displayName else { + report(test.function, "@Test에 이름이 없다 — @Test(\"~다\") 형태의 한국어 문장으로 쓴다") + continue + } + for problem in Self.problems(in: name) { + report(test.function, problem) + } + if let suiteID = test.suiteID { + if seen[suiteID, default: []].contains(name) { + report(test.function, "같은 스위트에 이름이 같은 테스트가 있다: \(name)") + } + seen[suiteID, default: []].insert(name) + } + } + return violations + } + + /// 이름 하나의 문제 목록. 비어 있으면 통과. + static func problems(in name: String) -> [String] { + var problems: [String] = [] + let trimmed = name.trimmingCharacters(in: .whitespaces) + if !SpecSyntax.hasHangul(trimmed) { + problems.append("이름이 한국어 문장이 아니다") + } + if !trimmed.hasSuffix("다") { + problems.append("이름이 '~다'로 끝나는 문장이 아니다") + } + if trimmed.contains("/") { + problems.append("이름에 '/'가 있다 — 테스트 리포터가 스위트 구분자로 읽는다") + } + if let identifier = firstIdentifier(in: trimmed) { + problems.append("이름에 코드 식별자 '\(identifier)'가 있다 — 동작을 말로 쓴다") + } + for word in vagueWords where trimmed.contains(word) { + problems.append("이름에 모호한 말 '\(word)'이 있다 — 무엇이 어떻게 되는지 쓴다") + } + return problems + } + + private static let identifierPatterns = [ + "`[^`]+`", // 백틱 + "[A-Za-z_][A-Za-z0-9_]*\\(", // 함수 호출 setOption( + "[A-Za-z_][A-Za-z0-9_]*\\.[A-Za-z_]+", // 멤버 접근 draft.option + "[a-z]+[A-Z][A-Za-z0-9]*", // camelCase + "[A-Z][a-z0-9]+[A-Z][A-Za-z0-9]*" // PascalCase 복합어(타입 이름). 한 단어(Apple)는 브랜드일 수 있어 두지 않는다 + ].map { try! NSRegularExpression(pattern: $0) } + + private static func firstIdentifier(in text: String) -> String? { + let range = NSRange(text.startIndex..., in: text) + for pattern in identifierPatterns { + if let match = pattern.firstMatch(in: text, range: range), let found = Range(match.range, in: text) { + return String(text[found]) + } + } + return nil + } +} diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestResultOnlyRule.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestResultOnlyRule.swift new file mode 100644 index 000000000..91acd4345 --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestResultOnlyRule.swift @@ -0,0 +1,54 @@ +import Foundation +import SwiftSyntax + +/// 테스트는 공개된 결과만 본다(#293 원칙 4 "버그 아니면 실패 안 함") — error. +/// - `@testable import` 금지: internal을 열어 보면 구현을 바꿀 때마다 테스트가 깨진다. +/// - Entity 테스트(`Tests/Entity/`)에 Mock 금지: Entity는 값과 규칙뿐이라 결과로 확인한다. +struct TestResultOnlyRule: Rule { + let id = "test-result-only" + let severity: Severity = .error + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Tests") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let visitor = ResultOnlyVisitor(checksMocks: path.contains("/Tests/Entity/")) + visitor.walk(tree) + return visitor.found.map { node, message in + Violation( + path: path, line: SpecSyntax.line(of: node, converter), + ruleID: id, message: message, severity: severity + ) + } + } +} + +private final class ResultOnlyVisitor: SyntaxVisitor { + private(set) var found: [(Syntax, String)] = [] + private let checksMocks: Bool + + init(checksMocks: Bool) { + self.checksMocks = checksMocks + super.init(viewMode: .sourceAccurate) + } + + override func visit(_ node: ImportDeclSyntax) -> SyntaxVisitorContinueKind { + if SpecSyntax.attribute(named: "testable", in: node.attributes) != nil { + found.append((Syntax(node), "@testable import — 공개 API로만 테스트한다(internal에 기대면 리팩터링마다 깨진다)")) + } + return .skipChildren + } + + override func visit(_ node: DeclReferenceExprSyntax) -> SyntaxVisitorContinueKind { + if checksMocks, Self.isMockName(node.baseName.text) { + found.append((Syntax(node), "Entity 테스트에 \(node.baseName.text) — Entity는 Mock 없이 결과로 확인한다")) + } + return .visitChildren + } + + private static func isMockName(_ name: String) -> Bool { + guard name.hasPrefix("Mock"), let next = name.dropFirst(4).first else { return false } + return next.isUppercase + } +} diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestSpecDocument.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestSpecDocument.swift new file mode 100644 index 000000000..5da947f3a --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestSpecDocument.swift @@ -0,0 +1,65 @@ +import Foundation +import SwiftSyntax + +/// 모듈의 테스트 목록 파일(`TEST_SPEC.md`) — 사람이 PR에서 주로 읽는 곳(#293). +/// 스위트·테스트 이름과 `arguments:` 항목을 뽑아 적는다. 테스트 이름이 바뀌면 이 파일의 diff로 보인다. +/// 손으로 고치지 않는다: `ArchLint --write-test-specs`가 만들고, 일반 실행은 최신인지 검사한다. +public enum TestSpecDocument { + public static let fileName = "TEST_SPEC.md" + static let ruleID = "test-spec-file" + + static func render(module: String, files: [ParsedFile]) -> String { + var lines = [ + "# \(module) 테스트 명세", + "", + "" + ] + + for file in files.sorted(by: { $0.path < $1.path }) { + let collector = SpecTestCollector() + collector.walk(file.tree) + let fileName = file.path.components(separatedBy: "/Tests/").last ?? file.path + for suite in collector.suites where suite.parentID == nil { + lines += suiteLines(suite, depth: 0, fileName: fileName, collector: collector) + } + } + return lines.joined(separator: "\n") + "\n" + } + + /// 스위트 하나와 그 안의 하위 스위트. 하위 스위트는 제목을 한 단계씩 내려 부모 아래에 둔다. + /// 파일 경로는 맨 위 스위트에만 적고, 테스트가 하나도 없는 스위트는 뺀다. + private static func suiteLines(_ suite: SpecSuite, depth: Int, fileName: String, collector: SpecTestCollector) -> [String] { + let tests = collector.tests.filter { $0.suiteID == suite.node.id } + let children = collector.suites + .filter { $0.parentID == suite.node.id } + .flatMap { suiteLines($0, depth: depth + 1, fileName: fileName, collector: collector) } + guard !tests.isEmpty || !children.isEmpty else { return [] } + + let heading = String(repeating: "#", count: min(depth + 2, 6)) + var lines = ["", "\(heading) \(suite.displayName ?? "(이름 없음)")", ""] + if depth == 0 { lines += ["`Tests/\(fileName)`", ""] } + // 직접 붙은 테스트가 없으면 하위 스위트의 앞 빈 줄과 겹치지 않게 뺀다. + if tests.isEmpty { lines.removeLast() } + for test in tests { + lines.append("- \(test.displayName ?? test.function.name.text)") + lines += argumentLines(test.arguments) + } + return lines + children + } + + /// `arguments:` 항목을 하위 목록으로. 배열이 아니면(`X.allCases`) 식을 그대로 적는다. + private static func argumentLines(_ arguments: ExprSyntax?) -> [String] { + guard let arguments else { return [] } + guard let array = SpecSyntax.argumentArray(arguments) else { + return [" - `\(arguments.trimmedDescription)`"] + } + return array.elements.map { element in + let comment = (Array(element.leadingTrivia) + Array(element.trailingTrivia)).compactMap { piece -> String? in + guard case .lineComment(let text) = piece else { return nil } + return text.dropFirst(2).trimmingCharacters(in: .whitespaces) + }.first + let value = "`\(element.expression.trimmedDescription)`" + return comment.map { " - \(value) — \($0)" } ?? " - \(value)" + } + } +} diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestSpecSupport.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestSpecSupport.swift new file mode 100644 index 000000000..4d0c4e5d7 --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestSpecSupport.swift @@ -0,0 +1,247 @@ +import Foundation +import SwiftSyntax + +// #293 "테스트 = 기능 명세" 규칙들이 함께 쓰는 도구 모음. +// 규칙 자체는 Test*Rule.swift 파일들에 있다. + +/// 명세 규칙이 적용되는 모듈. **재작성을 마친 모듈만** 넣는다 — +/// 아직 안 고친 모듈까지 넣으면 옛 테스트가 전부 error로 떠서 게이트가 막힌다. +enum TestSpecScope { + static let modules: Set = ["AuthDomain", "NovelReviewDomain", "BaseDomain", "CollectionDomain"] + + /// 경로에서 `Projects/<레이어>/<모듈>/<구역>/…`의 모듈과 구역(Sources·Tests·Testing)을 뽑는다. + static func locate(_ path: String) -> (module: String, part: String)? { + let components = path.split(separator: "/").map(String.init) + guard let index = components.firstIndex(of: "Projects"), components.count > index + 3 else { return nil } + return (components[index + 2], components[index + 3]) + } + + /// 명세 모듈의 해당 구역(`Tests`·`Testing`·`Sources`)에 있는 Swift 파일인가. + static func contains(_ path: String, part: String) -> Bool { + guard path.hasSuffix(".swift"), let location = locate(path) else { return false } + return modules.contains(location.module) && location.part == part + } +} + +/// `@Test`가 붙은 함수 하나. +struct SpecTest { + let function: FunctionDeclSyntax + let attribute: AttributeSyntax + /// `@Test("…")`의 첫 문자열. 없으면 nil. + let displayName: String? + /// `arguments:`에 넘긴 식. 없으면 nil. + let arguments: ExprSyntax? + /// 감싼 `@Suite` 타입의 구문 id. `@Suite` 밖이면 nil. + let suiteID: SyntaxIdentifier? +} + +/// `@Suite`가 붙은 타입 하나. +struct SpecSuite { + let node: Syntax + let displayName: String? + /// 감싼 `@Suite` 타입의 구문 id. 맨 위 스위트면 nil. + let parentID: SyntaxIdentifier? +} + +/// 파일에서 `@Suite` 타입과 `@Test` 함수를 모은다. +final class SpecTestCollector: SyntaxVisitor { + private(set) var tests: [SpecTest] = [] + private(set) var suites: [SpecSuite] = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind { + recordSuite(Syntax(node), node.attributes) + return .visitChildren + } + + override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind { + recordSuite(Syntax(node), node.attributes) + return .visitChildren + } + + override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { + guard let attribute = SpecSyntax.attribute(named: "Test", in: node.attributes) else { return .skipChildren } + tests.append(SpecTest( + function: node, + attribute: attribute, + displayName: SpecSyntax.displayName(of: attribute), + arguments: SpecSyntax.argument(labeled: "arguments", of: attribute), + suiteID: enclosingSuiteID(of: node) + )) + return .skipChildren + } + + private func recordSuite(_ node: Syntax, _ attributes: AttributeListSyntax) { + guard let attribute = SpecSyntax.attribute(named: "Suite", in: attributes) else { return } + suites.append(SpecSuite( + node: node, + displayName: SpecSyntax.displayName(of: attribute), + parentID: enclosingSuiteID(of: node) + )) + } + + /// 노드를 감싼 가장 가까운 타입이 `@Suite`면 그 id. + private func enclosingSuiteID(of node: some SyntaxProtocol) -> SyntaxIdentifier? { + var current = node.parent + while let parent = current { + if let decl = parent.as(StructDeclSyntax.self) { + return SpecSyntax.attribute(named: "Suite", in: decl.attributes) == nil ? nil : decl.id + } + if let decl = parent.as(ClassDeclSyntax.self) { + return SpecSyntax.attribute(named: "Suite", in: decl.attributes) == nil ? nil : decl.id + } + current = parent.parent + } + return nil + } +} + +/// 구문 트리에서 테스트 관련 모양을 읽는 함수들. +enum SpecSyntax { + /// `arguments:`의 배열 리터럴. `[…] as [(Date?, Date?)]`처럼 타입을 붙여도 배열을 꺼낸다 + /// (`nil`이 섞인 튜플은 타입을 적어야 컴파일된다). + static func argumentArray(_ expression: ExprSyntax?) -> ArrayExprSyntax? { + guard let expression else { return nil } + if let array = expression.as(ArrayExprSyntax.self) { return array } + if let cast = expression.as(AsExprSyntax.self) { return cast.expression.as(ArrayExprSyntax.self) } + if let sequence = expression.as(SequenceExprSyntax.self), + let first = sequence.elements.first?.as(ArrayExprSyntax.self), + sequence.elements.dropFirst().first?.is(UnresolvedAsExprSyntax.self) == true { + return first + } + return nil + } + + static func attribute(named name: String, in list: AttributeListSyntax) -> AttributeSyntax? { + for element in list { + if case .attribute(let attribute) = element, attribute.attributeName.trimmedDescription == name { + return attribute + } + } + return nil + } + + static func displayName(of attribute: AttributeSyntax) -> String? { + guard case .argumentList(let arguments)? = attribute.arguments, + let first = arguments.first, first.label == nil, + let literal = first.expression.as(StringLiteralExprSyntax.self) else { return nil } + return literal.segments.compactMap { $0.as(StringSegmentSyntax.self)?.content.text }.joined() + } + + static func argument(labeled label: String, of attribute: AttributeSyntax) -> ExprSyntax? { + guard case .argumentList(let arguments)? = attribute.arguments else { return nil } + return arguments.first { $0.label?.text == label }?.expression + } + + /// 문장이 매크로 호출(`#expect`·`#require` 등)이면 이름과 인자. `try`·`await`·`let x =`를 벗겨 본다. + static func macro(in node: Syntax) -> (name: String, arguments: LabeledExprListSyntax)? { + if let item = node.as(CodeBlockItemSyntax.self) { return macro(in: Syntax(item.item)) } + if let statement = node.as(ExpressionStmtSyntax.self) { return macro(in: Syntax(statement.expression)) } + if let expression = node.as(TryExprSyntax.self) { return macro(in: Syntax(expression.expression)) } + if let expression = node.as(AwaitExprSyntax.self) { return macro(in: Syntax(expression.expression)) } + if let expression = node.as(MacroExpansionExprSyntax.self) { + return (expression.macroName.text, expression.arguments) + } + if let declaration = node.as(MacroExpansionDeclSyntax.self) { + return (declaration.macroName.text, declaration.arguments) + } + if let declaration = node.as(VariableDeclSyntax.self), + declaration.bindings.count == 1, + let value = declaration.bindings.first?.initializer?.value { + return macro(in: Syntax(value)) + } + return nil + } + + /// `#expect`·`#require` 문장인가. + static func isAssertion(_ item: CodeBlockItemSyntax) -> Bool { + guard let name = macro(in: Syntax(item))?.name else { return false } + return name == "expect" || name == "require" + } + + /// `#expect(throws: …)` 문장인가. + static func isThrowsExpectation(_ item: CodeBlockItemSyntax) -> Bool { + guard let found = macro(in: Syntax(item)), found.name == "expect" else { return false } + return found.arguments.first?.label?.text == "throws" + } + + /// 함수 본문을 빈 줄 기준 구역으로 나눈다(준비 / 실행 / 확인). + static func sections(of body: CodeBlockSyntax) -> [[CodeBlockItemSyntax]] { + var sections: [[CodeBlockItemSyntax]] = [] + for (index, item) in body.statements.enumerated() { + if index == 0 || startsAfterBlankLine(item) { + sections.append([item]) + } else { + sections[sections.count - 1].append(item) + } + } + return sections + } + + /// 노드 앞에 빈 줄이 있는가. 주석 줄은 빈 줄로 치지 않는다. + static func startsAfterBlankLine(_ node: some SyntaxProtocol) -> Bool { + var newlines = 0 + for piece in node.leadingTrivia { + switch piece { + case .newlines(let count), .carriageReturnLineFeeds(let count), .carriageReturns(let count): + newlines += count + if newlines >= 2 { return true } + case .spaces, .tabs: + continue + default: + newlines = 0 + } + } + return false + } + + static func line(of node: some SyntaxProtocol, _ converter: SourceLocationConverter) -> Int { + node.startLocation(converter: converter, afterLeadingTrivia: true).line + } + + static func hasHangul(_ text: String) -> Bool { + text.unicodeScalars.contains { (0xAC00...0xD7A3).contains($0.value) } + } +} + +/// 노드 아래에서 이름이 같은 매크로 호출을 센다. +final class MacroCounter: SyntaxVisitor { + private(set) var names: [String] = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: MacroExpansionExprSyntax) -> SyntaxVisitorContinueKind { + names.append(node.macroName.text) + return .visitChildren + } + + override func visit(_ node: MacroExpansionDeclSyntax) -> SyntaxVisitorContinueKind { + names.append(node.macroName.text) + return .visitChildren + } +} + +/// `// archlint:allow <규칙 id> — 이유`가 위반 줄이나 바로 윗줄에 있으면 그 위반을 뺀다. +/// 이유가 비어 있으면 빼지 않는다 — 예외는 왜 예외인지 남겨야 사람이 리뷰할 수 있다. +enum AllowComment { + static func filter(_ violations: [Violation], lines: (String) -> [String]?) -> [Violation] { + violations.filter { violation in + guard let fileLines = lines(violation.path) else { return true } + let candidates = [violation.line - 1, violation.line - 2].filter { fileLines.indices.contains($0) } + return !candidates.contains { allows(fileLines[$0], ruleID: violation.ruleID) } + } + } + + static func allows(_ line: String, ruleID: String) -> Bool { + // 테스트 명세 규칙만 뺄 수 있다 — 의존 방향 같은 아키텍처 규칙을 주석 한 줄로 끄지 못하게. + guard ruleID.hasPrefix("test-") else { return false } + let marker = "archlint:allow " + ruleID + guard let range = line.range(of: marker) else { return false } + let rest = line[range.upperBound...] + // 접두만 같은 다른 규칙(test-aaa vs test-aaa-act)을 막는다. + if let next = rest.first, next != " " { return false } + let reason = rest.trimmingCharacters(in: CharacterSet(charactersIn: " —-:").union(.whitespaces)) + return !reason.isEmpty + } +} diff --git a/Tooling/ArchLint/Sources/ArchLintCore/TestStructureRule.swift b/Tooling/ArchLint/Sources/ArchLintCore/TestStructureRule.swift new file mode 100644 index 000000000..15cfcf30d --- /dev/null +++ b/Tooling/ArchLint/Sources/ArchLintCore/TestStructureRule.swift @@ -0,0 +1,176 @@ +import Foundation +import SwiftSyntax + +/// 테스트 본문은 준비 / 실행 / 확인(AAA) 구역을 빈 줄로 나눈다(#293 원칙 1 "읽힌다") — error. +/// - 구역은 3개 이하. 확인 구역은 맨 끝이고 `#expect`·`#require`만 담는다. 확인은 다른 구역에 섞지 않는다. +/// - 구역이 하나뿐이면 `#expect(throws:)` 한 줄짜리만 허용한다(실행이 그 안에 들어 있다). +/// - `// Given`·`// When`·`// Then` 같은 구역 라벨은 쓰지 않는다 — 빈 줄이 구역을 말한다. +/// - for·while·if·switch·guard·삼항을 쓰지 않는다 — 분기가 있으면 어느 경우를 확인했는지 읽히지 않는다. +/// 여러 입력은 `arguments:`로 나눈다. +struct TestStructureRule: Rule { + let id = "test-aaa" + let severity: Severity = .error + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Tests") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let collector = SpecTestCollector() + collector.walk(tree) + var violations: [Violation] = [] + func report(_ node: some SyntaxProtocol, _ message: String) { + violations.append(Violation( + path: path, line: SpecSyntax.line(of: node, converter), + ruleID: id, message: message, severity: severity + )) + } + + for test in collector.tests { + guard let body = test.function.body, !body.statements.isEmpty else { continue } + let sections = SpecSyntax.sections(of: body) + + if sections.count > 3 { + report(test.function, "구역이 \(sections.count)개다 — 준비 / 실행 / 확인 3구역 이하로 빈 줄로 나눈다") + } + if let last = sections.last, let offender = last.first(where: { !SpecSyntax.isAssertion($0) }) { + report(offender, "마지막 구역(확인)에는 #expect·#require만 둔다 — 실행과 확인 사이에 빈 줄을 넣는다") + } + for section in sections.dropLast() { + for item in section where SpecSyntax.isAssertion(item) { + report(item, "확인(#expect·#require)이 마지막 구역이 아닌 곳에 있다 — 확인은 맨 끝 구역에 모은다") + } + } + if sections.count == 1, !(sections[0].count == 1 && SpecSyntax.isThrowsExpectation(sections[0][0])) { + report(test.function, "준비·실행·확인이 한 덩어리다 — 빈 줄로 구역을 나눈다") + } + + let labels = SectionLabelFinder() + labels.walk(body) + for token in labels.found { + report(token, "구역 라벨 주석(Given·When·Then 등)은 쓰지 않는다 — 빈 줄이 구역을 나눈다") + } + + let branches = BranchFinder() + branches.walk(body) + for (node, kind) in branches.found { + report(node, "테스트 본문에 \(kind) — 어느 경우를 확인했는지 안 읽힌다. 입력이 여럿이면 arguments:로 나눈다") + } + } + return violations + } +} + +/// 실행 구역이 여러 문장이면 사람에게 설계를 묻는다 — warning. +/// 한 동작을 여러 호출로 해야 한다면 메서드를 합쳐야 한다는 신호일 수 있다. +/// 유지하기로 했으면 `// archlint:allow test-aaa-act — 이유`를 남긴다(PR 점검 목록에 오른다). +struct TestActSizeRule: Rule { + let id = "test-aaa-act" + let severity: Severity = .warning + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Tests") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let collector = SpecTestCollector() + collector.walk(tree) + return collector.tests.compactMap { test in + guard let body = test.function.body, + let act = Self.actSection(SpecSyntax.sections(of: body)), + act.count > 1 else { return nil } + return Violation( + path: path, line: SpecSyntax.line(of: act[0], converter), ruleID: id, + message: "실행 구역이 \(act.count)문장이다 — 한 동작을 여러 호출로 해야 한다면 메서드 설계를 점검한다(사람 확인 필요)", + severity: severity + ) + } + } + + /// 실행 구역: 3구역이면 가운데, 2구역이면 첫 구역(단 확인이 `#expect(throws:)`면 실행이 그 안에 있어 첫 구역은 준비). + static func actSection(_ sections: [[CodeBlockItemSyntax]]) -> [CodeBlockItemSyntax]? { + switch sections.count { + case 3: + return sections[1] + case 2: + let throwsExpectation = sections[1].contains { SpecSyntax.isThrowsExpectation($0) } + return throwsExpectation ? nil : sections[0] + default: + return nil + } + } +} + +/// 본문이 길면 읽히지 않는다 — warning. 길어지면 준비를 줄일 방법(입력 단순화·설계 점검)을 찾는다. +struct TestBodyLengthRule: Rule { + let id = "test-body-length" + let severity: Severity = .warning + + static let maxLines = 15 + + func applies(to path: String) -> Bool { + TestSpecScope.contains(path, part: "Tests") + } + + func check(_ tree: SourceFileSyntax, path: String, converter: SourceLocationConverter) -> [Violation] { + let collector = SpecTestCollector() + collector.walk(tree) + return collector.tests.compactMap { test in + guard let body = test.function.body else { return nil } + let open = body.leftBrace.startLocation(converter: converter).line + let close = body.rightBrace.startLocation(converter: converter).line + let lines = close - open - 1 + guard lines > Self.maxLines else { return nil } + return Violation( + path: path, line: SpecSyntax.line(of: test.function, converter), ruleID: id, + message: "본문이 \(lines)줄이다(상한 \(Self.maxLines)) — 한눈에 읽히도록 준비를 줄인다", + severity: severity + ) + } + } +} + +/// `// Given` 같은 구역 라벨 주석을 찾는다. +private final class SectionLabelFinder: SyntaxVisitor { + private(set) var found: [TokenSyntax] = [] + + private static let label = try! NSRegularExpression( + pattern: "^//\\s*((given|when|then|arrange|act|assert)\\b|(준비|실행|확인)\\s*(:|-|$))", + options: [.caseInsensitive] + ) + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind { + let pieces = Array(token.leadingTrivia) + Array(token.trailingTrivia) + for piece in pieces { + guard case .lineComment(let text) = piece else { continue } + let range = NSRange(text.startIndex..., in: text) + if Self.label.firstMatch(in: text, range: range) != nil { + found.append(token) + } + } + return .visitChildren + } +} + +/// 분기·반복을 찾는다. +private final class BranchFinder: SyntaxVisitor { + private(set) var found: [(Syntax, String)] = [] + + init() { super.init(viewMode: .sourceAccurate) } + + override func visit(_ node: ForStmtSyntax) -> SyntaxVisitorContinueKind { record(node, "for") } + override func visit(_ node: WhileStmtSyntax) -> SyntaxVisitorContinueKind { record(node, "while") } + override func visit(_ node: RepeatStmtSyntax) -> SyntaxVisitorContinueKind { record(node, "repeat") } + override func visit(_ node: IfExprSyntax) -> SyntaxVisitorContinueKind { record(node, "if") } + override func visit(_ node: SwitchExprSyntax) -> SyntaxVisitorContinueKind { record(node, "switch") } + override func visit(_ node: GuardStmtSyntax) -> SyntaxVisitorContinueKind { record(node, "guard") } + override func visit(_ node: UnresolvedTernaryExprSyntax) -> SyntaxVisitorContinueKind { record(node, "삼항") } + override func visit(_ node: TernaryExprSyntax) -> SyntaxVisitorContinueKind { record(node, "삼항") } + + private func record(_ node: some SyntaxProtocol, _ kind: String) -> SyntaxVisitorContinueKind { + found.append((Syntax(node), kind)) + return .visitChildren + } +} diff --git a/Tooling/ArchLint/Sources/Mutate/main.swift b/Tooling/ArchLint/Sources/Mutate/main.swift new file mode 100644 index 000000000..acc74a285 --- /dev/null +++ b/Tooling/ArchLint/Sources/Mutate/main.swift @@ -0,0 +1,357 @@ +import Foundation +import MutationCore + +// 뮤테이션 도구(#293) — 모듈 소스에 버그를 하나씩 심고 그 모듈 테스트를 돌려, 테스트가 못 잡은(살아남은) 버그를 보고한다. +// 살아남은 버그 = 테스트가 지키지 못하는 동작. 사람이 보고 "테스트를 더한다 / 의미 없는 변이다"를 판단한다. +// +// 사용법(레포 루트에서, tuist generate 후): +// swift run --package-path Tooling/ArchLint Mutate AuthDomain # 전체 실행 +// swift run --package-path Tooling/ArchLint Mutate AuthDomain --list # 심을 버그 목록만 +// swift run --package-path Tooling/ArchLint Mutate AuthDomain --changed-since # origin/develop 이후 바뀐 소스에만 +// swift run --package-path Tooling/ArchLint Mutate AuthDomain --changed-since=HEAD~3 # 다른 기준(`=`로 붙여 쓴다) +// `--changed-since`는 모듈의 테스트(`Tests/`)나 가짜 객체(`Testing/`)가 바뀌었으면 모듈 전체에 심는다 — +// 테스트가 약해지면 손대지 않은 소스의 버그도 새로 살아남기 때문이다. +// +// 소스 파일을 직접 고쳤다가 되돌리므로, 모듈 Sources에 커밋 안 한 변경이 있으면 시작하지 않는다. +// 원본은 시작할 때 읽어 두고, Ctrl-C나 실행 실패로 끝나도 되돌린다. 그래도 남으면 `git checkout -- <모듈>/Sources`. + +struct Options { + var module = "" + var root = "." + var listOnly = false + /// `--changed-since`의 기준 ref. nil이면 모듈 전체. + var changedSince: String? +} + +func parseOptions() -> Options { + var options = Options() + var arguments = CommandLine.arguments.dropFirst().makeIterator() + while let argument = arguments.next() { + switch argument { + case "--list": options.listOnly = true + case "--root": options.root = arguments.next() ?? "." + case "--changed-since": options.changedSince = "origin/develop" + case let flag where flag.hasPrefix("--changed-since="): + let ref = String(flag.dropFirst("--changed-since=".count)) + guard !ref.isEmpty else { fail("--changed-since= 뒤에 기준을 적는다(예: --changed-since=HEAD~3)") } + options.changedSince = ref + default: options.module = argument + } + } + return options +} + +/// 버그를 심기 전 소스 원본(경로 → 내용). 어떻게 끝나든 이것으로 되돌린다. +nonisolated(unsafe) var originals: [String: String] = [:] +/// 소스 쓰기를 한 번에 하나만 — Ctrl-C로 되돌린 뒤에 다음 버그가 심기지 않게 한다. +let sourceLock = NSLock() + +func restoreSources() { + sourceLock.lock() + for (path, source) in originals { + do { + try source.write(toFile: path, atomically: true, encoding: .utf8) + } catch { + // 되돌리지 못한 파일은 숨기지 않고 알린다 — 버그가 심긴 채 남아 있다. + FileHandle.standardError.write(Data("되돌리지 못했다: \(path) \(error) — `git checkout -- \(path)`\n".utf8)) + } + } +} + +/// 지금 돌고 있는 자식 프로세스(xcodebuild 등). 신호로 끝낼 때 고아로 남기지 않게 먼저 멈추고, +/// 시간 초과로 멈췄는지도 여기서 기록한다(다른 신호로 죽은 것과 가르기 위해). +final class ChildProcess: @unchecked Sendable { + private let lock = NSLock() + private var process: Process? + private var timedOut = false + private var stopped = false + + func start(_ newProcess: Process) { + lock.lock(); defer { lock.unlock() } + // 신호로 멈추기로 한 뒤에 뜬 프로세스도 바로 멈춘다(고아 방지). + if stopped { newProcess.terminate() } + process = newProcess + timedOut = false + } + + /// 끝난 프로세스를 내려놓고, 시간 초과로 멈췄는지 돌려준다. + func finish() -> Bool { + lock.lock(); defer { lock.unlock() } + process = nil + return timedOut + } + + func timeOut(_ target: Process) { + lock.lock(); defer { lock.unlock() } + guard process === target, target.isRunning else { return } + timedOut = true + target.terminate() + } + + func terminate() { + lock.lock(); defer { lock.unlock() } + stopped = true + process?.terminate() + } +} + +let child = ChildProcess() + +/// 파일로 보내도 버그 하나 끝날 때마다 바로 보이게 버퍼 없이 내보낸다. +func say(_ message: String) { + FileHandle.standardOutput.write(Data((message + "\n").utf8)) +} + +func fail(_ message: String) -> Never { + restoreSources() + FileHandle.standardError.write(Data((message + "\n").utf8)) + exit(2) +} + +@discardableResult +func run( + _ launchPath: String, _ arguments: [String], in directory: String, timeout: TimeInterval? = nil +) -> (status: Int32, output: String, timedOut: Bool) { + let process = Process() + process.executableURL = URL(fileURLWithPath: launchPath) + process.arguments = arguments + process.currentDirectoryURL = URL(fileURLWithPath: directory) + let pipe = Pipe() + process.standardOutput = pipe + process.standardError = pipe + do { try process.run() } catch { fail("실행 실패: \(launchPath) \(error)") } + child.start(process) + // 무한 루프가 생기는 버그도 있다 — 시간을 넘기면 끊는다. + let timer = DispatchWorkItem { child.timeOut(process) } + if let timeout { DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: timer) } + let data = pipe.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + timer.cancel() + let timedOut = child.finish() + return (process.terminationStatus, String(decoding: data, as: UTF8.self), timedOut) +} + +/// `Projects/<레이어>/<모듈>` 경로. +func moduleDirectory(_ module: String, root: String) -> String { + let projects = root + "/Projects" + let layers = (try? FileManager.default.contentsOfDirectory(atPath: projects)) ?? [] + for layer in layers { + let candidate = "\(projects)/\(layer)/\(module)" + if FileManager.default.fileExists(atPath: candidate + "/Project.swift") { return candidate } + } + fail("모듈을 찾지 못했다: \(module)") +} + +func swiftFiles(under directory: String) -> [String] { + let enumerator = FileManager.default.enumerator(atPath: directory) + var files: [String] = [] + while let relative = enumerator?.nextObject() as? String { + if relative.hasSuffix(".swift") { files.append(directory + "/" + relative) } + } + return files.sorted() +} + +/// 사용 가능한 iPhone 시뮬레이터 하나(CI와 같은 방식)와 지금 켜져 있는지. +func simulator() -> (id: String, isBooted: Bool) { + let result = run("/usr/bin/xcrun", ["simctl", "list", "devices", "available", "-j"], in: ".") + guard let json = try? JSONSerialization.jsonObject(with: Data(result.output.utf8)) as? [String: Any], + let devices = json["devices"] as? [String: [[String: Any]]] else { fail("시뮬레이터 목록을 읽지 못했다") } + for runtime in devices.keys.sorted(by: >) where runtime.contains("iOS") { + for device in devices[runtime] ?? [] { + if let name = device["name"] as? String, name.contains("iPhone"), let id = device["udid"] as? String { + return (id, device["state"] as? String == "Booted") + } + } + } + fail("iPhone 시뮬레이터가 없다") +} + +enum Outcome { + case killed, timedOut, survived, notCompiled +} + +let derivedDataPath = FileManager.default.temporaryDirectory.appendingPathComponent("wss-mutation-derived-data").path + +func runTests(scheme: String, root: String, simulator: String, timeout: TimeInterval? = nil) -> Outcome { + let result = run("/usr/bin/xcodebuild", [ + "test", + "-workspace", "WSS-iOS-V2.xcworkspace", + "-scheme", scheme, + "-sdk", "iphonesimulator", + "-destination", "platform=iOS Simulator,id=\(simulator)", + // Xcode가 쓰는 DerivedData와 따로 둔다 — 같은 곳을 동시에 빌드하면 build.db가 깨진다. + // 레포 안(.build)에 두지 않는다 — 레포 안 빌드 폴더가 rebase를 깬 적이 있다. + "-derivedDataPath", derivedDataPath, + // 테스트가 실패하면(버그를 잡으면) xcodebuild가 시뮬레이터 진단을 모으느라 몇 분씩 멈춘다. 이 도구엔 필요 없다. + "-collect-test-diagnostics", "never", + "-quiet" + ], in: root, timeout: timeout) + if result.status == 0 { return .survived } + if result.timedOut { return .timedOut } + let compileError = result.output.range(of: #"\.swift:\d+:\d+: error:"#, options: .regularExpression) != nil + return compileError ? .notCompiled : .killed +} + +// MARK: - 실행 + +let options = parseOptions() +guard !options.module.isEmpty else { + fail("사용법: Mutate <모듈 이름> [--list] [--changed-since[=기준, 기본 origin/develop]] [--root 레포루트]") +} + +func relative(_ path: String) -> String { + path.replacingOccurrences(of: options.root + "/", with: "") +} + +let moduleDir = moduleDirectory(options.module, root: options.root) +var sourceFiles = swiftFiles(under: moduleDir + "/Sources") + +/// 기준 ref와 갈라진 지점 이후 바뀐 파일(레포 루트 기준 상대 경로). +/// 작업 폴더까지 비교하고 추적 안 된 새 파일도 넣는다 — 커밋 전 테스트 수정도 범위에 반영되게. +func changedPaths(since ref: String) -> [String] { + // 한글 등 ASCII 밖 경로를 따옴표로 감싸지 않게 한다(그러면 소스 경로와 안 맞는다). + let git = ["-c", "core.quotePath=false"] + let base = run("/usr/bin/git", git + ["merge-base", ref, "HEAD"], in: options.root) + let mergeBase = base.output.trimmingCharacters(in: .whitespacesAndNewlines) + guard base.status == 0, !mergeBase.isEmpty else { + fail("기준 \(ref)과 갈라진 지점을 찾지 못했다(git merge-base \(ref) HEAD): \(base.output.trimmingCharacters(in: .whitespacesAndNewlines))") + } + let diff = run("/usr/bin/git", git + ["diff", "--name-only", "--relative", mergeBase], in: options.root) + guard diff.status == 0 else { fail("git diff 실패: \(diff.output)") } + let untracked = run("/usr/bin/git", git + ["ls-files", "--others", "--exclude-standard"], in: options.root) + guard untracked.status == 0 else { fail("git ls-files 실패: \(untracked.output)") } + return ChangedScope.paths(fromGitOutput: diff.output) + ChangedScope.paths(fromGitOutput: untracked.output) +} + +if let ref = options.changedSince { + // decide는 레포 루트 기준 상대 경로로 비교한다 — 실제 경로(`./Projects/…`)와 오가는 표를 둔다. + let actualPath = Dictionary(uniqueKeysWithValues: sourceFiles.map { (relative($0), $0) }) + let decision = ChangedScope.decide( + sourceFiles: sourceFiles.map(relative), + changedPaths: changedPaths(since: ref), + moduleDirectory: relative(moduleDir) + ) + switch decision { + case .wholeModule: + say("\(ref) 이후 테스트나 가짜 객체가 바뀌어 모듈 전체에 심는다") + case .onlyChanged(let files) where files.isEmpty: + say("\(ref) 이후 바뀐 소스가 없어 심을 버그가 없다") + exit(0) + case .onlyChanged(let files): + sourceFiles = files.compactMap { actualPath[$0] } + say("\(ref) 이후 바뀐 소스 \(files.count)개에만 심는다:") + for file in files { say(" \(file)") } + } +} + +var mutants: [Mutant] = [] +for file in sourceFiles { + guard let source = try? String(contentsOfFile: file, encoding: .utf8) else { continue } + originals[file] = source + mutants += MutantGenerator.mutants(in: source, path: file) +} + +if options.listOnly { + for mutant in mutants { say("\(relative(mutant.path)):\(mutant.line) \(mutant.summary)") } + say("심을 버그 \(mutants.count)개") + exit(0) +} + +let status = run("/usr/bin/git", ["status", "--porcelain", "--", moduleDir + "/Sources"], in: options.root) +guard status.output.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + fail("\(relative(moduleDir))/Sources에 커밋 안 한 변경이 있다 — 소스를 고쳤다 되돌리는 도구라 먼저 정리한다") +} + +// 테스트가 없으면 아래 시작 확인이 "테스트부터 실패한다"로 끝나 원인이 가려진다. 판단 코드가 없어 테스트를 다 뺀 모듈이 이 경우다. +guard !swiftFiles(under: moduleDir + "/Tests").isEmpty else { + fail("\(relative(moduleDir))/Tests에 테스트가 없다 — 잡을 테스트가 없어 뮤테이션을 돌릴 수 없다(판단 코드가 없는 모듈이면 건너뛴다)") +} + +// 꺼진 시뮬레이터를 넘기면 xcodebuild가 실행마다 켰다 끈다(한 번에 30초 넘게 든다). 미리 켜 두고, 도구가 켰으면 끝날 때 끈다. +let (simulatorID, wasBooted) = simulator() +if !wasBooted { + run("/usr/bin/xcrun", ["simctl", "boot", simulatorID], in: ".") + run("/usr/bin/xcrun", ["simctl", "bootstatus", simulatorID], in: ".") +} +func restoreSimulator() { + if !wasBooted { run("/usr/bin/xcrun", ["simctl", "shutdown", simulatorID], in: ".") } +} +// Ctrl-C·kill·터미널 닫기로 끊어도 심은 버그를 남기지 않는다. +let shutdownSimulatorOnInterrupt = !wasBooted +let interruptedSimulatorID = simulatorID +let interrupts = [SIGINT, SIGTERM, SIGHUP].map { signalNumber in + signal(signalNumber, SIG_IGN) + let source = DispatchSource.makeSignalSource(signal: signalNumber, queue: .global()) + source.setEventHandler { @Sendable in + child.terminate() // 돌던 xcodebuild를 고아로 남기지 않는다. + restoreSources() // 잠금을 풀지 않고 끝낸다 — 그 뒤로는 아무도 소스를 쓰지 못한다. + if shutdownSimulatorOnInterrupt { + // run()은 실패하면 fail() → restoreSources()로 같은 잠금을 다시 잡아 멈춘다. 여기선 직접 띄운다. + let shutdown = Process() + shutdown.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + shutdown.arguments = ["simctl", "shutdown", interruptedSimulatorID] + if (try? shutdown.run()) != nil { shutdown.waitUntilExit() } + } + FileHandle.standardError.write(Data("\n중단 — 소스를 되돌렸다\n".utf8)) + exit(128 + signalNumber) + } + source.resume() + return source +} + +say("시작: \(options.module) — 버그 \(mutants.count)개") + +guard runTests(scheme: options.module, root: options.root, simulator: simulatorID) == .survived else { + restoreSimulator() + fail("버그를 심기 전 테스트부터 실패한다 — 먼저 테스트를 통과시킨다") +} + +var survivors: [Mutant] = [] +var notCompiled = 0 +// 버그 하나에 보통 몇 초다. 이보다 오래 걸리면 버그가 무한 루프를 만든 것으로 본다. +let mutantTimeout: TimeInterval = 300 + +for (index, mutant) in mutants.enumerated() { + guard let original = originals[mutant.path] else { continue } + sourceLock.lock() + do { + try mutant.apply(to: original).write(toFile: mutant.path, atomically: true, encoding: .utf8) + } catch { + sourceLock.unlock() + restoreSimulator() + fail("버그를 심지 못했다: \(relative(mutant.path)) \(error)") + } + sourceLock.unlock() + let startedAt = Date() + let outcome = runTests(scheme: options.module, root: options.root, simulator: simulatorID, timeout: mutantTimeout) + sourceLock.lock() + do { + try original.write(toFile: mutant.path, atomically: true, encoding: .utf8) + } catch { + // 되돌리지 못한 채 다음 버그를 심으면 버그가 겹친다 — 여기서 멈춘다. + sourceLock.unlock() + restoreSimulator() + fail("소스를 되돌리지 못했다: \(relative(mutant.path)) \(error)") + } + sourceLock.unlock() + + let label: String + switch outcome { + case .killed: label = "잡힘" + case .timedOut: label = "잡힘(시간 초과)" + case .survived: label = "생존"; survivors.append(mutant) + case .notCompiled: label = "컴파일 안 됨"; notCompiled += 1 + } + let seconds = Int(Date().timeIntervalSince(startedAt)) + say("[\(index + 1)/\(mutants.count)] \(label) (\(seconds)초) \(relative(mutant.path)):\(mutant.line) \(mutant.summary)") +} + +restoreSimulator() + +let valid = mutants.count - notCompiled +say("") +say("결과: 버그 \(valid)개 중 \(valid - survivors.count)개를 테스트가 잡았다(컴파일 안 된 \(notCompiled)개 제외)") +if !survivors.isEmpty { + say("살아남은 버그 — 테스트가 이 동작을 지키지 않는다. 테스트를 더할지, 의미 없는 변이인지 사람이 판단한다:") + for mutant in survivors { say(" \(relative(mutant.path)):\(mutant.line) \(mutant.summary)") } +} diff --git a/Tooling/ArchLint/Sources/MutationCore/ChangedScope.swift b/Tooling/ArchLint/Sources/MutationCore/ChangedScope.swift new file mode 100644 index 000000000..f91d5f907 --- /dev/null +++ b/Tooling/ArchLint/Sources/MutationCore/ChangedScope.swift @@ -0,0 +1,39 @@ +import Foundation + +/// `--changed-since`로 돌릴 때 어떤 소스에 버그를 심을지 정한다. +/// 경로는 모두 레포 루트 기준 상대 경로(`Projects/Domain/AuthDomain/Sources/…`)다. +public enum ChangedScope { + + public enum Decision: Equatable, Sendable { + /// 모듈의 테스트나 가짜 객체가 바뀌었다 — 모듈 전체에 버그를 심는다. + case wholeModule + /// 바뀐 소스 파일에만 버그를 심는다. 비어 있으면 심을 곳이 없다. + case onlyChanged([String]) + } + + /// - Parameters: + /// - sourceFiles: 지금 모듈 `Sources/`에 있는 Swift 파일. + /// - changedPaths: 기준 이후 바뀐 파일(`git diff --name-only`). + /// - moduleDirectory: `Projects/<레이어>/<모듈>`. + /// + /// 테스트가 바뀌면 소스는 그대로여도 결과가 달라진다 — 테스트를 지우거나 약하게 바꾸면 + /// 손대지 않은 소스의 버그가 새로 살아남는다. 그래서 그때는 바뀐 파일만이 아니라 모듈 전체를 본다. + public static func decide(sourceFiles: [String], changedPaths: [String], moduleDirectory: String) -> Decision { + let module = moduleDirectory.hasSuffix("/") ? String(moduleDirectory.dropLast()) : moduleDirectory + let testsChanged = changedPaths.contains { path in + path.hasPrefix(module + "/Tests/") || path.hasPrefix(module + "/Testing/") + } + if testsChanged { return .wholeModule } + // 지워진 파일은 지금 소스 목록에 없으니 자연히 빠진다. + let changed = Set(changedPaths) + return .onlyChanged(sourceFiles.filter { changed.contains($0) }) + } + + /// `git diff --name-only` 출력을 줄 단위 경로로 나눈다. + public static func paths(fromGitOutput output: String) -> [String] { + output + .split(whereSeparator: \.isNewline) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + } +} diff --git a/Tooling/ArchLint/Sources/MutationCore/MutantGenerator.swift b/Tooling/ArchLint/Sources/MutationCore/MutantGenerator.swift new file mode 100644 index 000000000..590f14cae --- /dev/null +++ b/Tooling/ArchLint/Sources/MutationCore/MutantGenerator.swift @@ -0,0 +1,125 @@ +import ArchLintCore +import Foundation +import SwiftParser +import SwiftSyntax + +/// 소스에 심는 버그 하나. +public struct Mutant: Sendable, Equatable { + public let path: String + public let line: Int + public let original: String + public let replacement: String + /// 바꿀 구간(UTF-8 바이트 오프셋). + let start: Int + let end: Int + + public var summary: String { + let shown = original.split(separator: "\n").first.map(String.init) ?? original + return replacement.isEmpty ? "`\(shown)` 삭제" : "`\(shown)` → `\(replacement)`" + } + + public func apply(to source: String) -> String { + var bytes = Array(source.utf8) + bytes.replaceSubrange(start.. [Mutant] { + let tree = Parser.parse(source: source) + let skipped = Set(PassThroughFinder.passThroughUseCases(in: tree)) + let visitor = MutantVisitor(path: path, converter: SourceLocationConverter(fileName: path, tree: tree), skipped: skipped) + visitor.walk(tree) + return visitor.mutants + } +} + +private final class MutantVisitor: SyntaxVisitor { + private(set) var mutants: [Mutant] = [] + private let path: String + private let converter: SourceLocationConverter + private let skipped: Set + + private static let operatorSwaps: [String: String] = [ + "==": "!=", "!=": "==", + "<": "<=", "<=": "<", ">": ">=", ">=": ">", + "&&": "||", "||": "&&", + "+": "-", "-": "+" + ] + + init(path: String, converter: SourceLocationConverter, skipped: Set) { + self.path = path + self.converter = converter + self.skipped = skipped + super.init(viewMode: .sourceAccurate) + } + + override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind { + skipped.contains(node.name.text) ? .skipChildren : .visitChildren + } + + override func visit(_ node: BinaryOperatorExprSyntax) -> SyntaxVisitorContinueKind { + if let swapped = Self.operatorSwaps[node.operator.text] { + add(node.operator, swapped) + } + return .visitChildren + } + + override func visit(_ node: PrefixOperatorExprSyntax) -> SyntaxVisitorContinueKind { + if node.operator.text == "!" { + add(node, node.expression.trimmedDescription) + } + return .visitChildren + } + + override func visit(_ node: BooleanLiteralExprSyntax) -> SyntaxVisitorContinueKind { + add(node, node.literal.text == "true" ? "false" : "true") + return .visitChildren + } + + override func visit(_ node: IntegerLiteralExprSyntax) -> SyntaxVisitorContinueKind { + // Int.max에 1을 더하면 넘친다 — 그런 리터럴은 건너뛴다. + if let value = Int(node.literal.text.replacingOccurrences(of: "_", with: "")), value < Int.max { + add(node, String(value + 1)) + } + return .visitChildren + } + + override func visit(_ node: CodeBlockItemSyntax) -> SyntaxVisitorContinueKind { + if isDeletable(node) { add(node, "") } + return .visitChildren + } + + /// 함수·생성자·접근자 본문의 대입·호출·guard·if 문장. 선언과 return은 지우면 컴파일이 안 되거나 의미가 없어 뺀다. + private func isDeletable(_ node: CodeBlockItemSyntax) -> Bool { + guard node.parent?.parent?.is(CodeBlockSyntax.self) == true else { return false } + switch node.item { + case .expr: + return true + case .stmt(let statement): + if statement.is(GuardStmtSyntax.self) { return true } + return statement.as(ExpressionStmtSyntax.self) != nil + case .decl: + return false + } + } + + private func add(_ node: some SyntaxProtocol, _ replacement: String) { + let start = node.positionAfterSkippingLeadingTrivia.utf8Offset + let end = node.endPositionBeforeTrailingTrivia.utf8Offset + mutants.append(Mutant( + path: path, + line: node.startLocation(converter: converter, afterLeadingTrivia: true).line, + original: node.trimmedDescription, + replacement: replacement, + start: start, + end: end + )) + } +} diff --git a/Tooling/ArchLint/Tests/ArchLintCoreTests/TestSpecRuleTests.swift b/Tooling/ArchLint/Tests/ArchLintCoreTests/TestSpecRuleTests.swift new file mode 100644 index 000000000..eda4963a5 --- /dev/null +++ b/Tooling/ArchLint/Tests/ArchLintCoreTests/TestSpecRuleTests.swift @@ -0,0 +1,684 @@ +import Testing +@testable import ArchLintCore + +// #293 테스트 명세 규칙의 자체 테스트. 규칙마다 "잡아야 할 것"과 "잡으면 안 되는 것"을 함께 둔다. +// 레포가 이미 초록이라 위반 경로는 여기서만 검증된다. + +private let specTestPath = "/Projects/Domain/AuthDomain/Tests/Entity/SampleTests.swift" +private let specTestingPath = "/Projects/Domain/AuthDomain/Testing/Mock/MockSampleRepository.swift" +private let specSourcePath = "/Projects/Domain/AuthDomain/Sources/Entity/Sample.swift" +private let outOfScopeTestPath = "/Projects/Domain/NovelDomain/Tests/Entity/SampleTests.swift" + +/// 규칙에 걸리지 않는 기준 테스트. 각 테스트는 여기서 한 군데만 망가뜨려 본다. +private let cleanSpec = """ +import Testing + +import AuthDomain + +@Suite("샘플 작성") +struct SampleTests { + + @Test("내용은 80자까지 저장된다") + func keepsUpTo80() { + var draft = Draft() + let text = String(repeating: "가", count: 80) + + draft.setText(text) + + #expect(draft.text == text) + } +} +""" + +private func ids(_ violations: [Violation]) -> [String] { + violations.map(\.ruleID) +} + +@Suite("ArchLint 테스트 명세 규칙 자체 검증") +struct TestSpecRuleTests { + + // MARK: - 기준·범위 + + @Test("규칙에 맞는 테스트는 어떤 명세 규칙에도 걸리지 않는다") + func cleanSpecPassesEveryRule() { + #expect(lint(source: cleanSpec, path: specTestPath).isEmpty) + } + + @Test("명세 모듈이 아닌 곳의 테스트는 검사하지 않는다") + func outOfScopeModuleIsSkipped() { + let source = "@testable import NovelDomain\n@Test func a() { for _ in 0..<1 {} }" + #expect(lint(source: source, path: outOfScopeTestPath).isEmpty) + } + + // MARK: - test-name + + @Test( + "이름이 명세 문장이 아니면 잡는다", + arguments: [ + ("WithdrawalReasonDraft를 만든다", "코드 식별자"), // 타입 이름 + ("setText(_:)를 부르면 저장된다", "코드 식별자"), // 함수 호출 + ("draft.text가 바뀐다", "코드 식별자"), // 멤버 접근 + ("isSubmittable이 참이 된다", "코드 식별자"), // camelCase + ("저장한다/불러온다", "'/'"), // 리포터가 스위트로 쪼갠다 + ("성공적으로 저장된다", "모호한 말"), // 무엇이 되는지 말하지 않는다 + ("저장됨", "'~다'"), // 문장이 아니다 + ("saves text", "한국어") // 영어 + ] + ) + func namingCatchesNonSpecNames(name: String, expectedProblem: String) { + let problems = TestNamingRule.problems(in: name) + + #expect(problems.contains { $0.contains(expectedProblem) }) + } + + @Test("@Suite 밖 테스트·한국어 이름 없는 스위트·이름 없는 테스트·같은 이름을 잡는다") + func namingCatchesStructureProblems() { + let source = """ + @Test("밖에 있다") func loose() {} + @Suite struct Unnamed {} + @Suite("샘플") struct Named { + @Test func unnamed() {} + @Test("같은 이름이다") func a() {} + @Test("같은 이름이다") func b() {} + } + """ + + let violations = lint(source: source, path: specTestPath, rules: [TestNamingRule()]) + + #expect(violations.count == 4) + } + + // MARK: - test-assert + + @Test("#expect 없이 #require만 있으면 잡는다") + func assertionCatchesRequireOnly() { + let source = cleanSpec.replacingOccurrences(of: "#expect(draft.text == text)", with: "try #require(draft.text == text)") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestAssertionRule()])) == ["test-assert"]) + } + + @Test("!= nil 확인을 잡는다") + func assertionCatchesNotNil() { + let source = cleanSpec.replacingOccurrences(of: "draft.text == text", with: "draft.text != nil") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestAssertionRule()])) == ["test-assert"]) + } + + // MARK: - test-name-number + + @Test("이름의 숫자가 본문에 없으면 잡는다") + func assertionCatchesMissingNumber() { + let source = cleanSpec.replacingOccurrences(of: "count: 80", with: "count: 81") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestNameNumberRule()])) == ["test-name-number"]) + } + + @Test("이름의 숫자가 arguments 안에만 있어도 본문에 있는 것으로 본다") + func assertionFindsNumberInArguments() { + let source = """ + @Suite("샘플") struct S { + @Test("0.5 단위만 허용한다", arguments: [ + 0.5 // 가장 작은 단위 + ]) + func a(value: Double) { + let rating = Rating(value) + + #expect(rating.value == value) + } + } + """ + + #expect(lint(source: source, path: specTestPath, rules: [TestNameNumberRule()]).isEmpty) + } + + @Test("숫자가 단위를 말할 뿐이면 이유를 단 allow 주석으로 뺀다") + func nameNumberAllowsUnitWithReason() { + let source = """ + @Suite("샘플") struct S { + // archlint:allow test-name-number — 0.5는 단위를 말한다(넣는 값이 아니다) + @Test("0.5점 단위가 아니면 평점이 아니다", arguments: [ + 4.7 // 단위에서 벗어났다 + ]) + func a(value: Double) { + #expect(throws: Rating.ValidationError.invalidStep) { + try Rating(value) + } + } + } + """ + + let violations = lint(source: source, path: specTestPath, rules: [TestNameNumberRule()]) + + #expect(violations.isEmpty) + } + + // MARK: - test-aaa + + @Test("확인 구역에 실행이 섞이면 잡는다") + func structureCatchesActInAssertSection() { + let source = cleanSpec.replacingOccurrences(of: "draft.setText(text)\n\n", with: "draft.setText(text)\n") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestStructureRule()])) == ["test-aaa"]) + } + + @Test("확인이 중간 구역에 있으면 잡는다") + func structureCatchesEarlyAssertion() { + let source = cleanSpec.replacingOccurrences(of: "draft.setText(text)\n", with: "#expect(draft.text == \"\")\n draft.setText(text)\n") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestStructureRule()])).contains("test-aaa")) + } + + @Test("구역이 4개 이상이면 잡는다") + func structureCatchesTooManySections() { + let source = cleanSpec.replacingOccurrences(of: "var draft = Draft()\n", with: "var draft = Draft()\n\n") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestStructureRule()])) == ["test-aaa"]) + } + + @Test( + "본문의 분기·반복을 잡는다", + arguments: [ + "for _ in 0..<1 {}", // for + "if draft.text.isEmpty {}", // if + "_ = draft.text.isEmpty ? 1 : 2" // 삼항 + ] + ) + func structureCatchesBranches(statement: String) { + let source = cleanSpec.replacingOccurrences(of: "var draft = Draft()\n", with: "var draft = Draft()\n \(statement)\n") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestStructureRule()])) == ["test-aaa"]) + } + + @Test("// Given 같은 구역 라벨을 잡는다") + func structureCatchesSectionLabels() { + let source = cleanSpec.replacingOccurrences(of: " var draft = Draft()", with: " // Given\n var draft = Draft()") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestStructureRule()])) == ["test-aaa"]) + } + + @Test("설명 주석은 구역 라벨로 보지 않는다") + func structureAllowsExplanationComments() { + let source = cleanSpec.replacingOccurrences(of: " var draft = Draft()", with: " // 확인하려는 값보다 하나 길게 둔다\n var draft = Draft()") + + #expect(lint(source: source, path: specTestPath, rules: [TestStructureRule()]).isEmpty) + } + + @Test("#expect(throws:) 한 줄짜리 테스트는 구역이 하나여도 통과한다") + func structureAllowsSingleThrowsExpectation() { + let source = """ + @Suite("샘플") struct S { + @Test("음수는 만들 수 없다") + func a() { + #expect(throws: SampleError.negative) { try Sample(-1) } + } + } + """ + + #expect(lint(source: source, path: specTestPath, rules: [TestStructureRule()]).isEmpty) + } + + // MARK: - test-aaa-act · test-body-length (warning) + + @Test("실행 구역이 여러 문장이면 warning으로 묻는다") + func actSizeWarnsOnMultipleStatements() { + let source = cleanSpec.replacingOccurrences(of: "draft.setText(text)\n", with: "draft.setText(text)\n draft.setText(text)\n") + + let violations = lint(source: source, path: specTestPath, rules: [TestActSizeRule()]) + + #expect(violations.map(\.severity) == [.warning]) + } + + @Test("이유를 단 allow 주석이 있으면 그 위반을 뺀다") + func allowCommentSuppressesWithReason() { + let source = cleanSpec.replacingOccurrences(of: " draft.setText(text)\n", with: " // archlint:allow test-aaa-act — 두 번 저장해도 마지막 값만 남는지 보는 테스트\n draft.setText(text)\n draft.setText(text)\n") + + #expect(lint(source: source, path: specTestPath, rules: [TestActSizeRule()]).isEmpty) + } + + @Test( + "이유가 없거나 다른 규칙을 가리키는 allow 주석은 무시한다", + arguments: [ + "// archlint:allow test-aaa-act", // 이유 없음 + "// archlint:allow test-aaa — 이유가 있다" // 다른 규칙(접두만 같음) + ] + ) + func allowCommentNeedsReasonAndExactRule(comment: String) { + let source = cleanSpec.replacingOccurrences(of: " draft.setText(text)\n", with: " \(comment)\n draft.setText(text)\n draft.setText(text)\n") + + #expect(lint(source: source, path: specTestPath, rules: [TestActSizeRule()]).count == 1) + } + + @Test("allow 주석은 아키텍처 규칙을 끄지 못한다") + func allowCommentCannotSilenceArchitectureRules() { + let line = "// archlint:allow dependency-direction — 이유가 있다" + + let allowed = AllowComment.allows(line, ruleID: "dependency-direction") + + #expect(allowed == false) + } + + @Test("본문이 15줄을 넘으면 warning이다") + func bodyLengthWarnsOver15Lines() { + let padding = String(repeating: " draft.setText(text)\n", count: 15) + let source = cleanSpec.replacingOccurrences(of: " var draft = Draft()\n", with: " var draft = Draft()\n\(padding)") + + let violations = lint(source: source, path: specTestPath, rules: [TestBodyLengthRule()]) + + #expect(violations.map(\.severity) == [.warning]) + } + + // MARK: - test-arguments + + @Test("arguments 항목이 한 줄에 여럿이면 잡는다") + func argumentsCatchesSameLine() { + let source = """ + @Suite("샘플") struct S { + @Test("둘 다 거절한다", arguments: [Option.a, .b]) + func a(option: Option) { + let result = check(option) + + #expect(result == false) + } + } + """ + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestArgumentsRule()])) == ["test-arguments"]) + } + + @Test("리터럴 항목에 이유 주석이 없으면 잡고, enum case는 주석 없이 통과한다") + func argumentsRequiresCommentOnLiteralsOnly() { + let source = """ + @Suite("샘플") struct S { + @Test("빈 값은 거절한다", arguments: [ + "", + " " // 공백만 + ]) + func a(text: String) { + let result = check(text) + + #expect(result == false) + } + + @Test("모든 항목을 거절한다", arguments: [ + Option.a, + .b + ]) + func b(option: Option) { + let result = check(option) + + #expect(result == false) + } + } + """ + + let violations = lint(source: source, path: specTestPath, rules: [TestArgumentsRule()]) + + #expect(violations.map(\.line) == [3]) + } + + @Test("타입을 붙인 arguments 배열도 항목마다 이유 주석을 본다") + func argumentsChecksTypedArray() { + let source = """ + @Suite("샘플") struct S { + @Test("하나만 있어도 된다", arguments: [ + (day, nil), // 시작일만 + (nil, day) + ] as [(Date?, Date?)]) + func a(start: Date?, end: Date?) { + let result = check(start, end) + + #expect(result == true) + } + } + """ + + let violations = lint(source: source, path: specTestPath, rules: [TestArgumentsRule()]) + + #expect(violations.map(\.line) == [4]) + } + + // MARK: - test-determinism + + @Test( + "실행마다 달라지는 값을 잡는다", + arguments: [ + "let now = Date()", // 지금 시각 + "let now = Date.now", // 지금 시각 + "let calendar = Calendar.current", // 기기 설정 + "let locale = Locale.current", // 기기 설정 + "let id = UUID()", // 난수 + "let n = Int.random(in: 0...1)" // 난수 + ] + ) + func determinismCatchesVaryingValues(statement: String) { + let source = cleanSpec.replacingOccurrences(of: " var draft = Draft()\n", with: " var draft = Draft()\n \(statement)\n") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestDeterminismRule()])) == ["test-determinism"]) + } + + @Test("고정 날짜와 static var를 구분한다") + func determinismAllowsFixedDateButNotStaticVar() { + let source = """ + let fixed = Date(timeIntervalSince1970: 0) + enum Shared { static var count = 0 } + """ + + let violations = lint(source: source, path: specTestPath, rules: [TestDeterminismRule()]) + + #expect(violations.map(\.line) == [2]) + } + + // MARK: - test-result-only + + @Test("@testable import를 잡는다") + func resultOnlyCatchesTestable() { + let source = cleanSpec.replacingOccurrences(of: "import AuthDomain", with: "@testable import AuthDomain") + + #expect(ids(lint(source: source, path: specTestPath, rules: [TestResultOnlyRule()])) == ["test-result-only"]) + } + + @Test("Entity 테스트의 Mock은 잡고, UseCase 테스트의 Mock은 두며, MockingBird 같은 이름은 Mock으로 보지 않는다") + func resultOnlyCatchesMockOnlyInEntityTests() { + let source = "let a = MockSampleRepository()\nlet b = Mockingbird()" + let useCasePath = "/Projects/Domain/AuthDomain/Tests/UseCase/SampleUseCaseTests.swift" + + let entity = lint(source: source, path: specTestPath, rules: [TestResultOnlyRule()]) + let useCase = lint(source: source, path: useCasePath, rules: [TestResultOnlyRule()]) + + #expect(entity.map(\.line) == [1]) + #expect(useCase.isEmpty) + } + + // MARK: - test-double-query + + @Test("가짜 객체의 조회 메서드가 호출을 기록하면 잡고, 명령 메서드의 기록과 지역 변수로 결과를 만드는 것은 둔다") + func doubleQueryCatchesRecordingInQueriesOnly() { + let source = """ + public final class MockSampleRepository { + public var fetchResult: Result = .success(0) + public private(set) var fetchCount = 0 + public private(set) var saved: [Int] = [] + + public func fetchSample() throws -> Int { + fetchCount += 1 + return try fetchResult.get() + } + + public func loadAll() throws -> Int { + try fetchResult.get() + } + + public func save(_ value: Int) { + saved.append(value) + } + + public func searchSample(_ query: String) -> [Int] { + var results = [1] + results.append(2) + results += [3] + _ = query + return results + } + + public func loadAll(_ groups: [[Int]]) -> [Int] { + let flat = groups.reduce(into: []) { result, group in result.append(contentsOf: group) } + return groups.reduce(into: flat) { $0.append($1.count) } + } + } + """ + + let violations = lint(source: source, path: specTestingPath, rules: [TestDoubleQueryRule()]) + + #expect(violations.map(\.line) == [6]) + } + + @Test( + "조회 메서드 이름을 fetch·load·search 접두로 가린다", + arguments: [ + ("fetchNovel", true), // 조회 + ("load", true), // 접두만 + ("searchKeywords", true), // 검색도 조회다 + ("searcher", false), // 다른 단어 + ("loader", false), // 다른 단어 + ("save", false) // 명령 + ] + ) + func doubleQueryRecognizesQueryNames(name: String, isQuery: Bool) { + let result = TestDoubleQueryRule.isQueryName(name) + + #expect(result == isQuery) + } + + // MARK: - test-spec-file + + @Test("하위 스위트는 부모 스위트 아래에 한 단계 내린 제목으로 나온다") + func specFileNestsChildSuites() { + let source = """ + @Suite("샘플 작성") + struct SampleTests { + @Test("빈 샘플은 제출할 수 없다") func a() {} + + @Suite("이름") struct Name { + @Test("이름은 20자까지 입력할 수 있다") func b() {} + } + + @Suite("설명") struct Description { + @Test("설명은 60자까지 입력할 수 있다") func c() {} + } + } + """ + + let rendered = renderTestSpec(sources: [(specTestPath, source)], moduleName: "AuthDomain") + + #expect(rendered.hasSuffix(""" + + ## 샘플 작성 + + `Tests/Entity/SampleTests.swift` + + - 빈 샘플은 제출할 수 없다 + + ### 이름 + + - 이름은 20자까지 입력할 수 있다 + + ### 설명 + + - 설명은 60자까지 입력할 수 있다 + + """)) + } + + @Test("하위 스위트에만 테스트가 있어도 부모 제목과 파일 경로가 나온다") + func specFileKeepsParentWithoutOwnTests() { + let source = """ + @Suite("샘플 작성") + struct SampleTests { + @Suite("이름") struct Name { + @Test("이름은 20자까지 입력할 수 있다") func b() {} + } + @Suite("비어 있음") struct Empty {} + } + """ + + let rendered = renderTestSpec(sources: [(specTestPath, source)], moduleName: "AuthDomain") + + #expect(rendered.hasSuffix(""" + + ## 샘플 작성 + + `Tests/Entity/SampleTests.swift` + + ### 이름 + + - 이름은 20자까지 입력할 수 있다 + + """)) + } + + // MARK: - 모듈 단위 규칙 + + @Test("넘기기만 하는 UseCase를 테스트하면 잡고, 바꾸거나 거르는 UseCase는 테스트해도 된다") + func passThroughCatchesForwardingUseCaseTests() { + let sources = [ + (path: "/Projects/Domain/AuthDomain/Sources/UseCase/Forward.swift", source: """ + public final class DefaultForwardUseCase { + private let repository: Repo + public func execute(id: Int) async throws -> Int { + return try await repository.fetch(id: id) + } + } + public final class DefaultSelfForwardUseCase { + private let repository: Repo + public func execute(id: Int) async throws -> Int { + try await self.repository.fetch(id: id) + } + } + public final class DefaultLogicUseCase { + private let repository: Repo + public func execute(id: Int) async throws -> Int { + try await repository.fetch(id: id + 1) + } + } + public final class DefaultFilterUseCase { + private let repository: Repo + public func execute() async throws -> [Int] { + try await repository.fetch().filter { $0 > 0 } + } + } + public final class DefaultObserveUseCase { + private let repository: Repo + public func execute(id: Int) -> Stream { + repository.observe(id: id) { $0 * 2 } + } + } + public final class DefaultChainUseCase { + private let repository: Repo + public func execute(id: Int) async throws -> [Int] { + try await repository.fetch(id: id).sorted() + } + } + """), + (path: "/Projects/Domain/AuthDomain/Tests/UseCase/ForwardTests.swift", source: """ + let a = DefaultForwardUseCase(repository: stub) + let b = DefaultSelfForwardUseCase(repository: stub) + let c = DefaultLogicUseCase(repository: stub) + let d = DefaultFilterUseCase(repository: stub) + let e = DefaultChainUseCase(repository: stub) + let f = DefaultObserveUseCase(repository: stub) + """) + ] + + let violations = lintModule(sources: sources, moduleName: "AuthDomain", rule: TestPassThroughRule()) + + #expect(violations.map(\.line).sorted() == [1, 2]) + } + + @Test("분기·throw가 있는 타입이 테스트에 한 번도 안 나오면 잡는다") + func requiredCatchesUntestedBranchingType() { + let sources = [ + (path: specSourcePath, source: """ + public struct Tested { public func f(_ x: Int) -> Int { x > 0 ? x : 0 } } + public struct Untested { public func g() throws { throw E.x } } + public struct NoRule { public let value: Int } + """), + (path: specTestPath, source: "let t = Tested()") + ] + + let violations = lintModule(sources: sources, moduleName: "AuthDomain", rule: TestRequiredRule()) + + #expect(violations.map(\.message).allSatisfy { $0.hasPrefix("Untested") }) + #expect(violations.count == 1) + } + + @Test("Entity 에러 case 중 #expect(throws:)에 안 나온 것을 잡는다(타입만 적은 확인은 세지 않는다)") + func errorCaseCatchesMissingCases() { + let sources = [ + (path: specSourcePath, source: """ + public struct Draft { + public enum ValidationError: Error { + case tooLong(max: Int) + case empty + case duplicated + } + } + """), + (path: specTestPath, source: """ + func a() { #expect(throws: Draft.ValidationError.tooLong(max: 20)) { try f() } } + func b() { #expect(throws: Draft.ValidationError.self) { try g() } } + func c() { #expect(draft.error == .empty) } + """) + ] + + let violations = lintModule(sources: sources, moduleName: "AuthDomain", rule: TestErrorCaseRule()) + + #expect(violations.map(\.message).sorted() == [ + "ValidationError.duplicated가 나는 상황을 #expect(throws:)로 확인하는 테스트가 없다", + "ValidationError.empty가 나는 상황을 #expect(throws:)로 확인하는 테스트가 없다" + ]) + } + + @Test("저장소 에러(RepositoryError·Repository 폴더)는 대상이 아니다") + func errorCaseSkipsRepositoryErrors() { + let sources = [ + (path: "/Projects/Domain/AuthDomain/Sources/Repository/AuthError.swift", + source: "public enum AuthError: Error { case unknown }"), + (path: "/Projects/Domain/AuthDomain/Sources/RepositoryError.swift", + source: "public enum RepositoryError: Error { case notFound }") + ] + + #expect(lintModule(sources: sources, moduleName: "AuthDomain", rule: TestErrorCaseRule()).isEmpty) + } + + @Test("Entity 폴더 밖이나 다른 이름의 검증 에러도 검사한다") + func errorCaseChecksErrorsOutsideEntity() { + let sources = [ + (path: "/Projects/Domain/AuthDomain/Sources/Rating.swift", source: """ + public struct Rating { + public enum ValidationError: Error { case outOfRange } + } + """), + (path: "/Projects/Domain/AuthDomain/Sources/Entity/Feed.swift", source: """ + public struct Feed { + public enum PolicyError: LocalizedError { case notOwner } + } + """) + ] + + let violations = lintModule(sources: sources, moduleName: "AuthDomain", rule: TestErrorCaseRule()) + + #expect(violations.count == 2) + } + + @Test("테스트가 소스의 static let 상수를 쓰면 잡는다") + func sourceConstantCatchesStaticLetReference() { + let sources = [ + (path: specSourcePath, source: "public struct Draft { public static let maxLength = 80 }"), + (path: specTestPath, source: """ + let a = String(repeating: "가", count: Draft.maxLength) + let b = Option.maxLengthLabel + """) + ] + + let violations = lintModule(sources: sources, moduleName: "AuthDomain", rule: TestSourceConstantRule()) + + #expect(violations.map(\.line) == [1]) + } + + @Test("다른 타입의 같은 이름은 소스 상수로 보지 않는다") + func sourceConstantMatchesTypeAndName() { + let sources = [ + (path: specSourcePath, source: """ + public enum DeepLink { + case novelDetail(Int) + private enum View { static let novelDetail = "novelDetail" } + } + """), + (path: specTestPath, source: "let link = DeepLink.novelDetail(7)") + ] + + let violations = lintModule(sources: sources, moduleName: "AuthDomain", rule: TestSourceConstantRule()) + + #expect(violations.isEmpty) + } +} diff --git a/Tooling/ArchLint/Tests/MutationCoreTests/ChangedScopeTests.swift b/Tooling/ArchLint/Tests/MutationCoreTests/ChangedScopeTests.swift new file mode 100644 index 000000000..b943e9d07 --- /dev/null +++ b/Tooling/ArchLint/Tests/MutationCoreTests/ChangedScopeTests.swift @@ -0,0 +1,83 @@ +import Testing + +import MutationCore + +private let module = "Projects/Domain/AuthDomain" +private let token = "Projects/Domain/AuthDomain/Sources/Entity/Token.swift" +private let draft = "Projects/Domain/AuthDomain/Sources/Entity/WithdrawalDraft.swift" +private let useCase = "Projects/Domain/AuthDomain/Sources/UseCase/LogoutUseCase.swift" +private let sources = [token, draft, useCase] + +@Suite("뮤테이션 도구 — 바뀐 곳만 고르기") +struct ChangedScopeTests { + + @Test("바뀐 소스 파일에만 버그를 심는다") + func mutatesOnlyChangedSources() { + // 다른 모듈의 소스 변경도 섞어, 이 모듈 소스만 남는지 본다. + let changed = [draft, "Projects/Domain/NovelDomain/Sources/Entity/Novel.swift", token] + + let decision = ChangedScope.decide(sourceFiles: sources, changedPaths: changed, moduleDirectory: module) + + #expect(decision == .onlyChanged([token, draft])) + } + + @Test( + "모듈의 테스트나 가짜 객체가 바뀌면 바뀐 소스와 상관없이 모듈 전체에 심는다", + arguments: [ + "Projects/Domain/AuthDomain/Tests/Entity/WithdrawalDraftTests.swift", // 테스트를 약하게 고침 + "Projects/Domain/AuthDomain/Testing/Mock/MockAuthRepository.swift" // 가짜 객체가 바뀜 + ] + ) + func mutatesWholeModuleWhenTestsChange(testPath: String) { + let decision = ChangedScope.decide(sourceFiles: sources, changedPaths: [token, testPath], moduleDirectory: module) + + #expect(decision == .wholeModule) + } + + @Test("이름 앞부분만 같은 다른 모듈의 테스트가 바뀐 것은 모듈 전체에 심을 이유가 아니다") + func ignoresTestsOfModuleWithSamePrefix() { + let changed = [token, "Projects/Domain/AuthDomainX/Tests/SomeTests.swift"] + + let decision = ChangedScope.decide(sourceFiles: sources, changedPaths: changed, moduleDirectory: module) + + #expect(decision == .onlyChanged([token])) + } + + @Test("모듈 경로 끝에 슬래시가 있어도 테스트 변경을 알아본다") + func acceptsModuleDirectoryWithTrailingSlash() { + let changed = ["Projects/Domain/AuthDomain/Tests/Entity/TokenTests.swift"] + + let decision = ChangedScope.decide(sourceFiles: sources, changedPaths: changed, moduleDirectory: module + "/") + + #expect(decision == .wholeModule) + } + + @Test("지워진 소스 파일은 심을 곳에서 빠진다") + func skipsDeletedSources() { + // 지운 파일은 git diff에는 나오지만 지금 Sources에는 없다. + let deleted = "Projects/Domain/AuthDomain/Sources/Entity/OldToken.swift" + + let decision = ChangedScope.decide(sourceFiles: sources, changedPaths: [deleted, draft], moduleDirectory: module) + + #expect(decision == .onlyChanged([draft])) + } + + @Test("모듈 소스가 하나도 안 바뀌었으면 심을 곳이 없다") + func findsNothingWhenNoSourceChanged() { + // 같은 모듈이어도 Sources 밖(문서·프로젝트 설정)만 바뀐 경우. + let changed = ["Projects/Domain/AuthDomain/CLAUDE.md", "Projects/Domain/AuthDomain/Project.swift"] + + let decision = ChangedScope.decide(sourceFiles: sources, changedPaths: changed, moduleDirectory: module) + + #expect(decision == .onlyChanged([])) + } + + @Test("git 출력에서 빈 줄과 앞뒤 공백은 버리고 경로만 남긴다") + func readsPathsFromGitOutput() { + let output = "\(token)\n\n \(draft) \n" + + let paths = ChangedScope.paths(fromGitOutput: output) + + #expect(paths == [token, draft]) + } +} diff --git a/Tooling/ArchLint/Tests/MutationCoreTests/MutantGeneratorTests.swift b/Tooling/ArchLint/Tests/MutationCoreTests/MutantGeneratorTests.swift new file mode 100644 index 000000000..55a25eea9 --- /dev/null +++ b/Tooling/ArchLint/Tests/MutationCoreTests/MutantGeneratorTests.swift @@ -0,0 +1,82 @@ +import Testing +@testable import MutationCore + +private let path = "/Projects/Domain/SampleDomain/Sources/Entity/Sample.swift" + +private func summaries(_ source: String) -> [String] { + MutantGenerator.mutants(in: source, path: path).map(\.summary) +} + +@Suite("뮤테이션 도구 — 심을 버그 만들기") +struct MutantGeneratorTests { + + @Test( + "비교·논리·산술 연산자를 뒤집는다", + arguments: [ + ("a < b", "`<` → `<=`"), // 경계 하나 차이 + ("a >= b", "`>=` → `>`"), // 경계 하나 차이 + ("a == b", "`==` → `!=`"), // 정반대 + ("a && b", "`&&` → `||`"), // 조건 하나만 맞아도 통과 + ("a + 1", "`+` → `-`") // 계산 방향 + ] + ) + func swapsOperators(expression: String, expected: String) { + let found = summaries("let x = \(expression)") + + #expect(found.contains(expected)) + } + + @Test("부정(!)을 지우고, true와 false를 바꾸고, 정수를 1 키운다") + func flipsNegationBooleansAndIntegers() { + let found = summaries("let x = !flag\nlet y = true\nlet z = prefix(80)") + + #expect(found == ["`!flag` → `flag`", "`true` → `false`", "`80` → `81`"]) + } + + @Test("가장 큰 정수는 키우지 않는다(넘친다)") + func skipsLargestInteger() { + let found = summaries("let x = 9_223_372_036_854_775_807") + + #expect(found.isEmpty) + } + + @Test("함수 본문의 대입·호출·guard·if 문장을 지우고, 선언과 return은 두지 않는다") + func deletesStatementsButNotDeclarationsOrReturns() { + let source = """ + func f() -> Int { + let a = 1 + guard ready else { return 0 } + if reset { text = "" } + save() + return a + } + """ + + let deleted = summaries(source).filter { $0.hasSuffix("삭제") } + + #expect(deleted == ["`guard ready else { return 0 }` 삭제", "`if reset { text = \"\" }` 삭제", "`text = \"\"` 삭제", "`save()` 삭제"]) + } + + @Test("넘기기만 하는 UseCase는 변이 대상에서 뺀다") + func skipsPassThroughUseCases() { + let source = """ + public final class DefaultForwardUseCase { + public func execute(id: Int) async throws -> Int { + return try await repository.fetch(id: id) + } + } + """ + + #expect(summaries(source).isEmpty) + } + + @Test("버그를 심으면 그 구간만 바뀐다") + func applyReplacesOnlyTheRange() { + let source = "let a = x < 80 // 가나다" + let mutant = MutantGenerator.mutants(in: source, path: path).first { $0.original == "<" } + + let mutated = mutant?.apply(to: source) + + #expect(mutated == "let a = x <= 80 // 가나다") + } +} diff --git a/docs/DEFINITION_OF_DONE.md b/docs/DEFINITION_OF_DONE.md index 393214746..2c2fe32be 100644 --- a/docs/DEFINITION_OF_DONE.md +++ b/docs/DEFINITION_OF_DONE.md @@ -15,8 +15,10 @@ ## Domain 작업 시 (테스트 필수) -- [ ] 새 UseCase·Entity·정책에 **테스트 작성** ([docs/TESTING.md](TESTING.md) 규약). -- [ ] 커버리지 4종 고려: 정상 / 경계값 / 정책 위반 / 상태 변화. +- [ ] 판단하는 코드(분기·검증·계산이 있는 Entity·정책·UseCase)에 **테스트 작성** — 목록을 먼저 합의 ([docs/TESTING.md](TESTING.md) 작업 순서). +- [ ] 경계값은 "딱 그 값"과 "하나 넘는 값"을 둘 다, 에러는 case마다 `#expect(throws:)`. +- [ ] ArchLint 통과 + 테스트 이름을 바꿨으면 `TEST_SPEC.md` 갱신(`ArchLint --write-test-specs`). +- [ ] 뮤테이션 도구(`Mutate <모듈>`)의 살아남은 버그를 확인하고 판단을 PR에 남김. - [ ] 프로토콜/시그니처를 바꿨다면 **같은 PR에서 Mock·테스트 동기화** (drift 방지). ## Data 작업 시 diff --git a/docs/TESTING.md b/docs/TESTING.md index 536c2e5d8..24af5436c 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -1,99 +1,152 @@ # 테스트 가이드 -> **테스트는 필수다.** 새 UseCase·Entity·정책 메서드는 테스트 없이 머지하지 않는다. (현재 Domain 레이어 한정) +> **AI가 코드를 쓰고, 사람은 테스트를 보고 믿는다.** + +## 왜 이렇게 쓰나 + +구현과 리뷰를 AI가 맡으면서, 사람이 구현 코드를 모두 읽는 일이 병목이 됐다. +그래서 사람이 확인하는 최소 지점을 **테스트**로 잡는다. 테스트 이름이 "이 기능은 이렇게 동작한다"를 말하고, +그 말이 진짜라면 사람은 구현을 매번 다 읽지 않고도 테스트를 보고 믿을 수 있다. +테스트는 "적어도 여기까지는 봤다"는 하한이다 — 필요하면 구현도 읽는다. + +기준은 문서로만 두지 않는다. 지킬 수 있는 것은 전부 **ArchLint가 검사**한다(규칙 목록과 id → +[Tooling/ArchLint/README.md](../Tooling/ArchLint/README.md)의 "테스트 명세 규칙"). 이 문서는 규칙을 다시 적지 않고, +**규칙의 이유**와 **기계가 못 하는 사람의 판단**, **작업 순서**만 적는다. + +## 테스트가 지켜야 할 5가지 + +1. **읽힌다** — 테스트 이름만 읽어도 그 기능의 규칙을 알 수 있다. + 이름은 "무엇을 하면 어떻게 된다"를 말하는 한국어 문장이다. 메서드 이름·"성공 케이스" 같은 말은 쓰지 않는다. + 본문도 준비 / 실행 / 확인을 빈 줄로 나눠, 무엇을 하고 무엇을 확인하는지 한눈에 보이게 한다. +2. **판단하는 코드를 테스트한다** — 분기·검증·계산이 실제로 들어 있는 코드를 직접 불러서 테스트한다. + 넘기기만 하는 코드는 테스트하지 않는다. 테스트는 그 코드가 있는 모듈에 둔다. +3. **버그가 생기면 테스트가 잡아낼 수 있어야 한다** — 기대값은 정확한 값으로 비교한다. + `!= nil`처럼 "있다"만 보거나, 소스의 상수를 기대값으로 쓰면 버그가 나도 통과한다. +4. **버그가 아니면 테스트가 깨지지 않아야 한다** — 동작은 같고 구현만 바뀐 리팩터링에는 깨지지 않는다. + 그래서 "어떻게 했는지"(몇 번 불렀는지)가 아니라 바깥에서 보이는 결과(돌려받은 값·바뀐 상태·보낸 요청)를 본다. + 버그도 없는데 빨간불이 자주 켜지면 사람은 빨간불을 믿지 않고 테스트를 같이 고쳐 버린다. +5. **늘 같다** — 언제·어디서·어떤 순서로 돌려도 결과가 같다. 현재 시각·기기 설정·난수·공유 상태에 기대지 않는다. + +## 무엇을 테스트하고, 무엇을 안 하나 + +- **테스트한다**: Entity·Draft의 규칙(검증·정규화·상태 변화), 여러 저장소를 조합하거나 값을 바꾸는 UseCase. +- **테스트하지 않는다**: 저장소 호출을 그대로 넘기는 UseCase, 값만 담는 타입. + 넘기기만 하는 UseCase를 테스트하면 "Mock을 불렀다"만 확인하면서, 이름은 "토큰을 지운다"처럼 다른 레이어의 일을 확인한 것처럼 보이게 된다. + 그 일은 그 레이어(Data)에서 테스트한다. +- **담는 것은 넘기는 것이 아니다.** 규칙이 있는 Entity·Draft가 값을 담는 일(`rating = newRating`)은 그 타입 자신의 일이라 + 대신 지켜 줄 곳이 없다. 특히 **옵셔널 값**은 대입을 지워도 `nil`로 조용히 컴파일돼 컴파일러도 못 잡는다 + (NovelReview 평점이 이렇게 뮤테이션에서 살아남았다 — 지워지면 사용자가 매긴 평점이 사라진다). + 애매하면 뮤테이션 도구의 생존 여부로 판단한다. +- 테스트하지 않기로 한 것은 **목록 합의 때 이유와 함께 적는다**. 빠뜨린 것과 뺀 것을 구분하기 위해서다. + +## 작업 순서 + +1. **테스트 목록을 먼저 합의한다** — 스위트 이름, 하위 스위트로 나눌지와 그 묶음, 테스트 이름, 넣지 않는 테스트와 그 이유. 사람이 승인한다. +2. **테스트를 쓰고 통과시킨다** — 모듈 스킴으로 테스트 실행. +3. **ArchLint를 통과시킨다** — `swift run --package-path Tooling/ArchLint ArchLint .` + 테스트를 더하거나 빼거나 이름·`arguments`를 바꿨으면 `--write-test-specs`로 모듈 루트의 `TEST_SPEC.md`(테스트 목록)를 갱신해 같이 커밋한다(아래 "적용 범위"의 모듈만). +4. **뮤테이션 도구로 확인한다** — `swift run --package-path Tooling/ArchLint Mutate <모듈>`. + 소스에 버그를 하나씩 심어 테스트가 잡는지 본다. 살아남은 버그는 사람이 판단한다(아래). + `--changed-since`를 붙이면 `origin/develop` 이후 바뀐 소스에만 심는다(테스트가 바뀌었으면 테스트가 약해졌을 수 있어 모듈 전체). +5. **PR에서 사람이 읽는다** — 아래 "사람이 보는 곳". + +## 사람이 보는 곳 + +기계가 모양은 검사하지만, 아래는 사람이 판단한다. + +- **`TEST_SPEC.md`의 변화(주로 여기)** — 목록이 기능을 다 말하는가, 빠진 경계값·엣지 케이스는 없는가, 이름이 말하는 게 정말 원하는 동작인가. +- **테스트 본문(마지막 확인)** — 이름이 말한 것을 본문이 실제로 확인하는가. +- **살아남은 버그** — 테스트를 더할지, 결과가 같아 의미 없는 변이인지. +- **`// archlint:allow <규칙> — 이유` 주석** — 그 이유가 타당한가. 이유 없는 주석은 무시되므로, 이 주석이 곧 사람이 볼 예외 목록이다. +- **`test-aaa-act` 경고(실행이 여러 문장)** — 한 동작을 여러 번 호출해야 한다면 메서드 설계를 바꿀 신호일 수 있다. 유지하면 allow 주석에 이유를 남긴다. +- **단어** — 한 단어에 뜻 하나. 같은 단어가 두 뜻으로 쓰이면 목록이 안 읽힌다. + (예: 탈퇴 화면에서 고르는 것은 "항목", '직접입력'에서 쓰는 글은 "탈퇴 이유" — "사유"를 둘 다에 쓰지 않는다.) + +## 쓰는 법 -## 철학 — 테스트는 "읽히는 기능 명세"다 +```swift +import Testing -이 프로젝트의 테스트는 통과/실패를 넘어, **그 도메인이 무엇을 보장하는지** 코드를 안 봐도 읽어낼 수 있어야 한다. -`@Test("한글 문장")`의 설명이 곧 **명세 한 줄**이다. +import AuthDomain -좋은 예 — 테스트 이름만 읽어도 정책이 보인다: -```swift -@Suite -struct NovelTests { - // MARK: - markAsInterested - @Test("관심 없는 작품을 관심 등록하면 isInterested가 true가 되고 관심 수가 증가한다") ... - @Test("이미 관심 등록된 작품에 markAsInterested를 호출하면 상태가 변하지 않는다") ... - @Test("isInterested가 nil인 작품에 markAsInterested를 호출하면 상태가 변하지 않는다") ... - // MARK: - unmarkAsInterested - @Test("관심 수가 0일 때 unmarkAsInterested를 호출하면 관심 수가 0 이하로 내려가지 않는다") ... +@Suite("탈퇴 사유 작성") +struct WithdrawalReasonDraftTests { + + @Test("탈퇴 이유가 80자를 넘으면 앞 80자만 남는다") + func cutsReasonOver80Characters() { + var draft = WithdrawalReasonDraft() + draft.setOption(.custom) + // 81번째 글자만 다르게 둬서, 잘려 나간 쪽이 뒤인지 확인한다. + let reason = String(repeating: "가", count: 80) + "나" + + draft.setCustomReasonText(reason) + + #expect(draft.customReasonText == String(repeating: "가", count: 80)) + } + + @Test( + "'직접입력'은 탈퇴 이유가 비었거나 공백뿐이면 정책에 동의해도 제출할 수 없다", + arguments: [ + "", // 아무것도 쓰지 않음 + " ", // 스페이스만 + "\n\t " // 줄바꿈·탭도 공백으로 본다 + ] + ) + func customOptionCannotSubmitWithBlankReason(reason: String) { … } } ``` -원칙: -1. **이름 = 명세 문장**: "〜하면 〜가 된다 / 〜하지 않는다" 형태. 동작과 기대 결과를 한 문장에 담는다. ("test1", "성공 케이스" 같은 이름 금지) -2. **`@Suite`는 명세 대상**(타입/정책 단위), `// MARK: - 메서드명`으로 시나리오를 그룹핑. -3. **한 테스트 = 하나의 규칙**. 한 테스트에서 여러 행동을 검증하지 않는다. -4. **Given-When-Then**으로 본문도 읽히게. 준비 → 실행 → 단언이 시각적으로 구분되도록 빈 줄 사용. -5. 테스트 묶음을 위에서 아래로 읽으면 **그 도메인의 행동 사양서**가 되도록 배열한다. -## 프레임워크·위치·임포트 +- `@Suite`는 **기능 단위**(타입·메서드 단위가 아님). 함수 이름은 영어, 설명은 `@Test("…")`에. +- 사용자 동작이나 규칙 덩어리가 둘 이상으로 갈리면 하위 `@Suite`로 나눈다(예: `CollectionDraftTests`의 "이름"·"대표 작품 고르기"). 목록 파일에는 부모 아래 `###`로 나온다. + 기준은 **개념**이지 개수가 아니다 — 개념이 다르면 테스트 1개짜리 하위 스위트도 괜찮고, 전부 한 동작이면 많아도 나누지 않는다. 한 스위트가 10개쯤 넘으면 나눌 때인지 따져 보는 신호로만 쓴다. 나누는 묶음은 사람이 정할 몫이라 ArchLint로 강제하지 않고, 위 작업 순서 1번에서 승인받는다. + 하위 스위트는 바깥 타입의 멤버를 못 쓰니, `makeXxx` 같은 준비 함수는 파일 아래, 여러 하위 스위트가 같이 쓰는 고정 값(날짜 등)은 파일 위에 `private`으로 둔다. 여러 하위 주제를 함께 보는 테스트(처음 상태 등)는 부모에 바로 둬도 된다. 테스트 이름은 하위 스위트 없이도 읽히는 문장으로 쓴다(실패 로그엔 테스트 이름만 찍힌다). +- 여러 입력은 for/if 대신 `arguments:`로. 항목마다 줄을 바꾸고, 리터럴에는 왜 그 값인지 주석을 단다. + 튜플에 `nil`이 섞이면 컴파일러가 타입을 못 정해 "failed to produce diagnostic"으로 죽는다 — 배열 뒤에 `as [(Date?, Date?)]`처럼 타입을 붙인다(검사기·목록 파일은 그대로 읽는다). +- 경계값은 "딱 그 값"과 "하나 넘는 값"을 둘 다 둔다. 위 예처럼 넘는 쪽은 어디가 잘렸는지까지 보이게 만든다. +- 에러는 case를 적어 확인한다: `#expect(throws: CollectionDraft.ValidationError.nameOverLimit(max: 20)) { … }` (타입만 적으면 다른 case도 통과). +- 공개 API로만 테스트한다(`@testable import` ❌) — internal에 기대면 리팩터링마다 깨진다. -- **Swift Testing** (`@Test` / `#expect` / `@Suite`). **XCTest 금지.** -``` -Projects/Domain/Domain/ -├── Testing/Mock/Mock[Protocol].swift # Mock — 별도 타깃 DomainTesting -└── Tests/{Entity,UseCase}/[X]Tests.swift -``` -```swift -import Testing -@testable import [Module]Domain -import [Module]DomainTesting // Mock이 든 Testing 타깃 -import BaseDomain -``` -- **타 모듈의 Testing 타깃(Mock) 재사용**은 그 모듈 `Project.swift`에 `testDependencies: [.module(.domain(.base), type: .testing)]` 선언이 있어야 import 된다 — 없으면 "No such module"(템플릿 기본값은 빈 배열). 예: NovelDomain 테스트가 BaseDomain의 `MockKeywordRepository`를 재사용. +## 가짜 객체: Stub과 Mock -## 작성 규칙 +용어는 둘만 쓴다(클래스 이름은 `Mock…Repository`로 통일). -- 함수명: **`@Test("한글 설명") func englishName()`** — 한글은 설명에, 함수명은 영어로. (CI 호환, backtick 한글 함수명 금지) -- helper는 `make~` prefix, 보통 `extension XxxTests`에 `private func`로 분리. 파라미터 기본값으로 변형 케이스를 만든다. -- 에러 검증: `await #expect(throws: RepositoryError.unknown) { try await sut.execute(...) }`. -- **커버리지 4종 필수 고려**: 정상 / 경계값 / 정책 위반 / 상태 변화. +- **Stub — 조회(`fetch…`·`load…`·`search…`)**: 정해 둔 값을 돌려줄 뿐 호출을 기록하지 않는다. + 조회 입력이 맞는지는 Stub이 입력마다 다른 값을 돌려주게 해서 **결과로** 확인한다. + "몇 번 불렀나"를 확인하면 캐시를 붙이는 것 같은 정상 리팩터링에도 깨진다. +- **Mock — 명령(저장·삭제·전송)**: 호출 자체가 결과라 보낸 값을 기록하고 확인한다. +- 중복 요청 금지처럼 조회 횟수가 진짜 요구사항이면 allow 주석에 그 이유를 적는다. +- Entity 테스트에는 가짜 객체를 쓰지 않는다 — 값과 규칙뿐이라 결과로 확인한다. +- 가짜 객체는 `Testing/` 타깃(`DomainTesting`)에 둔다. 다른 모듈의 Testing 타깃을 쓰려면 그 모듈 + `Project.swift`에 `testDependencies: [.module(.domain(.base), type: .testing)]`처럼 선언해야 import 된다(없으면 "No such module"). -### Entity 테스트 (정책 검증) -순수 함수/`mutating` 정책을 직접 호출해 상태 전이를 단언. (위 `NovelTests` 예시) +## 위치 -### UseCase 테스트 (협력 검증) -Mock Repository를 주입해 결과 + **호출 사실**을 함께 검증. -```swift -@Test("작품 정보를 성공적으로 불러온다") -func loadNovelSuccess() async throws { - let mock = MockNovelRepository() // Given - let expected = makeNovelInformation() - mock.fetchNovelResult = .success(expected) - let usecase = DefaultLoadNovelUseCase(novelRepository: mock) - - let result = try await usecase.execute(id: NovelID(1)) // When - - #expect(result.novel.id == expected.novel.id) // Then - #expect(mock.fetchedNovelIDs.last == NovelID(1)) // 협력(호출) 검증 - #expect(mock.fetchedNovelIDs.count == 1) -} +``` +Projects/Domain/Domain/ +├── TEST_SPEC.md # 자동 생성 테스트 목록(손으로 고치지 않는다) +├── Testing/Mock/Mock[Protocol].swift # 가짜 객체 — 필요한 모듈만 +└── Tests/{Entity,UseCase}/[X]Tests.swift ``` -## Mock 패턴 (tracking array + Result) +- **Swift Testing**(`@Test`·`#expect`·`@Suite`). XCTest ❌. -```swift -public final class MockNovelRepository: NovelRepository { - public var fetchNovelResult: Result! // 반환 있는 메서드 - public var addInterestResult: Result = .success(()) // void는 기본 성공 - public private(set) var fetchedNovelIDs: [NovelID] = [] // 호출 추적 - public init() {} - - public func fetchNovel(id: NovelID) async throws(RepositoryError) -> NovelInformation { - fetchedNovelIDs.append(id) // 입력 기록 - return try fetchNovelResult.get() // 주입된 결과 반환/throw - } -} -``` -- 결과는 `Result` 프로퍼티로 주입, 입력은 배열/`last`/`callCount`로 기록 → `#expect`로 협력 검증. -- Mock은 `Testing/` 타깃(`DomainTesting`)에 둔다 (테스트와 분리, 다른 모듈도 재사용 가능). +## 적용 범위 (#293 진행 중) + +- ArchLint 테스트 규칙은 **재작성을 마친 모듈에만** 켜져 있다 — `Tooling/ArchLint/Sources/ArchLintCore/TestSpecSupport.swift`의 `TestSpecScope.modules`. + 모듈을 이 기준으로 다시 쓰면 거기에 추가한다. 다시 쓰는 순서는 `rewrite-domain-tests` 스킬(`.claude/skills/rewrite-domain-tests/SKILL.md`)이 따라간다. 안 고친 모듈까지 켜면 옛 테스트가 전부 error로 떠 게이트가 막힌다. + `TEST_SPEC.md`도 이 모듈만 만들고 검사한다 — 추가할 때 `--write-test-specs`로 먼저 만든다(없으면 `test-spec-file` error). +- **판단 코드가 하나도 없는 모듈**은 테스트 0개로 두고 `.tests`·`.testing` 타깃을 뺀다(빈 타깃은 CI가 돌려도 확인하는 게 없다). + 그래도 적용 범위엔 **넣는다** — `test-required`는 `Tests`가 없어도 소스를 보고, 나중에 분기·throw가 생기면 테스트 없이는 막는다. + `TEST_SPEC.md`는 제목만 있는 파일이 된다. 뮤테이션은 잡을 테스트가 없어 건너뛴다. +- 아직 안 켜진 Domain 모듈에도 **새로 쓰는 테스트는 이 기준**을 따른다. 옛 방식 테스트(예: `@testable`, 메서드별 `// MARK:`, 호출 횟수 확인)를 본뜨지 않는다. ## CI - 트리거: **develop 대상 PR을 올리면 자동 실행**. `/domain-test` 댓글·수동 `workflow_dispatch`는 재실행용. `.github/workflows/test.yml`. - `Project.swift`가 `.tests` 타깃을 선언한 **정식 모듈(Domain·Data·Feature)** 을 자동 스캔 → 선언만 하면 자동 포함. - 유령 폴더는 `Project.swift`가 없어 자동 제외된다(폴더 잔재가 매트릭스를 깨지 않는다). -- `All Tests Passed` job이 전체 통과를 판정 → develop 브랜치 보호의 필수 통과 체크로 걸 수 있다. +- `All Tests Passed` job이 전체 통과를, `Architecture Rules` job이 ArchLint(테스트 규칙·`TEST_SPEC.md` 최신 여부 포함)를 판정한다. +- 뮤테이션 도구는 느려서(버그마다 빌드+테스트) CI에 없다 — 로컬에서 수동으로 돌린다. ## 주의사항 (작업 중 발견 시 누적) @@ -101,6 +154,7 @@ public final class MockNovelRepository: NovelRepository { - ⚠️ **`tuist test`의 `Executed 0 tests, with 0 failures`는 테스트가 안 돌았다는 뜻이 아니다.** 그 줄은 XCTest 카운터라 Swift Testing(`@Test`)을 세지 않는다. 실제 실패는 `Failing tests:` + `** TEST FAILED **`로, 성공은 `Test Succeeded`로 나온다. 의심되면 일부러 실패하는 테스트를 하나 넣어 러너가 잡는지 확인하면 된다(카나리) — `0 tests`만 보고 러너가 죽었다고 판단하지 말 것. -- ⚠️ **`@Test("…")` 설명에 `/`를 넣지 말 것** — XcodeBuildMCP `test_sim` 리포터가 `/`를 스위트 구분자로 읽어 이름을 쪼갠다 +- ⚠️ **`@Test("…")` 설명에 `/`를 넣지 말 것**(ArchLint `test-name`이 막는다) — XcodeBuildMCP `test_sim` 리포터가 `/`를 스위트 구분자로 읽어 이름을 쪼갠다 (`"websoso://collections/{id}를 파싱하면…"` → 스위트 `websoso:/collections` + 테스트 `{id}를 파싱하면…`으로 보고됨, #228 실측). URL·경로가 들어가는 명세는 "websoso 스킴에 collections host와 id가 붙은 URL"처럼 말로 풀어 쓴다. +- 뮤테이션 도구는 소스를 고쳤다가 되돌린다 — 모듈 `Sources`에 커밋 안 한 변경이 있으면 시작하지 않는다. Ctrl-C나 kill(-9 제외)로 끊어도 원본으로 되돌리지만, 그래도 남으면 `git checkout -- <모듈>/Sources`. diff --git a/docs/WORKFLOW.md b/docs/WORKFLOW.md index 5b02c4f2a..af2d35a26 100644 --- a/docs/WORKFLOW.md +++ b/docs/WORKFLOW.md @@ -25,8 +25,8 @@ ## 테스트 (필수) -- 새 **Domain** 코드(UseCase/Entity/정책)는 **테스트 없이 머지 금지**. -- 철학·컨벤션·Mock 패턴은 [docs/TESTING.md](TESTING.md) (테스트=읽히는 명세). +- 새 **Domain** 코드 중 판단하는 코드(분기·검증·계산이 있는 Entity·정책·UseCase)는 **테스트 없이 머지 금지**. 넘기기만 하는 UseCase는 테스트하지 않는다. +- 작업 순서(목록 합의 → 작성 → ArchLint·`TEST_SPEC.md` → 뮤테이션)와 이유는 [docs/TESTING.md](TESTING.md) (테스트=읽히는 명세). - **테스트 없이 머지 금지 의무는 Domain 한정**. 단 Data·Feature에도 테스트가 있으면 CI가 함께 돌려 지킨다. ## CI @@ -36,7 +36,7 @@ - `Project.swift`가 `.tests` 타깃을 선언한 **정식 모듈(Domain·Data·Feature)** 을 자동 스캔해 모듈별 병렬 테스트. - 유령 폴더(레지스트리에 없는 rename/브랜치 잔재)는 `Project.swift`가 없어 자동 제외된다 — 폴더 잔재가 매트릭스를 깨지 않는다. - **머지 게이트**: `All Tests Passed` job이 전체 통과를 판정한다. develop 브랜치 보호에서 이 체크를 필수 통과(required status check)로 지정하면 빨간 PR은 머지가 막힌다(GitHub → Settings → Branches → develop → Require status checks → `All Tests Passed`). -- **아키텍처 검사**: `Architecture Rules` job이 자체 SwiftSyntax 검사기(`Tooling/ArchLint`)로 VM 계약(`ObservableObject` 계열 금지)을 **error**(막음), Service 분기를 **warning**(리포트만)으로 본다 — ubuntu + 공식 swift 컨테이너라 Xcode 불필요. 이 job(`Architecture Rules`)도 별도 필수 통과 체크로 걸 수 있다(develop이 초록인 걸 확인한 뒤). 규칙 추가·심각도 정책은 `Tooling/ArchLint/README.md`. +- **아키텍처 검사**: `Architecture Rules` job이 자체 SwiftSyntax 검사기(`Tooling/ArchLint`)로 VM 계약(`ObservableObject` 계열 금지)을 **error**(막음), Service 분기를 **warning**(리포트만)으로 본다. Domain 테스트 명세 규칙과 `TEST_SPEC.md` 최신 여부도 여기서 error로 본다(`docs/TESTING.md`) — ubuntu + 공식 swift 컨테이너라 Xcode 불필요. 이 job(`Architecture Rules`)도 별도 필수 통과 체크로 걸 수 있다(develop이 초록인 걸 확인한 뒤). 규칙 추가·심각도 정책은 `Tooling/ArchLint/README.md`. - **스타일 검사**: `Swift Format` job이 Apple swift-format(툴체인 번들 — 별도 설치 없음)으로 스타일을 검사한다 — **변경된 `.swift` 파일만**(레거시 전체 아님), 지금은 **report-only**(위반 출력만, 안 막음). 규칙 allowlist는 루트 `.swift-format`, 게이트 로직·규칙 선정 근거는 `Tooling/SwiftFormat/README.md`. develop 초록 확인 후 `--strict` + 필수 통과 체크로 승격 예정(전체 리포맷은 `docs/TODO.md`(AI 검증 후속) 3번). ## 배포 (App Store 심사 제출)