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/App/CLAUDE.md b/Projects/App/CLAUDE.md index 919e21287..37831da7f 100644 --- a/Projects/App/CLAUDE.md +++ b/Projects/App/CLAUDE.md @@ -187,16 +187,31 @@ FCM 수신·토큰 발급·서버 등록. **Firebase(`Messaging`) import는 App `Sources/Push/PushNotificationCenter.swift`(런타임 허브)와 `Sources/Push/AppDelegate.swift`(시스템 콜백). Domain/Data는 `DevicePushToken`/`RegisterDeviceTokenUseCase`(NotificationDomain) 추상화로 이미 격리돼 Firebase를 모른다. -- **등록 파이프라인은 새로 만든 게 아니라 이미 있던 슬롯을 채운 것** — `SplashDomain`의 부트스트랩 - (`BootstrapAppUseCase`)이 세션 있을 때 `registerDeviceTokenIfNeeded()`를 fire-and-forget으로 돌리고, 그게 - `AppDependencies`가 넘긴 `deviceTokenProvider`(async)를 당겨 토큰이 있으면 `pushSettingRepository.registerDeviceToken`으로 - 보낸다. #243 전엔 `deviceTokenProvider: { nil }`(등록 스킵)이었고, 지금은 `PushNotificationCenter.shared.currentDevicePushToken()`이다. -- **등록 경로는 둘, 둘 다 필요**: ① **부트스트랩 pull**(`currentDevicePushToken`) — 세션 있는 재방문·이미 권한 - 허용 사용자. ② **반응 push**(`setFCMRegistrationToken`) — 부트스트랩이 지나간 뒤 로그인/권한허용하는 신규 - 사용자(이게 없으면 신규 유저 토큰 등록이 다음 실행까지 밀린다). 반응 경로는 `isLoggedIn` 게이트를 통과할 때만 서버로 보낸다. +- **서버 등록(`POST /users/fcm-token`)의 주 경로는 "메인 탭 진입 → APNs 등록 → `token()` 직접 조회"다**(#287). + `MainTabView.task`가 `registerForRemoteNotifications()`를 부르면 iOS가 **매번** `didRegister…`를 다시 주고, + `setAPNSToken`이 곧바로 `Messaging.messaging().token()`을 조회해 `latestFCMToken`을 갱신하고 등록한다. 로그인·가입 + 직후에도 메인 탭을 지나므로 실행 중 로그인한 사용자는 이 경로가 책임진다. 보조 경로는 Firebase delegate + (`setFCMRegistrationToken`, 앱 시작 시·토큰 변경 시), `configure`(조립 시 보관 토큰), 포그라운드 복귀(`MainTabView`의 + `scenePhase`, 실패분 재시도). 전부 `registerLatestTokenIfNeeded` 하나로 모이고, **같은 세션에서 성공한 토큰은 다시 + 보내지 않는다**(`registeredToken`). + - ⚠️ **등록 기록은 앱 시작·세션 종료(`configure`)와 로그인 완료(`ContentView.finishOnboarding`) 두 곳에서 비운다** — + 로그인은 `AppDependencies`를 재조립하지 않아 `configure`가 안 불린다. 가입 미완료 세션으로 켜 인트로에 간 뒤 + 다른 계정으로 로그인하면, 이전 계정 몫으로 기록된 같은 토큰을 건너뛰어 새 계정이 미등록으로 남는다(#287 리뷰). + - ⚠️ **등록 요청은 한 번에 하나만** — 시작 시 delegate의 캐시 토큰 A와 `token()`의 새 토큰 B를 동시에 보내면 늦게 끝난 + A가 서버의 이 기기 행을 죽은 토큰으로 덮을 수 있다. 진행 중이면 새로 안 보내고, 끝난 뒤 `latestFCMToken`이 바뀌었으면 + 최신 값으로 한 번 더 보낸다. 병렬 전송으로 되돌리지 말 것. + - ⚠️ **delegate에만 기대면 등록이 빠진다** — #287 전엔 그랬고, "실행 중 로그아웃 → 재로그인"·"로그아웃 상태로 켬 → + 로그인"에서 다음 콜드 스타트까지 미등록이었다(실기기 실측). Firebase는 같은 APNs 토큰을 다시 넣거나 캐시 토큰에 + 묶인 APNs와 같은 값을 넣으면 **delegate를 부르지 않는다**(앱 시작 시 캐시 토큰으로 1회 + 실제 토큰 변경 때만). + - ⚠️ **런치(스플래시) 시점의 `token()`은 실기기에서 항상 실패한다** — APNs 토큰이 아직 없어 Firebase가 + `No APNS token specified before fetching FCM Token`으로 거절한다. 그래서 #243의 부트스트랩 pull + (`SplashDomain`의 `registerDeviceTokenIfNeeded`)을 #287에서 제거했다. `token()`은 `setAPNSToken` 뒤에서만 부를 것. + - **로그아웃은 서버에서 이 기기의 토큰 행을 지운다**(`deviceIdentifier` 기준, #287 실측) — 그래서 재로그인 때 + 다시 등록해야 하고, `registeredToken`이 로그인할 때마다 비워져야 한다. - **왜 `PushNotificationCenter.shared`(싱글턴)인가**: UIKit `AppDelegate`(시스템 콜백 수신)와 SwiftUI DI (`AppDependencies` — UseCase 조립)는 생명주기가 달라 인스턴스 공유 통로가 없다. V1의 `NotificationHelper.shared`와 같은 이유. - 세션 종료로 `AppDependencies`가 재조립되면 `configure(...)`가 다시 불려 새 UseCase/tokenStore로 갱신된다(idempotent). + 세션 종료로 `AppDependencies`가 재조립되면 `configure(...)`가 다시 불려 새 UseCase/tokenStore로 갱신된다. 등록 기록을 + 비우고 보관 토큰으로 등록을 시도하는 부수효과가 있어 멱등이 아니다 — `AppDependencies()`를 조립 시점 외에 만들지 말 것. - **method swizzling은 끈다**(`Support/Info.plist`의 `FirebaseAppDelegateProxyEnabled=NO`) — SwiftUI `@UIApplicationDelegateAdaptor` 환경에서 Firebase 자동 프록시가 불안정해, APNs device token을 `AppDelegate`가 받아 `Messaging.messaging().apnsToken`에 **직접** 대입한다(V1과 동일). 그래서 `willPresent`/`didReceive`에서 @@ -209,11 +224,20 @@ Domain/Data는 `DevicePushToken`/`RegisterDeviceTokenUseCase`(NotificationDomain **실제 적용**한다 — V1은 옵션을 만들고 버린 뒤 인자 없는 `configure()`를 불러 항상 운영 plist만 쓰던 버그가 있었으니 복붙하지 말 것. - ⚠️ **`Messaging.messaging()`을 만지는 새 코드는 반드시 `isFirebaseConfigured`(`FirebaseApp.app() != nil`)로 가드**한다 — 위 plist 미배치로 Firebase가 **미구성**이면 `Messaging.messaging()` 호출 자체가 "default app not configured"로 크래시한다 - (Codex 리뷰 실측). `PushNotificationCenter.currentDevicePushToken()`/`setAPNSToken()`이 그렇게 가드돼 있다. 델리게이트 + (Codex 리뷰 실측). `PushNotificationCenter.setAPNSToken()`(과 그 뒤의 `token()` 조회)이 그렇게 가드돼 있다. 델리게이트 콜백(`willPresent`/`didReceive`)의 `appDidReceiveMessage`는 델리게이트가 **구성 성공 시에만** 설정돼 미구성 땐 도달하지 않는다. - **권한 요청·원격 알림 등록 시점은 `MainTabView.task`**(V1 parity, 사용자 확정) — `MainTabView`는 세션이 있어야만 - 뜨므로 여기가 "로그인 상태의 메인 진입"이다. 미결정이면 권한 요청, 허용 상태면 `registerForRemoteNotifications()`. + 뜨므로 여기가 "로그인 상태의 메인 진입"이다. 미결정이면 권한을 요청하고, **권한 결과와 무관하게** + `registerForRemoteNotifications()`를 부른다(#287, 사용자 확정). ⚠️ **서버는 등록된 기기가 없으면 앱 내 알림도 + 만들지 않는다** — 권한 거절 사용자를 등록에서 빼면 앱 내 알림 목록까지 비게 된다. 배너는 iOS가 권한에 따라 거른다. (기존 홈 알림벨/설정의 화면별 권한 흐름은 그대로 — 이건 그 위에 추가된 진입 트리거다.) +- ⚠️ **FCM 토큰 캐시는 키체인(`com.google.iid-tokens`)에 있어 앱을 지워도 남는다** — 재설치 시 Firebase는 FCM 서버의 + 이전 등록만 지우고 캐시는 둔다. 그래서 delegate가 시작 시 넘겨주는 토큰이 이미 죽은 토큰일 수 있다. 명시적 `token()`은 + 신선도(설치 ID·앱 버전·앱 ID·APNs)를 검사해 낡았으면 재발급하므로, 위 주 경로가 이 경우도 막는다. +- ⚠️ **Messaging은 토큰 신선도를 `FIROptions.defaultOptions`(번들의 기본 이름 `GoogleService-Info.plist` = 운영)의 + 앱 ID로 판정한다**(`FIRMessagingUtilities.m`) — Debug는 `GoogleService-Info-Debug.plist`로 configure하는데 두 plist가 + 모두 번들에 들어가 있어, Debug에선 실행마다 "Firebase App IID change"로 캐시 토큰을 무효화하고 새로 받는다(#287 발견). + Release는 영향 없음. 구성별로 plist 하나만 번들에 넣으면 해소된다(#288에서 처리 예정). - **알림 탭 → 딥링크(화면 이동)는 서버 payload 스키마대로 연결됨**(#243) — 판별자는 **`view` 문자열**이고 서버가 `view`에 맞는 id만 채운다(나머진 빈 문자열 **또는 키 자체가 없음** — 실측: `view=notificationDetail` 공지 push는 `novelId` 키가 아예 없고 `feedId`만 빈 문자열). id는 전부 문자열이라 `AppDelegate.stringPayload`(String만 통과)를 diff --git a/Projects/App/Project.swift b/Projects/App/Project.swift index 6ccb8bf45..6bd5ebc15 100644 --- a/Projects/App/Project.swift +++ b/Projects/App/Project.swift @@ -75,7 +75,7 @@ let settings: Settings = // TARGETED_DEVICE_FAMILY(iPhone 전용)는 V1과 동일 — App Store Connect 업로드 검증이 iPad용 아이콘· // 방향 키를 요구하는 걸 피한다(2026-08-29 실측, V1 project.pbxproj 대조로 확인: TARGETED_DEVICE_FAMILY = 1). let appBaseSettings: SettingsDictionary = env.baseSetting.merging([ - "MARKETING_VERSION": "1.10.3", + "MARKETING_VERSION": "1.10.4", "CURRENT_PROJECT_VERSION": "1", "VERSIONING_SYSTEM": "apple-generic", "TARGETED_DEVICE_FAMILY": "1", diff --git a/Projects/App/Sources/ContentView.swift b/Projects/App/Sources/ContentView.swift index 3f076257d..597e2eb06 100644 --- a/Projects/App/Sources/ContentView.swift +++ b/Projects/App/Sources/ContentView.swift @@ -42,7 +42,7 @@ public struct ContentView: View { case .splash: splashView case .onboarding: - OnboardingRootView(dependencies: dependencies, onFinished: { route = .main }) + OnboardingRootView(dependencies: dependencies, onFinished: finishOnboarding) case .main: MainTabView( dependencies: dependencies, @@ -128,6 +128,17 @@ private extension ContentView { } } +// MARK: - 로그인 완료 + +private extension ContentView { + /// 로그인·가입을 마치고 메인으로 넘어간다. 로그인은 `AppDependencies`를 재조립하지 않으므로 FCM 등록 기록을 + /// 여기서 직접 비운다 — 안 비우면 이전 계정 몫으로 기록된 같은 토큰을 메인 진입 때 건너뛴다(#287). + func finishOnboarding() { + PushNotificationCenter.shared.resetRegistrationRecord() + route = .main + } +} + // MARK: - 세션 종료 수렴점 private extension ContentView { diff --git a/Projects/App/Sources/DI/AppDependencies.swift b/Projects/App/Sources/DI/AppDependencies.swift index e4004637d..ad2ca762e 100644 --- a/Projects/App/Sources/DI/AppDependencies.swift +++ b/Projects/App/Sources/DI/AppDependencies.swift @@ -75,7 +75,7 @@ final class AppDependencies { /// 런치 부트스트랩 게이트(강제 업데이트→세션→약관) 판정 — `ContentView`의 스플래시가 /// `DefaultBootstrapAppUseCase`로 감싸 호출한다(#236, #225 배선). let launchGateRepository: LaunchGateRepository - /// 런치 부수 태스크 4종(users/me·FCM·키워드·홈 프리페치) — 위와 같은 UseCase로 묶인다. + /// 런치 부수 태스크 3종(users/me·키워드·홈 프리페치) — 위와 같은 UseCase로 묶인다. let launchTaskRepository: LaunchTaskRepository /// 이벤트 트래킹(#249) — Release 스킴에서만 실제 Amplitude 인스턴스, Debug는 nil(모든 호출부가 /// `analyticsTracker?.track(...)`라 자동 no-op). `Logger`와 동일한 옵셔널 주입 패턴. @@ -210,7 +210,12 @@ final class AppDependencies { let markNotificationAsReadUseCase = DefaultMarkNotificationAsReadUseCase(repository: notificationRepository) PushNotificationCenter.shared.configure( registerDeviceToken: { devicePushToken in - try? await registerDeviceTokenUseCase.execute(devicePushToken: devicePushToken) + do { + try await registerDeviceTokenUseCase.execute(devicePushToken: devicePushToken) + return true + } catch { + return false + } }, isLoggedIn: { (try? tokenStore.accessToken()) != nil }, markNotificationAsRead: { notificationID in @@ -233,12 +238,8 @@ final class AppDependencies { ) // 프리페치를 실행하는 쪽 추천 레포는 store를 주입하지 않은 **별도 인스턴스**여야 한다 // (위 prefetchStore 주석의 짝 — 같은 인스턴스를 넘기면 프리페치가 스스로를 무효화한다). - // deviceTokenProvider는 App 레이어 FCM 허브에서 현재 토큰을 당겨온다(#243) — 권한 허용 상태에서만 - // 토큰을 만들어 주고, 미허용/실패면 nil을 돌려 부트스트랩이 등록을 조용히 건너뛴다(세션 있을 때만 호출됨). self.launchTaskRepository = SplashDataFactory.makeLaunchTaskRepository( profileRepository: profileRepository, - pushSettingRepository: pushSettingRepository, - deviceTokenProvider: { await PushNotificationCenter.shared.currentDevicePushToken() }, keywordRepository: keywordRepository, recommendationRepository: RecommendationDataFactory.makeRepository( network: client, diff --git a/Projects/App/Sources/Feed/FeedRootView.swift b/Projects/App/Sources/Feed/FeedRootView.swift index 2c8c622eb..d5427d01e 100644 --- a/Projects/App/Sources/Feed/FeedRootView.swift +++ b/Projects/App/Sources/Feed/FeedRootView.swift @@ -213,6 +213,10 @@ struct FeedRootView: View { path.append(Destination.novel(novelID)) case .editCollection: path.append(Destination.editCollection(id)) + case .userProfile(let userID): + // 피드 상세 작성자 탭과 같은 이중 가드(#196) — 내 프로필로는 절대 안 간다. + guard userID != currentUserID else { return } + path.append(Destination.userPage(userID)) } } ) diff --git a/Projects/App/Sources/Home/HomeRootView.swift b/Projects/App/Sources/Home/HomeRootView.swift index 2d9287322..3e16391b0 100644 --- a/Projects/App/Sources/Home/HomeRootView.swift +++ b/Projects/App/Sources/Home/HomeRootView.swift @@ -119,7 +119,7 @@ struct HomeRootView: View { loadUnreadNotificationStatusUseCase: DefaultLoadUnreadNotificationStatusUseCase( repository: dependencies.notificationRepository ), - loadPublicCollectionsUseCase: DefaultLoadPublicCollectionsUseCase( + loadRandomPublicCollectionsUseCase: DefaultLoadRandomPublicCollectionsUseCase( collectionRepository: dependencies.collectionRepository ), pushAuthorizationChecker: DefaultPushAuthorizationChecker(), @@ -213,6 +213,10 @@ struct HomeRootView: View { path.append(Destination.novel(novelID)) case .editCollection: path.append(Destination.editCollection(id)) + case .userProfile(let userID): + // 피드 상세 작성자 탭과 같은 이중 가드(#196) — 내 프로필로는 절대 안 간다. + guard userID != currentUserID else { return } + path.append(Destination.userPage(userID)) } } ) diff --git a/Projects/App/Sources/Library/LibraryRootView.swift b/Projects/App/Sources/Library/LibraryRootView.swift index 4e1f445e3..f8d3be4b4 100644 --- a/Projects/App/Sources/Library/LibraryRootView.swift +++ b/Projects/App/Sources/Library/LibraryRootView.swift @@ -193,6 +193,10 @@ struct LibraryRootView: View { path.append(Destination.novel(novelID)) case .editCollection: path.append(Destination.editCollection(id)) + case .userProfile(let userID): + // 피드 상세 작성자 탭과 같은 이중 가드(#196) — 내 프로필로는 절대 안 간다. + guard userID != currentUserID else { return } + path.append(Destination.userPage(userID)) } } ) diff --git a/Projects/App/Sources/Main/MainTabView.swift b/Projects/App/Sources/Main/MainTabView.swift index c353ebfaa..e9d9c77fa 100644 --- a/Projects/App/Sources/Main/MainTabView.swift +++ b/Projects/App/Sources/Main/MainTabView.swift @@ -49,6 +49,7 @@ struct MainTabView: View { /// 세션을 끝낸 것이라 되살리지 않는다. 어느 탭이 소비했는지도 같이 들어, 다른 탭의 딥링크 화면이 빠질 때 /// 이 값이 지워지지 않게 한다(탭마다 스택이 따로라 홈의 링크 A와 피드의 링크 B가 동시에 살아 있을 수 있다). @State private var deliveredDeepLink: (tab: MainTab, link: DeepLink)? + @Environment(\.scenePhase) private var scenePhase /// "나만의 컬렉션을 만들어보세요" 툴팁(#283) — 메인 진입 시(이 뷰가 새로 만들어질 때) 미확인이면 띄운다. /// 홈·피드·서재 탭을 오가도 유지되고, **떠 있는 동안** My 탭을 눌러야만 확인 처리된다(`tabSelection`). /// 확인 안 하고 앱을 끄면 다음 실행에 다시 뜬다. @@ -107,8 +108,14 @@ struct MainTabView: View { .task { // 푸시 권한 요청·원격 알림 등록(#243, V1 parity) — 메인 탭 진입 시 1회. `MainTabView`는 세션이 // 있어야만(부트스트랩 통과) 뜨므로 여기가 "로그인 상태의 메인 진입"에 해당한다. 미결정이면 권한을 - // 요청하고, 허용 상태면 APNs 등록을 시작해 FCM 토큰이 서버에 등록되도록 한다. - await PushNotificationCenter.shared.requestAuthorizationAndRegisterIfGranted() + // 요청하고, 권한 결과와 무관하게 APNs 등록을 시작해 FCM 토큰이 서버에 등록되도록 한다(#287 — 서버는 + // 등록 기기가 없으면 앱 내 알림도 만들지 않는다). 로그인·가입 직후에도 여기를 지나 서버 등록까지 이어진다. + await PushNotificationCenter.shared.requestAuthorizationAndRegisterForRemoteNotifications() + } + .onChange(of: scenePhase) { _, phase in + // 위 등록이 망 오류 등으로 실패했으면 다음 포그라운드 복귀 때 다시 보낸다(#287). 이미 등록됐으면 아무것도 안 한다. + guard phase == .active else { return } + PushNotificationCenter.shared.registerLatestTokenIfNeeded() } } } diff --git a/Projects/App/Sources/Mypage/MypageRootView.swift b/Projects/App/Sources/Mypage/MypageRootView.swift index df467084e..304e22df9 100644 --- a/Projects/App/Sources/Mypage/MypageRootView.swift +++ b/Projects/App/Sources/Mypage/MypageRootView.swift @@ -578,6 +578,10 @@ private extension MypageRootView { path.append(Destination.novel(novelID)) case .editCollection: path.append(Destination.editCollection(id)) + case .userProfile(let userID): + // 다른 탭의 프로필 탭 이중 가드(#196)와 동일 — 내 프로필로는 절대 안 간다. + guard userID.value != currentUserID else { return } + path.append(Destination.userPage(userID)) } } ) diff --git a/Projects/App/Sources/Push/PushNotificationCenter.swift b/Projects/App/Sources/Push/PushNotificationCenter.swift index 90915bf85..395c576f6 100644 --- a/Projects/App/Sources/Push/PushNotificationCenter.swift +++ b/Projects/App/Sources/Push/PushNotificationCenter.swift @@ -23,11 +23,16 @@ import NotificationDomain /// 마땅한 통로가 없다. V1도 같은 이유로 `NotificationHelper.shared`를 썼다. Firebase(`Messaging`) import는 /// 이 App 레이어 안(이 파일 + `AppDelegate`)에만 가둔다 — Domain/Data는 `DevicePushToken` 추상화로 이미 분리돼 있다. /// -/// **등록이 일어나는 두 경로**(둘 다 필요): -/// 1. 부트스트랩 pull — `currentDevicePushToken()`을 `SplashDomain`의 런치 태스크가 세션 있을 때 당겨간다 -/// (이미 권한을 허용한 재방문 사용자). 이 허브는 Firebase에서 현재 토큰을 만들어 돌려주기만 한다. -/// 2. 반응 push — 권한을 새로 허용하거나 토큰이 갱신되면 `setFCMRegistrationToken`이 로그인 상태에서 서버로 등록한다 -/// (부트스트랩이 이미 지나간 뒤 로그인/허용하는 신규 사용자 — 이게 없으면 다음 실행까지 등록이 밀린다). +/// **서버 등록이 일어나는 경로**(#287). 전부 `latestFCMToken`을 갱신한 뒤 `registerLatestTokenIfNeeded`로 모인다. +/// 같은 세션에서 같은 토큰은 한 번만 보내고, 요청은 한 번에 하나씩 보낸다. +/// 1. 메인 탭 진입 — `registerForRemoteNotifications` → `didRegister…` → `setAPNSToken`이 곧바로 `token()`을 조회해 +/// 등록한다. 로그인·가입 직후에도 메인 탭을 지나므로 **실행 중 로그인한 사용자를 책임지는 경로는 이것**이다. +/// 2. Firebase delegate(`setFCMRegistrationToken`) — 앱 시작 시 캐시 토큰으로 1회, 그리고 실행 중 토큰이 실제로 +/// 바뀔 때만 불린다. 같은 APNs 토큰을 다시 넣으면 Firebase는 아무것도 하지 않으므로 delegate만으로는 +/// "실행 중 로그아웃 → 재로그인"이나 "로그아웃 상태로 켬 → 로그인"을 놓친다(#287 실측). +/// 3. `configure` — 조립 시점에 이미 토큰을 들고 있고 로그인 상태일 때. 앱 시작 조립은 delegate보다 먼저라 보통 +/// 토큰이 없어, 실제로는 거의 타지 않는 방어용 경로다. +/// 4. 포그라운드 복귀(`MainTabView`) — 앞선 등록이 실패해 최신 토큰이 아직 미등록일 때 다시 보낸다. @MainActor final class PushNotificationCenter { @@ -35,13 +40,22 @@ final class PushNotificationCenter { private let deviceIdentifierStore: DeviceIdentifierStore /// `AppDependencies`가 조립 시 주입 — FCM 토큰을 서버에 등록하는 훅(`RegisterDeviceTokenUseCase` 래핑). - private var registerDeviceToken: (@Sendable (DevicePushToken) async -> Void)? + /// 성공 여부를 돌려준다 — 성공한 토큰만 `registeredToken`으로 기억해, 실패하면 포그라운드 복귀 때 다시 보낸다. + private var registerDeviceToken: (@Sendable (DevicePushToken) async -> Bool)? /// `AppDependencies`가 조립 시 주입 — 현재 로그인(세션 보유) 여부. private var isLoggedIn: (@Sendable () -> Bool)? /// `AppDependencies`가 조립 시 주입 — 알림 읽음 처리 훅(`MarkNotificationAsReadUseCase` 래핑, 인자는 알림 id). private var markNotificationAsRead: (@Sendable (Int) async -> Void)? - /// 마지막으로 받은 FCM 등록 토큰. 로그인 전에 도착하면 보관만 하고, 로그인/조립 시점에 등록에 쓴다. + /// 마지막으로 받은 FCM 등록 토큰. 서버에 보내는 값은 항상 이것이다 — 로그인 전에 도착하면 보관만 한다. private var latestFCMToken: String? + /// 이번 세션에서 서버 등록에 성공한 토큰 / 지금 등록 요청 중인 토큰. 한 실행 안에서 여러 경로(시작 시 delegate, + /// 메인 탭 진입의 `token()` 조회)가 같은 토큰을 거듭 보내지 않게 거른다. 앱 시작·세션 종료(`configure`)와 + /// 로그인 완료(`resetRegistrationRecord`)에서 비운다 — 서버가 로그아웃 때 이 기기의 토큰 행을 지우고, 등록은 + /// 계정마다 따로이기 때문에 새로 로그인한 계정에는 같은 토큰이라도 다시 보내야 한다. + private var registeredToken: String? + private var registeringToken: String? + /// 등록 기록을 비울 때마다 1씩 오른다. 이전 세션에서 시작된 등록 요청이 늦게 끝나 새 세션의 기록을 채우지 않게 한다. + private var sessionGeneration = 0 /// 알림 탭으로 만들어진 딥링크를 앱(`WSSIOSV2App`)의 `pendingDeepLink` 채널로 넘기는 통로. App이 등록한다. /// ⚠️ 콜드 스타트(알림 탭으로 앱이 실행)면 콜백 등록 전에 탭이 도착할 수 있어, 등록되는 순간 보관분을 flush한다. @@ -60,39 +74,77 @@ final class PushNotificationCenter { // MARK: - Configuration (AppDependencies가 조립 시 호출) - /// 서버 등록 훅과 로그인 판정을 주입한다. 세션이 끝나 `AppDependencies`가 재조립되면 다시 불려 - /// 새 UseCase/tokenStore로 갱신된다(idempotent). 이미 토큰을 들고 있고 로그인 상태면 여기서 한 번 등록을 시도한다 - /// (부트스트랩이 지나간 뒤 로그인한 신규 사용자가 이 조립 시점에 걸리는 경로). + /// 서버 등록 훅과 로그인 판정을 주입한다. 앱 시작과 세션 종료(`resetToOnboarding`)로 `AppDependencies`가 + /// 조립될 때마다 불려 새 UseCase/tokenStore로 갱신되고, 등록 기록도 비운다. 이미 토큰을 들고 있고 로그인 상태면 + /// 여기서 한 번 등록을 시도한다. func configure( - registerDeviceToken: @escaping @Sendable (DevicePushToken) async -> Void, + registerDeviceToken: @escaping @Sendable (DevicePushToken) async -> Bool, isLoggedIn: @escaping @Sendable () -> Bool, markNotificationAsRead: @escaping @Sendable (Int) async -> Void ) { self.registerDeviceToken = registerDeviceToken self.isLoggedIn = isLoggedIn self.markNotificationAsRead = markNotificationAsRead + resetRegistrationRecord() + registerLatestTokenIfNeeded() + } - guard let token = latestFCMToken, isLoggedIn() else { return } - let devicePushToken = DevicePushToken(token: token, deviceID: deviceIdentifier()) - Task { await registerDeviceToken(devicePushToken) } + /// 등록 기록을 비워 다음 등록 경로가 토큰을 다시 보내게 한다. `configure` 외에 **로그인 완료 시**(`ContentView`)에도 + /// 불린다 — 로그인 때는 `AppDependencies`를 재조립하지 않아 `configure`가 안 불리는데, 가입을 마치지 않은 세션으로 + /// 켜서 인트로에 간 뒤 다른 계정으로 로그인하면 이전 계정 몫으로 기록된 토큰을 건너뛰어 새 계정이 미등록으로 남는다. + func resetRegistrationRecord() { + registeredToken = nil + registeringToken = nil + sessionGeneration += 1 } // MARK: - AppDelegate가 전달하는 시스템 콜백 - /// APNs device token 수신 → Firebase에 직접 대입(method swizzling off — `FirebaseAppDelegateProxyEnabled=NO`). + /// APNs device token 수신 → Firebase에 직접 대입(method swizzling off — `FirebaseAppDelegateProxyEnabled=NO`)한 뒤, + /// FCM 토큰을 직접 조회해 등록한다. iOS는 `registerForRemoteNotifications`를 부를 때마다 이 콜백을 다시 주므로 + /// 메인 탭 진입마다 여기를 지난다. func setAPNSToken(_ deviceToken: Data) { guard isFirebaseConfigured else { return } Messaging.messaging().apnsToken = deviceToken + Task { await fetchFCMTokenAndRegister() } + } + + /// `token()`은 APNs 토큰이 있어야 성공하므로 `setAPNSToken` 뒤에서만 부른다. 캐시 토큰이 낡았으면(설치 ID·앱 버전· + /// 앱 ID·APNs 변경) Firebase가 새로 발급한다 — 재설치 뒤 FCM 서버에서 지워진 캐시 토큰을 계속 보내는 일도 이걸로 막는다. + private func fetchFCMTokenAndRegister() async { + guard let token = try? await Messaging.messaging().token() else { return } + latestFCMToken = token + registerLatestTokenIfNeeded() } /// FCM 등록 토큰 수신/갱신 → 보관 + 로그인 상태면 서버 등록. func setFCMRegistrationToken(_ token: String?) { guard let token else { return } latestFCMToken = token + registerLatestTokenIfNeeded() + } + + /// 로그인 상태면 `latestFCMToken`을 서버에 등록한다. 이번 세션에서 이미 성공한 토큰이면 건너뛴다. + /// 로그인 전이면 아무것도 안 한다 — 토큰은 `latestFCMToken`에 남아 있고, 로그인 후 메인 탭 진입이 다시 등록을 부른다. + /// ⚠️ **요청은 한 번에 하나만 보낸다** — 시작 시 delegate의 캐시 토큰 A와 `token()`이 새로 받은 B를 동시에 보내면 + /// 늦게 끝난 A가 서버의 이 기기 행을 죽은 토큰으로 덮을 수 있다. 진행 중이면 새로 보내지 않고, 끝난 뒤 그새 + /// `latestFCMToken`이 바뀌었으면 최신 값으로 한 번 더 보낸다 → 같은 세션 안에서는 서버에 마지막으로 남는 값이 최신 토큰이다. + /// (`resetRegistrationRecord`는 진행 중 요청을 기다리지 않으므로 세션 경계를 넘는 순서까지는 보장하지 않는다.) + func registerLatestTokenIfNeeded() { + guard let token = latestFCMToken, token != registeredToken, registeringToken == nil, + isLoggedIn?() == true, let registerDeviceToken + else { return } - guard isLoggedIn?() == true, let registerDeviceToken else { return } + registeringToken = token + let generation = sessionGeneration let devicePushToken = DevicePushToken(token: token, deviceID: deviceIdentifier()) - Task { await registerDeviceToken(devicePushToken) } + Task { + let succeeded = await registerDeviceToken(devicePushToken) + guard generation == sessionGeneration else { return } + registeringToken = nil + if succeeded { registeredToken = token } + if latestFCMToken != token { registerLatestTokenIfNeeded() } + } } /// 알림 탭(`AppDelegate.didReceive`)의 payload를 딥링크로 풀어 앱으로 넘긴다. `view`에 맞는 화면으로 @@ -119,41 +171,18 @@ final class PushNotificationCenter { Task { await markNotificationAsRead(id) } } - // MARK: - 부트스트랩 pull (SplashData의 deviceTokenProvider가 호출) - - /// 부트스트랩(세션 있을 때)이 당겨가는 현재 디바이스 푸시 토큰. 알림 권한이 허용된 경우에만 FCM 토큰을 - /// 만들어 돌려준다 — 미허용/실패면 nil을 주고, 런치 태스크는 등록을 조용히 건너뛴다. - func currentDevicePushToken() async -> DevicePushToken? { - guard isFirebaseConfigured else { return nil } - let settings = await UNUserNotificationCenter.current().notificationSettings() - guard settings.authorizationStatus == .authorized else { return nil } - guard let token = try? await Messaging.messaging().token() else { return nil } - - latestFCMToken = token - return DevicePushToken(token: token, deviceID: deviceIdentifier()) - } - // MARK: - 권한 요청 + 원격 알림 등록 (메인 탭 진입, V1 parity) - /// 로그인 상태의 메인 진입 시 호출(V1은 홈 진입에서 수행). 권한이 미결정이면 요청하고, 허용 상태면 APNs - /// 등록을 시작한다. 등록이 끝나면 `didRegister…`(AppDelegate) → `setAPNSToken` → `MessagingDelegate` → - /// `setFCMRegistrationToken`으로 이어져 서버 등록까지 흐른다. - func requestAuthorizationAndRegisterIfGranted() async { + /// 로그인 상태의 메인 진입 시 호출(V1은 홈 진입에서 수행). 권한이 미결정이면 요청하고, **결과와 무관하게** + /// APNs 등록을 시작한다(#287) — 서버는 등록된 기기가 없으면 앱 내 알림도 만들지 않으므로, 권한을 거절한 + /// 사용자도 기기 등록은 돼 있어야 한다(V1 parity). 배너 표시 여부는 iOS가 권한에 따라 알아서 거른다. + /// 등록이 끝나면 `didRegister…`(AppDelegate) → `setAPNSToken`으로 이어진다. + func requestAuthorizationAndRegisterForRemoteNotifications() async { let center = UNUserNotificationCenter.current() - let status = await center.notificationSettings().authorizationStatus - - switch status { - case .notDetermined: - let granted = (try? await center.requestAuthorization(options: [.alert, .badge, .sound])) ?? false - guard granted else { return } - UIApplication.shared.registerForRemoteNotifications() - case .authorized, .provisional, .ephemeral: - UIApplication.shared.registerForRemoteNotifications() - case .denied: - break - @unknown default: - break + if await center.notificationSettings().authorizationStatus == .notDetermined { + _ = try? await center.requestAuthorization(options: [.alert, .badge, .sound]) } + UIApplication.shared.registerForRemoteNotifications() } /// Firebase 기본 앱이 실제로 구성됐는지. `GoogleService-Info` plist가 없으면(gitignore돼 로컬/CI에 미배치) diff --git a/Projects/Data/CollectionData/CLAUDE.md b/Projects/Data/CollectionData/CLAUDE.md index 0595c131f..13c8bee4d 100644 --- a/Projects/Data/CollectionData/CLAUDE.md +++ b/Projects/Data/CollectionData/CLAUDE.md @@ -45,3 +45,6 @@ - **전체 공개 목록은 `CollectionsResponse`를 재사용하지 않고 `PublicCollectionsResponse`를 따로 둔다** — 같은 `nextCursor`·`hasNext` 구조지만 `collectionsCount`·`isPublic`·`representativeNovel`이 없고 `owner`가 있어, 공용 DTO에 optional을 늘리면 기존 두 목록의 필수값 디코딩 검증이 약해진다. 커서는 목록마다 서버가 따로 발급한다(다른 목록 커서를 넣으면 `COLLECTION-007`). +- **전체 공개 목록 쿼리도 `CollectionsQuery`가 아니라 `PublicCollectionsQuery`다**(#311 — `sort`가 이 API에만 있다). + 최신순은 서버 기본값이라 `sort`를 **생략**하고(`"latest"` 같은 값을 보내면 `COLLECTION-009`), 랜덤만 `sort=random`을 보낸다. + 서버가 받는 값은 `random` 하나뿐이다. 그래서 Endpoint `query` switch에서 `.getLikedCollections`와 case를 묶을 수 없다(바인딩 타입이 달라 컴파일 에러). diff --git a/Projects/Data/CollectionData/Sources/DTO/Query/PublicCollectionsQuery.swift b/Projects/Data/CollectionData/Sources/DTO/Query/PublicCollectionsQuery.swift new file mode 100644 index 000000000..4709bb4a3 --- /dev/null +++ b/Projects/Data/CollectionData/Sources/DTO/Query/PublicCollectionsQuery.swift @@ -0,0 +1,31 @@ +// +// PublicCollectionsQuery.swift +// CollectionData +// +// Created by YunhakLee on 11/27/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation +import Networking + +import CollectionDomain + +/// `GET /collections` 전용 쿼리. 다른 목록과 달리 `sort`가 있어 `CollectionsQuery`를 재사용하지 않는다. +/// nil인 값은 `QueryItemConvertible` 기본 구현이 쿼리에서 알아서 제외한다. +struct PublicCollectionsQuery: QueryItemConvertible { + /// 최신순은 서버 기본값이라 **생략**해서 보낸다(서버가 받는 값은 `random` 하나뿐, 그 외는 400 COLLECTION-009). + public let sort: String? + /// `sort=random`과 함께 보내면 빈 값이어도 400 COLLECTION-007이다 — 무작위 조회에선 nil이어야 한다. + public let cursor: String? + public let size: Int + + public init(sort: PublicCollectionSort, cursor: String?, size: Int) { + switch sort { + case .latest: self.sort = nil + case .random: self.sort = "random" + } + self.cursor = cursor + self.size = size + } +} diff --git a/Projects/Data/CollectionData/Sources/Endpoint/CollectionEndpoint.swift b/Projects/Data/CollectionData/Sources/Endpoint/CollectionEndpoint.swift index 4a262134c..5952807cf 100644 --- a/Projects/Data/CollectionData/Sources/Endpoint/CollectionEndpoint.swift +++ b/Projects/Data/CollectionData/Sources/Endpoint/CollectionEndpoint.swift @@ -20,7 +20,7 @@ enum CollectionEndpoint: Endpoint { case deleteCollectionLike(collectionID: Int) case getUserCollections(userID: Int, CollectionsQuery) case getLikedCollections(CollectionsQuery) - case getPublicCollections(CollectionsQuery) + case getPublicCollections(PublicCollectionsQuery) var baseURL: URL { URL(string: NetworkingConfig.baseURL) ?? URL(string: "")! @@ -63,8 +63,9 @@ enum CollectionEndpoint: Endpoint { return .convertible(query) case .getUserCollections(_, let query): return .convertible(query) - case .getLikedCollections(let query), - .getPublicCollections(let query): + case .getLikedCollections(let query): + return .convertible(query) + case .getPublicCollections(let query): return .convertible(query) default: return .none diff --git a/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift b/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift index d3f3b0d02..a706a90b5 100644 --- a/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift +++ b/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift @@ -115,6 +115,7 @@ struct DefaultCollectionRepository: CollectionRepository { } public func fetchPublicCollections( + sort: PublicCollectionSort, cursor: String?, size: Int ) async throws(RepositoryError) -> CursorPaginated { @@ -122,7 +123,7 @@ struct DefaultCollectionRepository: CollectionRepository { do { let response = try await service.getPublicCollections( - query: CollectionsQuery(cursor: cursor, size: size) + query: PublicCollectionsQuery(sort: sort, cursor: cursor, size: size) ) let result = CollectionMapper.publicCollectionCards(from: response, myID: myID) logger?.logSuccess(action: action.name) diff --git a/Projects/Data/CollectionData/Sources/Service/CollectionService.swift b/Projects/Data/CollectionData/Sources/Service/CollectionService.swift index 3677dee71..c9e70981c 100644 --- a/Projects/Data/CollectionData/Sources/Service/CollectionService.swift +++ b/Projects/Data/CollectionData/Sources/Service/CollectionService.swift @@ -11,7 +11,7 @@ import Foundation protocol CollectionService: Sendable { func getUserCollections(userID: Int, query: CollectionsQuery) async throws -> CollectionsResponse func getLikedCollections(query: CollectionsQuery) async throws -> CollectionsResponse - func getPublicCollections(query: CollectionsQuery) async throws -> PublicCollectionsResponse + func getPublicCollections(query: PublicCollectionsQuery) async throws -> PublicCollectionsResponse func getCollectionDetail(collectionID: Int, query: CollectionDetailQuery) async throws -> CollectionDetailResponse func postCollection(request: SubmitCollectionRequest) async throws -> CreateCollectionResponse func putCollection(collectionID: Int, request: SubmitCollectionRequest) async throws diff --git a/Projects/Data/CollectionData/Sources/Service/DefaultCollectionService.swift b/Projects/Data/CollectionData/Sources/Service/DefaultCollectionService.swift index e9f1a6419..86415f55a 100644 --- a/Projects/Data/CollectionData/Sources/Service/DefaultCollectionService.swift +++ b/Projects/Data/CollectionData/Sources/Service/DefaultCollectionService.swift @@ -32,7 +32,7 @@ struct DefaultCollectionService: CollectionService { ) } - public func getPublicCollections(query: CollectionsQuery) async throws -> PublicCollectionsResponse { + public func getPublicCollections(query: PublicCollectionsQuery) async throws -> PublicCollectionsResponse { try await network.request( CollectionEndpoint.getPublicCollections(query), decodeTo: PublicCollectionsResponse.self diff --git a/Projects/Data/SettingData/CLAUDE.md b/Projects/Data/SettingData/CLAUDE.md index 9b8422f40..0c52fe7ff 100644 --- a/Projects/Data/SettingData/CLAUDE.md +++ b/Projects/Data/SettingData/CLAUDE.md @@ -9,7 +9,7 @@ - `SettingDataFactory.makeTermsAgreementRepository(client:logger:)` - `SettingDataFactory.makeAppVersionProvider(bundle:)` - `AppVersionProviding` 실구현은 **`BundleAppVersionProvider`**(#225 — 강제 업데이트 게이트는 #236에서 App 배선 완료). - 파싱 실패 폴백은 `.zero`가 아니라 **절대 강제되지 않는 방향**(max 버전) — `.zero`면 앱이 업데이트 알럿에 잠긴다. + 파싱 실패 폴백은 0.0.0이 아니라 **절대 강제되지 않는 방향**(max 버전) — 0.0.0이면 앱이 업데이트 알럿에 잠긴다. ## 주의사항 (작업 중 발견 시 누적) diff --git a/Projects/Data/SettingData/Sources/Provider/BundleAppVersionProvider.swift b/Projects/Data/SettingData/Sources/Provider/BundleAppVersionProvider.swift index ade5ecfae..4a920233d 100644 --- a/Projects/Data/SettingData/Sources/Provider/BundleAppVersionProvider.swift +++ b/Projects/Data/SettingData/Sources/Provider/BundleAppVersionProvider.swift @@ -27,7 +27,7 @@ struct BundleAppVersionProvider: AppVersionProviding { self.currentVersion = parsed } else { // 파싱 실패는 사실상 불가(우리가 관리하는 MARKETING_VERSION)지만, 만에 하나 깨져도 - // `.zero` 폴백이면 최소 버전 비교에서 무조건 지므로 **앱이 강제 업데이트 알럿에 잠긴다**. + // 0.0.0으로 폴백하면 최소 버전 비교에서 무조건 지므로 **앱이 강제 업데이트 알럿에 잠긴다**. // "정책 조회/판정 실패는 통과" 철학에 맞춰 절대 강제되지 않는 방향으로 폴백한다. self.currentVersion = AppVersion(major: .max, minor: 0, patch: 0) } diff --git a/Projects/Data/SettingData/Tests/BundleAppVersionProviderTests.swift b/Projects/Data/SettingData/Tests/BundleAppVersionProviderTests.swift index 8a3a08aec..a87184904 100644 --- a/Projects/Data/SettingData/Tests/BundleAppVersionProviderTests.swift +++ b/Projects/Data/SettingData/Tests/BundleAppVersionProviderTests.swift @@ -14,7 +14,7 @@ import SettingDomain /// 강제 업데이트 게이트가 쓰는 **현재 앱 버전의 출처** 명세 — 번들의 버전 문자열을 파싱하되, /// 문자열이 없거나 깨졌을 때의 폴백은 **"절대 강제 업데이트가 뜨지 않는 방향"**(max 버전)이다. -/// `.zero`로 폴백하면 번들이 깨진 앱이 업데이트 알럿에 잠겨 영영 못 빠져나온다. +/// 0.0.0으로 폴백하면 번들이 깨진 앱이 업데이트 알럿에 잠겨 영영 못 빠져나온다. @Suite struct BundleAppVersionProviderTests { diff --git a/Projects/Data/SettingData/Tests/SettingMapperTests.swift b/Projects/Data/SettingData/Tests/SettingMapperTests.swift index 2efefd930..0d96d1a10 100644 --- a/Projects/Data/SettingData/Tests/SettingMapperTests.swift +++ b/Projects/Data/SettingData/Tests/SettingMapperTests.swift @@ -67,12 +67,21 @@ struct SettingMapperTests { #expect(result.updateDate == DateParser.date(from: "2026-04-20")) } - @Test("minimumVersion 형식이 올바르지 않으면 invalidConversion 에러를 던진다") - func throwsInvalidConversionWhenMinimumVersionIsInvalid() async { - let response = makeAppMinimumVersionResponse(minimumVersion: "1.2.3.4") + // 빈 자리("1.", "1..2")도 형식 오류다(#308) — 끝에 점이 붙은 "2.0."도 2.0.0으로 읽지 않으니, 서버 입력 실수면 + // 강제 업데이트 판정이 실패해 "실패는 통과" 정책으로 강제 업데이트가 걸리지 않는다. + @Test( + "minimumVersion 형식이 올바르지 않으면 invalidConversion 에러를 던진다", + arguments: [ + "1.2.3.4", // 자리가 넷 + "1.", // 끝에 빈 자리 + "1..2" // 가운데 빈 자리 + ] + ) + func throwsInvalidConversionWhenMinimumVersionIsInvalid(minimumVersion: String) async { + let response = makeAppMinimumVersionResponse(minimumVersion: minimumVersion) await #expect( - throws: MappingError.invalidConversion(type: "AppVersion", value: "1.2.3.4") + throws: MappingError.invalidConversion(type: "AppVersion", value: minimumVersion) ) { _ = try SettingMapper.appUpdatePolicy(from: response) } diff --git a/Projects/Data/SplashData/CLAUDE.md b/Projects/Data/SplashData/CLAUDE.md index 52c5eaaa3..2f4ac33d8 100644 --- a/Projects/Data/SplashData/CLAUDE.md +++ b/Projects/Data/SplashData/CLAUDE.md @@ -3,14 +3,14 @@ `SplashDomain`의 두 포트(`LaunchGateRepository`/`LaunchTaskRepository`) 구현 — **자기 네트워크 호출 없이 다른 도메인 Repository들에 위임만 하는 composite 모듈**(#225). 구성요소는 `Sources/`를 직접 보면 된다. -- 식별자: `ModuleType.data(.splash)` / 의존: Networking + 도메인 6종 프로토콜(**구현체 모름** — 인스턴스는 App DI가 주입) +- 식별자: `ModuleType.data(.splash)` / 의존: Networking + 도메인 5종 프로토콜(**구현체 모름** — 인스턴스는 App DI가 주입) - 진입점: `SplashDataFactory.makeLaunchGateRepository(...)` / `makeLaunchTaskRepository(...)` — 다른 Data 팩토리와 달리 `client:`가 아니라 **이미 조립된 Repository 인스턴스들**을 받는다. ## 주의사항 (작업 중 발견 시 누적) - **표준 Data 구성(DTO·Service·Mapper·BaseData·Logger·Demo·Testing)이 일부러 없다** — 위임뿐이라서. "다른 Data 모듈과 다르다"고 채워 넣지 말 것. 로깅도 위임받는 각 레포가 이미 한다. -- `deviceTokenProvider`가 nil을 주면 FCM 등록은 **조용히 건너뛴다** — 푸시 인프라(APNs/FCM SDK)가 App에 아직 없어서(2026-08-31 기준) 의도된 동작. 인프라가 생기면 App 조립에서 실제 provider만 꽂으면 된다. +- **FCM 토큰 등록은 여기서 하지 않는다**(#287에서 `deviceTokenProvider`·`PushSettingRepository` 의존 제거) — 런치 시점엔 APNs 토큰이 없어 실기기에서 항상 실패했다. 등록은 App의 `PushNotificationCenter`가 맡는다. - `checkForceUpdateRequired`는 조회 실패를 **그대로 던진다** — "실패는 통과" 정책은 `BootstrapAppUseCase`(SplashDomain)가 한 곳에서 결정한다. 여기서 삼키지 말 것. - `hasValidSession`은 토큰 **존재 여부만** 본다 — 만료 검증은 401 자동 재발급 경로(#184) 담당. - ⚠️ **`isOnboardingCompleted`(#257)만은 위임이 아니라 `AppStorage`(BaseData)를 직접 읽는다** — 그래서 이 모듈이 예외적으로 **BaseData에 의존**한다(`Project.swift`). `hasValidSession`이 `SessionTokenStore`(Keychain)를 직접 읽는 것과 같은 결의 로컬 조회라 "위임 전용" 원칙에 어긋나지 않는다(도메인 repo에 위임할 대상이 없는 순수 로컬 플래그). **값이 없으면 `?? true`(완료 간주)** — 기능 도입 전부터 로그인돼 있던 기존 유저를 온보딩으로 되돌리지 않기 위한 하위호환이니, 이 기본값을 false로 바꾸면 기존 유저가 전부 재로그인 유도된다. diff --git a/Projects/Data/SplashData/Project.swift b/Projects/Data/SplashData/Project.swift index 5dde3c3e7..12533fe75 100644 --- a/Projects/Data/SplashData/Project.swift +++ b/Projects/Data/SplashData/Project.swift @@ -24,7 +24,6 @@ let project = Project.createDataModule( .module(.domain(.splash)), // 구현 대상 포트 .module(.domain(.profile)), // ProfileRepository(users/me) .module(.domain(.setting)), // AppUpdate·TermsAgreement - .module(.domain(.notification)), // PushSettingRepository(디바이스 토큰) .module(.domain(.recommendation)) // RecommendationRepository·HomePrefetchStore ], // 위임 검증 테스트가 각 도메인의 기존 Mock을 재사용한다. @@ -32,7 +31,6 @@ let project = Project.createDataModule( .module(.domain(.base), type: .testing), .module(.domain(.profile), type: .testing), .module(.domain(.setting), type: .testing), - .module(.domain(.notification), type: .testing), .module(.domain(.recommendation), type: .testing) ] ) diff --git a/Projects/Data/SplashData/Sources/Factory/SplashDataFactory.swift b/Projects/Data/SplashData/Sources/Factory/SplashDataFactory.swift index 04a515094..5196aae3b 100644 --- a/Projects/Data/SplashData/Sources/Factory/SplashDataFactory.swift +++ b/Projects/Data/SplashData/Sources/Factory/SplashDataFactory.swift @@ -10,7 +10,6 @@ import Foundation import BaseDomain import BaseData -import NotificationDomain import ProfileDomain import RecommendationDomain import SettingDomain @@ -39,16 +38,12 @@ public enum SplashDataFactory { public static func makeLaunchTaskRepository( profileRepository: ProfileRepository, - pushSettingRepository: PushSettingRepository, - deviceTokenProvider: @escaping @Sendable () async -> DevicePushToken?, keywordRepository: KeywordRepository, recommendationRepository: RecommendationRepository, prefetchStore: HomePrefetchStore ) -> LaunchTaskRepository { DefaultLaunchTaskRepository( profileRepository: profileRepository, - pushSettingRepository: pushSettingRepository, - deviceTokenProvider: deviceTokenProvider, keywordRepository: keywordRepository, recommendationRepository: recommendationRepository, prefetchStore: prefetchStore diff --git a/Projects/Data/SplashData/Sources/Repository/DefaultLaunchTaskRepository.swift b/Projects/Data/SplashData/Sources/Repository/DefaultLaunchTaskRepository.swift index 4ee8aeee9..113a661e0 100644 --- a/Projects/Data/SplashData/Sources/Repository/DefaultLaunchTaskRepository.swift +++ b/Projects/Data/SplashData/Sources/Repository/DefaultLaunchTaskRepository.swift @@ -9,7 +9,6 @@ import Foundation import BaseDomain -import NotificationDomain import ProfileDomain import RecommendationDomain import SplashDomain @@ -18,25 +17,17 @@ import SplashDomain struct DefaultLaunchTaskRepository: LaunchTaskRepository { private let profileRepository: ProfileRepository - private let pushSettingRepository: PushSettingRepository - /// 현재 디바이스 푸시 토큰의 소스. 푸시 인프라(APNs/FCM)가 App에 배선되기 전까지는 nil을 돌려줘도 된다 — - /// 그 경우 등록을 조용히 건너뛴다. - private let deviceTokenProvider: @Sendable () async -> DevicePushToken? private let keywordRepository: KeywordRepository private let recommendationRepository: RecommendationRepository private let prefetchStore: HomePrefetchStore init( profileRepository: ProfileRepository, - pushSettingRepository: PushSettingRepository, - deviceTokenProvider: @escaping @Sendable () async -> DevicePushToken?, keywordRepository: KeywordRepository, recommendationRepository: RecommendationRepository, prefetchStore: HomePrefetchStore ) { self.profileRepository = profileRepository - self.pushSettingRepository = pushSettingRepository - self.deviceTokenProvider = deviceTokenProvider self.keywordRepository = keywordRepository self.recommendationRepository = recommendationRepository self.prefetchStore = prefetchStore @@ -46,11 +37,6 @@ struct DefaultLaunchTaskRepository: LaunchTaskRepository { try await profileRepository.syncUserBasicInfo() } - func registerDeviceTokenIfNeeded() async throws(RepositoryError) { - guard let token = await deviceTokenProvider() else { return } - try await pushSettingRepository.registerDeviceToken(token) - } - func syncKeywords() async { await keywordRepository.syncKeywords() } diff --git a/Projects/Data/SplashData/Tests/Repository/DefaultLaunchTaskRepositoryTests.swift b/Projects/Data/SplashData/Tests/Repository/DefaultLaunchTaskRepositoryTests.swift index 664e0447a..79e32ee4d 100644 --- a/Projects/Data/SplashData/Tests/Repository/DefaultLaunchTaskRepositoryTests.swift +++ b/Projects/Data/SplashData/Tests/Repository/DefaultLaunchTaskRepositoryTests.swift @@ -12,17 +12,14 @@ import Testing @testable import SplashData import BaseDomain import BaseDomainTesting -import NotificationDomain -import NotificationDomainTesting import ProfileDomain import ProfileDomainTesting import RecommendationDomain import RecommendationDomainTesting -/// 부수 태스크 4종(users/me 동기화·FCM 토큰 등록·키워드 동기화·홈 프리페치)을 -/// **각 도메인 Repository에 어떻게 위임하는지** 명세. 여기 있는 분기는 둘뿐이다 — -/// 토큰 소스가 없으면 FCM 등록을 조용히 건너뛰는 것, 프리페치 세 슬롯을 병렬로 채우되 -/// 실패한 쪽만 비워 두는 것. "언제 던지고 언제 기다리는지"는 `BootstrapAppUseCaseTests`가 명세한다. +/// 부수 태스크 3종(users/me 동기화·키워드 동기화·홈 프리페치)을 +/// **각 도메인 Repository에 어떻게 위임하는지** 명세. 여기 있는 분기는 하나뿐이다 — +/// 프리페치 세 슬롯을 병렬로 채우되 실패한 쪽만 비워 두는 것. "언제 던지고 언제 기다리는지"는 `BootstrapAppUseCaseTests`가 명세한다. @Suite struct DefaultLaunchTaskRepositoryTests { @@ -48,30 +45,6 @@ struct DefaultLaunchTaskRepositoryTests { #expect(keyword.syncKeywordsCallCount == 1) } - // MARK: - 디바이스 토큰 - - @Test("디바이스 토큰이 있으면 그 토큰을 서버에 등록한다") - func registersDeviceTokenWhenAvailable() async throws { - let push = MockPushSettingRepository() - let token = DevicePushToken(token: "fcm-token", deviceID: "device-1") - let sut = makeSUT(pushSettingRepository: push, deviceToken: token) - - try await sut.registerDeviceTokenIfNeeded() - - #expect(push.registerCallCount == 1) - #expect(push.lastRegisteredToken == token) - } - - @Test("디바이스 토큰 소스가 없으면 등록을 조용히 건너뛴다") - func skipsRegistrationWhenTokenUnavailable() async throws { - let push = MockPushSettingRepository() - let sut = makeSUT(pushSettingRepository: push, deviceToken: nil) - - try await sut.registerDeviceTokenIfNeeded() - - #expect(push.registerCallCount == 0) - } - // MARK: - 홈 프리페치 @Test("프리페치가 성공하면 세 슬롯을 모두 채운다") @@ -114,16 +87,12 @@ extension DefaultLaunchTaskRepositoryTests { private func makeSUT( profileRepository: MockProfileRepository = MockProfileRepository(), - pushSettingRepository: MockPushSettingRepository = MockPushSettingRepository(), - deviceToken: DevicePushToken? = nil, keywordRepository: MockKeywordRepository = MockKeywordRepository(), recommendationRepository: MockRecommendationRepository = MockRecommendationRepository(), prefetchStore: HomePrefetchStore = HomePrefetchStore() ) -> DefaultLaunchTaskRepository { DefaultLaunchTaskRepository( profileRepository: profileRepository, - pushSettingRepository: pushSettingRepository, - deviceTokenProvider: { deviceToken }, keywordRepository: keywordRepository, recommendationRepository: recommendationRepository, prefetchStore: prefetchStore 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..3d989a800 100644 --- a/Projects/Domain/BaseDomain/CLAUDE.md +++ b/Projects/Domain/BaseDomain/CLAUDE.md @@ -35,12 +35,12 @@ - **`Author.accessibleUserId`(#197 후속, 2026-08-28)** — 서버는 탈퇴한 유저를 `userId: -1`로 내려준다(피드 관련 응답 `TotalFeedResponse`/`FeedDetailResponse`/`NovelFeedResponse`가 전부 `userId: Int` non-optional이라 항상 채워진다 — `Author.userId`가 옵셔널인 건 다른 매퍼가 애초에 안 채우는 경우 대비일 뿐, 이 -1과는 - 무관). 이 센티널 판정을 `Author` 밖으로 새지 않게 캡슐화한 게 `accessibleUserId: UserID?`(nil이면 + 무관). 컬렉션 응답의 `owner`(상세·공개 목록)도 탈퇴 유저면 같은 `-1`이다(dev 서버 실측, 2026-11-27, #311). 이 센티널 판정을 `Author` 밖으로 새지 않게 캡슐화한 게 `accessibleUserId: UserID?`(nil이면 "이동할 프로필이 없다" — userId 미제공과 탈퇴 유저 둘 다 같은 의미로 묶는다). ⚠️ **`UserID` 자체 (`IDWrapper` typealias)를 확장해 `.withdrawn`을 두지 않았다** — `FeedID`/`NovelID` 등 다른 ID도 전부 같은 `IDWrapper`라 그렇게 하면 의미 없는 `FeedID.withdrawn`까지 새어버린다. 센티널은 `Author.swift` 안 `private` 상수로만 존재한다 — 다른 곳에서 `-1` 리터럴로 재판정하지 말고 이 프로퍼티를 - 재사용할 것(Feature 3곳 — `SosoFeedView`/`FeedDetailView`/`NovelDetailFeedTab` — 이 이미 이걸 쓴다). + 재사용할 것(Feature 4곳 — `SosoFeedView`/`FeedDetailView`/`NovelDetailFeedTab`/`CollectionDetailView`(#311) — 이 이미 이걸 쓴다). - `NovelGenre.myFeedFilter`(피드 필터용, 구 `filterGenre`)·`.searchGenre`(검색 화면 장르 그리드용)·`.onboardingGenre`(온보딩 3x3 배지 그리드용, #178)는 **의도적으로 다른 순서**의 별개 목록 — 한쪽을 고친다고 다른 쪽까지 맞추지 말 것. - **`KeywordCategory`는 `AttractivePoint`와 동일 패턴**(raw value 없는 순수 enum, `CaseIterable`) — 카테고리명·아이콘 같은 표시값은 도메인에 두지 않고 `WSSComponent`의 `DomainPresentation` 확장이 담당한다. - ⚠️ **매력포인트 표시 순서는 `AttractivePoint.allCases`(enum 선언 순서)가 정본이다** — enum 선언 순서 자체를 디자인 정본(**필력이 3번째**)에 맞춰뒀다(2026-09-09, 과거엔 WSSComponent의 `displayOrder` 별도 배열이 이 역할을 했으나 enum 순서를 정본으로 승격하며 제거). 감상평 작성·서재 필터·서재 리스트 셀(사용자 평가 매력포인트 정렬)이 전부 이 단일 순서를 공유한다(NovelGenre가 화면별로 여러 순서를 갖는 것과 달리 매력포인트는 하나). **케이스 선언 순서를 바꾸면 화면 표시 순서가 통째로 바뀌므로** 함부로 재정렬하지 말 것. 서버 응답의 `categoryImage`(카테고리 아이콘 URL)는 **의도적으로 매핑하지 않는다** — 아이콘은 로컬 고정 에셋(카테고리가 5종으로 고정)이라 서버 값을 매번 받을 필요가 없다는 판단. @@ -68,3 +68,7 @@ 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·SplashData 테스트가 쓴다). +- **`MockLoadTotalKeywordsUseCase`**(#308) — 키워드 캐시를 받아 쓰는 다른 모듈 UseCase 테스트용 Stub(`result`만 돌려준다). 프로토콜을 선언한 이 모듈이 가짜 객체도 갖는다는 원칙으로 여기 뒀다. 다른 모듈 테스트는 `MockKeywordRepository`+`DefaultLoadTotalKeywordsUseCase`를 조립하지 말고 이걸 쓴다 — 그래야 동기화·재조회라는 이 UseCase의 속사정에 묶이지 않는다(NovelDomain이 쓴다). +- **`ReadingPeriod.init`의 `calendar`**(#293)는 테스트용이다 — 미래 날짜 판정이 일 단위라 기기 시간대에 따라 결과가 갈린다. 앱 코드는 기본값(`.current`)을 쓰고, 테스트는 서울 달력을 넘긴다. diff --git a/Projects/Domain/BaseDomain/Sources/Author.swift b/Projects/Domain/BaseDomain/Sources/Author.swift index 6c8f3d60e..3b22e6e33 100644 --- a/Projects/Domain/BaseDomain/Sources/Author.swift +++ b/Projects/Domain/BaseDomain/Sources/Author.swift @@ -16,7 +16,8 @@ public struct Author: Sendable { /// 서버가 탈퇴한 유저를 가리킬 때 `userId` 자리에 내려주는 센티널 값(피드 관련 응답 실측 — /// `TotalFeedResponse`/`FeedDetailResponse`/`NovelFeedResponse` 전부 `userId: Int`가 non-optional - /// 이라 서버가 항상 값을 채우는데, 탈퇴 유저는 이 값이 -1로 온다). `UserID`(`IDWrapper`)를 + /// 이라 서버가 항상 값을 채우는데, 탈퇴 유저는 이 값이 -1로 온다). 컬렉션 응답의 `owner`(상세·공개 + /// 목록)도 탈퇴 유저면 똑같이 -1이다(dev 서버 실측, 2026-11-27). `UserID`(`IDWrapper`)를 /// 직접 확장하지 않는 이유: `FeedID`/`NovelID` 등 다른 ID 래퍼도 전부 같은 `IDWrapper` /// typealias라 그쪽까지 `.withdrawn`이 새어버린다 — `Author` 전용으로 가둔다. private static let withdrawnUserID = UserID(-1) 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/MockLoadTotalKeywordsUseCase.swift b/Projects/Domain/BaseDomain/Testing/Mock/MockLoadTotalKeywordsUseCase.swift new file mode 100644 index 000000000..66859da58 --- /dev/null +++ b/Projects/Domain/BaseDomain/Testing/Mock/MockLoadTotalKeywordsUseCase.swift @@ -0,0 +1,26 @@ +// +// MockLoadTotalKeywordsUseCase.swift +// BaseDomain +// +// Created by YunhakLee on 11/19/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation + +import BaseDomain + +/// 전체 키워드 불러오기 가짜 객체. +/// 조회라 정해 둔 값(`result`)만 돌려주고 호출을 기록하지 않는다(Stub). +/// 이 UseCase를 받아 쓰는 다른 모듈 테스트가, 키워드 저장소의 동기화·재조회 같은 속사정을 몰라도 되게 둔다. +public final class MockLoadTotalKeywordsUseCase: LoadTotalKeywordsUseCase { + public var result: Result<[KeywordGroup], RepositoryError> + + public init(result: Result<[KeywordGroup], RepositoryError> = .success([])) { + self.result = result + } + + public func execute() async throws(RepositoryError) -> [KeywordGroup] { + try result.get() + } +} 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..308a7db4d 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,11 @@ 서버에 owner를 요청할 것. `owner` 옵셔널도 같은 응답 빈틈 때문에 둔 임시 형태라 서버가 owner를 주면 함께 리팩터링한다. - `isPrivate`은 세 목록 모두 서버 값을 그대로 쓴다 — 남의 나만 보는 컬렉션은 서버가 애초에 내려주지 않는다. - `fetchPublicCollections`는 서버(`GET /collections`)가 전체 개수를 주지 않아 다른 목록과 달리 `(페이지, 개수)` 튜플이 아니라 페이지만 돌려준다. +- **공개 목록의 정렬(`PublicCollectionSort`)은 UseCase가 정하고 Repository는 받기만 한다**(#311). 전체 컬렉션뷰는 + `LoadPublicCollectionsUseCase`(`.latest`, 커서로 이어 받음), 홈 섹션은 `LoadRandomPublicCollectionsUseCase`(`.random`). + 랜덤을 Repository 메서드 이름에 숨기지 않은 건 "홈은 랜덤"이라는 제품 결정을 Data가 품지 않게 하려서다. + ⚠️ **`.random`은 한 페이지뿐이라 cursor를 같이 보내면 서버가 400(`COLLECTION-007`)으로 거부한다**(빈 값이어도) — + 그래서 랜덤 UseCase는 cursor를 받지 않고 배열만 돌려준다. 랜덤에 "더 불러오기"를 붙이려 하지 말 것. +- UseCase 10개(조회 6·생성·수정·삭제·좋아요)는 **일부러 테스트가 없다**(#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/Sources/Entity/PublicCollectionSort.swift b/Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionSort.swift new file mode 100644 index 000000000..3d156e32d --- /dev/null +++ b/Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionSort.swift @@ -0,0 +1,19 @@ +// +// PublicCollectionSort.swift +// CollectionDomain +// +// Created by YunhakLee on 11/27/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation + +/// 전체 공개 컬렉션 목록(`GET /collections`)의 정렬 기준. +public enum PublicCollectionSort: Sendable { + /// 최초 생성 시점 최신순. 수정·작품 재배치·좋아요로 순서가 바뀌지 않는다. 커서로 이어 받는다. + case latest + /// 공개·차단 조건을 통과한 전체 후보에서 중복 없이 무작위로 고른 **한 페이지**. + /// 페이지네이션이 없어 커서를 함께 보내면 서버가 거부한다(빈 값이어도 400). + /// 요청마다 새로 고르지만 매번 달라진다고 보장하지는 않는다. + case random +} diff --git a/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift b/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift index 41b1fc10f..6390bae26 100644 --- a/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift +++ b/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift @@ -41,12 +41,15 @@ public protocol CollectionRepository: Sendable { size: Int ) async throws(RepositoryError) -> (CursorPaginated, Int) - /// 모든 사용자의 공개 컬렉션 목록. 최초 생성 시점 최신순(수정·좋아요로 순서가 바뀌지 않는다). + /// 모든 사용자의 공개 컬렉션 목록. /// /// 조회자 본인의 비공개 컬렉션은 오지 않고, 로그인 상태면 차단 관계 작성자의 컬렉션이 빠진다. /// 서버가 전체 개수를 주지 않아 다른 목록과 달리 커서 페이지만 돌려준다. - /// - Parameter cursor: 직전 응답의 `nextCursor`. 첫 페이지는 nil. + /// - Parameters: + /// - sort: 정렬 기준. `.random`은 한 페이지뿐이라 `hasNext`가 항상 false다. + /// - cursor: 직전 응답의 `nextCursor`. 첫 페이지는 nil. **`.random`이면 반드시 nil**(서버가 400으로 거부). func fetchPublicCollections( + sort: PublicCollectionSort, cursor: String?, size: Int ) async throws(RepositoryError) -> CursorPaginated diff --git a/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift b/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift index b50ad51c2..11f687b4f 100644 --- a/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift +++ b/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift @@ -26,6 +26,6 @@ public final class DefaultLoadPublicCollectionsUseCase: LoadPublicCollectionsUse } public func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { - try await collectionRepository.fetchPublicCollections(cursor: cursor, size: size) + try await collectionRepository.fetchPublicCollections(sort: .latest, cursor: cursor, size: size) } } diff --git a/Projects/Domain/CollectionDomain/Sources/UseCase/LoadRandomPublicCollectionsUseCase.swift b/Projects/Domain/CollectionDomain/Sources/UseCase/LoadRandomPublicCollectionsUseCase.swift new file mode 100644 index 000000000..56276dde2 --- /dev/null +++ b/Projects/Domain/CollectionDomain/Sources/UseCase/LoadRandomPublicCollectionsUseCase.swift @@ -0,0 +1,32 @@ +// +// LoadRandomPublicCollectionsUseCase.swift +// CollectionDomain +// +// Created by YunhakLee on 11/27/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation + +import BaseDomain + +public protocol LoadRandomPublicCollectionsUseCase: Sendable { + /// 모든 사용자의 공개 컬렉션 중 무작위로 최대 `size`개를 가져온다(홈 "컬렉션 모음.zip" 섹션). + /// + /// 무작위 조회는 페이지네이션이 없어 커서를 받지 않고 배열만 돌려준다. + /// 요청마다 새로 고르므로 새로고침하면 다른 컬렉션이 나올 수 있다(매번 달라진다는 보장은 없다). + func execute(size: Int) async throws(RepositoryError) -> [CollectionCard] +} + +public final class DefaultLoadRandomPublicCollectionsUseCase: LoadRandomPublicCollectionsUseCase { + + private let collectionRepository: CollectionRepository + + public init(collectionRepository: CollectionRepository) { + self.collectionRepository = collectionRepository + } + + public func execute(size: Int) async throws(RepositoryError) -> [CollectionCard] { + try await collectionRepository.fetchPublicCollections(sort: .random, cursor: nil, size: size).items + } +} diff --git a/Projects/Domain/CollectionDomain/TEST_SPEC.md b/Projects/Domain/CollectionDomain/TEST_SPEC.md new file mode 100644 index 000000000..1fa1b4eeb --- /dev/null +++ b/Projects/Domain/CollectionDomain/TEST_SPEC.md @@ -0,0 +1,81 @@ +# 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..0b7cac049 100644 --- a/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDraftTests.swift +++ b/Projects/Domain/CollectionDomain/Tests/Entity/CollectionDraftTests.swift @@ -6,345 +6,404 @@ // 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) - @Test("설명이 없던 컬렉션을 초안으로 되돌리면 설명은 빈 문자열이 된다") - func initFromDetailWithoutDescription() { - let detail = makeDetail(description: nil) + #expect(draft.description == "") + } + + @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(draft.novelIDs == novelIDs) + } + + @Test("작품을 빼면 목록에서 사라진다") + func removingNovelDropsIt() { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) + + draft.removeNovel(NovelID(1)) - #expect(throws: CollectionDraft.ValidationError.novelOverLimit(max: 100)) { - try draft.addNovel(NovelID(101)) + #expect(draft.novelIDs == [NovelID(2)]) } } - // MARK: - removeNovel + @Suite("작품 목록 통째로 바꾸기") + struct SettingNovels { - @Test("작품을 빼면 목록에서 사라진다") - func removeNovel() { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) + @Test("작품 목록을 새 목록으로 통째로 바꿀 수 있다") + func settingNovelsReplacesAll() throws { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - draft.removeNovel(NovelID(1)) + try draft.setNovels([NovelID(3), NovelID(4), NovelID(5)]) - #expect(draft.novelIDs == [NovelID(2)]) - } + #expect(draft.novelIDs == [NovelID(3), NovelID(4), NovelID(5)]) + } - @Test("대표로 지정한 작품을 빼면 대표 지정도 함께 풀린다") - func removeRepresentativeNovel() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - try draft.setRepresentativeNovel(NovelID(1)) + @Test("새 목록이 100개여도 통째로 바꿀 수 있다") + func settingNovelsAcceptsUpToHundred() throws { + var draft = makeDraft(novelIDs: [NovelID(1)]) + let novelIDs = (1...100).map { NovelID($0) } - draft.removeNovel(NovelID(1)) + try draft.setNovels(novelIDs) - #expect(draft.representativeNovelID == nil) - } + #expect(draft.novelIDs == novelIDs) + } - @Test("대표가 아닌 작품을 빼면 대표 지정은 그대로 남는다") - func removeNonRepresentativeNovel() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - try draft.setRepresentativeNovel(NovelID(1)) + @Test("새 목록이 100개를 넘으면 바꿀 수 없다") + func settingOverHundredNovelsIsRejected() { + var draft = makeDraft(novelIDs: [NovelID(1)]) - draft.removeNovel(NovelID(2)) + #expect(throws: CollectionDraft.ValidationError.novelOverLimit(max: 100)) { + try draft.setNovels((1...101).map { NovelID($0) }) + } + #expect(draft.novelIDs == [NovelID(1)]) + } - #expect(draft.representativeNovelID == NovelID(1)) + @Test("새 목록에 같은 작품이 두 번 있으면 바꿀 수 없다") + func settingDuplicatedNovelsIsRejected() { + var draft = makeDraft(novelIDs: [NovelID(1)]) + + #expect(throws: CollectionDraft.ValidationError.duplicatedNovel) { + try draft.setNovels([NovelID(2), NovelID(3), NovelID(2)]) + } + #expect(draft.novelIDs == [NovelID(1)]) + } } - // MARK: - setNovels + @Suite("대표 작품 고르기") + struct Representative { - @Test("작품 리스트 전체를 새 선택 결과로 교체한다") - func setNovelsReplacesAll() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) + @Test("담긴 작품을 대표로 고를 수 있다") + func choosingIncludedNovelAsRepresentative() throws { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - try draft.setNovels([NovelID(3), NovelID(4), NovelID(5)]) + try draft.setRepresentativeNovel(NovelID(2)) - #expect(draft.novelIDs == [NovelID(3), NovelID(4), NovelID(5)]) - } + #expect(draft.representativeNovelID == NovelID(2)) + } - @Test("작품이 100개를 넘으면 교체할 수 없다") - func setNovelsOverLimit() { - var draft = makeDraft(novelIDs: [NovelID(1)]) + @Test("담기지 않은 작품은 대표로 고를 수 없다") + func choosingMissingNovelAsRepresentativeIsRejected() { + var draft = makeDraft(novelIDs: [NovelID(1)]) - #expect(throws: CollectionDraft.ValidationError.novelOverLimit(max: 100)) { - try draft.setNovels((1...101).map { NovelID($0) }) + #expect(throws: CollectionDraft.ValidationError.representativeNovelNotIncluded) { + try draft.setRepresentativeNovel(NovelID(99)) + } + #expect(draft.representativeNovelID == nil) } - #expect(draft.novelIDs == [NovelID(1)]) - } - @Test("대표 작품이 새 목록에 없으면 대표 지정도 함께 풀린다") - func setNovelsDropsRepresentativeWhenExcluded() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - try draft.setRepresentativeNovel(NovelID(1)) + @Test("대표를 고르지 않았으면 첫 작품이 대표다") + func firstNovelIsRepresentativeByDefault() { + let draft = makeDraft(novelIDs: [NovelID(7), NovelID(3)]) - try draft.setNovels([NovelID(2), NovelID(3)]) + let representative = draft.effectiveRepresentativeNovelID - #expect(draft.representativeNovelID == nil) - } + #expect(representative == NovelID(7)) + } + + @Test("대표를 골랐으면 고른 작품이 대표다") + func chosenNovelIsRepresentative() { + let draft = makeDraft(novelIDs: [NovelID(7), NovelID(3)], representativeNovelID: NovelID(3)) + + let representative = draft.effectiveRepresentativeNovelID + + #expect(representative == NovelID(3)) + } - @Test("대표 작품이 새 목록에도 있으면 대표 지정이 유지된다") - func setNovelsKeepsRepresentativeWhenIncluded() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) - try draft.setRepresentativeNovel(NovelID(1)) + @Test("작품이 없으면 대표도 없다") + func noRepresentativeWithoutNovel() { + let draft = makeDraft(novelIDs: []) - try draft.setNovels([NovelID(1), NovelID(3)]) + let representative = draft.effectiveRepresentativeNovelID - #expect(draft.representativeNovelID == NovelID(1)) + #expect(representative == nil) + } } - // MARK: - setRepresentativeNovel + @Suite("작품이 빠질 때 대표 작품") + struct RepresentativeAfterNovelChange { - @Test("담긴 작품 중 하나를 대표로 지정할 수 있다") - func setRepresentativeNovel() throws { - var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)]) + @Test("대표로 고른 작품을 빼면 대표 선택도 풀린다") + func removingRepresentativeClearsIt() { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)], representativeNovelID: NovelID(1)) - try draft.setRepresentativeNovel(NovelID(2)) + draft.removeNovel(NovelID(1)) - #expect(draft.representativeNovelID == NovelID(2)) - } + #expect(draft.representativeNovelID == nil) + } - @Test("담기지 않은 작품은 대표로 지정할 수 없다") - func setRepresentativeNovelNotIncluded() { - var draft = makeDraft(novelIDs: [NovelID(1)]) + @Test("대표로 고르지 않은 작품을 빼면 대표 선택은 그대로다") + func removingOtherNovelKeepsRepresentative() { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)], representativeNovelID: NovelID(1)) - #expect(throws: CollectionDraft.ValidationError.representativeNovelNotIncluded) { - try draft.setRepresentativeNovel(NovelID(99)) + draft.removeNovel(NovelID(2)) + + #expect(draft.representativeNovelID == NovelID(1)) } - } - // MARK: - effectiveRepresentativeNovelID + @Test("대표로 고른 작품이 새 목록에 없으면 대표 선택도 풀린다") + func settingNovelsWithoutRepresentativeClearsIt() throws { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)], representativeNovelID: NovelID(1)) - @Test("대표를 고르지 않았으면 표시 순서 첫 작품이 대표가 된다") - func effectiveRepresentativeFallsBackToFirst() { - let draft = makeDraft(novelIDs: [NovelID(7), NovelID(3)]) + try draft.setNovels([NovelID(2), NovelID(3)]) - #expect(draft.effectiveRepresentativeNovelID == NovelID(7)) - } + #expect(draft.representativeNovelID == nil) + } - @Test("대표를 골랐으면 첫 작품이 아니라 고른 작품이 대표가 된다") - func effectiveRepresentativeUsesChosen() throws { - var draft = makeDraft(novelIDs: [NovelID(7), NovelID(3)]) + @Test("대표로 고른 작품이 새 목록에도 있으면 대표 선택은 그대로다") + func settingNovelsWithRepresentativeKeepsIt() throws { + var draft = makeDraft(novelIDs: [NovelID(1), NovelID(2)], representativeNovelID: NovelID(1)) - try draft.setRepresentativeNovel(NovelID(3)) + try draft.setNovels([NovelID(3), NovelID(1)]) - #expect(draft.effectiveRepresentativeNovelID == NovelID(3)) + #expect(draft.representativeNovelID == NovelID(1)) + } } - @Test("작품이 하나도 없으면 대표도 없다") - func effectiveRepresentativeWithoutNovel() { - let draft = makeDraft(novelIDs: []) + @Suite("나만 보기") + struct Private { - #expect(draft.effectiveRepresentativeNovelID == nil) - } + @Test("컬렉션을 새로 만들 때 나만 보기는 꺼져 있다") + func privateIsOffForNewCollection() { + let draft = CollectionDraft() - // MARK: - togglePrivate + #expect(draft.isPrivate == false) + } - @Test("나만 보는 컬렉션은 기본적으로 꺼져 있다") - func privateIsOffByDefault() { - let draft = CollectionDraft() + @Test("꺼진 나만 보기를 누르면 켜진다") + func togglingPrivateTurnsItOn() { + var draft = makeDraft(isPrivate: false) - #expect(draft.isPrivate == false) - } + draft.togglePrivate() - @Test("나만 보기를 토글하면 상태가 뒤집힌다") - func togglePrivate() { - var draft = makeDraft() + #expect(draft.isPrivate == true) + } + + @Test("켜진 나만 보기를 누르면 꺼진다") + func togglingPrivateTurnsItOff() { + var draft = makeDraft(isPrivate: true) - draft.togglePrivate() + draft.togglePrivate() - #expect(draft.isPrivate) + #expect(draft.isPrivate == false) + } } } -// 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/NotificationDomain/Sources/Notification/UseCase/LoadNotificationListUseCase.swift b/Projects/Domain/NotificationDomain/Sources/Notification/UseCase/LoadNotificationListUseCase.swift index e16e5fc78..ca2140bf0 100644 --- a/Projects/Domain/NotificationDomain/Sources/Notification/UseCase/LoadNotificationListUseCase.swift +++ b/Projects/Domain/NotificationDomain/Sources/Notification/UseCase/LoadNotificationListUseCase.swift @@ -20,7 +20,7 @@ public final class DefaultLoadPagedNotificationsUseCase: LoadPagedNotificationsU self.repository = repository } - public func execute(lastNotificationID: NotificationID?, size: Int = 20) async throws(RepositoryError) -> PagedNotifications { + public func execute(lastNotificationID: NotificationID?, size: Int) async throws(RepositoryError) -> PagedNotifications { let size = size > 0 ? size : Self.defaultSize return try await repository.loadNotifications(lastNotificationID: lastNotificationID, size: size) } diff --git a/Projects/Domain/NotificationDomain/Sources/NovelNotification/UseCase/LoadNovelNotificationSubscriptionsUseCase.swift b/Projects/Domain/NotificationDomain/Sources/NovelNotification/UseCase/LoadNovelNotificationSubscriptionsUseCase.swift index 8b79f6ee2..b113f5411 100644 --- a/Projects/Domain/NotificationDomain/Sources/NovelNotification/UseCase/LoadNovelNotificationSubscriptionsUseCase.swift +++ b/Projects/Domain/NotificationDomain/Sources/NovelNotification/UseCase/LoadNovelNotificationSubscriptionsUseCase.swift @@ -27,7 +27,7 @@ public final class DefaultLoadNovelNotificationSubscriptionsUseCase: LoadNovelNo public func execute( type: NovelNotificationType, lastSubscriptionID: SubscriptionID?, - size: Int = 20 + size: Int ) async throws(RepositoryError) -> PagedNovelNotificationSubscriptions { let size = size > 0 ? size : Self.defaultSize return try await repository.loadSubscriptions(type: type, lastSubscriptionID: lastSubscriptionID, size: size) diff --git a/Projects/Domain/NotificationDomain/TEST_SPEC.md b/Projects/Domain/NotificationDomain/TEST_SPEC.md new file mode 100644 index 000000000..42a4a1c3b --- /dev/null +++ b/Projects/Domain/NotificationDomain/TEST_SPEC.md @@ -0,0 +1,25 @@ +# NotificationDomain 테스트 명세 + + + +## 알림 목록 불러오기 + +`Tests/Notification/UseCase/LoadPagedNotificationsUseCaseTests.swift` + +- 개수를 0 이하로 요청하면 20개씩 불러온다 + - `0` — 경계 + - `-1` — 음수 +- 개수를 1 이상으로 요청하면 그 개수대로 불러온다 + - `1` — 경계 + - `30` — 일반값 + +## 작품 알림 구독 목록 불러오기 + +`Tests/NovelNotification/UseCase/LoadNovelNotificationSubscriptionsUseCaseTests.swift` + +- 개수를 0 이하로 요청하면 20개씩 불러온다 + - `0` — 경계 + - `-1` — 음수 +- 개수를 1 이상으로 요청하면 그 개수대로 불러온다 + - `1` — 경계 + - `30` — 일반값 diff --git a/Projects/Domain/NotificationDomain/Testing/Mock/MockNotificationRepository.swift b/Projects/Domain/NotificationDomain/Testing/Mock/MockNotificationRepository.swift index 5f170eb41..dede6d8a0 100644 --- a/Projects/Domain/NotificationDomain/Testing/Mock/MockNotificationRepository.swift +++ b/Projects/Domain/NotificationDomain/Testing/Mock/MockNotificationRepository.swift @@ -11,95 +11,31 @@ import Foundation import NotificationDomain import BaseDomain -public final class MockNotificationRepository: NotificationRepository { +/// 알림 저장소 가짜 객체(Stub) — 호출을 기록하지 않는다. +/// 목록 조회는 **요청 개수마다** 답을 정해 둔다 — 정해 두지 않은 개수엔 빈 페이지를 준다. +/// 그래서 UseCase가 개수를 잘못 넘기면 결과가 달라진다. +/// 나머지 메서드는 이 모듈 테스트가 쓰지 않아 항상 `.unknown`을 던진다. +public final class MockNotificationRepository: NotificationRepository, @unchecked Sendable { + public var pagesBySize: [Int: PagedNotifications] = [:] - // MARK: - loadNotifications - - public var loadedLastNotificationID: NotificationID? - public var loadedSize: Int? - public var loadNotificationsCallCount = 0 - public var loadNotificationsResult: Result? + public init() {} public func loadNotifications( lastNotificationID: NotificationID?, size: Int ) async throws(RepositoryError) -> PagedNotifications { - loadNotificationsCallCount += 1 - loadedLastNotificationID = lastNotificationID - loadedSize = size - - guard let loadNotificationsResult else { - fatalError("loadNotificationsResult is not set") - } - - switch loadNotificationsResult { - case .success(let value): return value - case .failure(let error): throw error - } + pagesBySize[size] ?? PagedNotifications(items: [], isLoadable: false) } - // MARK: - loadNotificationDetail - - public var loadedDetailID: NotificationID? - public var loadDetailCallCount = 0 - public var loadDetailResult: Result? - - public func loadNotificationDetail( - id: NotificationID - ) async throws(RepositoryError) -> NotificationDetail { - loadDetailCallCount += 1 - loadedDetailID = id - - guard let loadDetailResult else { - fatalError("loadDetailResult is not set") - } - - switch loadDetailResult { - case .success(let value): return value - case .failure(let error): throw error - } + public func loadNotificationDetail(id: NotificationID) async throws(RepositoryError) -> NotificationDetail { + throw .unknown } - // MARK: - markAsRead - - public var markedIDs: [NotificationID] = [] - public var markAsReadCallCount = 0 - public var markAsReadResult: Result? - - public func markAsRead( - id: NotificationID - ) async throws(RepositoryError) { - markAsReadCallCount += 1 - markedIDs.append(id) - - if let markAsReadResult { - switch markAsReadResult { - case .success: - return - case .failure(let error): - throw error - } - } + public func markAsRead(id: NotificationID) async throws(RepositoryError) { + throw .unknown } - // MARK: - loadUnreadNotificationStatus - - public var loadUnreadStatusCallCount = 0 - public var loadUnreadStatusResult: Result? - - public func loadUnreadNotificationStatus( - ) async throws(RepositoryError) -> UnreadNotificationStatus { - loadUnreadStatusCallCount += 1 - - guard let loadUnreadStatusResult else { - fatalError("loadUnreadStatusResult is not set") - } - - switch loadUnreadStatusResult { - case .success(let value): return value - case .failure(let error): throw error - } + public func loadUnreadNotificationStatus() async throws(RepositoryError) -> UnreadNotificationStatus { + throw .unknown } - - public init() {} } diff --git a/Projects/Domain/NotificationDomain/Testing/Mock/MockNovelNotificationRepository.swift b/Projects/Domain/NotificationDomain/Testing/Mock/MockNovelNotificationRepository.swift index 57d27efeb..1f882cf91 100644 --- a/Projects/Domain/NotificationDomain/Testing/Mock/MockNovelNotificationRepository.swift +++ b/Projects/Domain/NotificationDomain/Testing/Mock/MockNovelNotificationRepository.swift @@ -11,105 +11,35 @@ import Foundation import NotificationDomain import BaseDomain -public final class MockNovelNotificationRepository: NovelNotificationRepository { +/// 작품 알림 저장소 가짜 객체(Stub) — 호출을 기록하지 않는다. +/// 구독 목록 조회는 **요청 개수마다** 답을 정해 둔다 — 정해 두지 않은 개수엔 빈 페이지를 준다. +/// 그래서 UseCase가 개수를 잘못 넘기면 결과가 달라진다. +/// 나머지 메서드는 이 모듈 테스트가 쓰지 않아 항상 `.unknown`을 던진다. +public final class MockNovelNotificationRepository: NovelNotificationRepository, @unchecked Sendable { + public var pagesBySize: [Int: PagedNovelNotificationSubscriptions] = [:] - // MARK: - loadSubscriptions - - public var loadedType: NovelNotificationType? - public var loadedLastSubscriptionID: SubscriptionID? - public var loadedSize: Int? - public var loadSubscriptionsCallCount = 0 - public var loadSubscriptionsResult: Result? + public init() {} public func loadSubscriptions( type: NovelNotificationType, lastSubscriptionID: SubscriptionID?, size: Int ) async throws(RepositoryError) -> PagedNovelNotificationSubscriptions { - loadSubscriptionsCallCount += 1 - loadedType = type - loadedLastSubscriptionID = lastSubscriptionID - loadedSize = size - - guard let loadSubscriptionsResult else { - fatalError("loadSubscriptionsResult is not set") - } - - switch loadSubscriptionsResult { - case .success(let value): return value - case .failure(let error): throw error - } + pagesBySize[size] ?? PagedNovelNotificationSubscriptions(subscriptions: [], isLoadable: false, nextSubscriptionID: nil) } - // MARK: - deleteSubscriptions - - public var deletedType: NovelNotificationType? - public var deletedNovelIDs: [NovelID]? - public var deleteSubscriptionsCallCount = 0 - public var deleteSubscriptionsResult: Result? - - public func deleteSubscriptions( - type: NovelNotificationType, - novelIDs: [NovelID] - ) async throws(RepositoryError) { - deleteSubscriptionsCallCount += 1 - deletedType = type - deletedNovelIDs = novelIDs - - if let deleteSubscriptionsResult { - switch deleteSubscriptionsResult { - case .success: - return - case .failure(let error): - throw error - } - } + public func deleteSubscriptions(type: NovelNotificationType, novelIDs: [NovelID]) async throws(RepositoryError) { + throw .unknown } - // MARK: - loadNotificationSetting - - public var loadedNovelID: NovelID? - public var loadNotificationSettingCallCount = 0 - public var loadNotificationSettingResult: Result? - public func loadNotificationSetting(novelID: NovelID) async throws(RepositoryError) -> NovelNotificationSetting { - loadNotificationSettingCallCount += 1 - loadedNovelID = novelID - - guard let loadNotificationSettingResult else { - fatalError("loadNotificationSettingResult is not set") - } - - switch loadNotificationSettingResult { - case .success(let value): return value - case .failure(let error): throw error - } + throw .unknown } - // MARK: - updateNotificationSetting - - public var updatedNovelID: NovelID? - public var updatedSetting: NovelNotificationSetting? - public var updateNotificationSettingCallCount = 0 - public var updateNotificationSettingResult: Result? - public func updateNotificationSetting( novelID: NovelID, setting: NovelNotificationSetting ) async throws(RepositoryError) { - updateNotificationSettingCallCount += 1 - updatedNovelID = novelID - updatedSetting = setting - - if let updateNotificationSettingResult { - switch updateNotificationSettingResult { - case .success: - return - case .failure(let error): - throw error - } - } + throw .unknown } - - public init() {} } diff --git a/Projects/Domain/NotificationDomain/Testing/Mock/MockPushSettingRepository.swift b/Projects/Domain/NotificationDomain/Testing/Mock/MockPushSettingRepository.swift deleted file mode 100644 index e05e262a7..000000000 --- a/Projects/Domain/NotificationDomain/Testing/Mock/MockPushSettingRepository.swift +++ /dev/null @@ -1,69 +0,0 @@ -// -// MockPushSettingRepository.swift -// NotificationDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation - -import NotificationDomain -import BaseDomain - -public final class MockPushSettingRepository: PushSettingRepository { - - // MARK: - Load - - public var loadCallCount = 0 - public var loadResult: Result? - - public func loadPushPreference() async throws(RepositoryError) -> PushPreference { - loadCallCount += 1 - guard let loadResult else { - fatalError("loadResult가 설정되지 않았습니다.") - } - switch loadResult { - case .success(let pref): return pref - case .failure(let err): throw err - } - } - - // MARK: - Update - - public var updateCallCount = 0 - public var lastUpdatedPreference: PushPreference? - public var updateResult: Result? - - public func updatePushPreference(_ preference: PushPreference) async throws(RepositoryError) { - updateCallCount += 1 - lastUpdatedPreference = preference - - if let updateResult { - switch updateResult { - case .success: return - case .failure(let err): throw err - } - } - } - - // MARK: - Register token - - public var registerCallCount = 0 - public var lastRegisteredToken: DevicePushToken? - public var registerResult: Result? - - public func registerDeviceToken(_ token: DevicePushToken) async throws(RepositoryError) { - registerCallCount += 1 - lastRegisteredToken = token - - if let registerResult { - switch registerResult { - case .success: return - case .failure(let err): throw err - } - } - } - - public init() {} -} diff --git a/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadNotificationDetailUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadNotificationDetailUseCaseTests.swift deleted file mode 100644 index f2755924a..000000000 --- a/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadNotificationDetailUseCaseTests.swift +++ /dev/null @@ -1,54 +0,0 @@ -// -// LoadNotificationDetailUseCaseTests.swift -// NotificationDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NotificationDomain -import NotificationDomainTesting -import BaseDomain - -@Suite("LoadNotificationDetailUseCase") -struct LoadNotificationDetailUseCaseTests { - - private func makeDetail() -> NotificationDetail { - return NotificationDetail( - title: "notificationTitle", - createdAtText: "2025.02.21", - body: "테스트 상세입니다.") - } - - @Test("주어진 알림 ID로 알림 상세를 조회한다") - func loadsDetailSuccessfully() async throws { - let repo = MockNotificationRepository() - let expected = makeDetail() - repo.loadDetailResult = .success(expected) - - let sut = DefaultLoadNotificationDetailUseCase(repository: repo) - - let id = NotificationID(3) - let result = try await sut.execute(id: id) - - #expect(repo.loadDetailCallCount == 1) - #expect(repo.loadedDetailID == id) - #expect(result == expected) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNotificationRepository() - repo.loadDetailResult = .failure(.serverUnavailable) - - let sut = DefaultLoadNotificationDetailUseCase(repository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - _ = try await sut.execute(id: NotificationID(3)) - } - - #expect(repo.loadDetailCallCount == 1) - } -} diff --git a/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadPagedNotificationsUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadPagedNotificationsUseCaseTests.swift index 6c016e2e3..4326f14e2 100644 --- a/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadPagedNotificationsUseCaseTests.swift +++ b/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadPagedNotificationsUseCaseTests.swift @@ -9,88 +9,64 @@ import Foundation import Testing -@testable import NotificationDomain -import NotificationDomainTesting import BaseDomain +import NotificationDomain +import NotificationDomainTesting -@Suite("LoadPagedNotificationsUseCase") +@Suite("알림 목록 불러오기") struct LoadPagedNotificationsUseCaseTests { - private func makeNotificationItem( - id: Int = 1, - isRead: Bool = false - ) -> NotificationItem { - NotificationItem( - id: NotificationID(id), - iconURL: URL(string: "https://example.com/icon.png"), - title: "테스트 알림 제목", - body: "테스트 알림 내용입니다.", - createdAtText: "2025.02.20", - isRead: isRead, - deeplink: makeDeeplink() - ) + @Test( + "개수를 0 이하로 요청하면 20개씩 불러온다", + arguments: [ + 0, // 경계 + -1 // 음수 + ] + ) + func nonPositiveSizeLoadsTwenty(size: Int) async throws { + let repository = MockNotificationRepository() + repository.pagesBySize[20] = page() + let useCase = DefaultLoadPagedNotificationsUseCase(repository: repository) + + let result = try await useCase.execute(lastNotificationID: nil, size: size) + + #expect(result == page()) } - private func makeDeeplink() -> NotificationDeeplink? { - // 프로젝트 정의에 맞게 수정 - // 예: feed 상세로 이동하는 딥링크 - return .feedDetail(id: FeedID(100)) + @Test( + "개수를 1 이상으로 요청하면 그 개수대로 불러온다", + arguments: [ + 1, // 경계 + 30 // 일반값 + ] + ) + func positiveSizeLoadsAsRequested(size: Int) async throws { + let repository = MockNotificationRepository() + repository.pagesBySize[size] = page() + let useCase = DefaultLoadPagedNotificationsUseCase(repository: repository) + + let result = try await useCase.execute(lastNotificationID: nil, size: size) + + #expect(result == page()) } - private func makePaged( - count: Int = 1, - isLoadable: Bool = true - ) -> PagedNotifications { - let items = (1...count).map { - makeNotificationItem(id: $0) - } - - return PagedNotifications( - items: items, - isLoadable: isLoadable + // MARK: - Helpers + + /// Stub이 그 개수에만 돌려주는 페이지 — 개수를 잘못 넘기면 빈 페이지가 와서 결과가 달라진다. + private func page() -> PagedNotifications { + PagedNotifications( + items: [ + NotificationItem( + id: NotificationID(1), + iconURL: nil, + title: "알림", + body: "내용", + createdAtText: "2026.11.19", + isRead: false, + deeplink: nil + ) + ], + isLoadable: true ) } - - @Test("lastID 이후의 알림 목록을 size 만큼 조회할 수 있다") - func loadsNotificationsWithParameters() async throws { - let repo = MockNotificationRepository() - repo.loadNotificationsResult = .success(makePaged()) - - let sut = DefaultLoadPagedNotificationsUseCase(repository: repo) - - let lastID = NotificationID(10) - _ = try await sut.execute(lastNotificationID: lastID, size: 30) - - #expect(repo.loadNotificationsCallCount == 1) - #expect(repo.loadedLastNotificationID == lastID) - #expect(repo.loadedSize == 30) - } - - @Test("size가 0 이하이면 기본 size(20)로 조회한다") - func usesDefaultSizeWhenNonPositive() async throws { - let repo = MockNotificationRepository() - repo.loadNotificationsResult = .success(makePaged()) - - let sut = DefaultLoadPagedNotificationsUseCase(repository: repo) - - _ = try await sut.execute(lastNotificationID: nil, size: 0) - #expect(repo.loadedSize == 20) - - _ = try await sut.execute(lastNotificationID: nil, size: -1) - #expect(repo.loadedSize == 20) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNotificationRepository() - repo.loadNotificationsResult = .failure(.networkUnavailable) - - let sut = DefaultLoadPagedNotificationsUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - _ = try await sut.execute(lastNotificationID: nil, size: 20) - } - - #expect(repo.loadNotificationsCallCount == 1) - } } diff --git a/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadUnreadNotificationStatusUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadUnreadNotificationStatusUseCaseTests.swift deleted file mode 100644 index ff69d159f..000000000 --- a/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/LoadUnreadNotificationStatusUseCaseTests.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// LoadUnreadNotificationStatusUseCaseTests.swift -// NotificationDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NotificationDomain -import NotificationDomainTesting -import BaseDomain - -@Suite("LoadUnreadNotificationStatusUseCase") -struct LoadUnreadNotificationStatusUseCaseTests { - - @Test("읽지 않은 알림 존재 여부를 조회한다") - func loadsUnreadStatusSuccessfully() async throws { - let repo = MockNotificationRepository() - let expected = UnreadNotificationStatus(hasUnreadNotifications: true) - repo.loadUnreadStatusResult = .success(expected) - - let sut = DefaultLoadUnreadNotificationStatusUseCase(repository: repo) - - let result = try await sut.execute() - - #expect(repo.loadUnreadStatusCallCount == 1) - #expect(result == expected) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNotificationRepository() - repo.loadUnreadStatusResult = .failure(.unknown) - - let sut = DefaultLoadUnreadNotificationStatusUseCase(repository: repo) - - await #expect(throws: RepositoryError.self) { - _ = try await sut.execute() - } - - #expect(repo.loadUnreadStatusCallCount == 1) - } -} diff --git a/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/MarkNotificationAsReadUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/MarkNotificationAsReadUseCaseTests.swift deleted file mode 100644 index f2ef5d40a..000000000 --- a/Projects/Domain/NotificationDomain/Tests/Notification/UseCase/MarkNotificationAsReadUseCaseTests.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// MarkNotificationAsReadUseCaseTests.swift -// NotificationDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NotificationDomain -import NotificationDomainTesting -import BaseDomain - -@Suite("MarkNotificationAsReadUseCase") -struct MarkNotificationAsReadUseCaseTests { - - @Test("주어진 알림 ID를 읽음 처리한다") - func marksAsReadSuccessfully() async throws { - let repo = MockNotificationRepository() - repo.markAsReadResult = .success(()) - - let sut = DefaultMarkNotificationAsReadUseCase(repository: repo) - - let id = NotificationID(7) - try await sut.execute(id: id) - - #expect(repo.markAsReadCallCount == 1) - #expect(repo.markedIDs == [id]) - } - - @Test("읽음 처리 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNotificationRepository() - repo.markAsReadResult = .failure(.authenticationRequired) - - let sut = DefaultMarkNotificationAsReadUseCase(repository: repo) - - await #expect(throws: RepositoryError.authenticationRequired) { - try await sut.execute(id: NotificationID(7)) - } - - #expect(repo.markAsReadCallCount == 1) - } -} diff --git a/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/DeleteNovelNotificationSubscriptionsUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/DeleteNovelNotificationSubscriptionsUseCaseTests.swift deleted file mode 100644 index a2410ce83..000000000 --- a/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/DeleteNovelNotificationSubscriptionsUseCaseTests.swift +++ /dev/null @@ -1,47 +0,0 @@ -// -// DeleteNovelNotificationSubscriptionsUseCaseTests.swift -// NotificationDomain -// -// Created by Guryss on 8/17/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import NotificationDomain -import NotificationDomainTesting -import BaseDomain - -@Suite("DeleteNovelNotificationSubscriptionsUseCase") -struct DeleteNovelNotificationSubscriptionsUseCaseTests { - - @Test("선택한 작품 ID 목록과 알림 타입을 그대로 레포지토리에 전달한다") - func deletesSubscriptionsWithParameters() async throws { - let repo = MockNovelNotificationRepository() - repo.deleteSubscriptionsResult = .success(()) - - let sut = DefaultDeleteNovelNotificationSubscriptionsUseCase(repository: repo) - - let novelIDs = [NovelID(1), NovelID(2)] - try await sut.execute(type: .completion, novelIDs: novelIDs) - - #expect(repo.deleteSubscriptionsCallCount == 1) - #expect(repo.deletedType == .completion) - #expect(repo.deletedNovelIDs == novelIDs) - } - - @Test("삭제 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNovelNotificationRepository() - repo.deleteSubscriptionsResult = .failure(.networkUnavailable) - - let sut = DefaultDeleteNovelNotificationSubscriptionsUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - try await sut.execute(type: .hiatusReturn, novelIDs: [NovelID(1)]) - } - - #expect(repo.deleteSubscriptionsCallCount == 1) - } -} diff --git a/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/LoadNovelNotificationSettingUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/LoadNovelNotificationSettingUseCaseTests.swift deleted file mode 100644 index 3b588135d..000000000 --- a/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/LoadNovelNotificationSettingUseCaseTests.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// LoadNovelNotificationSettingUseCaseTests.swift -// NotificationDomain -// -// Created by Guryss on 8/17/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import NotificationDomain -import NotificationDomainTesting -import BaseDomain - -@Suite("LoadNovelNotificationSettingUseCase") -struct LoadNovelNotificationSettingUseCaseTests { - - @Test("작품 ID로 완결·휴재복귀 알림 설정을 조회한다") - func loadsNotificationSetting() async throws { - let repo = MockNovelNotificationRepository() - let expected = NovelNotificationSetting( - isCompletionNotificationEnabled: true, - isHiatusReturnNotificationEnabled: false - ) - repo.loadNotificationSettingResult = .success(expected) - - let sut = DefaultLoadNovelNotificationSettingUseCase(repository: repo) - - let novelID = NovelID(1) - let result = try await sut.execute(novelID: novelID) - - #expect(result == expected) - #expect(repo.loadNotificationSettingCallCount == 1) - #expect(repo.loadedNovelID == novelID) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNovelNotificationRepository() - repo.loadNotificationSettingResult = .failure(.networkUnavailable) - - let sut = DefaultLoadNovelNotificationSettingUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - _ = try await sut.execute(novelID: NovelID(1)) - } - - #expect(repo.loadNotificationSettingCallCount == 1) - } -} diff --git a/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/LoadNovelNotificationSubscriptionsUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/LoadNovelNotificationSubscriptionsUseCaseTests.swift index fd851acc2..0fd5cc72a 100644 --- a/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/LoadNovelNotificationSubscriptionsUseCaseTests.swift +++ b/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/LoadNovelNotificationSubscriptionsUseCaseTests.swift @@ -9,77 +9,64 @@ import Foundation import Testing -@testable import NotificationDomain -import NotificationDomainTesting import BaseDomain +import NotificationDomain +import NotificationDomainTesting -@Suite("LoadNovelNotificationSubscriptionsUseCase") +@Suite("작품 알림 구독 목록 불러오기") struct LoadNovelNotificationSubscriptionsUseCaseTests { - private func makeSubscription(id: Int = 1) -> NovelNotificationSubscription { - NovelNotificationSubscription( - id: SubscriptionID(id), - novelID: NovelID(id), - novelTitle: "테스트 작품 \(id)", - novelThumbnailImage: URL(string: "https://image.websoso.kr/novel/\(id).jpg"), - novelAuthor: "테스트 작가", - registeredDateText: "2026.08.06" - ) - } - - private func makePaged( - count: Int = 1, - isLoadable: Bool = true, - nextSubscriptionID: SubscriptionID? = nil - ) -> PagedNovelNotificationSubscriptions { - PagedNovelNotificationSubscriptions( - subscriptions: (1...count).map { makeSubscription(id: $0) }, - isLoadable: isLoadable, - nextSubscriptionID: nextSubscriptionID - ) + @Test( + "개수를 0 이하로 요청하면 20개씩 불러온다", + arguments: [ + 0, // 경계 + -1 // 음수 + ] + ) + func nonPositiveSizeLoadsTwenty(size: Int) async throws { + let repository = MockNovelNotificationRepository() + repository.pagesBySize[20] = page() + let useCase = DefaultLoadNovelNotificationSubscriptionsUseCase(repository: repository) + + let result = try await useCase.execute(type: .completion, lastSubscriptionID: nil, size: size) + + #expect(result == page()) } - @Test("완결·휴재복귀 타입과 lastSubscriptionID·size를 그대로 레포지토리에 전달한다") - func loadsSubscriptionsWithParameters() async throws { - let repo = MockNovelNotificationRepository() - repo.loadSubscriptionsResult = .success(makePaged()) - - let sut = DefaultLoadNovelNotificationSubscriptionsUseCase(repository: repo) - - let lastID = SubscriptionID(10) - _ = try await sut.execute(type: .hiatusReturn, lastSubscriptionID: lastID, size: 30) - - #expect(repo.loadSubscriptionsCallCount == 1) - #expect(repo.loadedType == .hiatusReturn) - #expect(repo.loadedLastSubscriptionID == lastID) - #expect(repo.loadedSize == 30) + @Test( + "개수를 1 이상으로 요청하면 그 개수대로 불러온다", + arguments: [ + 1, // 경계 + 30 // 일반값 + ] + ) + func positiveSizeLoadsAsRequested(size: Int) async throws { + let repository = MockNovelNotificationRepository() + repository.pagesBySize[size] = page() + let useCase = DefaultLoadNovelNotificationSubscriptionsUseCase(repository: repository) + + let result = try await useCase.execute(type: .completion, lastSubscriptionID: nil, size: size) + + #expect(result == page()) } - @Test("size가 0 이하이면 기본 size(20)로 조회한다") - func usesDefaultSizeWhenNonPositive() async throws { - let repo = MockNovelNotificationRepository() - repo.loadSubscriptionsResult = .success(makePaged()) + // MARK: - Helpers - let sut = DefaultLoadNovelNotificationSubscriptionsUseCase(repository: repo) - - _ = try await sut.execute(type: .completion, lastSubscriptionID: nil, size: 0) - #expect(repo.loadedSize == 20) - - _ = try await sut.execute(type: .completion, lastSubscriptionID: nil, size: -1) - #expect(repo.loadedSize == 20) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNovelNotificationRepository() - repo.loadSubscriptionsResult = .failure(.networkUnavailable) - - let sut = DefaultLoadNovelNotificationSubscriptionsUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - _ = try await sut.execute(type: .completion, lastSubscriptionID: nil, size: 20) - } - - #expect(repo.loadSubscriptionsCallCount == 1) + /// Stub이 그 개수에만 돌려주는 페이지 — 개수를 잘못 넘기면 빈 페이지가 와서 결과가 달라진다. + private func page() -> PagedNovelNotificationSubscriptions { + PagedNovelNotificationSubscriptions( + subscriptions: [ + NovelNotificationSubscription( + id: SubscriptionID(1), + novelID: NovelID(1), + novelTitle: "작품", + novelThumbnailImage: nil, + novelAuthor: "작가", + registeredDateText: "2026.11.19" + ) + ], + isLoadable: true, + nextSubscriptionID: SubscriptionID(2) + ) } } diff --git a/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/UpdateNovelNotificationSettingUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/UpdateNovelNotificationSettingUseCaseTests.swift deleted file mode 100644 index 9536cabd1..000000000 --- a/Projects/Domain/NotificationDomain/Tests/NovelNotification/UseCase/UpdateNovelNotificationSettingUseCaseTests.swift +++ /dev/null @@ -1,56 +0,0 @@ -// -// UpdateNovelNotificationSettingUseCaseTests.swift -// NotificationDomain -// -// Created by Guryss on 8/17/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import NotificationDomain -import NotificationDomainTesting -import BaseDomain - -@Suite("UpdateNovelNotificationSettingUseCase") -struct UpdateNovelNotificationSettingUseCaseTests { - - @Test("작품 ID와 갱신할 알림 설정을 그대로 레포지토리에 전달한다") - func updatesNotificationSetting() async throws { - let repo = MockNovelNotificationRepository() - repo.updateNotificationSettingResult = .success(()) - - let sut = DefaultUpdateNovelNotificationSettingUseCase(repository: repo) - - let novelID = NovelID(1) - let setting = NovelNotificationSetting( - isCompletionNotificationEnabled: true, - isHiatusReturnNotificationEnabled: true - ) - try await sut.execute(novelID: novelID, setting: setting) - - #expect(repo.updateNotificationSettingCallCount == 1) - #expect(repo.updatedNovelID == novelID) - #expect(repo.updatedSetting == setting) - } - - @Test("갱신 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockNovelNotificationRepository() - repo.updateNotificationSettingResult = .failure(.networkUnavailable) - - let sut = DefaultUpdateNovelNotificationSettingUseCase(repository: repo) - - let setting = NovelNotificationSetting( - isCompletionNotificationEnabled: false, - isHiatusReturnNotificationEnabled: false - ) - - await #expect(throws: RepositoryError.networkUnavailable) { - try await sut.execute(novelID: NovelID(1), setting: setting) - } - - #expect(repo.updateNotificationSettingCallCount == 1) - } -} diff --git a/Projects/Domain/NotificationDomain/Tests/Push/UseCase/LoadPushPreferenceUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/Push/UseCase/LoadPushPreferenceUseCaseTests.swift deleted file mode 100644 index 638f88810..000000000 --- a/Projects/Domain/NotificationDomain/Tests/Push/UseCase/LoadPushPreferenceUseCaseTests.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// LoadPushPreferenceUseCaseTests.swift -// NotificationDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NotificationDomain -import NotificationDomainTesting -import BaseDomain - -@Suite("LoadPushPreferenceUseCase") -struct LoadPushPreferenceUseCaseTests { - - private func makePreference() -> PushPreference { - return PushPreference(isEnabled: false) - } - - @Test("푸시 알림 수신 여부를 조회할 수 있다") - func loadsPushPreferenceSuccessfully() async throws { - let repo = MockPushSettingRepository() - let expected = makePreference() - repo.loadResult = .success(expected) - - let sut = DefaultLoadPushPreferenceUseCase(repository: repo) - - let result = try await sut.execute() - - #expect(repo.loadCallCount == 1) - #expect(result == expected) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockPushSettingRepository() - repo.loadResult = .failure(.networkUnavailable) - - let sut = DefaultLoadPushPreferenceUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - _ = try await sut.execute() - } - - #expect(repo.loadCallCount == 1) - } -} diff --git a/Projects/Domain/NotificationDomain/Tests/Push/UseCase/RegisterDeviceTokenUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/Push/UseCase/RegisterDeviceTokenUseCaseTests.swift deleted file mode 100644 index a8633587e..000000000 --- a/Projects/Domain/NotificationDomain/Tests/Push/UseCase/RegisterDeviceTokenUseCaseTests.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// RegisterDeviceTokenUseCaseTests.swift -// NotificationDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NotificationDomain -import NotificationDomainTesting -import BaseDomain - -@Suite("RegisterDeviceTokenUseCase") -struct RegisterDeviceTokenUseCaseTests { - - private func makeToken() -> DevicePushToken { - return DevicePushToken(token: "fcm_token", deviceID: "device_id") - } - - @Test("디바이스 푸시 토큰을 등록할 수 있다") - func registersDeviceTokenSuccessfully() async throws { - let repo = MockPushSettingRepository() - repo.registerResult = .success(()) - - let sut = DefaultRegisterDeviceTokenUseCase(repository: repo) - let token = makeToken() - - try await sut.execute(devicePushToken: token) - - #expect(repo.registerCallCount == 1) - #expect(repo.lastRegisteredToken == token) - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockPushSettingRepository() - repo.registerResult = .failure(.authenticationRequired) - - let sut = DefaultRegisterDeviceTokenUseCase(repository: repo) - - await #expect(throws: RepositoryError.authenticationRequired) { - try await sut.execute(devicePushToken: makeToken()) - } - - #expect(repo.registerCallCount == 1) - } -} diff --git a/Projects/Domain/NotificationDomain/Tests/Push/UseCase/UpdatePushPreferenceUseCaseTests.swift b/Projects/Domain/NotificationDomain/Tests/Push/UseCase/UpdatePushPreferenceUseCaseTests.swift deleted file mode 100644 index bf32954aa..000000000 --- a/Projects/Domain/NotificationDomain/Tests/Push/UseCase/UpdatePushPreferenceUseCaseTests.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// UpdatePushPreferenceUseCaseTests.swift -// NotificationDomain -// -// Created by YunhakLee on 2/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NotificationDomain -import NotificationDomainTesting -import BaseDomain - -@Suite("UpdatePushPreferenceUseCase") -struct UpdatePushPreferenceUseCaseTests { - - private func makePreference() -> PushPreference { - return PushPreference(isEnabled: true) - } - - @Test("푸시 알림 수신 여부를 변경할 수 있다") - func updatesPushPreferenceSuccessfully() async throws { - let repo = MockPushSettingRepository() - repo.updateResult = .success(()) - - let sut = DefaultUpdatePushPreferenceUseCase(repository: repo) - let pref = makePreference() - - try await sut.execute(pushPreference: pref) - - #expect(repo.updateCallCount == 1) - #expect(repo.lastUpdatedPreference == pref) - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockPushSettingRepository() - repo.updateResult = .failure(.serverUnavailable) - - let sut = DefaultUpdatePushPreferenceUseCase(repository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - try await sut.execute(pushPreference: makePreference()) - } - - #expect(repo.updateCallCount == 1) - } -} diff --git a/Projects/Domain/NovelDomain/CLAUDE.md b/Projects/Domain/NovelDomain/CLAUDE.md index 5a8a39560..a6c737334 100644 --- a/Projects/Domain/NovelDomain/CLAUDE.md +++ b/Projects/Domain/NovelDomain/CLAUDE.md @@ -31,8 +31,8 @@ - **내 서재 필터·정렬 로컬 영속화(#221)는 `NovelRepository`가 아니라 별도 계약 `MyLibraryFilterRepository`** (`Load/SaveMyLibraryFilterUseCase`가 감싼다)에 있다. **분리한 이유**: ① 순수 로컬 저장이라 서버·userID와 무관해 `NovelRepository`(네트워크)와 관심사가 다르고, ② 큰 `NovelRepository`에 얹으면 그걸 목킹하는 6곳 - (Testing Mock·Demo 4곳·App)이 전부 새 메서드를 구현해야 한다 — 별 계약이면 새 목 하나(`MockMyLibraryFilterRepository`)만 - 추가된다. ⚠️ **이 두 UseCase/Repository는 `async throws`가 아니라 동기·비-throwing이다** — 복원을 + (Testing Mock·Demo 4곳·App)이 전부 새 메서드를 구현해야 한다 — 별 계약이면 그 구현만 따로 두면 된다 + (넘기기만 하는 두 UseCase라 테스트가 없어 #308에서 `MockMyLibraryFilterRepository`는 지웠다). ⚠️ **이 두 UseCase/Repository는 `async throws`가 아니라 동기·비-throwing이다** — 복원을 ViewModel `init`에서 동기로 해야 첫 로드가 복원된 필터로 나가서다(이유 정본은 [LibraryFeature](../../Feature/LibraryFeature/CLAUDE.md)). Sendable 프로토콜이라 `Default*UseCase`는 `final class`(다른 UseCase와 동일 규칙). 구현·저장 포맷은 `NovelData`. - `fetchMyLibraryNovels`/`fetchRegisteredNovelStats`는 **로그인 사용자 기준** (구현체가 저장된 userID 사용). 타 사용자 조회는 `fetchUserLibraryNovels(id:_:)` / `fetchUserRegisteredNovelStats(id:)` 별도 — Repository에 "내" 버전과 "유저" 버전이 쌍으로 존재하는 게 이 모듈의 고정 패턴이니, 서재 관련 조회를 새로 추가할 땐 이 쌍을 먼저 따라간다. @@ -54,3 +54,4 @@ - **`MyLibraryFilter.clearAll()`(시트 "초기화")은 시트 필터 6종만 리셋** — 관심(isInterest)·정렬(sortType)은 시트 소속이 아니라 유지된다. - **연재상태(`publicationStatus`)가 단일 선택인 건 의도된 설계** — 서버 쿼리가 `isCompleted: Bool?` **하나뿐**이라 애초에 "연재중+완결작"을 표현할 수단이 없다. 구 WSSiOS는 이걸 배열로 들고 UI에서 둘 다 켤 수 있게 해뒀지만, Repository가 `count == 1`일 때만 파라미터를 실어서 **둘 다 고르면 필터가 통째로 무시**됐다(칩은 2개인데 결과는 전체). V1이 다중이라는 이유로 배열로 되돌리지 말 것. - 서재 정렬은 공용 `SortType`(2종)이 아니라 **서재 전용 `LibrarySortType`(6종)** — 내 서재·타유저 서재 **둘 다** 이걸 쓴다(같은 V2 엔드포인트라 서버가 받는 정렬 문자열이 같다). 공용 `SortType`을 쓰던 구 `LibraryFilter`는 #166에서 `LibrarySortType`으로 전환했다. +- **`MockNovelRepository`는 "넘겨받은 키워드 캐시마다" 답을 정해 둔다**(#308) — 작품 상세·서재 조회는 `Set`를 키로 답을 찾고, 없으면 `.notFound`를 던진다. 그래서 "모든 그룹의 키워드를 넘긴다"·"키워드를 못 불러오면 빈 키워드로"를 호출 기록 없이 결과로 확인한다. 키워드 쪽은 BaseDomain의 `MockLoadTotalKeywordsUseCase`를 쓴다(동기화·재조회는 그 UseCase의 일이라 여기서 다시 보지 않는다). diff --git a/Projects/Domain/NovelDomain/Project.swift b/Projects/Domain/NovelDomain/Project.swift index 5ff87f9eb..05f371e5a 100644 --- a/Projects/Domain/NovelDomain/Project.swift +++ b/Projects/Domain/NovelDomain/Project.swift @@ -13,6 +13,6 @@ let project = Project.createDomainModule( name: ModuleType.domain(.novel).name, targets: [.sources, .testing, .tests], internalDependencies: [.module(.domain(.base))], - // LoadNovelUseCase 테스트가 BaseDomain의 MockKeywordRepository를 재사용한다. + // 키워드를 붙여 불러오는 UseCase 테스트가 BaseDomain의 MockLoadTotalKeywordsUseCase를 쓴다. testDependencies: [.module(.domain(.base), type: .testing)] ) diff --git a/Projects/Domain/NovelDomain/TEST_SPEC.md b/Projects/Domain/NovelDomain/TEST_SPEC.md new file mode 100644 index 000000000..cdf30c338 --- /dev/null +++ b/Projects/Domain/NovelDomain/TEST_SPEC.md @@ -0,0 +1,145 @@ +# NovelDomain 테스트 명세 + + + +## 다른 사람 서재 필터 + +`Tests/Entity/LibraryFilterTests.swift` + +- 다른 사람 서재의 초기 정렬 타입은 등록 최신순이다 +- 다른 사람 서재의 정렬 타입을 변경할 수 있다 + +## 서재 요청 개수 + +`Tests/Entity/LibraryPageSizePolicyTests.swift` + +### 다시 들어올 때 보던 만큼 받기 + +- 보던 개수만큼 다시 요청한다 +- 아직 한 페이지를 다 받지 못했으면 한 페이지(15개)를 요청한다 + - `0` — 아무것도 못 받음 + - `14` — 한 페이지에서 하나 모자람 +- 보던 개수가 100개를 넘으면 100개에서 자른다 + - `100` — 딱 상한 + - `101` — 상한에서 하나 넘음 + +### 그사이 늘어난 만큼 더 받기 + +- 비운 사이 늘어난 만큼만 이어서 요청한다 + - `(26, 1)` — 1개 늘어남(이어 받는 가장 작은 경우) + - `(27, 2)` — 2개 늘어남 +- 늘지 않았거나 줄었으면 이어서 요청하지 않는다 + - `25` — 그대로(0개 늘어남) + - `22` — 3개 줄어듦 +- 다음 페이지가 없으면 늘었어도 이어서 요청하지 않는다 +- 늘어난 개수가 100개를 넘으면 100개에서 자른다 + - `110` — 100개 늘어남(딱 상한) + - `111` — 101개 늘어남(상한에서 하나 넘음) + +## 내 서재 필터 + +`Tests/Entity/MyLibraryFilterTests.swift` + +### 관심 + +- 내 서재의 관심 필터는 처음에 꺼져 있다 +- 관심은 누를 때마다 켜지고 꺼진다 + - `(false, true)` — 꺼져 있으면 켜진다 + - `(true, false)` — 켜져 있으면 꺼진다 + +### 독서 상태 + +- 독서 상태를 고르면 담긴다 +- 이미 고른 독서 상태를 또 고르면 그대로다 +- 고른 독서 상태를 빼면 사라진다 + +### 장르 + +- 장르를 고르면 담긴다 +- 이미 고른 장르를 또 고르면 그대로다 +- 고른 장르를 빼면 사라진다 + +### 매력 포인트 + +- 매력 포인트를 고르면 담긴다 +- 이미 고른 매력 포인트를 또 고르면 그대로다 +- 고른 매력 포인트를 빼면 사라진다 + +### 키워드 + +- 키워드를 고르면 담긴다 +- 이미 고른 키워드를 또 고르면 그대로다 +- 고른 키워드를 빼면 사라진다 + +### 연재 상태 + +- 연재 상태는 하나만 고를 수 있어 새로 고르면 바뀐다 +- 연재 상태 선택을 해제하면 아무것도 선택되지 않은 상태가 된다 + +### 별점 + +- 고른 별점 범위가 담긴다 + - `(1.0, 3.0)` — 보통 범위 + - `(2.0, 2.0)` — 최소와 최대가 같아도 범위다 +- 별점 범위가 0점에서 5점 밖이면 안으로 맞춘다 + - `(-1, 3, 0, 3)` — 최소가 0점 아래 + - `(1, 6, 1, 5)` — 최대가 5점 위 +- 최소가 최대보다 크면 받지 않고 이전 별점 범위를 지킨다 +- 0점에서 5점 전체를 고르면 별점 필터가 없다 + - `(0, 5)` — 딱 전체 범위 + - `(-1, 6)` — 안으로 맞추면 전체 범위가 된다 +- 별점 없는 작품만 보기를 고르면 별점 범위 대신 걸린다 +- 별점 필터를 해제하면 아무 별점 범위도 선택되지 않은 상태가 된다 + +### 정렬 + +- 내 서재의 초기 정렬 타입은 등록 최신순이다 +- 내 서재의 정렬 타입을 변경할 수 있다 + +### 초기화 + +- 초기화하면 시트 필터(독서 상태·장르·연재 상태·별점·매력 포인트·키워드)를 모두 비운다 +- 초기화해도 관심과 정렬은 그대로 둔다 + +### 필터 표시 + +- 시트 필터 중 하나라도 걸리면 필터가 걸린 상태다 + - `MyLibraryFilter(readingStatus: [.watching])` — 독서 상태 + - `MyLibraryFilter(genres: [.fantasy])` — 장르 + - `MyLibraryFilter(publicationStatus: .completed)` — 연재 상태 + - `MyLibraryFilter(rating: .unratedOnly)` — 별점 + - `MyLibraryFilter(attractivePoint: [.worldview])` — 매력 포인트 + - `MyLibraryFilter(keywords: [regression])` — 키워드 +- 관심이나 정렬만 바꿨으면 필터가 걸린 상태가 아니다 + +## 작품 상세의 대표 독서 상태 + +`Tests/Entity/NovelInformationTests.swift` + +- 읽은 사람이 없으면 대표 독서 상태가 없다 + - `[:]` — 독서 상태 수가 비어 있음 + - `[.watching: 0, .watched: 0, .quit: 0]` — 모두 0명 +- 가장 많이 고른 독서 상태가 대표가 된다 +- 한 명만 골랐어도 그 독서 상태가 대표가 된다 +- 수가 같으면 보는 중, 봤음, 하차 순으로 대표를 정한다 + - `([.watching: 6, .watched: 6, .quit: 4], .watching)` — 보는 중 = 봤음이면 보는 중 + - `([.watching: 2, .watched: 6, .quit: 6], .watched)` — 봤음 = 하차면 봤음 + +## 작품의 키워드 알아보기 + +`Tests/UseCase/NovelKeywordLookupTests.swift` + +### 작품 상세 + +- 작품 상세를 불러올 때 모든 카테고리의 키워드를 넘긴다 +- 전체 키워드를 못 불러와도 작품 상세는 불러온다 + +### 내 서재 + +- 내 서재를 불러올 때 모든 카테고리의 키워드를 넘긴다 +- 전체 키워드를 못 불러와도 내 서재 목록은 불러온다 + +### 다른 사람 서재 + +- 다른 사람 서재를 불러올 때 모든 카테고리의 키워드를 넘긴다 +- 전체 키워드를 못 불러와도 다른 사람 서재 목록은 불러온다 diff --git a/Projects/Domain/NovelDomain/Testing/Mock/MockMyLibraryFilterRepository.swift b/Projects/Domain/NovelDomain/Testing/Mock/MockMyLibraryFilterRepository.swift deleted file mode 100644 index 88493238e..000000000 --- a/Projects/Domain/NovelDomain/Testing/Mock/MockMyLibraryFilterRepository.swift +++ /dev/null @@ -1,33 +0,0 @@ -// -// MockMyLibraryFilterRepository.swift -// NovelDomain -// -// Created by YunhakLee on 8/31/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation - -import NovelDomain -import BaseDomain - -public final class MockMyLibraryFilterRepository: MyLibraryFilterRepository { - - public var storedFilter: MyLibraryFilter? - public private(set) var savedFilters: [MyLibraryFilter] = [] - public private(set) var loadCallCount = 0 - - public init(storedFilter: MyLibraryFilter? = nil) { - self.storedFilter = storedFilter - } - - public func loadFilter() -> MyLibraryFilter? { - loadCallCount += 1 - return storedFilter - } - - public func saveFilter(_ filter: MyLibraryFilter) { - savedFilters.append(filter) - storedFilter = filter - } -} diff --git a/Projects/Domain/NovelDomain/Testing/Mock/MockNovelRepository.swift b/Projects/Domain/NovelDomain/Testing/Mock/MockNovelRepository.swift index fc47a268c..461f1a5bd 100644 --- a/Projects/Domain/NovelDomain/Testing/Mock/MockNovelRepository.swift +++ b/Projects/Domain/NovelDomain/Testing/Mock/MockNovelRepository.swift @@ -11,50 +11,26 @@ import Foundation import NovelDomain import BaseDomain +/// 작품 저장소 가짜 객체. +/// 조회는 정해 둔 값만 돌려주고 호출을 기록하지 않는다(Stub). +/// 작품 상세·서재 조회는 **넘겨받은 키워드 캐시마다** 답을 정해 둔다 — 정해 두지 않은 캐시로 부르면 `.notFound`를 던진다. +/// 그래서 UseCase가 키워드를 잘못 넘기면 결과가 달라진다. 키워드 순서는 따지지 않는다(`Set`). +/// 나머지 조회와 관심 추가·해제(명령)는 쓰는 테스트가 없어 답을 정해 두지 않는다 — 필요해지면 그때 더한다. public final class MockNovelRepository: NovelRepository { - - public var fetchNovelResult: Result! - public var addInterestResult: Result = .success(()) - public var removeInterestResult: Result = .success(()) - public var fetchMyLibraryResult: Result<(CursorPaginated, Int), RepositoryError>! - public var fetchUserLibraryResult: Result<(CursorPaginated, Int), RepositoryError>! - public var fetchMyLibraryKeywordsResult: Result<[Keyword], RepositoryError>! - public var fetchRegisteredNovelStatsResult: Result! - public var fetchUserRegisteredNovelStatsResult: Result! - - public private(set) var fetchedNovelIDs: [NovelID] = [] - public private(set) var lastCachedKeywords: [Keyword]? - public private(set) var addedInterestIDs: [NovelID] = [] - public private(set) var removedInterestIDs: [NovelID] = [] - public private(set) var fetchedMyLibraryFilters: [MyLibraryFilter] = [] - public private(set) var fetchedMyLibraryCursors: [String?] = [] - public private(set) var fetchedMyLibrarySizes: [Int] = [] - public private(set) var lastMyLibraryCachedKeywords: [Keyword]? - public private(set) var fetchedUserLibraryIDs: [UserID] = [] - public private(set) var fetchedUserLibraryFilters: [LibraryFilter] = [] - public private(set) var fetchedUserLibraryCursors: [String?] = [] - public private(set) var lastUserLibraryCachedKeywords: [Keyword]? - public private(set) var fetchMyLibraryKeywordsCallCount = 0 - public private(set) var fetchRegisteredNovelStatsCallCount = 0 - public private(set) var fetchedUserRegisteredNovelStatsIDs: [UserID] = [] + public var novelsByCachedKeywords: [Set: NovelInformation] = [:] + public var myLibraryByCachedKeywords: [Set: (CursorPaginated, Int)] = [:] + public var userLibraryByCachedKeywords: [Set: (CursorPaginated, Int)] = [:] public init() {} public func fetchNovel(id: NovelID, cachedKeywords: [Keyword]) async throws(RepositoryError) -> NovelInformation { - fetchedNovelIDs.append(id) - lastCachedKeywords = cachedKeywords - return try fetchNovelResult.get() + guard let novel = novelsByCachedKeywords[Set(cachedKeywords)] else { throw .notFound } + return novel } - public func addNovelInterest(id: NovelID) async throws(RepositoryError) { - addedInterestIDs.append(id) - try addInterestResult.get() - } + public func addNovelInterest(id: NovelID) async throws(RepositoryError) {} - public func removeNovelInterest(id: NovelID) async throws(RepositoryError) { - removedInterestIDs.append(id) - try removeInterestResult.get() - } + public func removeNovelInterest(id: NovelID) async throws(RepositoryError) {} public func fetchMyLibraryNovels( _ filter: MyLibraryFilter, @@ -62,16 +38,8 @@ public final class MockNovelRepository: NovelRepository { size: Int, cachedKeywords: [Keyword] ) async throws(RepositoryError) -> (CursorPaginated, Int) { - fetchedMyLibraryFilters.append(filter) - fetchedMyLibraryCursors.append(cursor) - fetchedMyLibrarySizes.append(size) - lastMyLibraryCachedKeywords = cachedKeywords - return try fetchMyLibraryResult.get() - } - - public func fetchMyLibraryKeywords() async throws(RepositoryError) -> [Keyword] { - fetchMyLibraryKeywordsCallCount += 1 - return try fetchMyLibraryKeywordsResult.get() + guard let page = myLibraryByCachedKeywords[Set(cachedKeywords)] else { throw .notFound } + return page } public func fetchUserLibraryNovels( @@ -80,20 +48,19 @@ public final class MockNovelRepository: NovelRepository { cursor: String?, cachedKeywords: [Keyword] ) async throws(RepositoryError) -> (CursorPaginated, Int) { - fetchedUserLibraryIDs.append(id) - fetchedUserLibraryFilters.append(filter) - fetchedUserLibraryCursors.append(cursor) - lastUserLibraryCachedKeywords = cachedKeywords - return try fetchUserLibraryResult.get() + guard let page = userLibraryByCachedKeywords[Set(cachedKeywords)] else { throw .notFound } + return page + } + + public func fetchMyLibraryKeywords() async throws(RepositoryError) -> [Keyword] { + throw .notFound } public func fetchRegisteredNovelStats() async throws(RepositoryError) -> RegisteredNovelStats { - fetchRegisteredNovelStatsCallCount += 1 - return try fetchRegisteredNovelStatsResult.get() + throw .notFound } public func fetchUserRegisteredNovelStats(id: UserID) async throws(RepositoryError) -> RegisteredNovelStats { - fetchedUserRegisteredNovelStatsIDs.append(id) - return try fetchUserRegisteredNovelStatsResult.get() + throw .notFound } } diff --git a/Projects/Domain/NovelDomain/Tests/Entity/LibraryFilterTests.swift b/Projects/Domain/NovelDomain/Tests/Entity/LibraryFilterTests.swift new file mode 100644 index 000000000..649f20069 --- /dev/null +++ b/Projects/Domain/NovelDomain/Tests/Entity/LibraryFilterTests.swift @@ -0,0 +1,31 @@ +// +// LibraryFilterTests.swift +// NovelDomain +// +// Created by YunhakLee on 11/19/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Testing + +import NovelDomain + +@Suite("다른 사람 서재 필터") +struct LibraryFilterTests { + + @Test("다른 사람 서재의 초기 정렬 타입은 등록 최신순이다") + func startsWithRegisteredNewest() { + let filter = LibraryFilter() + + #expect(filter.sortType == .registeredNewest) + } + + @Test("다른 사람 서재의 정렬 타입을 변경할 수 있다") + func keepsChangedSortType() { + var filter = LibraryFilter() + + filter.setSortType(.title) + + #expect(filter.sortType == .title) + } +} diff --git a/Projects/Domain/NovelDomain/Tests/Entity/LibraryPageSizePolicyTests.swift b/Projects/Domain/NovelDomain/Tests/Entity/LibraryPageSizePolicyTests.swift index 564e0e013..345804a38 100644 --- a/Projects/Domain/NovelDomain/Tests/Entity/LibraryPageSizePolicyTests.swift +++ b/Projects/Domain/NovelDomain/Tests/Entity/LibraryPageSizePolicyTests.swift @@ -8,92 +8,95 @@ import Testing -@testable import NovelDomain +import NovelDomain -@Suite +@Suite("서재 요청 개수") struct LibraryPageSizePolicyTests { - // MARK: - 기본 페이지 크기 + @Suite("다시 들어올 때 보던 만큼 받기") + struct Refresh { - @Test("서재 기본 요청 개수는 15개다") - func pageSizeIsFifteen() { - #expect(LibraryPageSizePolicy.pageSize == 15) - } - - // MARK: - 갱신 1차 크기 + @Test("보던 개수만큼 다시 요청한다") + func requestsLoadedCount() { + let size = LibraryPageSizePolicy.refreshSize(loadedCount: 47) - @Test("갱신은 보고 있던 개수만큼 요청한다") - func refreshRequestsLoadedCount() { - #expect(LibraryPageSizePolicy.refreshSize(loadedCount: 47) == 47) - } + #expect(size == 47) + } - @Test("아직 한 페이지도 못 받았으면 첫 페이지 크기로 요청한다") - func refreshFallsBackToPageSize() { - #expect(LibraryPageSizePolicy.refreshSize(loadedCount: 0) == LibraryPageSizePolicy.pageSize) - #expect(LibraryPageSizePolicy.refreshSize(loadedCount: 7) == LibraryPageSizePolicy.pageSize) - } - - @Test("보고 있던 개수가 서버 상한과 같으면 그대로 요청한다") - func refreshAtExactMaxSize() { - #expect( - LibraryPageSizePolicy.refreshSize(loadedCount: LibraryPageSizePolicy.maxSize) - == LibraryPageSizePolicy.maxSize + @Test( + "아직 한 페이지를 다 받지 못했으면 한 페이지(15개)를 요청한다", + arguments: [ + 0, // 아무것도 못 받음 + 14 // 한 페이지에서 하나 모자람 + ] ) - } + func requestsOnePageWhenLessThanPage(loadedCount: Int) { + let size = LibraryPageSizePolicy.refreshSize(loadedCount: loadedCount) + + #expect(size == 15) + } + + @Test( + "보던 개수가 100개를 넘으면 100개에서 자른다", + arguments: [ + 100, // 딱 상한 + 101 // 상한에서 하나 넘음 + ] + ) + func capsAt100(loadedCount: Int) { + let size = LibraryPageSizePolicy.refreshSize(loadedCount: loadedCount) - @Test("보고 있던 개수가 서버 상한을 넘으면 상한에서 자른다") - func refreshClampsToMaxSize() { - #expect(LibraryPageSizePolicy.refreshSize(loadedCount: 140) == LibraryPageSizePolicy.maxSize) + #expect(size == 100) + } } - // MARK: - 갱신 2차 크기 + @Suite("그사이 늘어난 만큼 더 받기") + struct FollowUp { - @Test("자리를 비운 사이 늘어난 만큼만 이어서 요청한다") - func followUpRequestsOnlyDelta() { - let size = LibraryPageSizePolicy.followUpSize( - previousTotalCount: 25, - newTotalCount: 27, - hasNext: true + @Test( + "비운 사이 늘어난 만큼만 이어서 요청한다", + arguments: [ + (26, 1), // 1개 늘어남(이어 받는 가장 작은 경우) + (27, 2) // 2개 늘어남 + ] ) - #expect(size == 2) - } + func requestsOnlyIncrease(newTotalCount: Int, expected: Int) { + let size = LibraryPageSizePolicy.followUpSize(previousTotalCount: 25, newTotalCount: newTotalCount, hasNext: true) + + #expect(size == expected) + } + + @Test( + "늘지 않았거나 줄었으면 이어서 요청하지 않는다", + arguments: [ + 25, // 그대로(0개 늘어남) + 22 // 3개 줄어듦 + ] + ) + func noFollowUpWithoutIncrease(newTotalCount: Int) { + let size = LibraryPageSizePolicy.followUpSize(previousTotalCount: 25, newTotalCount: newTotalCount, hasNext: true) - @Test("늘어난 작품이 없으면 이어서 요청하지 않는다") - func noFollowUpWhenNothingAdded() { - #expect(LibraryPageSizePolicy.followUpSize( - previousTotalCount: 25, - newTotalCount: 25, - hasNext: true - ) == nil) - } + #expect(size == nil) + } - @Test("작품이 줄었으면 이어서 요청하지 않는다") - func noFollowUpWhenDeleted() { - // 목록이 짧아질 이유가 없으므로 보정이 필요 없다. - #expect(LibraryPageSizePolicy.followUpSize( - previousTotalCount: 25, - newTotalCount: 22, - hasNext: true - ) == nil) - } + @Test("다음 페이지가 없으면 늘었어도 이어서 요청하지 않는다") + func noFollowUpWithoutNextPage() { + let size = LibraryPageSizePolicy.followUpSize(previousTotalCount: 25, newTotalCount: 27, hasNext: false) - @Test("다음 페이지가 없으면 늘어났어도 이어서 요청하지 않는다") - func noFollowUpWhenNoNextPage() { - // 1차 응답이 이미 끝까지 받은 경우 — 이어붙일 것이 없다. - #expect(LibraryPageSizePolicy.followUpSize( - previousTotalCount: 25, - newTotalCount: 27, - hasNext: false - ) == nil) - } + #expect(size == nil) + } - @Test("늘어난 개수가 서버 상한을 넘으면 상한에서 자른다") - func followUpClampsToMaxSize() { - let size = LibraryPageSizePolicy.followUpSize( - previousTotalCount: 10, - newTotalCount: 500, - hasNext: true + @Test( + "늘어난 개수가 100개를 넘으면 100개에서 자른다", + arguments: [ + 110, // 100개 늘어남(딱 상한) + 111 // 101개 늘어남(상한에서 하나 넘음) + ] ) - #expect(size == LibraryPageSizePolicy.maxSize) + func capsAt100(newTotalCount: Int) { + let size = LibraryPageSizePolicy.followUpSize(previousTotalCount: 10, newTotalCount: newTotalCount, hasNext: true) + + #expect(size == 100) + } } } diff --git a/Projects/Domain/NovelDomain/Tests/Entity/MyLibraryFilterTests.swift b/Projects/Domain/NovelDomain/Tests/Entity/MyLibraryFilterTests.swift index 20e5b2e4d..5b35950cd 100644 --- a/Projects/Domain/NovelDomain/Tests/Entity/MyLibraryFilterTests.swift +++ b/Projects/Domain/NovelDomain/Tests/Entity/MyLibraryFilterTests.swift @@ -8,314 +8,352 @@ import Testing -@testable import NovelDomain -import NovelDomainTesting import BaseDomain +import NovelDomain -@Suite -struct MyLibraryFilterTests { +private let regression = Keyword(id: KeywordID(11), name: "회귀") +private let possession = Keyword(id: KeywordID(12), name: "빙의") - // MARK: - Interest +@Suite("내 서재 필터") +struct MyLibraryFilterTests { - @Test("관심 필터를 토글하면 켜지고, 다시 토글하면 꺼진다") - func toggleInterest() { - var filter = makeFilter() + @Suite("관심") + struct Interest { - filter.toggleInterest() - #expect(filter.isInterest) + @Test("내 서재의 관심 필터는 처음에 꺼져 있다") + func startsWithInterestOff() { + let filter = MyLibraryFilter() - filter.toggleInterest() - #expect(!filter.isInterest) - } + #expect(!filter.isInterest) + } - // MARK: - ReadingStatus - - @Test("읽기 상태를 추가할 수 있다") - func addReadingStatus() { - var filter = makeFilter() + @Test( + "관심은 누를 때마다 켜지고 꺼진다", + arguments: [ + (false, true), // 꺼져 있으면 켜진다 + (true, false) // 켜져 있으면 꺼진다 + ] + ) + func togglesOnEachTap(isInterest: Bool, expected: Bool) { + var filter = MyLibraryFilter(isInterest: isInterest) - filter.addReadingStatus(.watching) + filter.toggleInterest() - #expect(filter.readingStatus == [.watching]) + #expect(filter.isInterest == expected) + } } - @Test("이미 추가된 읽기 상태는 중복 추가되지 않는다") - func addReadingStatusDuplicate() { - var filter = makeFilter(readingStatus: [.watching]) + @Suite("독서 상태") + struct ReadingStatusSelection { - filter.addReadingStatus(.watching) + @Test("독서 상태를 고르면 담긴다") + func addsStatus() { + var filter = MyLibraryFilter() - #expect(filter.readingStatus == [.watching]) - } + filter.addReadingStatus(.watching) - @Test("특정 읽기 상태를 제거할 수 있다") - func removeReadingStatus() { - var filter = makeFilter(readingStatus: [.watching, .watched]) + #expect(filter.readingStatus == [.watching]) + } - filter.removeReadingStatus(.watching) + @Test("이미 고른 독서 상태를 또 고르면 그대로다") + func ignoresDuplicateStatus() { + var filter = MyLibraryFilter(readingStatus: [.watching]) - #expect(filter.readingStatus == [.watched]) - } + filter.addReadingStatus(.watching) - // MARK: - Genre + #expect(filter.readingStatus == [.watching]) + } - @Test("장르를 추가할 수 있다") - func addGenre() { - var filter = makeFilter() + @Test("고른 독서 상태를 빼면 사라진다") + func removesStatus() { + var filter = MyLibraryFilter(readingStatus: [.watching, .watched]) - filter.addGenre(.fantasy) + filter.removeReadingStatus(.watching) - #expect(filter.genres == [.fantasy]) + #expect(filter.readingStatus == [.watched]) + } } - @Test("이미 추가된 장르는 중복 추가되지 않는다") - func addGenreDuplicate() { - var filter = makeFilter(genres: [.fantasy]) + @Suite("장르") + struct GenreSelection { - filter.addGenre(.fantasy) + @Test("장르를 고르면 담긴다") + func addsGenre() { + var filter = MyLibraryFilter() - #expect(filter.genres == [.fantasy]) - } + filter.addGenre(.fantasy) - @Test("특정 장르를 제거할 수 있다") - func removeGenre() { - var filter = makeFilter(genres: [.fantasy, .romance]) + #expect(filter.genres == [.fantasy]) + } - filter.removeGenre(.fantasy) + @Test("이미 고른 장르를 또 고르면 그대로다") + func ignoresDuplicateGenre() { + var filter = MyLibraryFilter(genres: [.fantasy]) - #expect(filter.genres == [.romance]) - } + filter.addGenre(.fantasy) - // MARK: - PublicationStatus + #expect(filter.genres == [.fantasy]) + } - @Test("연재 상태를 설정할 수 있다") - func setPublicationStatus() { - var filter = makeFilter() + @Test("고른 장르를 빼면 사라진다") + func removesGenre() { + var filter = MyLibraryFilter(genres: [.fantasy, .romance]) - filter.setPublicationStatus(.onGoing) + filter.removeGenre(.fantasy) - #expect(filter.publicationStatus == .onGoing) + #expect(filter.genres == [.romance]) + } } - @Test("연재 상태에 nil을 전달하면 해제된다") - func clearPublicationStatus() { - var filter = makeFilter(publicationStatus: .completed) + @Suite("매력 포인트") + struct AttractivePointSelection { - filter.setPublicationStatus(nil) + @Test("매력 포인트를 고르면 담긴다") + func addsAttractivePoint() { + var filter = MyLibraryFilter() - #expect(filter.publicationStatus == nil) - } + filter.addAttractivePoint(.worldview) - // MARK: - Rating (setRatingRange) + #expect(filter.attractivePoint == [.worldview]) + } - @Test("별점 범위를 설정할 수 있다") - func setRatingRange() { - var filter = makeFilter() + @Test("이미 고른 매력 포인트를 또 고르면 그대로다") + func ignoresDuplicateAttractivePoint() { + var filter = MyLibraryFilter(attractivePoint: [.worldview]) - filter.setRatingRange(min: 3.5, max: 4.0) + filter.addAttractivePoint(.worldview) - #expect(filter.rating == .range(min: 3.5, max: 4.0)) - } + #expect(filter.attractivePoint == [.worldview]) + } - @Test("별점 범위가 경계를 벗어나면 경계값으로 보정된다") - func setRatingRangeClampsToBounds() { - var filter = makeFilter() + @Test("고른 매력 포인트를 빼면 사라진다") + func removesAttractivePoint() { + var filter = MyLibraryFilter(attractivePoint: [.worldview, .character]) - filter.setRatingRange(min: -1.0, max: 4.0) + filter.removeAttractivePoint(.worldview) - #expect(filter.rating == .range(min: 0.0, max: 4.0)) + #expect(filter.attractivePoint == [.character]) + } } - @Test("min이 max보다 크면 별점 범위 설정이 무시된다") - func setRatingRangeIgnoresInvertedRange() { - var filter = makeFilter() - filter.setRatingRange(min: 3.5, max: 4.0) + @Suite("키워드") + struct KeywordSelection { - filter.setRatingRange(min: 4.5, max: 4.0) + @Test("키워드를 고르면 담긴다") + func addsKeyword() { + var filter = MyLibraryFilter() - #expect(filter.rating == .range(min: 3.5, max: 4.0)) - } + filter.addKeyword(regression) - @Test("전체 범위(0.0~5.0)를 설정하면 별점 필터가 없는 상태로 정규화된다") - func setRatingRangeFullRangeNormalizesToNil() { - var filter = makeFilter() - filter.setRatingRange(min: 3.5, max: 4.0) + #expect(filter.keywords == [regression]) + } - filter.setRatingRange(min: 0.0, max: 5.0) + @Test("이미 고른 키워드를 또 고르면 그대로다") + func ignoresDuplicateKeyword() { + var filter = MyLibraryFilter(keywords: [regression]) - #expect(filter.rating == nil) - } + filter.addKeyword(regression) - // MARK: - Rating (unratedOnly) + #expect(filter.keywords == [regression]) + } - @Test("별점 없음 필터를 설정하면 기존 범위 필터를 대체한다") - func setUnratedOnlyReplacesRange() { - var filter = makeFilter() - filter.setRatingRange(min: 3.5, max: 4.0) + @Test("고른 키워드를 빼면 사라진다") + func removesKeyword() { + var filter = MyLibraryFilter(keywords: [regression, possession]) - filter.setUnratedOnly() + filter.removeKeyword(regression) - #expect(filter.rating == .unratedOnly) + #expect(filter.keywords == [possession]) + } } - @Test("별점 필터를 해제할 수 있다") - func clearRating() { - var filter = makeFilter() - filter.setUnratedOnly() + @Suite("연재 상태") + struct PublicationStatusSelection { - filter.clearRating() + @Test("연재 상태는 하나만 고를 수 있어 새로 고르면 바뀐다") + func replacesStatus() { + var filter = MyLibraryFilter(publicationStatus: .onGoing) - #expect(filter.rating == nil) - } + filter.setPublicationStatus(.completed) - // MARK: - AttractivePoint + #expect(filter.publicationStatus == .completed) + } - @Test("매력 포인트를 추가할 수 있다") - func addAttractivePoint() { - var filter = makeFilter() + @Test("연재 상태 선택을 해제하면 아무것도 선택되지 않은 상태가 된다") + func clearsStatus() { + var filter = MyLibraryFilter(publicationStatus: .onGoing) - filter.addAttractivePoint(.worldview) + filter.setPublicationStatus(nil) - #expect(filter.attractivePoint == [.worldview]) + #expect(filter.publicationStatus == nil) + } } - @Test("이미 추가된 매력 포인트는 중복 추가되지 않는다") - func addAttractivePointDuplicate() { - var filter = makeFilter(attractivePoint: [.worldview]) - - filter.addAttractivePoint(.worldview) + @Suite("별점") + struct Rating { - #expect(filter.attractivePoint == [.worldview]) - } + @Test( + "고른 별점 범위가 담긴다", + arguments: [ + (1.0, 3.0), // 보통 범위 + (2.0, 2.0) // 최소와 최대가 같아도 범위다 + ] as [(Float, Float)] + ) + func keepsRange(min: Float, max: Float) { + var filter = MyLibraryFilter() - @Test("특정 매력 포인트를 제거할 수 있다") - func removeAttractivePoint() { - var filter = makeFilter(attractivePoint: [.worldview, .character]) + filter.setRatingRange(min: min, max: max) - filter.removeAttractivePoint(.worldview) + #expect(filter.rating == .range(min: min, max: max)) + } - #expect(filter.attractivePoint == [.character]) - } + @Test( + "별점 범위가 0점에서 5점 밖이면 안으로 맞춘다", + arguments: [ + (-1, 3, 0, 3), // 최소가 0점 아래 + (1, 6, 1, 5) // 최대가 5점 위 + ] as [(Float, Float, Float, Float)] + ) + func clampsIntoBounds(min: Float, max: Float, expectedMin: Float, expectedMax: Float) { + var filter = MyLibraryFilter() - // MARK: - Keyword + filter.setRatingRange(min: min, max: max) - @Test("키워드를 추가할 수 있다") - func addKeyword() { - var filter = makeFilter() - let keyword = makeKeyword(id: 1, name: "빙의") + #expect(filter.rating == .range(min: expectedMin, max: expectedMax)) + } - filter.addKeyword(keyword) + @Test("최소가 최대보다 크면 받지 않고 이전 별점 범위를 지킨다") + func rejectsInvertedRange() { + var filter = MyLibraryFilter(rating: .range(min: 1.0, max: 3.0)) - #expect(filter.keywords == [keyword]) - } + filter.setRatingRange(min: 4.0, max: 2.0) - @Test("이미 추가된 키워드는 중복 추가되지 않는다") - func addKeywordDuplicate() { - let keyword = makeKeyword(id: 1, name: "빙의") - var filter = makeFilter(keywords: [keyword]) + #expect(filter.rating == .range(min: 1.0, max: 3.0)) + } - filter.addKeyword(keyword) + @Test( + "0점에서 5점 전체를 고르면 별점 필터가 없다", + arguments: [ + (0, 5), // 딱 전체 범위 + (-1, 6) // 안으로 맞추면 전체 범위가 된다 + ] as [(Float, Float)] + ) + func fullRangeMeansNoFilter(min: Float, max: Float) { + var filter = MyLibraryFilter(rating: .range(min: 1.0, max: 3.0)) - #expect(filter.keywords == [keyword]) - } + filter.setRatingRange(min: min, max: max) - @Test("특정 키워드를 제거할 수 있다") - func removeKeyword() { - let binge = makeKeyword(id: 1, name: "빙의") - let regret = makeKeyword(id: 2, name: "후회") - var filter = makeFilter(keywords: [binge, regret]) + #expect(filter.rating == nil) + } - filter.removeKeyword(binge) + @Test("별점 없는 작품만 보기를 고르면 별점 범위 대신 걸린다") + func unratedOnlyReplacesRange() { + var filter = MyLibraryFilter(rating: .range(min: 1.0, max: 3.0)) - #expect(filter.keywords == [regret]) - } + filter.setUnratedOnly() - // MARK: - SortType + #expect(filter.rating == .unratedOnly) + } - @Test("정렬 기준을 변경할 수 있다") - func setSortType() { - var filter = makeFilter() + @Test("별점 필터를 해제하면 아무 별점 범위도 선택되지 않은 상태가 된다") + func clearsRating() { + var filter = MyLibraryFilter(rating: .range(min: 1.0, max: 3.0)) - filter.setSortType(.ratingHighest) + filter.clearRating() - #expect(filter.sortType == .ratingHighest) + #expect(filter.rating == nil) + } } - // MARK: - Clear All - - @Test("초기화하면 시트 필터 6종이 모두 리셋된다") - func clearAllResetsSheetFilters() { - var filter = makeFilter( - readingStatus: [.watching], - genres: [.fantasy], - publicationStatus: .onGoing, - attractivePoint: [.worldview], - keywords: [makeKeyword(id: 1, name: "빙의")] - ) - filter.setRatingRange(min: 3.5, max: 4.0) + @Suite("정렬") + struct Sort { - filter.clearAll() + @Test("내 서재의 초기 정렬 타입은 등록 최신순이다") + func startsWithRegisteredNewest() { + let filter = MyLibraryFilter() - #expect(filter.readingStatus.isEmpty) - #expect(filter.genres.isEmpty) - #expect(filter.publicationStatus == nil) - #expect(filter.rating == nil) - #expect(filter.attractivePoint.isEmpty) - #expect(filter.keywords.isEmpty) - } + #expect(filter.sortType == .registeredNewest) + } - @Test("초기화해도 관심 토글과 정렬 기준은 유지된다") - func clearAllKeepsInterestAndSortType() { - var filter = makeFilter(readingStatus: [.watching]) - filter.toggleInterest() - filter.setSortType(.title) + @Test("내 서재의 정렬 타입을 변경할 수 있다") + func keepsChangedSortType() { + var filter = MyLibraryFilter() - filter.clearAll() + filter.setSortType(.title) - #expect(filter.isInterest) - #expect(filter.sortType == .title) + #expect(filter.sortType == .title) + } } - // MARK: - hasActiveSheetFilter + @Suite("초기화") + struct ClearAll { - @Test("시트 필터가 하나라도 걸려 있으면 hasActiveSheetFilter가 true다") - func hasActiveSheetFilterWhenFiltered() { - var filter = makeFilter() + @Test("초기화하면 시트 필터(독서 상태·장르·연재 상태·별점·매력 포인트·키워드)를 모두 비운다") + func clearsSheetFilters() { + var filter = makeFilterWithEverything() - filter.addGenre(.fantasy) + filter.clearAll() - #expect(filter.hasActiveSheetFilter) - } + #expect(filter.readingStatus.isEmpty) + #expect(filter.genres.isEmpty) + #expect(filter.publicationStatus == nil) + #expect(filter.rating == nil) + #expect(filter.attractivePoint.isEmpty) + #expect(filter.keywords.isEmpty) + } - @Test("관심 토글과 정렬만 바뀐 상태는 hasActiveSheetFilter가 false다") - func hasActiveSheetFilterIgnoresInterestAndSort() { - var filter = makeFilter() + @Test("초기화해도 관심과 정렬은 그대로 둔다") + func keepsInterestAndSort() { + var filter = makeFilterWithEverything() - filter.toggleInterest() - filter.setSortType(.readDate) + filter.clearAll() - #expect(!filter.hasActiveSheetFilter) + #expect(filter.isInterest) + #expect(filter.sortType == .title) + } } -} -extension MyLibraryFilterTests { - private func makeFilter( - readingStatus: [ReadingStatus] = [], - genres: [NovelGenre] = [], - publicationStatus: NovelPublicationStatus? = nil, - attractivePoint: [AttractivePoint] = [], - keywords: [Keyword] = [] - ) -> MyLibraryFilter { - MyLibraryFilter( - readingStatus: readingStatus, - genres: genres, - publicationStatus: publicationStatus, - attractivePoint: attractivePoint, - keywords: keywords + @Suite("필터 표시") + struct ActiveSheetFilter { + + @Test( + "시트 필터 중 하나라도 걸리면 필터가 걸린 상태다", + arguments: [ + MyLibraryFilter(readingStatus: [.watching]), // 독서 상태 + MyLibraryFilter(genres: [.fantasy]), // 장르 + MyLibraryFilter(publicationStatus: .completed), // 연재 상태 + MyLibraryFilter(rating: .unratedOnly), // 별점 + MyLibraryFilter(attractivePoint: [.worldview]), // 매력 포인트 + MyLibraryFilter(keywords: [regression]) // 키워드 + ] ) - } + func activeWithAnySheetFilter(filter: MyLibraryFilter) { + let isActive = filter.hasActiveSheetFilter + + #expect(isActive) + } - private func makeKeyword(id: Int, name: String) -> Keyword { - Keyword(id: KeywordID(id), name: name) + @Test("관심이나 정렬만 바꿨으면 필터가 걸린 상태가 아니다") + func inactiveWithOnlyInterestAndSort() { + let filter = MyLibraryFilter(isInterest: true, sortType: .title) + + let isActive = filter.hasActiveSheetFilter + + #expect(!isActive) + } } } + +/// 시트 필터 전부와 관심·정렬을 모두 건 필터. +private func makeFilterWithEverything() -> MyLibraryFilter { + MyLibraryFilter( + isInterest: true, + readingStatus: [.watching], + genres: [.fantasy], + publicationStatus: .completed, + rating: .range(min: 1.0, max: 3.0), + attractivePoint: [.worldview], + keywords: [regression], + sortType: .title + ) +} diff --git a/Projects/Domain/NovelDomain/Tests/Entity/NovelInformationTests.swift b/Projects/Domain/NovelDomain/Tests/Entity/NovelInformationTests.swift index 0359c8219..39245f4d8 100644 --- a/Projects/Domain/NovelDomain/Tests/Entity/NovelInformationTests.swift +++ b/Projects/Domain/NovelDomain/Tests/Entity/NovelInformationTests.swift @@ -8,77 +8,67 @@ import Testing -@testable import NovelDomain -import NovelDomainTesting import BaseDomain +import NovelDomain -@Suite +@Suite("작품 상세의 대표 독서 상태") struct NovelInformationTests { - // - 가장 많은 읽기 상태 반환 - - @Test("readingStatusCount가 비어있으면 dominantReadStatus는 nil이다") - func dominantReadStatus_emptyDictionary_returnsNil() { - let info = makeNovelInformation(readingStatusCount: [:]) + @Test( + "읽은 사람이 없으면 대표 독서 상태가 없다", + arguments: [ + [:], // 독서 상태 수가 비어 있음 + [.watching: 0, .watched: 0, .quit: 0] // 모두 0명 + ] as [[ReadingStatus: Int]] + ) + func noDominantStatusWithoutReaders(readingStatusCount: [ReadingStatus: Int]) { + let information = makeNovelInformation(readingStatusCount: readingStatusCount) - #expect(info.dominantReadStatus == nil) - } - - @Test("모든 count가 0이면 dominantReadStatus는 nil이다") - func dominantReadStatus_allZero_returnsNil() { - let info = makeNovelInformation(readingStatusCount: [ - .watching: 0, - .watched: 0, - .quit: 0 - ]) + let dominant = information.dominantReadStatus - #expect(info.dominantReadStatus == nil) + #expect(dominant == nil) } - @Test("최댓값 count를 가진 읽기 상태를 반환한다") - func dominantReadStatus_returnsMaxStatus() { - let info = makeNovelInformation(readingStatusCount: [ - .watching: 3, - .watched: 6, - .quit: 4 - ]) + @Test("가장 많이 고른 독서 상태가 대표가 된다") + func mostChosenStatusIsDominant() { + let information = makeNovelInformation(readingStatusCount: [.watching: 3, .watched: 6, .quit: 4]) + + let dominant = information.dominantReadStatus - let dominant = info.dominantReadStatus #expect(dominant?.status == .watched) #expect(dominant?.count == 6) } - @Test("동률이면 우선순위(watching → watched → quit)에 따라 결정한다") - func dominantReadStatus_tieBreakByOrder() { - let info = makeNovelInformation(readingStatusCount: [ - .watching: 6, - .watched: 6, - .quit: 4 - ]) + @Test("한 명만 골랐어도 그 독서 상태가 대표가 된다") + func singleReaderStatusIsDominant() { + let information = makeNovelInformation(readingStatusCount: [.watching: 1, .watched: 0, .quit: 0]) + + let dominant = information.dominantReadStatus - let dominant = info.dominantReadStatus #expect(dominant?.status == .watching) - #expect(dominant?.count == 6) + #expect(dominant?.count == 1) } - @Test("동률이더라도 우선순위 상 앞선 값이 딕셔너리에 없으면 다음 우선순위를 선택한다") - func dominantReadStatus_tieBreak_skipsMissingKey() { - let info = makeNovelInformation(readingStatusCount: [ - .watched: 6, - .quit: 6 - // .watching 없음 - ]) + @Test( + "수가 같으면 보는 중, 봤음, 하차 순으로 대표를 정한다", + arguments: [ + ([.watching: 6, .watched: 6, .quit: 4], .watching), // 보는 중 = 봤음이면 보는 중 + ([.watching: 2, .watched: 6, .quit: 6], .watched) // 봤음 = 하차면 봤음 + ] as [([ReadingStatus: Int], ReadingStatus)] + ) + func tieFollowsStatusOrder(readingStatusCount: [ReadingStatus: Int], expected: ReadingStatus) { + let information = makeNovelInformation(readingStatusCount: readingStatusCount) - let dominant = info.dominantReadStatus - // watched가 quit보다 우선 - #expect(dominant?.status == .watched) + let dominant = information.dominantReadStatus + + #expect(dominant?.status == expected) #expect(dominant?.count == 6) } } -extension NovelInformationTests { - private func makeNovel() -> Novel { - Novel( +private func makeNovelInformation(readingStatusCount: [ReadingStatus: Int]) -> NovelInformation { + NovelInformation( + novel: Novel( id: NovelID(1), thumbnailImage: nil, title: "전지적 독자 시점", @@ -88,26 +78,14 @@ extension NovelInformationTests { rating: 4.5, ratingCount: 50, isInterested: nil - ) - } - - private func makeNovelInformation( - description: String = "재밌는 소설입니다.", - platforms: [NovelPlatform] = [], - attractivePoints: [AttractivePoint] = [], - keywords: [NovelKeyword] = [], - readingStatusCount: [ReadingStatus: Int] = [:] - ) -> NovelInformation { - NovelInformation( - novel: makeNovel(), - feedCount: 4, - publicationStatus: .completed, - userReview: nil, - description: description, - platforms: platforms, - attractivePoints: attractivePoints, - keywords: keywords, - readingStatusCount: readingStatusCount - ) - } + ), + feedCount: 4, + publicationStatus: .completed, + userReview: nil, + description: "재밌는 소설입니다.", + platforms: [], + attractivePoints: [], + keywords: [], + readingStatusCount: readingStatusCount + ) } diff --git a/Projects/Domain/NovelDomain/Tests/Entity/RegisteredNovelStatsTests.swift b/Projects/Domain/NovelDomain/Tests/Entity/RegisteredNovelStatsTests.swift deleted file mode 100644 index a41f758cd..000000000 --- a/Projects/Domain/NovelDomain/Tests/Entity/RegisteredNovelStatsTests.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// RegisteredNovelStatsTests.swift -// NovelDomain -// -// Created by Seoyeon Choi on 2/27/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelDomain -import NovelDomainTesting -import BaseDomain - -@Suite -struct RegisteredNovelStatsTests { - - @Test("RegisteredNovelStats를 정상적으로 생성한다") - func createStats() { - let stats = makeStats() - - #expect(stats.interest == 10) - #expect(stats.watching == 20) - #expect(stats.watched == 30) - #expect(stats.quit == 5) - } - - @Test("모든 카운트가 0인 경우에도 생성된다") - func createStatsWithZeroCounts() { - let stats = makeStats(interest: 0, watching: 0, watched: 0, quit: 0) - - #expect(stats.interest == 0) - #expect(stats.watching == 0) - #expect(stats.watched == 0) - #expect(stats.quit == 0) - } -} - -extension RegisteredNovelStatsTests { - - private func makeStats( - interest: Int = 10, - watching: Int = 20, - watched: Int = 30, - quit: Int = 5 - ) -> RegisteredNovelStats { - RegisteredNovelStats(interest: interest, watching: watching, watched: watched, quit: quit) - } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryKeywordsUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryKeywordsUseCaseTests.swift deleted file mode 100644 index a1fbfbc98..000000000 --- a/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryKeywordsUseCaseTests.swift +++ /dev/null @@ -1,58 +0,0 @@ -// -// LoadMyLibraryKeywordsUseCaseTests.swift -// NovelDomain -// -// Created by YunhakLee on 7/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelDomain -import NovelDomainTesting -import BaseDomain - -@Suite -struct LoadMyLibraryKeywordsUseCaseTests { - - @Test("서재에 등록한 키워드 목록을 정상적으로 불러온다") - func loadMyLibraryKeywordsSuccess() async throws { - let mock = MockNovelRepository() - let expected = [ - Keyword(id: KeywordID(1), name: "빙의"), - Keyword(id: KeywordID(2), name: "후회") - ] - mock.fetchMyLibraryKeywordsResult = .success(expected) - - let usecase = DefaultLoadMyLibraryKeywordsUseCase(novelRepository: mock) - - let result = try await usecase.execute() - - #expect(result == expected) - #expect(mock.fetchMyLibraryKeywordsCallCount == 1) - } - - @Test("등록한 키워드가 없으면 빈 목록을 반환한다") - func loadMyLibraryKeywordsEmpty() async throws { - let mock = MockNovelRepository() - mock.fetchMyLibraryKeywordsResult = .success([]) - - let usecase = DefaultLoadMyLibraryKeywordsUseCase(novelRepository: mock) - - let result = try await usecase.execute() - - #expect(result.isEmpty) - } - - @Test("키워드 조회에 실패하면 에러를 던진다") - func loadMyLibraryKeywordsFailureThrows() async { - let mock = MockNovelRepository() - mock.fetchMyLibraryKeywordsResult = .failure(RepositoryError.serverUnavailable) - - let usecase = DefaultLoadMyLibraryKeywordsUseCase(novelRepository: mock) - - await #expect(throws: RepositoryError.serverUnavailable) { - try await usecase.execute() - } - } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryUseCaseTests.swift deleted file mode 100644 index 62916507f..000000000 --- a/Projects/Domain/NovelDomain/Tests/UseCase/LoadMyLibraryUseCaseTests.swift +++ /dev/null @@ -1,179 +0,0 @@ -// -// LoadMyLibraryUseCaseTests.swift -// NovelDomain -// -// Created by Seoyeon Choi on 2/22/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelDomain -import NovelDomainTesting -import BaseDomain -import BaseDomainTesting - -@Suite -struct LoadMyLibraryUseCaseTests { - - @Test("내 서재 목록을 정상적으로 불러온다") - func loadMyLibrarySuccess() async throws { - let mock = MockNovelRepository() - let expected = makeLibraryPage() - mock.fetchMyLibraryResult = .success((expected, 2)) - - let usecase = makeUseCase(novelRepository: mock) - - let result = try await usecase.execute(filter: MyLibraryFilter(), cursor: nil, size: 20) - - #expect(result.0.items.count == expected.items.count) - #expect(result.0.hasNext == expected.hasNext) - #expect(mock.fetchedMyLibraryFilters.count == 1) - } - - @Test("내 서재 조회 결과에 전체 작품 수가 포함된다") - func loadMyLibraryReturnsCount() async throws { - let mock = MockNovelRepository() - mock.fetchMyLibraryResult = .success((makeLibraryPage(), 37)) - - let usecase = makeUseCase(novelRepository: mock) - let result = try await usecase.execute(filter: MyLibraryFilter(), cursor: nil, size: 20) - - #expect(result.1 == 37) - } - - @Test("필터 조건이 저장소에 그대로 전달된다") - func filterIsPassedToRepository() async throws { - let mock = MockNovelRepository() - mock.fetchMyLibraryResult = .success((makeLibraryPage(), 3)) - - let usecase = makeUseCase(novelRepository: mock) - var filter = MyLibraryFilter() - filter.addReadingStatus(.watching) - filter.addGenre(.fantasy) - - _ = try await usecase.execute(filter: filter, cursor: nil, size: 20) - - let passedFilter = mock.fetchedMyLibraryFilters.last - #expect(passedFilter?.readingStatus == [.watching]) - #expect(passedFilter?.genres == [.fantasy]) - } - - @Test("커서가 저장소에 그대로 전달된다") - func cursorIsPassedToRepository() async throws { - let mock = MockNovelRepository() - mock.fetchMyLibraryResult = .success((makeLibraryPage(), 3)) - - let usecase = makeUseCase(novelRepository: mock) - - _ = try await usecase.execute(filter: MyLibraryFilter(), cursor: "cursor-42", size: 20) - - #expect(mock.fetchedMyLibraryCursors.last == "cursor-42") - } - - @Test("요청 개수(size)가 저장소에 그대로 전달된다") - func sizeIsPassedToRepository() async throws { - let mock = MockNovelRepository() - mock.fetchMyLibraryResult = .success((makeLibraryPage(), 3)) - - let usecase = makeUseCase(novelRepository: mock) - - // 재진입 갱신은 "보고 있던 개수만큼" 한 번에 받으므로 페이지 크기가 고정이 아니다. - _ = try await usecase.execute(filter: MyLibraryFilter(), cursor: nil, size: 47) - - #expect(mock.fetchedMyLibrarySizes.last == 47) - } - - @Test("첫 페이지 조회는 커서 없이(nil) 저장소에 전달된다") - func firstPagePassesNilCursor() async throws { - let mock = MockNovelRepository() - mock.fetchMyLibraryResult = .success((makeLibraryPage(), 3)) - - let usecase = makeUseCase(novelRepository: mock) - - _ = try await usecase.execute(filter: MyLibraryFilter(), cursor: nil, size: 20) - - #expect(mock.fetchedMyLibraryCursors.last == .some(nil)) - } - - @Test("키워드 캐시를 서재 저장소에 전달한다") - func passesCachedKeywordsToRepository() async throws { - let novelRepository = MockNovelRepository() - novelRepository.fetchMyLibraryResult = .success((makeLibraryPage(), 3)) - let keyword = Keyword(id: KeywordID(11), name: "회귀") - let keywordRepository = MockKeywordRepository() - keywordRepository.fetchKeywordsResult = .success([ - KeywordGroup(category: .material, keywords: [keyword]) - ]) - let usecase = DefaultLoadMyLibraryUseCase( - novelRepository: novelRepository, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: keywordRepository) - ) - - _ = try await usecase.execute(filter: MyLibraryFilter(), cursor: nil, size: 20) - - #expect(novelRepository.lastMyLibraryCachedKeywords == [keyword]) - #expect(keywordRepository.fetchKeywordsCallCount == 1) - } - - @Test("키워드 캐시 조회에 실패해도 서재 목록은 빈 캐시로 정상 조회된다") - func fallsBackToEmptyKeywordsWhenCacheFails() async throws { - let novelRepository = MockNovelRepository() - let expected = makeLibraryPage() - novelRepository.fetchMyLibraryResult = .success((expected, 2)) - let keywordRepository = MockKeywordRepository() - keywordRepository.fetchKeywordsResult = .failure(RepositoryError.networkUnavailable) - let usecase = DefaultLoadMyLibraryUseCase( - novelRepository: novelRepository, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: keywordRepository) - ) - - let result = try await usecase.execute(filter: MyLibraryFilter(), cursor: nil, size: 20) - - #expect(result.0.items.count == expected.items.count) - #expect(novelRepository.lastMyLibraryCachedKeywords == []) - // LoadTotalKeywordsUseCase가 캐시 미스 시 서버 동기화 후 1회 재조회하므로 2번 호출된다. - #expect(keywordRepository.fetchKeywordsCallCount == 2) - #expect(keywordRepository.syncKeywordsCallCount == 1) - } - - @Test("내 서재 조회에 실패하면 에러를 던진다") - func loadMyLibraryFailureThrows() async { - let mock = MockNovelRepository() - mock.fetchMyLibraryResult = .failure(RepositoryError.unknown) - - let usecase = makeUseCase(novelRepository: mock) - - await #expect(throws: RepositoryError.unknown) { - try await usecase.execute(filter: MyLibraryFilter(), cursor: nil, size: 20) - } - } -} - -extension LoadMyLibraryUseCaseTests { - - private func makeUseCase(novelRepository: MockNovelRepository) -> DefaultLoadMyLibraryUseCase { - DefaultLoadMyLibraryUseCase( - novelRepository: novelRepository, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: MockKeywordRepository()) - ) - } - - private func makeLibraryPage() -> CursorPaginated { - CursorPaginated( - items: [ - LibraryNovel( - id: NovelID(1), - title: "전지적 독자 시점", - thumbnailImage: nil, - rating: 4.5, - isInterested: true, - userReview: nil, - writtenFeeds: [] - ) - ], - hasNext: false, - nextCursor: nil - ) - } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/LoadNovelUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/LoadNovelUseCaseTests.swift deleted file mode 100644 index 3d6f2b239..000000000 --- a/Projects/Domain/NovelDomain/Tests/UseCase/LoadNovelUseCaseTests.swift +++ /dev/null @@ -1,84 +0,0 @@ -// -// LoadNovelUseCaseTests.swift -// NovelDomain -// -// Created by Seoyeon Choi on 2/11/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelDomain -import NovelDomainTesting -import BaseDomain -import BaseDomainTesting - -@Suite -struct LoadNovelUseCaseTests { - - @Test("작품 정보를 성공적으로 불러온다") - func loadNovelSuccess() async throws { - let mock = MockNovelRepository() - let expected = makeNovelInformation() - mock.fetchNovelResult = .success(expected) - - let usecase = DefaultLoadNovelUseCase( - novelRepository: mock, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: MockKeywordRepository()) - ) - let novelID = NovelID(1) - - let result = try await usecase.execute(id: novelID) - - #expect(result.novel.id == expected.novel.id) - #expect(result.description == expected.description) - #expect(mock.fetchedNovelIDs.last == novelID) - #expect(mock.fetchedNovelIDs.count == 1) - } - - @Test("작품 조회에 실패하면 에러를 던진다") - func loadNovelFailureThrows() async { - let mock = MockNovelRepository() - mock.fetchNovelResult = .failure(RepositoryError.unknown) - - let usecase = DefaultLoadNovelUseCase( - novelRepository: mock, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: MockKeywordRepository()) - ) - - await #expect(throws: RepositoryError.unknown) { - try await usecase.execute(id: NovelID(1)) - } - } -} - -extension LoadNovelUseCaseTests { - - private func makeNovel() -> Novel { - Novel( - id: NovelID(1), - thumbnailImage: nil, - title: "전지적 독자 시점", - authors: ["싱숑"], - genres: [.BL], - interestCount: 100, - rating: 4.5, - ratingCount: 50, - isInterested: true - ) - } - - private func makeNovelInformation() -> NovelInformation { - NovelInformation( - novel: makeNovel(), - feedCount: 4, - publicationStatus: .completed, - userReview: nil, - description: "재밌는 소설입니다.", - platforms: [], - attractivePoints: [.worldview, .character], - keywords: [NovelKeyword(keyword: Keyword(id: KeywordID(1), name: "이세계"), count: 3)], - readingStatusCount: [.watching: 10, .watched: 30] - ) - } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/LoadRegisteredNovelStatsUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/LoadRegisteredNovelStatsUseCaseTests.swift deleted file mode 100644 index 511a309e4..000000000 --- a/Projects/Domain/NovelDomain/Tests/UseCase/LoadRegisteredNovelStatsUseCaseTests.swift +++ /dev/null @@ -1,66 +0,0 @@ -// -// LoadRegisteredNovelStatsUseCaseTests.swift -// NovelDomain -// -// Created by Seoyeon Choi on 2/27/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelDomain -import NovelDomainTesting -import BaseDomain - -@Suite -struct LoadRegisteredNovelStatsUseCaseTests { - - @Test("등록된 소설 통계를 정상적으로 불러온다") - func loadRegisteredNovelStatsSuccess() async throws { - let mock = MockNovelRepository() - let expected = makeStats() - mock.fetchRegisteredNovelStatsResult = .success(expected) - - let usecase = DefaultLoadRegisteredNovelStatsUseCase(novelRepository: mock) - let result = try await usecase.execute() - - #expect(result.interest == expected.interest) - #expect(result.watching == expected.watching) - #expect(result.watched == expected.watched) - #expect(result.quit == expected.quit) - } - - @Test("Repository가 정확히 한 번 호출된다") - func repositoryCalledOnce() async throws { - let mock = MockNovelRepository() - mock.fetchRegisteredNovelStatsResult = .success(makeStats()) - - let usecase = DefaultLoadRegisteredNovelStatsUseCase(novelRepository: mock) - _ = try await usecase.execute() - - #expect(mock.fetchRegisteredNovelStatsCallCount == 1) - } - - @Test("조회에 실패하면 에러를 던진다") - func loadRegisteredNovelStatsFailureThrows() async { - let mock = MockNovelRepository() - mock.fetchRegisteredNovelStatsResult = .failure(RepositoryError.unknown) - - let usecase = DefaultLoadRegisteredNovelStatsUseCase(novelRepository: mock) - - await #expect(throws: RepositoryError.unknown) { - try await usecase.execute() - } - } -} - -extension LoadRegisteredNovelStatsUseCaseTests { - private func makeStats( - interest: Int = 10, - watching: Int = 20, - watched: Int = 30, - quit: Int = 5 - ) -> RegisteredNovelStats { - RegisteredNovelStats(interest: interest, watching: watching, watched: watched, quit: quit) - } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserLibraryUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserLibraryUseCaseTests.swift deleted file mode 100644 index 507ebec0f..000000000 --- a/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserLibraryUseCaseTests.swift +++ /dev/null @@ -1,166 +0,0 @@ -// -// LoadUserLibraryUseCaseTests.swift -// NovelDomain -// -// Created by Seoyeon Choi on 2/22/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import NovelDomain -import NovelDomainTesting -import BaseDomain -import BaseDomainTesting - -@Suite -struct LoadUserLibraryUseCaseTests { - - @Test("타유저 서재 목록을 정상적으로 불러온다") - func loadUserLibrarySuccess() async throws { - let mock = MockNovelRepository() - let expected = makeLibraryPage() - mock.fetchUserLibraryResult = .success((expected, 2)) - - let usecase = makeUseCase(novelRepository: mock) - let userID = UserID(1003) - - let result = try await usecase.execute(id: userID, filter: LibraryFilter(), cursor: nil) - - #expect(result.0.items.count == expected.items.count) - #expect(result.0.hasNext == expected.hasNext) - #expect(mock.fetchedUserLibraryIDs.last == userID) - #expect(mock.fetchedUserLibraryIDs.count == 1) - } - - @Test("타유저 서재 조회 결과에 전체 작품 수가 포함된다") - func loadUserLibraryReturnsCount() async throws { - let mock = MockNovelRepository() - mock.fetchUserLibraryResult = .success((makeLibraryPage(), 15)) - - let usecase = makeUseCase(novelRepository: mock) - let result = try await usecase.execute(id: UserID(1003), filter: LibraryFilter(), cursor: nil) - - #expect(result.1 == 15) - } - - @Test("정렬 조건이 저장소에 그대로 전달된다") - func sortTypeIsPassedToRepository() async throws { - let mock = MockNovelRepository() - mock.fetchUserLibraryResult = .success((makeLibraryPage(), 3)) - - let usecase = makeUseCase(novelRepository: mock) - var filter = LibraryFilter() - filter.setSortType(.ratingHighest) - - _ = try await usecase.execute(id: UserID(1003), filter: filter, cursor: nil) - - #expect(mock.fetchedUserLibraryFilters.last?.sortType == .ratingHighest) - } - - @Test("커서가 저장소에 그대로 전달된다") - func cursorIsPassedToRepository() async throws { - let mock = MockNovelRepository() - mock.fetchUserLibraryResult = .success((makeLibraryPage(), 3)) - - let usecase = makeUseCase(novelRepository: mock) - - _ = try await usecase.execute(id: UserID(1003), filter: LibraryFilter(), cursor: "cursor-42") - - #expect(mock.fetchedUserLibraryCursors.last == "cursor-42") - } - - @Test("첫 페이지 조회는 커서 없이(nil) 저장소에 전달된다") - func firstPagePassesNilCursor() async throws { - let mock = MockNovelRepository() - mock.fetchUserLibraryResult = .success((makeLibraryPage(), 3)) - - let usecase = makeUseCase(novelRepository: mock) - - _ = try await usecase.execute(id: UserID(1003), filter: LibraryFilter(), cursor: nil) - - #expect(mock.fetchedUserLibraryCursors.last == .some(nil)) - } - - @Test("키워드 캐시를 서재 저장소에 전달한다") - func passesCachedKeywordsToRepository() async throws { - let novelRepository = MockNovelRepository() - novelRepository.fetchUserLibraryResult = .success((makeLibraryPage(), 3)) - let keyword = Keyword(id: KeywordID(11), name: "회귀") - let keywordRepository = MockKeywordRepository() - keywordRepository.fetchKeywordsResult = .success([ - KeywordGroup(category: .material, keywords: [keyword]) - ]) - let usecase = DefaultLoadUserLibraryUseCase( - novelRepository: novelRepository, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: keywordRepository) - ) - - _ = try await usecase.execute(id: UserID(1003), filter: LibraryFilter(), cursor: nil) - - #expect(novelRepository.lastUserLibraryCachedKeywords == [keyword]) - #expect(keywordRepository.fetchKeywordsCallCount == 1) - } - - @Test("키워드 캐시 조회에 실패해도 서재 목록은 빈 캐시로 정상 조회된다") - func fallsBackToEmptyKeywordsWhenCacheFails() async throws { - let novelRepository = MockNovelRepository() - let expected = makeLibraryPage() - novelRepository.fetchUserLibraryResult = .success((expected, 2)) - let keywordRepository = MockKeywordRepository() - keywordRepository.fetchKeywordsResult = .failure(RepositoryError.networkUnavailable) - let usecase = DefaultLoadUserLibraryUseCase( - novelRepository: novelRepository, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: keywordRepository) - ) - - let result = try await usecase.execute(id: UserID(1003), filter: LibraryFilter(), cursor: nil) - - #expect(result.0.items.count == expected.items.count) - #expect(novelRepository.lastUserLibraryCachedKeywords == []) - // LoadTotalKeywordsUseCase가 캐시 미스 시 서버 동기화 후 1회 재조회하므로 2번 호출된다. - #expect(keywordRepository.fetchKeywordsCallCount == 2) - #expect(keywordRepository.syncKeywordsCallCount == 1) - } - - @Test("타유저 서재 조회에 실패하면 에러를 던진다") - func loadUserLibraryFailureThrows() async { - let mock = MockNovelRepository() - mock.fetchUserLibraryResult = .failure(RepositoryError.unknown) - - let usecase = makeUseCase(novelRepository: mock) - - await #expect(throws: RepositoryError.unknown) { - try await usecase.execute(id: UserID(1), filter: LibraryFilter(), cursor: nil) - } - } -} - -extension LoadUserLibraryUseCaseTests { - - private func makeUseCase(novelRepository: MockNovelRepository) -> DefaultLoadUserLibraryUseCase { - DefaultLoadUserLibraryUseCase( - novelRepository: novelRepository, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: MockKeywordRepository()) - ) - } - - private func makeLibraryPage() -> CursorPaginated { - CursorPaginated( - items: [ - LibraryNovel( - id: NovelID(1), - title: "어쿠스틱 러브", - thumbnailImage: URL(string: "https://example.com/image.jpg"), - rating: 3.45, - isInterested: false, - userReview: nil, - writtenFeeds: ["이 작품은 너무 재밌어요"] - ) - ], - hasNext: true, - nextCursor: "cursor-next" - ) - } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserRegisteredNovelStatsUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserRegisteredNovelStatsUseCaseTests.swift deleted file mode 100644 index 82cb442bb..000000000 --- a/Projects/Domain/NovelDomain/Tests/UseCase/LoadUserRegisteredNovelStatsUseCaseTests.swift +++ /dev/null @@ -1,67 +0,0 @@ -// -// LoadUserRegisteredNovelStatsUseCaseTests.swift -// NovelDomain -// -// Created by Seoyeon Choi on 7/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelDomain -import NovelDomainTesting -import BaseDomain - -@Suite -struct LoadUserRegisteredNovelStatsUseCaseTests { - - @Test("다른 유저의 등록된 소설 통계를 정상적으로 불러온다") - func loadUserRegisteredNovelStatsSuccess() async throws { - let mock = MockNovelRepository() - let expected = makeStats() - mock.fetchUserRegisteredNovelStatsResult = .success(expected) - - let usecase = DefaultLoadUserRegisteredNovelStatsUseCase(novelRepository: mock) - let result = try await usecase.execute(id: UserID(1003)) - - #expect(result.interest == expected.interest) - #expect(result.watching == expected.watching) - #expect(result.watched == expected.watched) - #expect(result.quit == expected.quit) - } - - @Test("Repository가 전달한 유저 ID로 정확히 한 번 호출된다") - func repositoryCalledOnceWithGivenID() async throws { - let mock = MockNovelRepository() - mock.fetchUserRegisteredNovelStatsResult = .success(makeStats()) - - let usecase = DefaultLoadUserRegisteredNovelStatsUseCase(novelRepository: mock) - let userID = UserID(1003) - _ = try await usecase.execute(id: userID) - - #expect(mock.fetchedUserRegisteredNovelStatsIDs == [userID]) - } - - @Test("조회에 실패하면 에러를 던진다") - func loadUserRegisteredNovelStatsFailureThrows() async { - let mock = MockNovelRepository() - mock.fetchUserRegisteredNovelStatsResult = .failure(RepositoryError.unknown) - - let usecase = DefaultLoadUserRegisteredNovelStatsUseCase(novelRepository: mock) - - await #expect(throws: RepositoryError.unknown) { - try await usecase.execute(id: UserID(1)) - } - } -} - -extension LoadUserRegisteredNovelStatsUseCaseTests { - private func makeStats( - interest: Int = 10, - watching: Int = 20, - watched: Int = 30, - quit: Int = 5 - ) -> RegisteredNovelStats { - RegisteredNovelStats(interest: interest, watching: watching, watched: watched, quit: quit) - } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/MyLibraryFilterUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/MyLibraryFilterUseCaseTests.swift deleted file mode 100644 index 7c604a51f..000000000 --- a/Projects/Domain/NovelDomain/Tests/UseCase/MyLibraryFilterUseCaseTests.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// MyLibraryFilterUseCaseTests.swift -// NovelDomain -// -// Created by YunhakLee on 8/31/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelDomain -import NovelDomainTesting -import BaseDomain - -@Suite -struct MyLibraryFilterUseCaseTests { - - // MARK: - Load - - @Test("저장된 필터가 있으면 그대로 복원한다") - func loadReturnsStoredFilter() { - let stored = MyLibraryFilter(genres: [.romance], sortType: .ratingHighest) - let mock = MockMyLibraryFilterRepository(storedFilter: stored) - let usecase = DefaultLoadMyLibraryFilterUseCase(repository: mock) - - let result = usecase.execute() - - #expect(result == stored) - #expect(mock.loadCallCount == 1) - } - - @Test("저장된 필터가 없으면 nil을 반환한다(화면은 기본 필터로 시작)") - func loadReturnsNilWhenEmpty() { - let mock = MockMyLibraryFilterRepository(storedFilter: nil) - let usecase = DefaultLoadMyLibraryFilterUseCase(repository: mock) - - #expect(usecase.execute() == nil) - } - - // MARK: - Save - - @Test("저장하면 넘긴 필터를 Repository에 그대로 위임한다") - func saveDelegatesFilter() { - let mock = MockMyLibraryFilterRepository() - let usecase = DefaultSaveMyLibraryFilterUseCase(repository: mock) - let filter = MyLibraryFilter(isInterest: true, sortType: .title) - - usecase.execute(filter) - - #expect(mock.savedFilters == [filter]) - } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/NovelInterestUseCaseTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/NovelInterestUseCaseTests.swift deleted file mode 100644 index d72d16498..000000000 --- a/Projects/Domain/NovelDomain/Tests/UseCase/NovelInterestUseCaseTests.swift +++ /dev/null @@ -1,73 +0,0 @@ -// -// NovelInterestUseCaseTests.swift -// NovelDomain -// -// Created by Seoyeon Choi on 2/22/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import NovelDomain -import NovelDomainTesting -import BaseDomain - -@Suite -struct NovelInterestUseCaseTests { - - @Test("작품 관심을 정상적으로 추가한다") - func addInterestSuccess() async throws { - let mock = MockNovelRepository() - mock.addInterestResult = .success(()) - - let usecase = DefaultNovelInterestUseCase(novelRepository: mock) - let novelID = NovelID(42) - - try await usecase.add(id: novelID) - - #expect(mock.addedInterestIDs.last == novelID) - #expect(mock.addedInterestIDs.count == 1) - } - - @Test("작품 관심 추가에 실패하면 에러를 던진다") - func addInterestFailureThrows() async { - let mock = MockNovelRepository() - mock.addInterestResult = .failure(RepositoryError.unknown) - - let usecase = DefaultNovelInterestUseCase(novelRepository: mock) - - await #expect(throws: RepositoryError.unknown) { - try await usecase.add(id: NovelID(1)) - } - } - - @Test("작품 관심을 정상적으로 삭제한다") - func removeInterestSuccess() async throws { - let mock = MockNovelRepository() - mock.removeInterestResult = .success(()) - - let usecase = DefaultNovelInterestUseCase(novelRepository: mock) - let novelID = NovelID(42) - - try await usecase.remove(id: novelID) - - #expect(mock.removedInterestIDs.last == novelID) - #expect(mock.removedInterestIDs.count == 1) - } - - @Test("작품 관심 삭제에 실패하면 에러를 던진다") - func removeInterestFailureThrows() async { - let mock = MockNovelRepository() - mock.removeInterestResult = .failure(RepositoryError.unknown) - - let usecase = DefaultNovelInterestUseCase(novelRepository: mock) - - await #expect(throws: RepositoryError.unknown) { - try await usecase.remove(id: NovelID(1)) - } - } -} - -extension NovelInterestUseCaseTests { - private enum TestError: Error { case networkFail } -} diff --git a/Projects/Domain/NovelDomain/Tests/UseCase/NovelKeywordLookupTests.swift b/Projects/Domain/NovelDomain/Tests/UseCase/NovelKeywordLookupTests.swift new file mode 100644 index 000000000..7cdd43603 --- /dev/null +++ b/Projects/Domain/NovelDomain/Tests/UseCase/NovelKeywordLookupTests.swift @@ -0,0 +1,153 @@ +// +// NovelKeywordLookupTests.swift +// NovelDomain +// +// Created by YunhakLee on 11/19/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Testing + +import BaseDomain +import BaseDomainTesting +import NovelDomain +import NovelDomainTesting + +// 서버는 작품의 키워드를 이름으로만 준다. 앱은 전체 키워드 목록에서 같은 이름을 찾아 키워드로 바꾸므로, +// 불러오는 UseCase는 모든 카테고리의 키워드를 넘겨야 한다. +// 카테고리를 둘로 나눠 둬서, 한 카테고리의 키워드만 넘기면 저장소가 답을 찾지 못한다. +private let keywordGroups = [ + KeywordGroup(category: .material, keywords: [ + Keyword(id: KeywordID(11), name: "회귀") + ]), + KeywordGroup(category: .character, keywords: [ + Keyword(id: KeywordID(21), name: "먼치킨"), + Keyword(id: KeywordID(22), name: "사이다") + ]) +] +private let allKeywords = Set(keywordGroups.flatMap(\.keywords)) +private let emptyPage = CursorPaginated(items: [], hasNext: false, nextCursor: nil) + +@Suite("작품의 키워드 알아보기") +struct NovelKeywordLookupTests { + + @Suite("작품 상세") + struct NovelDetail { + + @Test("작품 상세를 불러올 때 모든 카테고리의 키워드를 넘긴다") + func passesKeywordsOfAllCategories() async throws { + let novelRepository = MockNovelRepository() + novelRepository.novelsByCachedKeywords = [allKeywords: makeNovelInformation(feedCount: 7)] + let useCase = DefaultLoadNovelUseCase( + novelRepository: novelRepository, + loadTotalKeywordsUseCase: MockLoadTotalKeywordsUseCase(result: .success(keywordGroups)) + ) + + let information = try await useCase.execute(id: NovelID(1)) + + #expect(information.feedCount == 7) + } + + @Test("전체 키워드를 못 불러와도 작품 상세는 불러온다") + func loadsWithoutKeywords() async throws { + let novelRepository = MockNovelRepository() + novelRepository.novelsByCachedKeywords = [[]: makeNovelInformation(feedCount: 7)] + let useCase = DefaultLoadNovelUseCase( + novelRepository: novelRepository, + loadTotalKeywordsUseCase: MockLoadTotalKeywordsUseCase(result: .failure(.networkUnavailable)) + ) + + let information = try await useCase.execute(id: NovelID(1)) + + #expect(information.feedCount == 7) + } + } + + @Suite("내 서재") + struct MyLibrary { + + @Test("내 서재를 불러올 때 모든 카테고리의 키워드를 넘긴다") + func passesKeywordsOfAllCategories() async throws { + let novelRepository = MockNovelRepository() + novelRepository.myLibraryByCachedKeywords = [allKeywords: (emptyPage, 37)] + let useCase = DefaultLoadMyLibraryUseCase( + novelRepository: novelRepository, + loadTotalKeywordsUseCase: MockLoadTotalKeywordsUseCase(result: .success(keywordGroups)) + ) + + let (_, totalCount) = try await useCase.execute(filter: MyLibraryFilter(), cursor: nil, size: 15) + + #expect(totalCount == 37) + } + + @Test("전체 키워드를 못 불러와도 내 서재 목록은 불러온다") + func loadsWithoutKeywords() async throws { + let novelRepository = MockNovelRepository() + novelRepository.myLibraryByCachedKeywords = [[]: (emptyPage, 37)] + let useCase = DefaultLoadMyLibraryUseCase( + novelRepository: novelRepository, + loadTotalKeywordsUseCase: MockLoadTotalKeywordsUseCase(result: .failure(.networkUnavailable)) + ) + + let (_, totalCount) = try await useCase.execute(filter: MyLibraryFilter(), cursor: nil, size: 15) + + #expect(totalCount == 37) + } + } + + @Suite("다른 사람 서재") + struct UserLibrary { + + @Test("다른 사람 서재를 불러올 때 모든 카테고리의 키워드를 넘긴다") + func passesKeywordsOfAllCategories() async throws { + let novelRepository = MockNovelRepository() + novelRepository.userLibraryByCachedKeywords = [allKeywords: (emptyPage, 37)] + let useCase = DefaultLoadUserLibraryUseCase( + novelRepository: novelRepository, + loadTotalKeywordsUseCase: MockLoadTotalKeywordsUseCase(result: .success(keywordGroups)) + ) + + let (_, totalCount) = try await useCase.execute(id: UserID(3), filter: LibraryFilter(), cursor: nil) + + #expect(totalCount == 37) + } + + @Test("전체 키워드를 못 불러와도 다른 사람 서재 목록은 불러온다") + func loadsWithoutKeywords() async throws { + let novelRepository = MockNovelRepository() + novelRepository.userLibraryByCachedKeywords = [[]: (emptyPage, 37)] + let useCase = DefaultLoadUserLibraryUseCase( + novelRepository: novelRepository, + loadTotalKeywordsUseCase: MockLoadTotalKeywordsUseCase(result: .failure(.networkUnavailable)) + ) + + let (_, totalCount) = try await useCase.execute(id: UserID(3), filter: LibraryFilter(), cursor: nil) + + #expect(totalCount == 37) + } + } +} + +private func makeNovelInformation(feedCount: Int) -> NovelInformation { + NovelInformation( + novel: Novel( + id: NovelID(1), + thumbnailImage: nil, + title: "전지적 독자 시점", + authors: ["싱숑"], + genres: [.fantasy], + interestCount: 100, + rating: 4.5, + ratingCount: 50, + isInterested: nil + ), + feedCount: feedCount, + publicationStatus: .completed, + userReview: nil, + description: "재밌는 소설입니다.", + platforms: [], + attractivePoints: [], + keywords: [], + readingStatusCount: [:] + ) +} 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/Projects/Domain/ProfileDomain/CLAUDE.md b/Projects/Domain/ProfileDomain/CLAUDE.md index 813829b15..050b71d07 100644 --- a/Projects/Domain/ProfileDomain/CLAUDE.md +++ b/Projects/Domain/ProfileDomain/CLAUDE.md @@ -20,6 +20,8 @@ - **`BirthYear.maxYear`는 하드코딩이 아니라 현재 연도(`Calendar.current...`) 계산값**(#222) — 생년 휠 상한이 이 값을 그대로 쓴다(`WSSBirthYearWheel`, OnboardingFeature·SettingFeature 공용). 고정값으로 되돌리면 해가 바뀔 때마다 stale해진다(V1·구 V2가 2025/2024 하드코딩이라 그랬다). `Foundation` import가 이 때문에 필요하다. + `init`은 `today`·`calendar`(기본값 지금·`.current`)를 받는다(#308) — 테스트가 올해를 고정하려는 것이다. 테스트 기대값을 + `BirthYear.maxYear`에서 가져오면 상한 계산이 틀려도 함께 틀려 못 잡으니, 고정 날짜를 넘기고 연도는 리터럴로 쓴다. - 본인/타인 로직이 `ProfileTarget`에 숨어있음 — 새 조회 추가 시 두 케이스 모두 고려. - userDefaults 저장 책임이 도메인 계약 주석에 박혀있음 (구현은 Data). 어떤 필드가 로컬인지 헷갈리면 `ProfileRepository.swift` 주석 확인. - `GenrePreference.genre`는 자유 문자열이 아니라 `BaseDomain.NovelGenre`(9개 케이스) 타입이다 — 서버가 그 9개 밖의 장르 토큰을 내려주면 Data의 `novelGenre(from:)` 매핑이 실패해 `RepositoryError.invalidData`로 전파된다(예전엔 임의 문자열을 그대로 통과시켰음). 표시용 한글 라벨/아이콘은 `WSSComponent`의 `NovelGenre+Presentation`(`displayName`/`iconImage`) 재사용. @@ -27,4 +29,6 @@ - `fetchGenrePreferences`가 반환하는 `[GenrePreference]`는 **서버가 이미 개수 내림차순으로 정렬해 내려준다** — 클라이언트(Feature)에서 재정렬하지 않는다. 매핑(`ProfileMapper.genrePreferences`)도 배열 `.map`이라 순서를 그대로 보존한다. - `validateNickname(_:)`의 `Bool` 반환은 **`true` = 사용 가능(중복 아님)** 이다("검증 통과"가 아니라 "가용"으로 읽을 것). `ProfileData`의 `NicknameValidationResponse.isValid`를 그대로 전달한다. - `ProfileDraft.removeGenrePreference(_:)`는 `GenrePreference`의 **완전 일치(Equatable: genre+count)** 비교로 제거한다 — `GenrePreference(genre: someGenre, count: 0)`처럼 count를 임의로 채운 새 값으로는 지워지지 않고 조용히 실패한다. 토글 등에서 제거하려면 `genrePreferences.first(where: { $0.genre == genre })`로 draft에 실제 들어있는 인스턴스를 찾아 그대로 넘겨야 한다. +- **`MockProfileRepository`는 #308에서 줄였다** — 선호 작품 조회만 키워드 캐시별 Stub(`novelPreferencesByCachedKeywords`, 정해 두지 않은 캐시면 `.notFound`), 동기화만 호출 횟수 Mock(SplashData 런치 작업 테스트가 씀). 나머지 조회는 `.notFound`를 던지고 명령은 no-op이니, 다른 메서드가 필요한 테스트를 쓰면 그때 답을 더한다. +- `ProfileDraft`의 빈 닉네임 저장·소개글 줄 수 판단·수정 화면 장르 타입(`GenrePreference` 개수·순서) 문제는 #309로 넘겼다 — 테스트는 이 동작들을 명세로 적지 않았다(고칠 동작을 굳히지 않으려고). - `ProfileDraft.updateIntroduction(_:)`은 더 이상 3줄 제한을 하지 않는다(50자 길이만 즉시 clamp). 3줄 제한은 별도 `truncateIntroductionToLineLimit()`로 분리됐고, 호출자(Feature)가 **제출 직전에 직접 호출**해야만 적용된다 — 안 부르면 4줄 이상도 그대로 저장됨. 이 메서드는 `\n` 개수만 세므로 워드랩으로 시각적으로 3줄을 넘는 입력은 걸러내지 못한다(예전 UIKit `NSLayoutManager` 기반 실시간 검증을 걷어내고 단순화한 결과 — Feature `MyPageEditView` 참고). diff --git a/Projects/Domain/ProfileDomain/Project.swift b/Projects/Domain/ProfileDomain/Project.swift index 7f320ef02..c353e9a87 100644 --- a/Projects/Domain/ProfileDomain/Project.swift +++ b/Projects/Domain/ProfileDomain/Project.swift @@ -12,5 +12,7 @@ import DependencyPlugin let project = Project.createDomainModule( name: ModuleType.domain(.profile).name, targets: [.sources, .testing, .tests], - internalDependencies: [.module(.domain(.base))] + internalDependencies: [.module(.domain(.base))], + // 선호 작품 불러오기 테스트가 BaseDomain의 MockLoadTotalKeywordsUseCase를 쓴다. + testDependencies: [.module(.domain(.base), type: .testing)] ) diff --git a/Projects/Domain/ProfileDomain/Sources/Entity/AssistantEntity/BirthYear.swift b/Projects/Domain/ProfileDomain/Sources/Entity/AssistantEntity/BirthYear.swift index 2ac959be7..ee6677047 100644 --- a/Projects/Domain/ProfileDomain/Sources/Entity/AssistantEntity/BirthYear.swift +++ b/Projects/Domain/ProfileDomain/Sources/Entity/AssistantEntity/BirthYear.swift @@ -15,15 +15,20 @@ public struct BirthYear: Equatable, Sendable { /// 생년 상한 = 현재 연도(하드코딩하지 않는다 — 해가 바뀌어도 자동 반영, #222). /// V1·구 V2는 고정값(2025/2024)이라 해가 지나면 stale해졌다. 생년 휠 상한이 이 값을 그대로 쓴다. static public var maxYear: Int { - Calendar.current.component(.year, from: Date()) + maxYear(today: Date(), calendar: .current) } - public init(_ value: Int) throws { - guard (Self.minYear...Self.maxYear).contains(value) else { + /// `today`·`calendar`는 테스트가 올해를 고정하려고 넘긴다. 앱은 기본값(지금·기기 달력)을 쓴다. + public init(_ value: Int, today: Date = Date(), calendar: Calendar = .current) throws { + guard (Self.minYear...Self.maxYear(today: today, calendar: calendar)).contains(value) else { throw ValidationError.invalidRange } self.value = value } + + private static func maxYear(today: Date, calendar: Calendar) -> Int { + calendar.component(.year, from: today) + } public enum ValidationError: Error { case invalidRange diff --git a/Projects/Domain/ProfileDomain/Sources/Entity/ProfileDraft.swift b/Projects/Domain/ProfileDomain/Sources/Entity/ProfileDraft.swift index 7cd0c2ab0..44a7eaf81 100644 --- a/Projects/Domain/ProfileDomain/Sources/Entity/ProfileDraft.swift +++ b/Projects/Domain/ProfileDomain/Sources/Entity/ProfileDraft.swift @@ -91,9 +91,11 @@ public struct ProfileDraft: Sendable { /// 저장 직전에만 줄 수를 제한한다(입력 중엔 자유롭게 타이핑하게 두고, 제출 시점에 앞 `maxLineCount`줄만 남긴다). public mutating func truncateIntroductionToLineLimit() { - let lines = introduction.components(separatedBy: "\n") - guard lines.count > Self.maxLineCount else { return } - introduction = lines.prefix(Self.maxLineCount).joined(separator: "\n") + // 세 줄 이하면 쪼갰다 다시 붙여도 원래 그대로라, 줄 수를 따로 검사하지 않는다(#308 뮤테이션). + introduction = introduction + .components(separatedBy: "\n") + .prefix(Self.maxLineCount) + .joined(separator: "\n") } // - genre preferences diff --git a/Projects/Domain/ProfileDomain/TEST_SPEC.md b/Projects/Domain/ProfileDomain/TEST_SPEC.md new file mode 100644 index 000000000..3668f60e3 --- /dev/null +++ b/Projects/Domain/ProfileDomain/TEST_SPEC.md @@ -0,0 +1,98 @@ +# ProfileDomain 테스트 명세 + + + +## 계정 정보 수정 + +`Tests/Entity/AccountInfoDraftTests.swift` + +- 성별을 바꾸면 담긴다 +- 생년을 바꾸면 담긴다 + +## 생년 + +`Tests/Entity/BirthYearTests.swift` + +- 1900년부터 올해까지는 생년으로 고를 수 있다 + - `1900` — 가장 이른 해 + - `2026` — 올해 +- 1900년 전이나 올해 뒤는 생년으로 고를 수 없다 + - `1900 - 1` — 가장 이른 해 바로 전 + - `2027` — 내년 + +## 닉네임 입력 + +`Tests/Entity/NicknameDraftTests.swift` + +### 입력 길이 + +- 닉네임은 10자까지만 입력된다 +- 10자를 넘겨 쳐도 잘린 결과가 같으면 중복 확인 결과가 그대로다 + +### 입력 상태 + +- 닉네임이 비어 있으면 아직 입력 전 상태다 +- 처음 닉네임과 같으면 바뀌지 않아 쓸 수 없다 +- 다른 닉네임을 쳤다가 처음 닉네임으로 되돌리면 바뀌지 않아 쓸 수 없다 +- 공백·줄바꿈·탭이 들어가면 쓸 수 없다 + - `"새 이름"` — 가운데 공백 + - `"새이름\n"` — 줄바꿈 + - `"새\t이름"` — 탭 +- 공백이 들어가 있으면 처음 닉네임과 같아도 공백 때문에 쓸 수 없다고 알린다 +- 한 글자이거나 한글·영문·숫자 말고 다른 문자가 있으면 쓸 수 없다 + - `"가"` — 한 글자 — 두 글자부터 쓸 수 있다 + - `"새이름!"` — 특수문자 + - `"ㄱㄴㄷ"` — 완성되지 않은 한글(자음만) +- 두 글자이고 규칙에 맞으면 중복 확인이 필요하다 + +### 중복 확인 + +- 중복이면 쓸 수 없다 +- 중복이 아니면 쓸 수 있다 +- 확인하는 사이에 닉네임이 바뀌었으면 늦게 온 결과는 버린다 +- 중복 확인 뒤 닉네임을 고치면 다시 확인해야 한다 + +## 프로필 수정 + +`Tests/Entity/ProfileDraftTests.swift` + +### 바뀐 것 알아보기 + +- 처음에는 바뀐 것이 없다 +- 다른 캐릭터를 고르면 캐릭터가 바뀐 것이다 +- 같은 캐릭터를 다시 고르면 캐릭터가 바뀐 것이 아니다 +- 닉네임은 중복 확인까지 통과해야 바뀐 것이다 + - `(NicknameDraft.DuplicationCheckState.notYet, false)` — 확인 전 + - `(.duplicated, false)` — 중복 + - `(.notDuplicated, true)` — 통과 +- 소개글을 고쳤다가 처음대로 되돌리면 바뀐 것이 아니다 +- 장르를 넣었다 빼서 처음과 같아지면 바뀐 것이 아니다 + +### 저장 가능 여부 + +- 아무것도 안 바꾸면 저장할 수 없다 +- 캐릭터·닉네임·소개글·장르 중 하나만 바꿔도 저장할 수 있다 + - `Edit.allCases` +- 닉네임이 확인 전·중복·공백·규칙 위반이면 다른 걸 바꿔도 저장할 수 없다 + - `BlockingNickname.allCases` + +### 소개글 + +- 소개글은 50자까지만 입력된다 + - `(50, 50)` — 딱 50자는 그대로 + - `(51, 50)` — 넘치면 50자로 자른다 +- 저장 직전에 소개글을 세 줄까지만 남긴다 + - `("하나\n둘\n셋", "하나\n둘\n셋")` — 세 줄은 그대로 + - `("하나\n둘\n셋\n넷", "하나\n둘\n셋")` — 넷째 줄부터 버린다 + +### 선호 장르 + +- 장르를 고르면 담긴다 +- 고른 장르를 빼면 사라진다 + +## 선호 작품 불러오기 + +`Tests/UseCase/LoadNovelPreferencesUseCaseTests.swift` + +- 선호 작품을 불러올 때 모든 카테고리의 키워드를 넘긴다 +- 전체 키워드를 못 불러와도 선호 작품은 불러온다 diff --git a/Projects/Domain/ProfileDomain/Testing/Mock/MockProfileRepository.swift b/Projects/Domain/ProfileDomain/Testing/Mock/MockProfileRepository.swift index 1633c7c20..a19be31d0 100644 --- a/Projects/Domain/ProfileDomain/Testing/Mock/MockProfileRepository.swift +++ b/Projects/Domain/ProfileDomain/Testing/Mock/MockProfileRepository.swift @@ -2,7 +2,7 @@ // MockProfileRepository.swift // ProfileDomain // -// Created by YunhakLee on 2/25/26. +// Created by Seoyeon Choi on 2/25/26. // Copyright © 2026 kr.websoso.app. All rights reserved. // @@ -11,215 +11,52 @@ import Foundation import ProfileDomain import BaseDomain +/// 프로필 저장소 가짜 객체. +/// - 선호 작품 조회는 **넘겨받은 키워드 캐시마다** 답을 정해 둔다(Stub) — 정해 두지 않은 캐시로 부르면 `.notFound`. +/// 그래서 UseCase가 키워드를 잘못 넘기면 결과가 달라진다. 키워드 순서는 따지지 않는다(`Set`). +/// - 기본 정보 동기화(명령)는 호출 횟수를 센다(Mock) — SplashData 런치 작업 테스트가 쓴다. +/// - 나머지 조회는 쓰는 테스트가 없어 `.notFound`, 나머지 명령은 아무것도 하지 않는다 — 필요해지면 그때 더한다. public final class MockProfileRepository: ProfileRepository { - - // MARK: - Call tracking - + public var novelPreferencesByCachedKeywords: [Set: NovelPreference] = [:] public private(set) var syncUserBasicInfoCallCount = 0 - public private(set) var validateNicknameCallCount = 0 - public private(set) var validatedNicknames: [String] = [] - - public private(set) var registerProfileCallCount = 0 - public private(set) var registeredProfiles: [ProfileRegistration] = [] - - public private(set) var loadAccountInfoDraftCallCount = 0 - - public private(set) var saveAccountInfoCallCount = 0 - public private(set) var savedAccountInfos: [AccountInfoDraft] = [] - - public private(set) var loadLocalGenderAndBirthCallCount = 0 - - public private(set) var loadProfileVisibilityCallCount = 0 - - public private(set) var updateProfileVisibilityCallCount = 0 - public private(set) var updatedVisibilities: [ProfileVisibility] = [] - - public private(set) var fetchUserProfileCallCount = 0 - public private(set) var fetchedUserProfileTargets: [ProfileTarget] = [] - - public private(set) var fetchGenrePreferencesCallCount = 0 - public private(set) var fetchedGenrePreferenceTargets: [ProfileTarget] = [] - - public private(set) var fetchNovelPreferencesCallCount = 0 - public private(set) var fetchedNovelPreferenceTargets: [ProfileTarget] = [] - public private(set) var fetchedNovelPreferenceCachedKeywords: [[Keyword]] = [] - - public private(set) var fetchProfileCharactersCallCount = 0 - - public private(set) var loadInitialProfileCallCount = 0 - - public private(set) var updateProfileCallCount = 0 - public private(set) var updatedDrafts: [ProfileDraft] = [] - - // MARK: - Results (set by tests) - - public var syncUserBasicInfoResult: Result = .success(()) - public var validateNicknameResult: Result = .success(false) - public var registerProfileResult: Result = .success(()) - - public var loadAccountInfoDraftResult: Result! - public var saveAccountInfoResult: Result = .success(()) - - public var loadLocalGenderAndBirthResult: Result! - - public var loadProfileVisibilityResult: Result! - public var updateProfileVisibilityResult: Result = .success(()) - - public var fetchUserProfileResult: Result! - public var fetchGenrePreferencesResult: Result<[GenrePreference], RepositoryError>! - public var fetchNovelPreferencesResult: Result! - public var fetchProfileCharactersResult: Result<[ProfileCharacter], RepositoryError>! - - public var loadInitialProfileResult: Result! - public var updateProfileResult: Result = .success(()) - public init() {} - // MARK: - ProfileRepository - public func syncUserBasicInfo() async throws(RepositoryError) { syncUserBasicInfoCallCount += 1 - switch syncUserBasicInfoResult { - case .success: - return - case .failure(let e): - throw e - } - } - - public func validateNickname(_ nickname: String) async throws(RepositoryError) -> Bool { - validateNicknameCallCount += 1 - validatedNicknames.append(nickname) - - switch validateNicknameResult { - case .success(let value): - return value - case .failure(let e): - throw e - } - } - - public func registerProfile(_ profile: ProfileRegistration) async throws(RepositoryError) { - registerProfileCallCount += 1 - registeredProfiles.append(profile) - - switch registerProfileResult { - case .success: - return - case .failure(let e): - throw e - } } - public func loadAccountInfoDraft() async throws(RepositoryError) -> AccountInfoDraft { - loadAccountInfoDraftCallCount += 1 - - switch loadAccountInfoDraftResult! { - case .success(let draft): - return draft - case .failure(let e): - throw e - } + public func fetchNovelPreferences( + _ target: ProfileTarget, + cachedKeywords: [Keyword] + ) async throws(RepositoryError) -> NovelPreference { + guard let preference = novelPreferencesByCachedKeywords[Set(cachedKeywords)] else { throw .notFound } + return preference } - public func saveAccountInfo(_ info: AccountInfoDraft) async throws(RepositoryError) { - saveAccountInfoCallCount += 1 - savedAccountInfos.append(info) - - switch saveAccountInfoResult { - case .success: - return - case .failure(let e): - throw e - } - } + public func validateNickname(_ nickname: String) async throws(RepositoryError) -> Bool { throw .notFound } - public func loadLocalGenderAndBirth() async throws(RepositoryError) -> AccountInfoDraft { - loadLocalGenderAndBirthCallCount += 1 + public func registerProfile(_ profile: ProfileRegistration) async throws(RepositoryError) {} - switch loadLocalGenderAndBirthResult! { - case .success(let draft): - return draft - case .failure(let e): - throw e - } - } + public func loadAccountInfoDraft() async throws(RepositoryError) -> AccountInfoDraft { throw .notFound } - public func loadProfileVisibility() async throws(RepositoryError) -> ProfileVisibility { - loadProfileVisibilityCallCount += 1 + public func saveAccountInfo(_ info: AccountInfoDraft) async throws(RepositoryError) {} - switch loadProfileVisibilityResult! { - case .success(let v): - return v - case .failure(let e): - throw e - } - } + public func loadLocalGenderAndBirth() async throws(RepositoryError) -> AccountInfoDraft { throw .notFound } - public func updateProfileVisibility(_ visibility: ProfileVisibility) async throws(RepositoryError) { - updateProfileVisibilityCallCount += 1 - updatedVisibilities.append(visibility) + public func loadProfileVisibility() async throws(RepositoryError) -> ProfileVisibility { throw .notFound } - switch updateProfileVisibilityResult { - case .success: - return - case .failure(let e): - throw e - } - } + public func updateProfileVisibility(_ visibility: ProfileVisibility) async throws(RepositoryError) {} - public func fetchUserProfile(target: ProfileTarget) async throws(RepositoryError) -> Profile { - fetchUserProfileCallCount += 1 - fetchedUserProfileTargets.append(target) - switch fetchUserProfileResult! { - case .success(let value): return value - case .failure(let e): throw e - } - } + public func fetchUserProfile(target: ProfileTarget) async throws(RepositoryError) -> Profile { throw .notFound } public func fetchGenrePreferences(_ target: ProfileTarget) async throws(RepositoryError) -> [GenrePreference] { - fetchGenrePreferencesCallCount += 1 - fetchedGenrePreferenceTargets.append(target) - switch fetchGenrePreferencesResult! { - case .success(let value): return value - case .failure(let e): throw e - } - } - - public func fetchNovelPreferences(_ target: ProfileTarget, cachedKeywords: [Keyword]) async throws(RepositoryError) -> NovelPreference { - fetchNovelPreferencesCallCount += 1 - fetchedNovelPreferenceTargets.append(target) - fetchedNovelPreferenceCachedKeywords.append(cachedKeywords) - switch fetchNovelPreferencesResult! { - case .success(let value): return value - case .failure(let e): throw e - } + throw .notFound } - public func fetchProfileCharacters() async throws(RepositoryError) -> [ProfileCharacter] { - fetchProfileCharactersCallCount += 1 - switch fetchProfileCharactersResult! { - case .success(let value): return value - case .failure(let e): throw e - } - } + public func fetchProfileCharacters() async throws(RepositoryError) -> [ProfileCharacter] { throw .notFound } - public func loadInitialProfile() async throws(RepositoryError) -> ProfileDraft { - loadInitialProfileCallCount += 1 - switch loadInitialProfileResult! { - case .success(let value): return value - case .failure(let e): throw e - } - } + public func loadInitialProfile() async throws(RepositoryError) -> ProfileDraft { throw .notFound } - public func updateProfile(_ profile: ProfileDraft) async throws(RepositoryError) { - updateProfileCallCount += 1 - updatedDrafts.append(profile) - - switch updateProfileResult { - case .success: return - case .failure(let e): throw e - } - } + public func updateProfile(_ profile: ProfileDraft) async throws(RepositoryError) {} } diff --git a/Projects/Domain/ProfileDomain/Tests/Entity/AccountInfoDraftTests.swift b/Projects/Domain/ProfileDomain/Tests/Entity/AccountInfoDraftTests.swift index 0ebb098e4..371e9f54e 100644 --- a/Projects/Domain/ProfileDomain/Tests/Entity/AccountInfoDraftTests.swift +++ b/Projects/Domain/ProfileDomain/Tests/Entity/AccountInfoDraftTests.swift @@ -2,60 +2,33 @@ // AccountInfoDraftTests.swift // ProfileDomain // -// Created by YunhakLee on 2/25/26. +// Created by YunhakLee on 11/24/26. // Copyright © 2026 kr.websoso.app. All rights reserved. // import Testing -@testable import ProfileDomain +import ProfileDomain -@Suite("AccountInfoDraft") +// 규칙은 없지만 설정 화면은 이 메서드로만 값을 바꾼다 — 안 담기면 고른 값 대신 옛 값이 저장된다(#308 뮤테이션). +@Suite("계정 정보 수정") struct AccountInfoDraftTests { - private func makeBirthYear(_ year: Int) -> BirthYear { - try! BirthYear(year) - } - - private func makeDraft( - email: String? = "test@email.com", - gender: Gender = .male, - birth: BirthYear = try! BirthYear(2002) - ) -> AccountInfoDraft { - AccountInfoDraft( - email: email, - gender: gender, - birth: birth - ) - } - - @Test("초기화 시 전달한 값으로 생성된다") - func initializesWithGivenValues() { - let draft = makeDraft( - email: "hello@test.com", - gender: .female, - birth: makeBirthYear(1999) - ) - - #expect(draft.email == "hello@test.com") - #expect(draft.gender == .female) - #expect(draft.birth == makeBirthYear(1999)) - } - @Test("성별을 변경할 수 있다") - func changesGender() { - var draft = makeDraft(gender: .male) + @Test("성별을 바꾸면 담긴다") + func setsGender() throws { + var draft = AccountInfoDraft(email: nil, gender: .male, birth: try BirthYear(2000)) draft.setGender(.female) #expect(draft.gender == .female) } - @Test("출생년도를 변경할 수 있다") - func changesBirthYear() { - var draft = makeDraft(birth: makeBirthYear(2000)) + @Test("생년을 바꾸면 담긴다") + func setsBirth() throws { + var draft = AccountInfoDraft(email: nil, gender: .male, birth: try BirthYear(2000)) - draft.setBirth(makeBirthYear(1995)) + draft.setBirth(try BirthYear(1999)) - #expect(draft.birth == makeBirthYear(1995)) + #expect(draft.birth == (try BirthYear(1999))) } } diff --git a/Projects/Domain/ProfileDomain/Tests/Entity/BirthYearTests.swift b/Projects/Domain/ProfileDomain/Tests/Entity/BirthYearTests.swift new file mode 100644 index 000000000..745fc1bba --- /dev/null +++ b/Projects/Domain/ProfileDomain/Tests/Entity/BirthYearTests.swift @@ -0,0 +1,51 @@ +// +// BirthYearTests.swift +// ProfileDomain +// +// Created by YunhakLee on 11/23/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation +import Testing + +import ProfileDomain + +// 상한은 고정값이 아니라 올해다(#222 — 하드코딩하면 해가 바뀔 때마다 낡는다). +// 테스트는 오늘을 2026년 6월 1일(서울)로 고정한다 — 기대값을 소스의 `maxYear`에서 가져오면 상한이 틀려도 함께 틀려 못 잡는다. +private let seoul: Calendar = { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "Asia/Seoul")! + return calendar +}() +private let today = seoul.date(from: DateComponents(year: 2026, month: 6, day: 1))! + +@Suite("생년") +struct BirthYearTests { + + @Test( + "1900년부터 올해까지는 생년으로 고를 수 있다", + arguments: [ + 1900, // 가장 이른 해 + 2026 // 올해 + ] + ) + func acceptsYearsInRange(year: Int) throws { + let birth = try BirthYear(year, today: today, calendar: seoul) + + #expect(birth.value == year) + } + + @Test( + "1900년 전이나 올해 뒤는 생년으로 고를 수 없다", + arguments: [ + 1900 - 1, // 가장 이른 해 바로 전 + 2027 // 내년 + ] + ) + func rejectsYearsOutOfRange(year: Int) { + #expect(throws: BirthYear.ValidationError.invalidRange) { + try BirthYear(year, today: today, calendar: seoul) + } + } +} diff --git a/Projects/Domain/ProfileDomain/Tests/Entity/NicknameDraftTests.swift b/Projects/Domain/ProfileDomain/Tests/Entity/NicknameDraftTests.swift index 1e282b279..2153c248b 100644 --- a/Projects/Domain/ProfileDomain/Tests/Entity/NicknameDraftTests.swift +++ b/Projects/Domain/ProfileDomain/Tests/Entity/NicknameDraftTests.swift @@ -8,131 +8,161 @@ import Testing -@testable import ProfileDomain +import ProfileDomain -@Suite("NicknameDraft") +@Suite("닉네임 입력") struct NicknameDraftTests { - // MARK: - Helpers + @Suite("입력 길이") + struct Length { - private func makeDraft(initial: String = "기존닉네임") -> NicknameDraft { - NicknameDraft(initial) - } + @Test("닉네임은 10자까지만 입력된다") + func clipsToMaxLength() { + var draft = NicknameDraft("서연") - // MARK: - Init + draft.setText(String(repeating: "가", count: 11)) - @Test("초기화 시 text는 초기 닉네임이다") - func initSetsTextToInitialName() { - let draft = NicknameDraft("윤학") - #expect(draft.text == "윤학") - } - - // MARK: - Length clipping - - @Test("닉네임은 최대 10자까지만 입력된다") - func clipsToMaxLength10() { - var draft = makeDraft() - draft.setText("일이삼사오육칠팔구십일") // 11 chars - #expect(draft.text == "일이삼사오육칠팔구십") - } + #expect(draft.text == String(repeating: "가", count: 10)) + } - // MARK: - notAvailable + @Test("10자를 넘겨 쳐도 잘린 결과가 같으면 중복 확인 결과가 그대로다") + func keepsDuplicationCheckWhenClippedTextIsSame() { + let tenLetters = String(repeating: "가", count: 10) + var draft = NicknameDraft("서연") + draft.setText(tenLetters) + draft.applyDuplicationCheckResult(.notDuplicated, checkedText: tenLetters) - @Test("닉네임이 비어있으면 어떠한 검증도 불가하므로 notStarted 상태다") - func emptyTextIsNotStarted() { - let draft = makeDraft(initial: "") - #expect(draft.validationState == .notStarted) - } - - @Test("초기 닉네임과 동일하면 notAvailable(notChanged) 상태다") - func initialSameAsLastNicknameIsNotChanged() { - let draft = makeDraft(initial: "윤학") - #expect(draft.validationState == .notAvailable(reason: .notChanged)) - } - - @Test("초기 닉네임으로 되돌리면 notAvailable(notChanged) 상태다") - func revertingToLastNicknameIsNotChanged() { - var draft = makeDraft(initial: "윤학") - draft.setText("abcd") - #expect(draft.validationState == .needDuplicatedCheck) - - draft.setText("윤학") - #expect(draft.validationState == .notAvailable(reason: .notChanged)) + draft.setText(tenLetters + "나") + + #expect(draft.validationState == .available) + } } - @Test("공백 또는 줄바꿈/탭이 포함되면 notAvailable(whiteSpaceIncluded) 상태다") - func whitespaceIncludedIsNotAvailable() { - var draft = makeDraft(initial: "윤학") + @Suite("입력 상태") + struct Validation { - draft.setText("ab cd") - #expect(draft.validationState == .notAvailable(reason: .whiteSpaceIncluded)) + @Test("닉네임이 비어 있으면 아직 입력 전 상태다") + func emptyIsNotStarted() { + var draft = NicknameDraft("서연") - draft.setText("ab\tcd") - #expect(draft.validationState == .notAvailable(reason: .whiteSpaceIncluded)) + draft.setText("") - draft.setText("ab\ncd") - #expect(draft.validationState == .notAvailable(reason: .whiteSpaceIncluded)) - } + #expect(draft.validationState == .notStarted) + } - @Test("정규식 조건을 만족하지 않으면 notAvailable(invalidCharacterOrLimitExceeded) 상태다") - func invalidPatternIsNotAvailable() { - var draft = makeDraft(initial: "윤학") - draft.setText("ab!cd") // '!' not allowed - #expect(draft.validationState == .notAvailable(reason: .invalidCharacterOrLimitExceeded)) - } + @Test("처음 닉네임과 같으면 바뀌지 않아 쓸 수 없다") + func initialNicknameIsNotChanged() { + let draft = NicknameDraft("서연") - // MARK: - Duplication check flow + let state = draft.validationState - @Test("유효한 닉네임을 입력했지만 중복 검사 전이면 needDuplicatedCheck 상태다") - func validButNotCheckedIsNeedDuplicatedCheck() { - var draft = makeDraft(initial: "윤학") - draft.setText("abcd") // valid, changed - #expect(draft.validationState == .needDuplicatedCheck) - } + #expect(state == .notAvailable(reason: .notChanged)) + } - @Test("중복 검사 결과가 duplicated면 notAvailable(duplicated) 상태다") - func duplicatedResultMakesNotAvailableDuplicated() { - var draft = makeDraft(initial: "윤학") - draft.setText("abcd") + @Test("다른 닉네임을 쳤다가 처음 닉네임으로 되돌리면 바뀌지 않아 쓸 수 없다") + func revertedNicknameIsNotChanged() { + var draft = NicknameDraft("서연") + draft.setText("새이름") - draft.applyDuplicationCheckResult(.duplicated, checkedText: "abcd") - #expect(draft.validationState == .notAvailable(reason: .duplicated)) - } + draft.setText("서연") - @Test("중복 검사 결과가 notDuplicated면 available 상태다") - func notDuplicatedResultMakesAvailable() { - var draft = makeDraft(initial: "윤학") - draft.setText("abcd") + #expect(draft.validationState == .notAvailable(reason: .notChanged)) + } - draft.applyDuplicationCheckResult(.notDuplicated, checkedText: "abcd") - #expect(draft.validationState == .available) - } + @Test( + "공백·줄바꿈·탭이 들어가면 쓸 수 없다", + arguments: [ + "새 이름", // 가운데 공백 + "새이름\n", // 줄바꿈 + "새\t이름" // 탭 + ] + ) + func whitespaceIsNotAvailable(text: String) { + var draft = NicknameDraft("서연") + + draft.setText(text) + + #expect(draft.validationState == .notAvailable(reason: .whiteSpaceIncluded)) + } + + @Test("공백이 들어가 있으면 처음 닉네임과 같아도 공백 때문에 쓸 수 없다고 알린다") + func whitespaceIsReportedBeforeNotChanged() { + let draft = NicknameDraft("서 연") + + let state = draft.validationState - @Test("중복 검사 결과는 검사를 실행한 checkedText가 현재 text와 다르면 무시된다(비동기 동작 대비)") - func ignoresDuplicationResultWhenCheckedTextMismatch() { - var draft = makeDraft(initial: "윤학") - draft.setText("abcd") + #expect(state == .notAvailable(reason: .whiteSpaceIncluded)) + } - // user typed again before response arrives - draft.setText("abcde") + @Test( + "한 글자이거나 한글·영문·숫자 말고 다른 문자가 있으면 쓸 수 없다", + arguments: [ + "가", // 한 글자 — 두 글자부터 쓸 수 있다 + "새이름!", // 특수문자 + "ㄱㄴㄷ" // 완성되지 않은 한글(자음만) + ] + ) + func invalidPatternIsNotAvailable(text: String) { + var draft = NicknameDraft("서연") - // late response for old text - draft.applyDuplicationCheckResult(.notDuplicated, checkedText: "abcd") + draft.setText(text) - // still need check for current text - #expect(draft.validationState == .needDuplicatedCheck) + #expect(draft.validationState == .notAvailable(reason: .invalidCharacterOrLimitExceeded)) + } + + @Test("두 글자이고 규칙에 맞으면 중복 확인이 필요하다") + func shortestValidNicknameNeedsDuplicationCheck() { + var draft = NicknameDraft("서연") + + draft.setText("Ab") + + #expect(draft.validationState == .needDuplicatedCheck) + } } - @Test("텍스트가 변경되면 중복 검사 상태는 notYet으로 리셋된다") - func changingTextResetsDuplicationState() { - var draft = makeDraft(initial: "윤학") - draft.setText("abcd") - draft.applyDuplicationCheckResult(.notDuplicated, checkedText: "abcd") - #expect(draft.validationState == .available) - - // change -> should require check again - // isValidPattern && notYet -> needDuplicatedCheck - draft.setText("abcde") - #expect(draft.validationState == .needDuplicatedCheck) + @Suite("중복 확인") + struct DuplicationCheck { + + @Test("중복이면 쓸 수 없다") + func duplicatedIsNotAvailable() { + var draft = NicknameDraft("서연") + draft.setText("새이름") + + draft.applyDuplicationCheckResult(.duplicated, checkedText: "새이름") + + #expect(draft.validationState == .notAvailable(reason: .duplicated)) + } + + @Test("중복이 아니면 쓸 수 있다") + func notDuplicatedIsAvailable() { + var draft = NicknameDraft("서연") + draft.setText("새이름") + + draft.applyDuplicationCheckResult(.notDuplicated, checkedText: "새이름") + + #expect(draft.validationState == .available) + } + + @Test("확인하는 사이에 닉네임이 바뀌었으면 늦게 온 결과는 버린다") + func ignoresResultForOldText() { + var draft = NicknameDraft("서연") + draft.setText("새이름") + draft.setText("새이름1") + + draft.applyDuplicationCheckResult(.notDuplicated, checkedText: "새이름") + + #expect(draft.validationState == .needDuplicatedCheck) + } + + @Test("중복 확인 뒤 닉네임을 고치면 다시 확인해야 한다") + func editingAfterCheckNeedsCheckAgain() { + var draft = NicknameDraft("서연") + draft.setText("새이름") + draft.applyDuplicationCheckResult(.notDuplicated, checkedText: "새이름") + + draft.setText("새이름1") + + #expect(draft.validationState == .needDuplicatedCheck) + } } } diff --git a/Projects/Domain/ProfileDomain/Tests/Entity/ProfileDraftTests.swift b/Projects/Domain/ProfileDomain/Tests/Entity/ProfileDraftTests.swift index d5bbe35e0..95fa68e7d 100644 --- a/Projects/Domain/ProfileDomain/Tests/Entity/ProfileDraftTests.swift +++ b/Projects/Domain/ProfileDomain/Tests/Entity/ProfileDraftTests.swift @@ -8,301 +8,234 @@ import Testing -@testable import ProfileDomain import BaseDomain +import ProfileDomain -@Suite("ProfileDraft") -struct ProfileDraftTests { - - // MARK: - Init - - @Test("초기화 시 전달한 값으로 생성된다") - func initializesWithGivenValues() { - let genre = makeGenre() - let draft = makeDraft(characterID: 3, - nickname: "서연", - introduction: "반가워요", - genrePreferences: [genre]) - - #expect(draft.characterID == 3) - #expect(draft.nickname.text == "서연") - #expect(draft.introduction == "반가워요") - #expect(draft.genrePreferences == [genre]) - } - - // MARK: - Change Detection - - @Test("초기화 직후에는 변경된 항목이 없다") - func noChangesRightAfterInit() { - let draft = makeDraft() - - #expect(draft.isCharacterChanged == false) - #expect(draft.isNicknameChanged == false) - #expect(draft.isIntroductionChanged == false) - #expect(draft.isGenrePreferencesChanged == false) - } - - @Test("다른 캐릭터로 변경하면 isCharacterChanged가 true다") - func isCharacterChangedWhenDifferentID() { - var draft = makeDraft(characterID: 1) - draft.setCharacter(2) - - #expect(draft.isCharacterChanged == true) - } - - @Test("동일한 캐릭터로 설정하면 isCharacterChanged가 false다") - func isCharacterNotChangedWhenSameID() { - var draft = makeDraft(characterID: 1) - draft.setCharacter(1) - - #expect(draft.isCharacterChanged == false) - } +// 프로필 수정 화면은 저장소가 불러온 값으로 시작한다. 장르 개수는 수정 화면에서 쓰지 않아 0으로 채워 온다. +private let romance = GenrePreference(genre: .romance, count: 0) +private let fantasy = GenrePreference(genre: .fantasy, count: 0) - @Test("닉네임이 변경되고 중복확인까지 통과하면 isNicknameChanged가 true다") - func isNicknameChangedWhenAvailable() { - let draft = makeDraftWithAvailableNickname() - - #expect(draft.isNicknameChanged == true) - } - - @Test("닉네임이 변경됐지만 중복확인 전이면 isNicknameChanged가 false다") - func isNicknameNotChangedBeforeDuplicationCheck() { - var draft = makeDraft(nickname: "서연") - draft.updateNickname("newNick") - - #expect(draft.isNicknameChanged == false) - } - - @Test("소개글을 다른 값으로 변경하면 isIntroductionChanged가 true다") - func isIntroductionChangedWhenDifferent() { - var draft = makeDraft(introduction: "안녕하세요") - draft.updateIntroduction("반가워요") - - #expect(draft.isIntroductionChanged == true) - } - - @Test("소개글을 초기값으로 되돌리면 isIntroductionChanged가 false다") - func isIntroductionNotChangedWhenReverted() { - var draft = makeDraft(introduction: "안녕하세요") - draft.updateIntroduction("반가워요") - draft.updateIntroduction("안녕하세요") +private func makeDraft() -> ProfileDraft { + ProfileDraft(characterID: 1, nickname: "서연", introduction: "반가워요", genrePreferences: [romance]) +} - #expect(draft.isIntroductionChanged == false) +/// 저장 가능 여부를 볼 때 바꿔 볼 항목 하나. +enum Edit: CaseIterable { + case character + case nickname + case introduction + case genre + + func apply(to draft: inout ProfileDraft) { + switch self { + case .character: + draft.setCharacter(2) + case .nickname: + draft.updateNickname("새이름") + draft.applyNicknameDuplicationCheck(.notDuplicated, checkedText: "새이름") + case .introduction: + draft.updateIntroduction("새 소개") + case .genre: + draft.addGenrePreference(fantasy) + } } +} - @Test("장르를 추가하면 isGenrePreferencesChanged가 true다") - func isGenreChangedAfterAdd() { - var draft = makeDraft(genrePreferences: []) - draft.addGenrePreference(makeGenre()) - - #expect(draft.isGenrePreferencesChanged == true) +/// 다른 항목을 바꿔도 저장을 막는 닉네임 상태. +// 빈 닉네임은 여기 없다 — 지금은 다른 항목을 바꾸면 저장되는데, 막아야 할 동작이라 #309에서 고친다. +enum BlockingNickname: CaseIterable { + case notChecked + case duplicated + case whitespace + case invalidPattern + + func apply(to draft: inout ProfileDraft) { + switch self { + case .notChecked: + draft.updateNickname("새이름") + case .duplicated: + draft.updateNickname("새이름") + draft.applyNicknameDuplicationCheck(.duplicated, checkedText: "새이름") + case .whitespace: + draft.updateNickname("새 이름") + case .invalidPattern: + draft.updateNickname("새이름!") + } } +} - @Test("장르를 추가했다가 삭제해 초기 상태로 돌아오면 isGenrePreferencesChanged가 false다") - func isGenreNotChangedWhenReverted() { - let genre = makeGenre() - var draft = makeDraft(genrePreferences: [genre]) - draft.removeGenrePreference(genre) - draft.addGenrePreference(genre) - - #expect(draft.isGenrePreferencesChanged == false) - } +@Suite("프로필 수정") +struct ProfileDraftTests { - // MARK: - isSubmittable + @Suite("바뀐 것 알아보기") + struct ChangeDetection { - @Test("아무것도 변경되지 않으면 isSubmittable이 false다") - func notSubmittableWhenNothingChanged() { - let draft = makeDraft() + @Test("처음에는 바뀐 것이 없다") + func nothingChangedAtFirst() { + let draft = makeDraft() - #expect(draft.isSubmittable == false) - } + let changes = [ + draft.isCharacterChanged, + draft.isNicknameChanged, + draft.isIntroductionChanged, + draft.isGenrePreferencesChanged + ] - @Test("캐릭터만 변경해도 isSubmittable이 true다") - func submittableWhenOnlyCharacterChanged() { - var draft = makeDraft(characterID: 1) - draft.setCharacter(2) + #expect(changes == [false, false, false, false]) + } - #expect(draft.isSubmittable == true) - } + @Test("다른 캐릭터를 고르면 캐릭터가 바뀐 것이다") + func otherCharacterIsChanged() { + var draft = makeDraft() - @Test("닉네임만 변경하고 중복확인까지 통과하면 isSubmittable이 true다") - func submittableWhenNicknameAvailable() { - let draft = makeDraftWithAvailableNickname() + draft.setCharacter(2) - #expect(draft.isSubmittable == true) - } + #expect(draft.isCharacterChanged) + } - @Test("소개글만 변경해도 isSubmittable이 true다") - func submittableWhenOnlyIntroductionChanged() { - var draft = makeDraft(introduction: "안녕하세요") - draft.updateIntroduction("반가워요") + @Test("같은 캐릭터를 다시 고르면 캐릭터가 바뀐 것이 아니다") + func sameCharacterIsNotChanged() { + var draft = makeDraft() - #expect(draft.isSubmittable == true) - } + draft.setCharacter(1) - @Test("장르만 변경해도 isSubmittable이 true다") - func submittableWhenOnlyGenreChanged() { - var draft = makeDraft(genrePreferences: []) - draft.addGenrePreference(makeGenre()) + #expect(!draft.isCharacterChanged) + } - #expect(draft.isSubmittable == true) - } + @Test( + "닉네임은 중복 확인까지 통과해야 바뀐 것이다", + arguments: [ + (NicknameDraft.DuplicationCheckState.notYet, false), // 확인 전 + (.duplicated, false), // 중복 + (.notDuplicated, true) // 통과 + ] + ) + func nicknameIsChangedOnlyAfterPassingCheck( + check: NicknameDraft.DuplicationCheckState, + isChanged: Bool + ) { + var draft = makeDraft() + draft.updateNickname("새이름") - @Test("닉네임이 중복확인 필요 상태면 다른 필드가 변경되어도 isSubmittable이 false다") - func notSubmittableWhenNeedDuplicatedCheck() { - var draft = makeDraft(nickname: "서연") - draft.updateNickname("newNick") // needDuplicatedCheck - draft.setCharacter(2) + draft.applyNicknameDuplicationCheck(check, checkedText: "새이름") - #expect(draft.isSubmittable == false) - } + #expect(draft.isNicknameChanged == isChanged) + } - @Test("닉네임이 중복이면 다른 필드가 변경되어도 isSubmittable이 false다") - func notSubmittableWhenNicknameDuplicated() { - var draft = makeDraft(nickname: "서연") - draft.updateNickname("newNick") - draft.applyNicknameDuplicationCheck(.duplicated, checkedText: "newNick") - draft.setCharacter(2) + @Test("소개글을 고쳤다가 처음대로 되돌리면 바뀐 것이 아니다") + func revertedIntroductionIsNotChanged() { + var draft = makeDraft() + draft.updateIntroduction("새 소개") - #expect(draft.isSubmittable == false) - } + draft.updateIntroduction("반가워요") - @Test("닉네임에 공백이 포함되면 다른 필드가 변경되어도 isSubmittable이 false다") - func notSubmittableWhenNicknameHasWhitespace() { - var draft = makeDraft(nickname: "서연") - draft.updateNickname("new Nick") - draft.setCharacter(2) + #expect(!draft.isIntroductionChanged) + } - #expect(draft.isSubmittable == false) - } + @Test("장르를 넣었다 빼서 처음과 같아지면 바뀐 것이 아니다") + func revertedGenresAreNotChanged() { + var draft = makeDraft() + draft.addGenrePreference(fantasy) - @Test("닉네임이 유효하지 않은 패턴이면 다른 필드가 변경되어도 isSubmittable이 false다") - func notSubmittableWhenNicknameInvalidPattern() { - var draft = makeDraft(nickname: "서연") - draft.updateNickname("ab!cd") - draft.setCharacter(2) + draft.removeGenrePreference(fantasy) - #expect(draft.isSubmittable == false) + #expect(!draft.isGenrePreferencesChanged) + } } - // MARK: - update Introduction + @Suite("저장 가능 여부") + struct Submittable { - @Test("소개글 50자 이하면 그대로 저장된다") - func keepsIntroductionUnder50Characters() { - var draft = makeDraft() - let text = String(repeating: "가", count: 50) - draft.updateIntroduction(text) + @Test("아무것도 안 바꾸면 저장할 수 없다") + func cannotSubmitWithoutChanges() { + let draft = makeDraft() - #expect(draft.introduction.count == 50) - } + let isSubmittable = draft.isSubmittable - @Test("소개글이 50자를 초과하면 50자까지만 저장된다") - func clipsIntroductionTo50Characters() { - var draft = makeDraft() - let text = String(repeating: "가", count: 60) - draft.updateIntroduction(text) + #expect(!isSubmittable) + } - #expect(draft.introduction.count == 50) - } - - @Test("소개글에 앞뒤 공백이 포함되어도 그대로 저장된다") - func allowsWhitespaceInIntroduction() { - var draft = makeDraft() - draft.updateIntroduction(" 공백 포함 ") + @Test("캐릭터·닉네임·소개글·장르 중 하나만 바꿔도 저장할 수 있다", arguments: Edit.allCases) + func canSubmitWithOneChange(edit: Edit) { + var draft = makeDraft() - #expect(draft.introduction == " 공백 포함 ") - } + edit.apply(to: &draft) - @Test("소개글을 빈 문자열로 업데이트할 수 있다") - func allowsEmptyIntroduction() { - var draft = makeDraft(introduction: "안녕하세요") - draft.updateIntroduction("") + #expect(draft.isSubmittable) + } - #expect(draft.introduction == "") - } - - // MARK: - truncate Introduction To Line Limit + @Test( + "닉네임이 확인 전·중복·공백·규칙 위반이면 다른 걸 바꿔도 저장할 수 없다", + arguments: BlockingNickname.allCases + ) + func blockingNicknamePreventsSubmit(nickname: BlockingNickname) { + var draft = makeDraft() + draft.updateIntroduction("새 소개") - @Test("소개글이 3줄 이하면 그대로 저장된다") - func keeps3LinesExactlyOnTruncate() { - var draft = makeDraft() - draft.updateIntroduction("1줄\n2줄\n3줄") - draft.truncateIntroductionToLineLimit() + nickname.apply(to: &draft) - #expect(draft.introduction == "1줄\n2줄\n3줄") + #expect(!draft.isSubmittable) + } } - @Test("소개글이 3줄을 초과하면 3줄까지만 저장된다") - func clipsIntroductionTo3LinesOnTruncate() { - var draft = makeDraft() - draft.updateIntroduction("1줄\n2줄\n3줄\n4줄") - draft.truncateIntroductionToLineLimit() + @Suite("소개글") + struct Introduction { - #expect(draft.introduction == "1줄\n2줄\n3줄") - } - - // MARK: - Genre Preference + @Test( + "소개글은 50자까지만 입력된다", + arguments: [ + (50, 50), // 딱 50자는 그대로 + (51, 50) // 넘치면 50자로 자른다 + ] + ) + func clipsToMaxLength(inputCount: Int, savedCount: Int) { + var draft = makeDraft() + // 50자를 넘는 글자만 "나"로 둬서, 잘려 나간 쪽이 뒤인지 확인한다. + let introduction = String(repeating: "가", count: 50) + String(repeating: "나", count: inputCount - 50) + + draft.updateIntroduction(introduction) + + #expect(draft.introduction == String(repeating: "가", count: savedCount)) + } + + // 줄 수 판단이 자르기 전 소개글을 봐서, 넷째 줄만 더하면 바뀐 게 없는데 저장할 수 있다 — #309에서 고친다. + @Test( + "저장 직전에 소개글을 세 줄까지만 남긴다", + arguments: [ + ("하나\n둘\n셋", "하나\n둘\n셋"), // 세 줄은 그대로 + ("하나\n둘\n셋\n넷", "하나\n둘\n셋") // 넷째 줄부터 버린다 + ] + ) + func keepsUpToThreeLinesBeforeSaving(typed: String, saved: String) { + var draft = makeDraft() + draft.updateIntroduction(typed) - @Test("장르를 추가할 수 있다") - func addsGenrePreference() { - var draft = makeDraft() - let genre = makeGenre(genre: .romance) - draft.addGenrePreference(genre) + draft.truncateIntroductionToLineLimit() - #expect(draft.genrePreferences.contains(genre)) + #expect(draft.introduction == saved) + } } - @Test("장르를 삭제할 수 있다") - func removesGenrePreference() { - let genre = makeGenre(genre: .romance) - var draft = makeDraft(genrePreferences: [genre]) - draft.removeGenrePreference(genre) + // 장르는 장르+개수가 모두 같아야 빠지고, 뺐다 다시 넣으면 순서가 바뀌어 바뀐 것으로 본다 — #309에서 고친다. + @Suite("선호 장르") + struct GenrePreferences { - #expect(draft.genrePreferences.isEmpty) - } + @Test("장르를 고르면 담긴다") + func addsGenre() { + var draft = makeDraft() - @Test("존재하지 않는 장르를 삭제해도 기존 장르는 유지된다") - func removingNonExistentGenreKeepsOthers() { - let romance = makeGenre(genre: .romance) - let fantasy = makeGenre(genre: .fantasy) - var draft = makeDraft(genrePreferences: [romance]) - draft.removeGenrePreference(fantasy) + draft.addGenrePreference(fantasy) - #expect(draft.genrePreferences == [romance]) - } -} + #expect(draft.genrePreferences == [romance, fantasy]) + } -extension ProfileDraftTests { - - // MARK: - Helpers - - private func makeDraft( - characterID: Int = 1, - nickname: String = "서연", - introduction: String = "안녕하세요", - genrePreferences: [GenrePreference] = [] - ) -> ProfileDraft { - ProfileDraft( - characterID: characterID, - nickname: nickname, - introduction: introduction, - genrePreferences: genrePreferences - ) - } + @Test("고른 장르를 빼면 사라진다") + func removesGenre() { + var draft = makeDraft() - private func makeGenre(genre: NovelGenre = .romance) -> GenrePreference { - GenrePreference(genre: genre, count: 0) - } + draft.removeGenrePreference(romance) - // 닉네임 변경 + 중복확인까지 통과한 draft - private func makeDraftWithAvailableNickname( - initial: String = "서연", - new: String = "newNick" - ) -> ProfileDraft { - var draft = makeDraft(nickname: initial) - draft.updateNickname(new) - draft.applyNicknameDuplicationCheck(.notDuplicated, checkedText: new) - return draft + #expect(draft.genrePreferences == []) + } } - } diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadAccountInfoDraftUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/LoadAccountInfoDraftUseCaseTests.swift deleted file mode 100644 index 2c11f6752..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadAccountInfoDraftUseCaseTests.swift +++ /dev/null @@ -1,50 +0,0 @@ -// -// LoadAccountInfoDraftUseCaseTests.swift -// ProfileDomain -// -// Created by YunhakLee on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("LoadAccountInfoDraftUseCase") -struct LoadAccountInfoDraftUseCaseTests { - - private func makeAccountInfoDraft() -> AccountInfoDraft { - // ✅ 프로젝트 타입에 맞게 여기만 조정하면 됨 - AccountInfoDraft(email: "H@Gmail.com", gender: .female, birth: try! BirthYear(1990)) - } - - @Test("계정 정보 초안을 조회할 수 있다") - func loadsAccountInfoDraft() async throws { - let repo = MockProfileRepository() - let expected = makeAccountInfoDraft() - repo.loadAccountInfoDraftResult = .success(expected) - - let sut = DefaultLoadAccountInfoDraftUseCase(repository: repo) - - let result = try await sut.execute() - - #expect(repo.loadAccountInfoDraftCallCount == 1) - #expect(result == expected) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.loadAccountInfoDraftResult = .failure(.notFound) - - let sut = DefaultLoadAccountInfoDraftUseCase(repository: repo) - - await #expect(throws: RepositoryError.notFound) { - _ = try await sut.execute() - } - - #expect(repo.loadAccountInfoDraftCallCount == 1) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadGenrePreferencesUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/LoadGenrePreferencesUseCaseTests.swift deleted file mode 100644 index 78afad5c2..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadGenrePreferencesUseCaseTests.swift +++ /dev/null @@ -1,68 +0,0 @@ -// -// LoadGenrePreferencesUseCaseTests.swift -// ProfileDomain -// -// Created by Seoyeon Choi on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("LoadGenrePreferencesUseCase") -struct LoadGenrePreferencesUseCaseTests { - - @Test("장르 취향 목록을 반환한다") - func returnsGenrePreferences() async throws { - let repo = MockProfileRepository() - let expected = [makeGenre(genre: .romance), makeGenre(genre: .fantasy)] - repo.fetchGenrePreferencesResult = .success(expected) - - let sut = DefaultLoadGenrePreferencesUseCase(profileRepository: repo) - - let result = try await sut.execute(.me) - - #expect(repo.fetchGenrePreferencesCallCount == 1) - guard case .me = repo.fetchedGenrePreferenceTargets.first else { - Issue.record(".me 타겟이 전달되어야 한다") - return - } - #expect(result == expected) - } - - @Test("장르 취향이 없으면 빈 배열을 반환한다") - func returnsEmptyWhenNoGenrePreferences() async throws { - let repo = MockProfileRepository() - repo.fetchGenrePreferencesResult = .success([]) - - let sut = DefaultLoadGenrePreferencesUseCase(profileRepository: repo) - - let result = try await sut.execute(.me) - - #expect(result.isEmpty) - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.fetchGenrePreferencesResult = .failure(.serverUnavailable) - - let sut = DefaultLoadGenrePreferencesUseCase(profileRepository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - _ = try await sut.execute(.me) - } - - #expect(repo.fetchGenrePreferencesCallCount == 1) - } -} - -extension LoadGenrePreferencesUseCaseTests { - - private func makeGenre(genre: NovelGenre = .romance) -> GenrePreference { - GenrePreference(genre: genre, count: 0) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadLocalGenderAndBirthUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/LoadLocalGenderAndBirthUseCaseTests.swift deleted file mode 100644 index 944fb5bbe..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadLocalGenderAndBirthUseCaseTests.swift +++ /dev/null @@ -1,49 +0,0 @@ -// -// LoadLocalGenderAndBirthUseCaseTests.swift -// ProfileDomain -// -// Created by Seoyeon Choi on 7/16/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("LoadLocalGenderAndBirthUseCase") -struct LoadLocalGenderAndBirthUseCaseTests { - - private func makeAccountInfoDraft() -> AccountInfoDraft { - AccountInfoDraft(email: nil, gender: .female, birth: try! BirthYear(1990)) - } - - @Test("userDefaults에 저장된 성별/출생연도를 조회할 수 있다") - func loadsLocalGenderAndBirth() async throws { - let repo = MockProfileRepository() - let expected = makeAccountInfoDraft() - repo.loadLocalGenderAndBirthResult = .success(expected) - - let sut = DefaultLoadLocalGenderAndBirthUseCase(repository: repo) - - let result = try await sut.execute() - - #expect(repo.loadLocalGenderAndBirthCallCount == 1) - #expect(result == expected) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.loadLocalGenderAndBirthResult = .failure(.notFound) - - let sut = DefaultLoadLocalGenderAndBirthUseCase(repository: repo) - - await #expect(throws: RepositoryError.notFound) { - _ = try await sut.execute() - } - - #expect(repo.loadLocalGenderAndBirthCallCount == 1) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadNovelPreferencesUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/LoadNovelPreferencesUseCaseTests.swift index dc3d44280..81f89a2bb 100644 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadNovelPreferencesUseCaseTests.swift +++ b/Projects/Domain/ProfileDomain/Tests/UseCase/LoadNovelPreferencesUseCaseTests.swift @@ -2,72 +2,63 @@ // LoadNovelPreferencesUseCaseTests.swift // ProfileDomain // -// Created by Seoyeon Choi on 2/25/26. +// Created by YunhakLee on 11/23/26. // Copyright © 2026 kr.websoso.app. All rights reserved. // import Testing -@testable import ProfileDomain -import ProfileDomainTesting import BaseDomain +import BaseDomainTesting +import ProfileDomain +import ProfileDomainTesting -@Suite("LoadNovelPreferencesUseCase") -struct LoadNovelPreferencesUseCaseTests { +// 서버는 선호 키워드를 이름으로만 준다. 앱은 전체 키워드 목록에서 같은 이름을 찾아 키워드로 바꾸므로, +// 불러오는 UseCase는 모든 카테고리의 키워드를 넘겨야 한다. +// 카테고리를 둘로 나눠 둬서, 한 카테고리의 키워드만 넘기면 저장소가 답을 찾지 못한다. +private let keywordGroups = [ + KeywordGroup(category: .material, keywords: [ + Keyword(id: KeywordID(11), name: "회귀") + ]), + KeywordGroup(category: .character, keywords: [ + Keyword(id: KeywordID(21), name: "먼치킨"), + Keyword(id: KeywordID(22), name: "사이다") + ]) +] +private let allKeywords = Set(keywordGroups.flatMap(\.keywords)) - @Test("작품 취향을 반환한다") - func returnsNovelPreferences() async throws { - let repo = MockProfileRepository() - let expected = makeNovelPreference(attractivePoints: [.worldview, .character]) - repo.fetchNovelPreferencesResult = .success(expected) +@Suite("선호 작품 불러오기") +struct LoadNovelPreferencesUseCaseTests { - let sut = DefaultLoadNovelPreferencesUseCase( - profileRepository: repo, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: StubKeywordRepository()) + @Test("선호 작품을 불러올 때 모든 카테고리의 키워드를 넘긴다") + func passesKeywordsOfAllCategories() async throws { + let profileRepository = MockProfileRepository() + profileRepository.novelPreferencesByCachedKeywords = [ + allKeywords: NovelPreference(attractivePoints: [.vibe], keywords: []) + ] + let useCase = DefaultLoadNovelPreferencesUseCase( + profileRepository: profileRepository, + loadTotalKeywordsUseCase: MockLoadTotalKeywordsUseCase(result: .success(keywordGroups)) ) - let result = try await sut.execute(.me) + let preference = try await useCase.execute(.me) - #expect(repo.fetchNovelPreferencesCallCount == 1) - guard case .me = repo.fetchedNovelPreferenceTargets.first else { - Issue.record(".me 타겟이 전달되어야 한다") - return - } - #expect(result.attractivePoints == expected.attractivePoints) - #expect(result.keywords == expected.keywords) + #expect(preference.attractivePoints == [.vibe]) } - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.fetchNovelPreferencesResult = .failure(.serverUnavailable) - - let sut = DefaultLoadNovelPreferencesUseCase( - profileRepository: repo, - loadTotalKeywordsUseCase: DefaultLoadTotalKeywordsUseCase(keywordRepository: StubKeywordRepository()) + @Test("전체 키워드를 못 불러와도 선호 작품은 불러온다") + func loadsWithoutKeywords() async throws { + let profileRepository = MockProfileRepository() + profileRepository.novelPreferencesByCachedKeywords = [ + []: NovelPreference(attractivePoints: [.vibe], keywords: []) + ] + let useCase = DefaultLoadNovelPreferencesUseCase( + profileRepository: profileRepository, + loadTotalKeywordsUseCase: MockLoadTotalKeywordsUseCase(result: .failure(.networkUnavailable)) ) - await #expect(throws: RepositoryError.serverUnavailable) { - _ = try await sut.execute(.me) - } - - #expect(repo.fetchNovelPreferencesCallCount == 1) - } -} - -private final class StubKeywordRepository: KeywordRepository { - func fetchKeywords() async throws(RepositoryError) -> [KeywordGroup] { [] } - func searchKeywords(_ query: String) async throws(RepositoryError) -> [KeywordGroup] { [] } - func syncKeywords() async {} - func fetchPopularKeywords() async throws(RepositoryError) -> PopularKeywords { PopularKeywords(keywords: []) } -} - -extension LoadNovelPreferencesUseCaseTests { + let preference = try await useCase.execute(.me) - private func makeNovelPreference( - attractivePoints: [AttractivePoint] = [], - keywords: [KeywordPreference] = [] - ) -> NovelPreference { - NovelPreference(attractivePoints: attractivePoints, keywords: keywords) + #expect(preference.attractivePoints == [.vibe]) } } diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileCharacterUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileCharacterUseCaseTests.swift deleted file mode 100644 index 04d0de011..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileCharacterUseCaseTests.swift +++ /dev/null @@ -1,75 +0,0 @@ -// -// LoadProfileCharacterUseCaseTests.swift -// ProfileDomain -// -// Created by Seoyeon Choi on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("LoadProfileCharacterUseCase") -struct LoadProfileCharacterUseCaseTests { - - @Test("프로필 캐릭터 목록을 반환한다") - func returnsProfileCharacters() async throws { - let repo = MockProfileRepository() - let expected = [makeCharacter(id: 1, isRepresentative: true), makeCharacter(id: 2)] - repo.fetchProfileCharactersResult = .success(expected) - - let sut = DefaultLoadProfileCharacterUseCase(profileRepository: repo) - - let result = try await sut.execute() - - #expect(repo.fetchProfileCharactersCallCount == 1) - #expect(result.count == 2) - #expect(result.first?.id == 1) - } - - @Test("캐릭터가 없으면 빈 배열을 반환한다") - func returnsEmptyWhenNoCharacters() async throws { - let repo = MockProfileRepository() - repo.fetchProfileCharactersResult = .success([]) - - let sut = DefaultLoadProfileCharacterUseCase(profileRepository: repo) - - let result = try await sut.execute() - - #expect(result.isEmpty) - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.fetchProfileCharactersResult = .failure(.serverUnavailable) - - let sut = DefaultLoadProfileCharacterUseCase(profileRepository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - _ = try await sut.execute() - } - - #expect(repo.fetchProfileCharactersCallCount == 1) - } -} - -extension LoadProfileCharacterUseCaseTests { - - private func makeCharacter( - id: Int = 1, - isRepresentative: Bool = false - ) -> ProfileCharacter { - ProfileCharacter( - id: id, - name: "캐릭터\(id)", - line: "한마디", - representativeImage: nil, - thumbnailImage: nil, - isRepresentative: isRepresentative - ) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileDraftUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileDraftUseCaseTests.swift deleted file mode 100644 index d46ee93eb..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileDraftUseCaseTests.swift +++ /dev/null @@ -1,65 +0,0 @@ -// -// LoadProfileDraftUseCaseTests.swift -// ProfileDomain -// -// Created by Seoyeon Choi on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("LoadProfileDraftUseCase") -struct LoadProfileDraftUseCaseTests { - - @Test("레포지토리에서 받은 ProfileDraft를 그대로 반환한다") - func returnsProfileDraftFromRepository() async throws { - let repo = MockProfileRepository() - let expected = makeProfileDraft() - repo.loadInitialProfileResult = .success(expected) - - let sut = DefaultLoadProfileDraftUseCase(profileRepository: repo) - - let result = try await sut.execute() - - #expect(repo.loadInitialProfileCallCount == 1) - #expect(result.characterID == expected.characterID) - #expect(result.nickname.text == expected.nickname.text) - #expect(result.introduction == expected.introduction) - #expect(result.genrePreferences == expected.genrePreferences) - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.loadInitialProfileResult = .failure(.serverUnavailable) - - let sut = DefaultLoadProfileDraftUseCase(profileRepository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - _ = try await sut.execute() - } - - #expect(repo.loadInitialProfileCallCount == 1) - } -} - -extension LoadProfileDraftUseCaseTests { - - private func makeProfileDraft( - characterID: Int = 1, - nickname: String = "서연", - introduction: String = "안녕하세요", - genrePreferences: [GenrePreference] = [] - ) -> ProfileDraft { - ProfileDraft( - characterID: characterID, - nickname: nickname, - introduction: introduction, - genrePreferences: genrePreferences - ) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileUseCaseTests.swift deleted file mode 100644 index a429454d5..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileUseCaseTests.swift +++ /dev/null @@ -1,85 +0,0 @@ -// -// LoadProfileUseCaseTests.swift -// ProfileDomain -// -// Created by Seoyeon Choi on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("LoadProfileUseCase") -struct LoadProfileUseCaseTests { - - @Test(".me 타겟으로 프로필을 조회할 수 있다") - func loadsProfileWithMeTarget() async throws { - let repo = MockProfileRepository() - let expected = makeProfile() - repo.fetchUserProfileResult = .success(expected) - - let sut = DefaultLoadProfileUseCase(profileRepository: repo) - - let result = try await sut.execute(target: .me) - - #expect(repo.fetchUserProfileCallCount == 1) - guard case .me = repo.fetchedUserProfileTargets.first else { - Issue.record(".me 타겟이 전달되어야 한다") - return - } - #expect(result.nickname == expected.nickname) - #expect(result.introduction == expected.introduction) - #expect(result.isPublic == expected.isPublic) - } - - @Test(".user 타겟으로 다른 유저의 프로필을 조회할 수 있다") - func loadsProfileWithUserTarget() async throws { - let repo = MockProfileRepository() - repo.fetchUserProfileResult = .success(makeProfile(nickname: "다른유저")) - - let sut = DefaultLoadProfileUseCase(profileRepository: repo) - - _ = try await sut.execute(target: .user(UserID(42))) - - #expect(repo.fetchUserProfileCallCount == 1) - guard case .user(let id) = repo.fetchedUserProfileTargets.first else { - Issue.record(".user 타겟이 전달되어야 한다") - return - } - #expect(id == UserID(42)) - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.fetchUserProfileResult = .failure(.serverUnavailable) - - let sut = DefaultLoadProfileUseCase(profileRepository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - _ = try await sut.execute(target: .me) - } - - #expect(repo.fetchUserProfileCallCount == 1) - } -} - -extension LoadProfileUseCaseTests { - - private func makeProfile( - nickname: String = "서연", - introduction: String = "안녕하세요", - isPublic: Bool = true - ) -> Profile { - Profile( - nickname: nickname, - introduction: introduction, - characterImage: nil, - isPublic: isPublic, - genrePreferences: [] - ) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileVisibilityUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileVisibilityUseCaseTests.swift deleted file mode 100644 index cdcb18f07..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/LoadProfileVisibilityUseCaseTests.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// LoadProfileVisibilityUseCaseTests.swift -// ProfileDomain -// -// Created by YunhakLee on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("LoadProfileVisibilityUseCase") -struct LoadProfileVisibilityUseCaseTests { - - @Test("프로필 공개 여부를 조회할 수 있다") - func loadsProfileVisibility() async throws { - let repo = MockProfileRepository() - let expected = ProfileVisibility(isPublic: true) - repo.loadProfileVisibilityResult = .success(expected) - - let sut = DefaultLoadProfileVisibilityUseCase(repository: repo) - - let result = try await sut.execute() - - #expect(repo.loadProfileVisibilityCallCount == 1) - #expect(result == expected) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.loadProfileVisibilityResult = .failure(.networkUnavailable) - - let sut = DefaultLoadProfileVisibilityUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - _ = try await sut.execute() - } - - #expect(repo.loadProfileVisibilityCallCount == 1) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/RegisterProfileUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/RegisterProfileUseCaseTests.swift deleted file mode 100644 index c6632436f..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/RegisterProfileUseCaseTests.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// RegisterProfileUseCaseTests.swift -// ProfileDomain -// -// Created by YunhakLee on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("RegisterProfileUseCase") -struct RegisterProfileUseCaseTests { - - private func makeProfileRegistration() -> ProfileRegistration { - // ✅ 프로젝트 타입에 맞게 여기만 조정하면 됨 - ProfileRegistration( - nickname: "밝보", - gender: .male, - birthYear: try! BirthYear(2002), - genrePreferences: [.romance, .wuxia] - ) - } - - @Test("프로필을 최초 등록할 수 있다") - func registersProfile() async throws { - let repo = MockProfileRepository() - repo.registerProfileResult = .success(()) - - let sut = DefaultRegisterProfileUseCase(repository: repo) - let profile = makeProfileRegistration() - - try await sut.execute(profile) - - #expect(repo.registerProfileCallCount == 1) - #expect(repo.registeredProfiles == [profile]) - } - - @Test("등록 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.registerProfileResult = .failure(.authenticationRequired) - - let sut = DefaultRegisterProfileUseCase(repository: repo) - - await #expect(throws: RepositoryError.authenticationRequired) { - try await sut.execute(makeProfileRegistration()) - } - - #expect(repo.registerProfileCallCount == 1) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/SaveAccountInfoDraftUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/SaveAccountInfoDraftUseCaseTests.swift deleted file mode 100644 index bcf844a84..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/SaveAccountInfoDraftUseCaseTests.swift +++ /dev/null @@ -1,50 +0,0 @@ -// -// SaveAccountInfoDraftUseCaseTests.swift -// ProfileDomain -// -// Created by YunhakLee on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("SaveAccountInfoDraftUseCase") -struct SaveAccountInfoDraftUseCaseTests { - - private func makeAccountInfoDraft() -> AccountInfoDraft { - // ✅ 프로젝트 타입에 맞게 여기만 조정하면 됨 - AccountInfoDraft(email: "H@Gmail.com", gender: .female, birth: try! BirthYear(1990)) - } - - @Test("계정 정보 초안을 저장할 수 있다") - func savesAccountInfoDraft() async throws { - let repo = MockProfileRepository() - repo.saveAccountInfoResult = .success(()) - - let sut = DefaultSaveAccountInfoDraftUseCase(repository: repo) - let info = makeAccountInfoDraft() - - try await sut.execute(info) - - #expect(repo.saveAccountInfoCallCount == 1) - #expect(repo.savedAccountInfos == [info]) - } - - @Test("저장 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.saveAccountInfoResult = .failure(.serverUnavailable) - - let sut = DefaultSaveAccountInfoDraftUseCase(repository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - try await sut.execute(makeAccountInfoDraft()) - } - - #expect(repo.saveAccountInfoCallCount == 1) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/SyncUserBasicInfoUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/SyncUserBasicInfoUseCaseTests.swift deleted file mode 100644 index bad15e12b..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/SyncUserBasicInfoUseCaseTests.swift +++ /dev/null @@ -1,43 +0,0 @@ -// -// SyncUserBasicInfoUseCaseTests.swift -// ProfileDomain -// -// Created by YunhakLee on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("SyncUserBasicInfoUseCase") -struct SyncUserBasicInfoUseCaseTests { - - @Test("유저 기본 정보를 동기화할 수 있다") - func syncsUserBasicInfo() async throws { - let repo = MockProfileRepository() - repo.syncUserBasicInfoResult = .success(()) - - let sut = DefaultSyncUserBasicInfoUseCase(repository: repo) - - try await sut.execute() - - #expect(repo.syncUserBasicInfoCallCount == 1) - } - - @Test("동기화 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.syncUserBasicInfoResult = .failure(.networkUnavailable) - - let sut = DefaultSyncUserBasicInfoUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - try await sut.execute() - } - - #expect(repo.syncUserBasicInfoCallCount == 1) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/UpdateProfileUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/UpdateProfileUseCaseTests.swift deleted file mode 100644 index b1d0390e1..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/UpdateProfileUseCaseTests.swift +++ /dev/null @@ -1,65 +0,0 @@ -// -// UpdateProfileUseCaseTests.swift -// ProfileDomain -// -// Created by Seoyeon Choi on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("UpdateProfileUseCase") -struct UpdateProfileUseCaseTests { - - @Test("레포지토리의 updateProfile이 draft와 함께 호출된다") - func callsUpdateProfileWithGivenDraft() async throws { - let repo = MockProfileRepository() - repo.updateProfileResult = .success(()) - let draft = makeProfileDraft(characterID: 5, nickname: "newNick", introduction: "새 소개글") - - let sut = DefaultUpdateProfileUseCase(profileRepository: repo) - - try await sut.execute(draft) - - #expect(repo.updateProfileCallCount == 1) - #expect(repo.updatedDrafts.first?.characterID == 5) - #expect(repo.updatedDrafts.first?.nickname.text == "newNick") - #expect(repo.updatedDrafts.first?.introduction == "새 소개글") - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.updateProfileResult = .failure(.serverUnavailable) - let draft = makeProfileDraft() - - let sut = DefaultUpdateProfileUseCase(profileRepository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - try await sut.execute(draft) - } - - #expect(repo.updateProfileCallCount == 1) - } -} - -extension UpdateProfileUseCaseTests { - - private func makeProfileDraft( - characterID: Int = 1, - nickname: String = "서연", - introduction: String = "안녕하세요", - genrePreferences: [GenrePreference] = [] - ) -> ProfileDraft { - ProfileDraft( - characterID: characterID, - nickname: nickname, - introduction: introduction, - genrePreferences: genrePreferences - ) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/UpdateProfileVisibilityUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/UpdateProfileVisibilityUseCaseTests.swift deleted file mode 100644 index 7e2be5d08..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/UpdateProfileVisibilityUseCaseTests.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// UpdateProfileVisibilityUseCaseTests.swift -// ProfileDomain -// -// Created by YunhakLee on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("UpdateProfileVisibilityUseCase") -struct UpdateProfileVisibilityUseCaseTests { - - @Test("프로필 공개 여부를 변경할 수 있다") - func updatesProfileVisibility() async throws { - let repo = MockProfileRepository() - repo.updateProfileVisibilityResult = .success(()) - - let sut = DefaultUpdateProfileVisibilityUseCase(repository: repo) - let visibility = ProfileVisibility(isPublic: false) - - try await sut.execute(visibility) - - #expect(repo.updateProfileVisibilityCallCount == 1) - #expect(repo.updatedVisibilities == [visibility]) - } - - @Test("변경 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.updateProfileVisibilityResult = .failure(.authenticationRequired) - - let sut = DefaultUpdateProfileVisibilityUseCase(repository: repo) - - await #expect(throws: RepositoryError.authenticationRequired) { - try await sut.execute(ProfileVisibility(isPublic: true)) - } - - #expect(repo.updateProfileVisibilityCallCount == 1) - } -} diff --git a/Projects/Domain/ProfileDomain/Tests/UseCase/ValidateNicknameUseCaseTests.swift b/Projects/Domain/ProfileDomain/Tests/UseCase/ValidateNicknameUseCaseTests.swift deleted file mode 100644 index 3efbd79d1..000000000 --- a/Projects/Domain/ProfileDomain/Tests/UseCase/ValidateNicknameUseCaseTests.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// ValidateNicknameUseCaseTests.swift -// ProfileDomain -// -// Created by YunhakLee on 2/25/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import ProfileDomain -import ProfileDomainTesting -import BaseDomain - -@Suite("ValidateNicknameUseCase") -struct ValidateNicknameUseCaseTests { - - @Test("닉네임 중복 여부를 조회할 수 있다") - func returnsDuplicationStatus() async throws { - let repo = MockProfileRepository() - repo.validateNicknameResult = .success(true) - - let sut = DefaultValidateNicknameUseCase(repository: repo) - - let isDuplicated = try await sut.execute("갑갑") - - #expect(repo.validateNicknameCallCount == 1) - #expect(repo.validatedNicknames == ["갑갑"]) - #expect(isDuplicated == true) - } - - @Test("조회 중 레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockProfileRepository() - repo.validateNicknameResult = .failure(.serverUnavailable) - - let sut = DefaultValidateNicknameUseCase(repository: repo) - - await #expect(throws: RepositoryError.serverUnavailable) { - _ = try await sut.execute("갑갑") - } - - #expect(repo.validateNicknameCallCount == 1) - } -} diff --git a/Projects/Domain/RecommendationDomain/TEST_SPEC.md b/Projects/Domain/RecommendationDomain/TEST_SPEC.md new file mode 100644 index 000000000..46c23a6f5 --- /dev/null +++ b/Projects/Domain/RecommendationDomain/TEST_SPEC.md @@ -0,0 +1,31 @@ +# RecommendationDomain 테스트 명세 + + + +## 런치스크린에서 미리 받아 둔 홈 데이터 + +`Tests/Store/HomePrefetchStoreTests.swift` + +### 홈 첫 로드에서 한 번만 쓴다 + +- 홈 첫 로드는 미리 받아 둔 세 가지를 그대로 받는다 +- 홈 첫 로드가 쓰고 나면 탭 복귀 때는 미리 받아 둔 값이 없다 +- 미리 받아 둔 게 없으면 홈 첫 로드도 받을 값이 없다 + +### 홈 첫 로드가 지난 뒤 도착한 값은 쓰지 않는다 + +- 홈 첫 로드가 쓴 뒤 다시 받아 온 값은 탭 복귀 때 쓰지 않는다 +- 홈 첫 로드보다 늦게 도착한 값은 탭 복귀 때 쓰지 않는다 + +## 홈 데이터 불러오기 + +`Tests/UseCase/LoadHomeDataUseCaseTests.swift` + +- 추천 세 가지(오늘의 발견·지금 뜨는 글·선호 장르 작품)를 하나로 모아 돌려준다 +- 로컬에 저장된 닉네임을 함께 담는다 +- 저장된 닉네임이 없으면 닉네임이 비어 있다 +- 세 가지를 동시에 불러온다 +- 홈은 관심글을 불러오지 않는다 +- 오늘의 발견을 불러오지 못하면 그 에러로 실패한다 +- 지금 뜨는 글을 불러오지 못하면 그 에러로 실패한다 +- 선호 장르 작품을 불러오지 못하면 그 에러로 실패한다 diff --git a/Projects/Domain/RecommendationDomain/Testing/MockRecommendationRepository.swift b/Projects/Domain/RecommendationDomain/Testing/MockRecommendationRepository.swift index f0da26a8f..650e9c5db 100644 --- a/Projects/Domain/RecommendationDomain/Testing/MockRecommendationRepository.swift +++ b/Projects/Domain/RecommendationDomain/Testing/MockRecommendationRepository.swift @@ -8,118 +8,46 @@ import Foundation -import RecommendationDomain import BaseDomain +import RecommendationDomain -/// `LoadHomeDataUseCase`가 세 호출을 `async let`으로 **동시에** 부르므로 카운터가 동시에 증가한다. -/// 락 없이 두면 호출 횟수 자체를 믿을 수 없어 테스트가 조용히 흔들린다. +/// 추천 저장소 가짜 객체. 전부 조회라 정해 둔 값만 돌려주고 호출을 기록하지 않는다(Stub). +/// +/// 값은 실행 전에 정해 두고 실행 중에는 읽기만 한다 — `LoadHomeDataUseCase`가 세 조회를 동시에 불러도 +/// 쓰기가 겹치지 않아 락 없이 `@unchecked Sendable`로 둔다. public final class MockRecommendationRepository: RecommendationRepository, @unchecked Sendable { - private struct State { - var fetchTodayDiscoveriesCallCount = 0 - var fetchTrendingFeedsCallCount = 0 - var fetchInterestFeedsCallCount = 0 - var fetchRecommendedNovelsCallCount = 0 - var fetchSosoPickCallCount = 0 - var fetchCachedNicknameCallCount = 0 + public var cachedNickname: String? - var cachedNickname: String? - - var fetchTodayDiscoveriesResult: Result<[TodayDiscovery], RepositoryError> = .success([]) - var fetchTrendingFeedsResult: Result<[TrendingFeed], RepositoryError> = .success([]) - var fetchInterestFeedsResult: Result = .success(.noInterestSettings) - var fetchRecommendedNovelsResult: Result = .success(.noGenreSettings) - var fetchSosoPickResult: Result<[SosoPick], RepositoryError> = .success([]) - } - - private let lock = NSLock() - private var state = State() + public var fetchTodayDiscoveriesResult: Result<[TodayDiscovery], RepositoryError> = .success([]) + public var fetchTrendingFeedsResult: Result<[TrendingFeed], RepositoryError> = .success([]) + public var fetchInterestFeedsResult: Result = .success(.noInterestSettings) + public var fetchRecommendedNovelsResult: Result = .success(.noGenreSettings) + public var fetchSosoPickResult: Result<[SosoPick], RepositoryError> = .success([]) public init() {} - // MARK: - 호출 횟수 - - public var fetchTodayDiscoveriesCallCount: Int { withLock { state.fetchTodayDiscoveriesCallCount } } - public var fetchTrendingFeedsCallCount: Int { withLock { state.fetchTrendingFeedsCallCount } } - public var fetchInterestFeedsCallCount: Int { withLock { state.fetchInterestFeedsCallCount } } - public var fetchRecommendedNovelsCallCount: Int { withLock { state.fetchRecommendedNovelsCallCount } } - public var fetchSosoPickCallCount: Int { withLock { state.fetchSosoPickCallCount } } - public var fetchCachedNicknameCallCount: Int { withLock { state.fetchCachedNicknameCallCount } } - - // MARK: - 스텁 - - public var cachedNickname: String? { - get { withLock { state.cachedNickname } } - set { withLock { state.cachedNickname = newValue } } - } - - public var fetchTodayDiscoveriesResult: Result<[TodayDiscovery], RepositoryError> { - get { withLock { state.fetchTodayDiscoveriesResult } } - set { withLock { state.fetchTodayDiscoveriesResult = newValue } } - } - - public var fetchTrendingFeedsResult: Result<[TrendingFeed], RepositoryError> { - get { withLock { state.fetchTrendingFeedsResult } } - set { withLock { state.fetchTrendingFeedsResult = newValue } } - } - - public var fetchInterestFeedsResult: Result { - get { withLock { state.fetchInterestFeedsResult } } - set { withLock { state.fetchInterestFeedsResult = newValue } } - } - - public var fetchRecommendedNovelsResult: Result { - get { withLock { state.fetchRecommendedNovelsResult } } - set { withLock { state.fetchRecommendedNovelsResult = newValue } } - } - - public var fetchSosoPickResult: Result<[SosoPick], RepositoryError> { - get { withLock { state.fetchSosoPickResult } } - set { withLock { state.fetchSosoPickResult = newValue } } - } - - // MARK: - RecommendationRepository - public func fetchTodayDiscoveries() async throws(RepositoryError) -> [TodayDiscovery] { - try resolve(withLock { state.fetchTodayDiscoveriesCallCount += 1; return state.fetchTodayDiscoveriesResult }) + try fetchTodayDiscoveriesResult.get() } public func fetchTrendingFeeds() async throws(RepositoryError) -> [TrendingFeed] { - try resolve(withLock { state.fetchTrendingFeedsCallCount += 1; return state.fetchTrendingFeedsResult }) + try fetchTrendingFeedsResult.get() } public func fetchInterestFeeds() async throws(RepositoryError) -> InterestFeedState { - try resolve(withLock { state.fetchInterestFeedsCallCount += 1; return state.fetchInterestFeedsResult }) + try fetchInterestFeedsResult.get() } public func fetchPreferenceGenreNovels() async throws(RepositoryError) -> PreferenceGenreNovelState { - try resolve(withLock { state.fetchRecommendedNovelsCallCount += 1; return state.fetchRecommendedNovelsResult }) + try fetchRecommendedNovelsResult.get() } public func fetchSosoPick() async throws(RepositoryError) -> [SosoPick] { - try resolve(withLock { state.fetchSosoPickCallCount += 1; return state.fetchSosoPickResult }) + try fetchSosoPickResult.get() } public func fetchCachedNickname() -> String? { - withLock { - state.fetchCachedNicknameCallCount += 1 - return state.cachedNickname - } - } - - // MARK: - Helper - - /// `NSLock`은 async 컨텍스트에서 직접 쓸 수 없어 동기 함수로 감싼다. - private func withLock(_ body: () -> T) -> T { - lock.lock() - defer { lock.unlock() } - return body() - } - - private func resolve(_ result: Result) throws(RepositoryError) -> T { - switch result { - case .success(let value): return value - case .failure(let error): throw error - } + cachedNickname } } diff --git a/Projects/Domain/RecommendationDomain/Tests/Entity/InterestFeedTests.swift b/Projects/Domain/RecommendationDomain/Tests/Entity/InterestFeedTests.swift deleted file mode 100644 index 682b4ce3c..000000000 --- a/Projects/Domain/RecommendationDomain/Tests/Entity/InterestFeedTests.swift +++ /dev/null @@ -1,105 +0,0 @@ -// -// InterestFeedTests.swift -// RecommendationDomain -// -// Created by Seoyeon Choi on 2/20/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import RecommendationDomain -import RecommendationDomainTesting -import BaseDomain - -@Suite -struct InterestFeedTests { - - // MARK: - Helpers - - private func makeInterestFeed( - novelID: NovelID = NovelID(1), - novelTitle: String = "테스트 소설", - novelRating: Float = 4.5, - novelRatingCount: Int = 100, - userComment: String = "재미있는 소설입니다" - ) -> InterestFeed { - InterestFeed( - novelID: novelID, - novelTitle: novelTitle, - novelThumbnailImage: nil, - novelRating: novelRating, - novelRatingCount: novelRatingCount, - user: Author( - userId: UserID(1), - nickname: "테스트유저", - profileImage: URL(string: "") - ), - userComment: userComment - ) - } - - // MARK: - feeds 상태 - - @Test("feeds 상태에서 피드 목록을 확인할 수 있다") - func feedsStateContainsFeedList() { - let feed = makeInterestFeed(novelTitle: "소설 제목") - let state = InterestFeedState.feeds([feed]) - - guard case .feeds(let feeds) = state else { - Issue.record("feeds 상태여야 합니다") - return - } - - #expect(feeds.count == 1) - #expect(feeds.first?.novelTitle == "소설 제목") - } - - @Test("feeds 상태에서 여러 피드를 포함할 수 있다") - func feedsStateCanContainMultipleFeeds() { - let feeds = [makeInterestFeed(), makeInterestFeed(), makeInterestFeed()] - let state = InterestFeedState.feeds(feeds) - - guard case .feeds(let result) = state else { - Issue.record("feeds 상태여야 합니다") - return - } - - #expect(result.count == 3) - } - - @Test("feeds 상태에서 피드 목록이 비어있을 수 있다") - func feedsStateCanBeEmpty() { - let state = InterestFeedState.feeds([]) - - guard case .feeds(let feeds) = state else { - Issue.record("feeds 상태여야 합니다") - return - } - - #expect(feeds.isEmpty) - } - - // MARK: - 비활성 상태 - - @Test("관심 설정을 하지 않은 상태를 표현할 수 있다") - func canRepresentNoInterestSettingsState() { - let state = InterestFeedState.noInterestSettings - - var isMatch = false - if case .noInterestSettings = state { isMatch = true } - - #expect(isMatch) - } - - @Test("관련 피드가 없는 상태를 표현할 수 있다") - func canRepresentNoAssociatedFeedsState() { - let state = InterestFeedState.noAssociatedFeeds - - var isMatch = false - if case .noAssociatedFeeds = state { isMatch = true } - - #expect(isMatch) - } -} diff --git a/Projects/Domain/RecommendationDomain/Tests/Entity/SosoPickTests.swift b/Projects/Domain/RecommendationDomain/Tests/Entity/SosoPickTests.swift deleted file mode 100644 index 38cb48b67..000000000 --- a/Projects/Domain/RecommendationDomain/Tests/Entity/SosoPickTests.swift +++ /dev/null @@ -1,50 +0,0 @@ -// -// SosoPickTests.swift -// RecommendationDomain -// -// Created by Seoyeon Choi on 2/20/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import RecommendationDomain -import RecommendationDomainTesting -import BaseDomain - -@Suite -struct SosoPickTests { - - // MARK: - Helpers - - private func makeSosoPick( - novelID: NovelID = NovelID(1), - novelTitle: String = "소소 픽 소설", - novelThumbnailimage: URL? = nil - ) -> SosoPick { - SosoPick( - novelID: novelID, - novelTitle: novelTitle, - novelThumbnailimage: novelThumbnailimage - ) - } - - // MARK: - Tests - - @Test("소소픽을 생성할 수 있다") - func canCreateSosoPick() { - let pick = makeSosoPick(novelID: NovelID(42), novelTitle: "추천 소설") - - #expect(pick.novelID == NovelID(42)) - #expect(pick.novelTitle == "추천 소설") - } - - @Test("썸네일 이미지를 포함하여 생성할 수 있다") - func canCreateSosoPickWithThumbnailImage() { - let url = URL(string: "https://example.com/thumbnail.jpg") - let pick = makeSosoPick(novelThumbnailimage: url) - - #expect(pick.novelThumbnailimage != nil) - } -} diff --git a/Projects/Domain/RecommendationDomain/Tests/Entity/TodayDiscoveryTests.swift b/Projects/Domain/RecommendationDomain/Tests/Entity/TodayDiscoveryTests.swift deleted file mode 100644 index d1250e4dd..000000000 --- a/Projects/Domain/RecommendationDomain/Tests/Entity/TodayDiscoveryTests.swift +++ /dev/null @@ -1,128 +0,0 @@ -// -// TodayDiscoveryTests.swift -// RecommendationDomain -// -// Created by Seoyeon Choi on 2/20/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import RecommendationDomain -import RecommendationDomainTesting -import BaseDomain - -@Suite -struct TodayDiscoveryTests { - - // MARK: - Content 타입 - - @Test("novel 타입으로 오늘의 발견을 생성할 수 있다") - func canCreateTodayDiscoveryWithNovelType() { - let discovery = makeTodayDiscovery(content: .novel) - - var isMatch = false - if case .novel = discovery.content { isMatch = true } - - #expect(isMatch) - } - - @Test("userComment 타입으로 오늘의 발견을 생성할 수 있다") - func canCreateTodayDiscoveryWithUserCommentType() { - let discovery = makeTodayDiscovery( - content: .userComment(user: makeAuthor()) - ) - - var isMatch = false - if case .userComment = discovery.content { isMatch = true } - - #expect(isMatch) - } - - @Test("userComment 타입에서 유저 정보를 가져올 수 있다") - func canGetUserInfoFromUserCommentType() { - let author = makeAuthor() - let discovery = makeTodayDiscovery( - content: .userComment(user: author) - ) - - guard case .userComment(let user) = discovery.content else { - Issue.record("userComment 타입이어야 합니다") - return - } - - #expect(user.nickname == author.nickname) - } - - @Test("contentDescription에 본문 텍스트가 저장된다") - func contentDescriptionStoresBodyText() { - let discovery = makeTodayDiscovery(contentDescription: "본문 내용") - - #expect(discovery.contentDescription == "본문 내용") - } - - // MARK: - 작품 정보 - - @Test("작품의 작가·장르·연재상태를 함께 담는다") - func carriesNovelMetadata() { - let discovery = makeTodayDiscovery( - novelAuthor: "캐슈", - novelGenre: .BL, - publicationStatus: .completed - ) - - #expect(discovery.novelAuthor == "캐슈") - #expect(discovery.novelGenre == .BL) - #expect(discovery.publicationStatus == .completed) - } - - @Test("작품 키워드를 순서 그대로 담는다") - func carriesKeywordsInOrder() { - let discovery = makeTodayDiscovery(keywords: ["사랑꾼", "짝사랑"]) - - #expect(discovery.keywords == ["사랑꾼", "짝사랑"]) - } - - @Test("키워드가 없는 작품은 빈 배열을 담는다") - func carriesEmptyKeywordsWhenNone() { - let discovery = makeTodayDiscovery(keywords: []) - - #expect(discovery.keywords.isEmpty) - } -} - -extension TodayDiscoveryTests { - - private func makeAuthor() -> Author { - Author( - userId: UserID(1), - nickname: "테스트유저", - profileImage: URL(string: "") - ) - } - - private func makeTodayDiscovery( - novelID: NovelID = NovelID(1), - novelTitle: String = "오늘의 발견 소설", - novelThumbnailImage: URL? = nil, - novelAuthor: String = "테스트작가", - novelGenre: NovelGenre = .romance, - publicationStatus: NovelPublicationStatus = .onGoing, - keywords: [String] = ["빙의"], - content: TodayDiscovery.Content = .novel, - contentDescription: String = "소설 설명" - ) -> TodayDiscovery { - TodayDiscovery( - novelID: novelID, - novelTitle: novelTitle, - novelThumbnailImage: novelThumbnailImage, - novelAuthor: novelAuthor, - novelGenre: novelGenre, - publicationStatus: publicationStatus, - keywords: keywords, - content: content, - contentDescription: contentDescription - ) - } -} diff --git a/Projects/Domain/RecommendationDomain/Tests/Entity/TrendingFeedTests.swift b/Projects/Domain/RecommendationDomain/Tests/Entity/TrendingFeedTests.swift deleted file mode 100644 index 7d84bdd03..000000000 --- a/Projects/Domain/RecommendationDomain/Tests/Entity/TrendingFeedTests.swift +++ /dev/null @@ -1,102 +0,0 @@ -// -// TrendingFeedTests.swift -// RecommendationDomain -// -// Created by Seoyeon Choi on 2/20/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import RecommendationDomain -import RecommendationDomainTesting -import BaseDomain - -@Suite -struct TrendingFeedTests { - - // MARK: - 생성 - - @Test("지금 뜨는 글을 생성할 수 있다") - func canCreateTrendingFeed() { - let feed = makeTrendingFeed(feedID: FeedID(99), description: "인기 글 내용") - - #expect(feed.feedID == FeedID(99)) - #expect(feed.description == "인기 글 내용") - } - - @Test("좋아요 수와 댓글 수를 포함한다") - func includesLikeCountAndCommentCount() { - let feed = makeTrendingFeed(likeCount: 150, commentCount: 30) - - #expect(feed.likeCount == 150) - #expect(feed.commentCount == 30) - } - - @Test("서로 다른 feedID로 구별할 수 있다") - func canDistinguishByDifferentFeedIDs() { - let feed1 = makeTrendingFeed(feedID: FeedID(1)) - let feed2 = makeTrendingFeed(feedID: FeedID(2)) - - #expect(feed1.feedID != feed2.feedID) - } - - // MARK: - 작품 정보 - - @Test("글이 달린 작품의 제목·표지·장르를 함께 담는다") - func carriesNovelInformation() { - let thumbnail = URL(string: "https://image.example/cover.jpg") - let feed = makeTrendingFeed( - novelTitle: "우아한 오브리", - novelThumbnailImage: thumbnail, - novelGenre: .romanceFantasy - ) - - #expect(feed.novelTitle == "우아한 오브리") - #expect(feed.novelThumbnailImage == thumbnail) - #expect(feed.novelGenre == .romanceFantasy) - } - - // MARK: - 스포일러 - - @Test("스포일러 글도 원본 내용을 그대로 보관한다") - func spoilerFeedKeepsOriginalDescription() { - let feed = makeTrendingFeed(description: "원본 내용", isSpoiler: true) - - #expect(feed.isSpoiler) - #expect(feed.description == "원본 내용") - } - - @Test("스포일러가 아닌 글은 isSpoiler가 false다") - func nonSpoilerFeedHasFalseFlag() { - let feed = makeTrendingFeed(description: "원본 내용", isSpoiler: false) - - #expect(feed.isSpoiler == false) - } -} - -extension TrendingFeedTests { - - private func makeTrendingFeed( - feedID: FeedID = FeedID(1), - novelTitle: String = "테스트 작품", - novelThumbnailImage: URL? = nil, - novelGenre: NovelGenre = .romance, - description: String = "지금 뜨는 글 내용", - isSpoiler: Bool = false, - likeCount: Int = 10, - commentCount: Int = 5 - ) -> TrendingFeed { - TrendingFeed( - feedID: feedID, - novelTitle: novelTitle, - novelThumbnailImage: novelThumbnailImage, - novelGenre: novelGenre, - description: description, - isSpoiler: isSpoiler, - likeCount: likeCount, - commentCount: commentCount - ) - } -} diff --git a/Projects/Domain/RecommendationDomain/Tests/Store/HomePrefetchStoreTests.swift b/Projects/Domain/RecommendationDomain/Tests/Store/HomePrefetchStoreTests.swift index 89f1276e6..f9ee8d122 100644 --- a/Projects/Domain/RecommendationDomain/Tests/Store/HomePrefetchStoreTests.swift +++ b/Projects/Domain/RecommendationDomain/Tests/Store/HomePrefetchStoreTests.swift @@ -9,140 +9,136 @@ import Foundation import Testing -@testable import RecommendationDomain import BaseDomain +import RecommendationDomain -/// 런치 프리페치 저장소의 **저장·소비 규칙** 명세 — 부트스트랩(SplashData)이 채우고 -/// 홈 레포(`DefaultRecommendationRepositoryTests`)가 소비하는 사이의 계약이다. -/// 핵심 두 규칙: **single-shot**(소비는 1회, TTL 캐시 아님 — 홈의 "탭 복귀마다 갱신" 계약 보호)과 -/// **소비 창**(첫 consume 시도에 창이 닫혀, 늦게 착지한 프리페치가 나중 갱신을 stale로 덮지 못한다). -@Suite +/// 런치스크린에서 미리 받아 둔 홈 데이터를 홈 첫 로드가 한 번 꺼내 쓰는 저장고(#225). +/// 채우는 쪽은 SplashData, 꺼내는 쪽은 RecommendationData다. +@Suite("런치스크린에서 미리 받아 둔 홈 데이터") struct HomePrefetchStoreTests { - // MARK: - single-shot 소비 - - @Test("채운 슬롯을 consume하면 그 값을 돌려주고 슬롯을 비운다") - func consumeReturnsFilledValueAndEmptiesSlot() async { - let store = HomePrefetchStore() - let discoveries = [makeTodayDiscovery()] - await store.fillTodayDiscoveries(discoveries) - - let first = await store.consumeTodayDiscoveries() - let second = await store.consumeTodayDiscoveries() - - #expect(first?.map(\.novelID) == discoveries.map(\.novelID)) - #expect(second == nil) - } - - @Test("선호장르 슬롯도 같은 규칙이다 — consume은 값을 돌려주고 슬롯을 비운다") - func preferenceGenreSlotIsAlsoSingleShot() async { - let store = HomePrefetchStore() - await store.fillPreferenceGenreNovels(.noGenreSettings) - - let first = await store.consumePreferenceGenreNovels() - let second = await store.consumePreferenceGenreNovels() - - #expect(first != nil) - if case .noGenreSettings = first {} else { Issue.record("채운 상태 그대로 돌아와야 한다") } - #expect(second == nil) - } - - @Test("채우지 않은 슬롯을 consume하면 nil을 돌려준다") - func consumeEmptySlotReturnsNil() async { - let store = HomePrefetchStore() - - let discoveries = await store.consumeTodayDiscoveries() - let feeds = await store.consumeTrendingFeeds() - let preference = await store.consumePreferenceGenreNovels() - - #expect(discoveries == nil) - #expect(feeds == nil) - #expect(preference == nil) - } - - // MARK: - 소비 창(window) - - @Test("소비한 뒤 도착한 fill은 폐기한다") - func refillAfterConsumeIsDiscarded() async { - let store = HomePrefetchStore() - let feeds = [makeTrendingFeed()] - await store.fillTrendingFeeds(feeds) - _ = await store.consumeTrendingFeeds() - - await store.fillTrendingFeeds(feeds) - let second = await store.consumeTrendingFeeds() - - #expect(second == nil) + /// 홈은 탭 복귀마다 새로 불러온다 — 한 번 꺼낸 값이 남아 있으면 복귀 때 런치 시점 데이터가 다시 뜬다. + @Suite("홈 첫 로드에서 한 번만 쓴다") + struct ConsumeOnce { + + @Test("홈 첫 로드는 미리 받아 둔 세 가지를 그대로 받는다") + func consumesFilledValueFromEachSlot() async { + let store = HomePrefetchStore() + // 슬롯마다 id를 다르게 둬서, 값이 다른 슬롯으로 새지 않았는지 보이게 한다. + await store.fillTodayDiscoveries([makeTodayDiscovery(id: 1)]) + await store.fillTrendingFeeds([makeTrendingFeed(id: 2)]) + await store.fillPreferenceGenreNovels(.novels([makePreferenceGenreNovel(id: 3)])) + + let consumed = ( + await store.consumeTodayDiscoveries(), + await store.consumeTrendingFeeds(), + await store.consumePreferenceGenreNovels() + ) + + #expect(consumed.0?.map(\.novelID) == [NovelID(1)]) + #expect(consumed.1?.map(\.feedID) == [FeedID(2)]) + #expect(consumed.2.flatMap(novelIDs(in:)) == [NovelID(3)]) + } + + @Test("홈 첫 로드가 쓰고 나면 탭 복귀 때는 미리 받아 둔 값이 없다") + func consumedSlotIsEmpty() async { + let store = HomePrefetchStore() + await store.fillTodayDiscoveries([makeTodayDiscovery(id: 1)]) + _ = await store.consumeTodayDiscoveries() + + let second = await store.consumeTodayDiscoveries() + + #expect(second == nil) + } + + @Test("미리 받아 둔 게 없으면 홈 첫 로드도 받을 값이 없다") + func unfilledSlotIsEmpty() async { + let store = HomePrefetchStore() + + let consumed = ( + await store.consumeTodayDiscoveries(), + await store.consumeTrendingFeeds(), + await store.consumePreferenceGenreNovels() + ) + + #expect(consumed.0 == nil) + #expect(consumed.1 == nil) + #expect(consumed.2 == nil) + } } - // 프리페치가 홈 첫 로드보다 늦게 착지하는 상황 — 창을 닫지 않으면 이 값이 - // 다음 탭 복귀 갱신에서 소비돼 런치 시점 데이터가 뒤늦게 뜬다. - @Test("빈 슬롯을 소비하려 한 뒤 늦게 도착한 fill도 폐기한다") - func lateFillAfterEmptyConsumeIsDiscarded() async { - let store = HomePrefetchStore() + /// 프리페치는 기다리지 않고 던져 두는 요청이라 홈 첫 로드보다 늦게 도착할 수 있다. + /// 그 값을 받아 두면 다음 탭 복귀 갱신에서 꺼내져 런치 시점 데이터가 뒤늦게 뜬다(#225 리뷰). + @Suite("홈 첫 로드가 지난 뒤 도착한 값은 쓰지 않는다") + struct DiscardLateFill { - let first = await store.consumeTodayDiscoveries() // 홈 첫 로드 → 슬롯이 아직 비어 있어 네트워크로 감 - await store.fillTodayDiscoveries([makeTodayDiscovery()]) // 늦게 착지한 프리페치 - let second = await store.consumeTodayDiscoveries() // 탭 복귀 갱신 + @Test("홈 첫 로드가 쓴 뒤 다시 받아 온 값은 탭 복귀 때 쓰지 않는다") + func fillAfterConsumeIsDiscarded() async { + let store = HomePrefetchStore() + await store.fillTrendingFeeds([makeTrendingFeed(id: 1)]) + _ = await store.consumeTrendingFeeds() + await store.fillTrendingFeeds([makeTrendingFeed(id: 2)]) - #expect(first == nil) - #expect(second == nil) - } + let second = await store.consumeTrendingFeeds() - // MARK: - 슬롯 독립성 + #expect(second == nil) + } - @Test("한 슬롯만 채우면 다른 슬롯은 여전히 nil이다") - func slotsAreIndependent() async { - let store = HomePrefetchStore() - await store.fillTodayDiscoveries([makeTodayDiscovery()]) + @Test("홈 첫 로드보다 늦게 도착한 값은 탭 복귀 때 쓰지 않는다") + func lateFillAfterEmptyConsumeIsDiscarded() async { + let store = HomePrefetchStore() + _ = await store.consumeTodayDiscoveries() // 홈 첫 로드 — 아직 비어 있어 서버로 간다 + await store.fillTodayDiscoveries([makeTodayDiscovery(id: 1)]) // 늦게 도착한 프리페치 - let feeds = await store.consumeTrendingFeeds() + let second = await store.consumeTodayDiscoveries() // 탭 복귀 갱신 - #expect(feeds == nil) + #expect(second == nil) + } } +} - @Test("한 슬롯의 소비가 다른 슬롯을 비우지 않는다") - func consumingOneSlotKeepsTheOther() async { - let store = HomePrefetchStore() - let feeds = [makeTrendingFeed()] - await store.fillTodayDiscoveries([makeTodayDiscovery()]) - await store.fillTrendingFeeds(feeds) - - _ = await store.consumeTodayDiscoveries() - let remaining = await store.consumeTrendingFeeds() +// MARK: - Helper - #expect(remaining?.map(\.feedID) == feeds.map(\.feedID)) - } +private func novelIDs(in state: PreferenceGenreNovelState) -> [NovelID]? { + guard case .novels(let novels) = state else { return nil } + return novels.map(\.novelID) } -// MARK: - Helper +private func makeTodayDiscovery(id: Int) -> TodayDiscovery { + TodayDiscovery( + novelID: NovelID(id), + novelTitle: "오늘의 발견", + novelThumbnailImage: nil, + novelAuthor: "작가", + novelGenre: .romance, + publicationStatus: .onGoing, + keywords: [], + content: .novel, + contentDescription: "작품 소개" + ) +} -extension HomePrefetchStoreTests { - - private func makeTodayDiscovery() -> TodayDiscovery { - TodayDiscovery( - novelID: NovelID(1), - novelTitle: "오늘의 발견", - novelThumbnailImage: nil, - novelAuthor: "테스트작가", - novelGenre: .romance, - publicationStatus: .onGoing, - keywords: ["빙의"], - content: .novel, - contentDescription: "소설 설명" - ) - } +private func makeTrendingFeed(id: Int) -> TrendingFeed { + TrendingFeed( + feedID: FeedID(id), + novelTitle: "작품", + novelThumbnailImage: nil, + novelGenre: .romance, + description: "지금 뜨는 글", + isSpoiler: false, + likeCount: 0, + commentCount: 0 + ) +} - private func makeTrendingFeed() -> TrendingFeed { - TrendingFeed( - feedID: FeedID(1), - novelTitle: "테스트 작품", - novelThumbnailImage: nil, - novelGenre: .romance, - description: "뜨는 글 내용", - isSpoiler: false, - likeCount: 10, - commentCount: 3 - ) - } +private func makePreferenceGenreNovel(id: Int) -> PreferenceGenreNovel { + PreferenceGenreNovel( + novelID: NovelID(id), + novelTitle: "선호 장르 작품", + novelThumbnailImage: nil, + novelAuthors: [], + interestCount: 0, + ratingCount: 0, + rating: 0 + ) } diff --git a/Projects/Domain/RecommendationDomain/Tests/UseCase/LoadHomeDataUseCaseTests.swift b/Projects/Domain/RecommendationDomain/Tests/UseCase/LoadHomeDataUseCaseTests.swift index 5f2b6aa2e..68326fc78 100644 --- a/Projects/Domain/RecommendationDomain/Tests/UseCase/LoadHomeDataUseCaseTests.swift +++ b/Projects/Domain/RecommendationDomain/Tests/UseCase/LoadHomeDataUseCaseTests.swift @@ -8,190 +8,163 @@ import Foundation import Testing -@testable import RecommendationDomain -@testable import BaseDomain -@testable import RecommendationDomainTesting -@Suite -struct LoadHomeDataUseCaseTests { +import BaseDomain +import RecommendationDomain +import RecommendationDomainTesting - // MARK: - 동시성 +@Suite("홈 데이터 불러오기") +struct LoadHomeDataUseCaseTests { - /// ⚠️ 이 테스트가 이 UseCase의 **퇴행 방지선**이다. - /// 과거 `async let`이 순차 `try await`로 펴진 적이 있고(c1e19ed0), 그때 아무 테스트도 깨지지 않아 - /// 홈 로딩이 조용히 2~3배 느려졌다. 같은 시각에 겹쳐 있는 호출 수를 세서 병렬임을 못 박는다. - @Test("세 호출이 동시에 나간다 — 순차로 펴면 이 테스트가 깨진다") - func issuesThreeCallsConcurrently() async throws { - let probe = ConcurrencyProbeRepository() + @Test("추천 세 가지(오늘의 발견·지금 뜨는 글·선호 장르 작품)를 하나로 모아 돌려준다") + func combinesThreeRecommendations() async throws { + let repository = MockRecommendationRepository() + // 세 목록의 id를 서로 다르게 둬서, 각 목록이 제자리에 담겼는지 보이게 한다. + repository.fetchTodayDiscoveriesResult = .success([makeTodayDiscovery(id: 1)]) + repository.fetchTrendingFeedsResult = .success([makeTrendingFeed(id: 2)]) + repository.fetchRecommendedNovelsResult = .success(.novels([makePreferenceGenreNovel(id: 3)])) + let useCase = DefaultLoadHomeDataUseCase(repository: repository) - let usecase = DefaultLoadHomeDataUseCase(repository: probe) - _ = try await usecase.execute() + let homeData = try await useCase.execute() - // 순차라면 항상 1이다. - #expect(probe.peakConcurrentCalls == 3) + #expect(homeData.todayDiscoveries.map(\.novelID) == [NovelID(1)]) + #expect(homeData.trendingFeeds.map(\.feedID) == [FeedID(2)]) + #expect(novelIDs(in: homeData.preferenceGenreNovelState) == [NovelID(3)]) } - // MARK: - 협력 - - @Test("홈 화면이 그리는 세 가지 API를 모두 호출한다") - func callsAllThreeApis() async { - let mock = MockRecommendationRepository() - mock.fetchTodayDiscoveriesResult = .success([]) - mock.fetchTrendingFeedsResult = .success([]) - mock.fetchRecommendedNovelsResult = .success(.novels([])) + @Test("로컬에 저장된 닉네임을 함께 담는다") + func includesCachedNickname() async throws { + let repository = MockRecommendationRepository() + repository.cachedNickname = "웹소소" + let useCase = DefaultLoadHomeDataUseCase(repository: repository) - let usecase = DefaultLoadHomeDataUseCase(repository: mock) - _ = try? await usecase.execute() + let homeData = try await useCase.execute() - #expect(mock.fetchTodayDiscoveriesCallCount == 1) - #expect(mock.fetchTrendingFeedsCallCount == 1) - #expect(mock.fetchRecommendedNovelsCallCount == 1) + #expect(homeData.nickname == "웹소소") } - @Test("홈에 섹션이 없는 관심글은 호출하지 않는다") - func doesNotCallInterestFeeds() async { - let mock = MockRecommendationRepository() + @Test("저장된 닉네임이 없으면 닉네임이 비어 있다") + func nicknameIsEmptyWhenNotCached() async throws { + let repository = MockRecommendationRepository() + repository.cachedNickname = nil + let useCase = DefaultLoadHomeDataUseCase(repository: repository) - let usecase = DefaultLoadHomeDataUseCase(repository: mock) - _ = try? await usecase.execute() + let homeData = try await useCase.execute() - #expect(mock.fetchInterestFeedsCallCount == 0) + #expect(homeData.nickname == nil) } - // MARK: - 결과 조립 - - @Test("모든 데이터를 성공적으로 불러온다") - func loadsAllDataSuccessfully() async throws { - let mock = MockRecommendationRepository() - mock.fetchTodayDiscoveriesResult = .success([makeTodayDiscovery()]) - mock.fetchTrendingFeedsResult = .success([makeTrendingFeed()]) - mock.fetchRecommendedNovelsResult = .success(.novels([])) + /// ⚠️ 이 UseCase의 퇴행 방지선이다. 세 호출이 순차로 펴진 적이 있는데(c1e19ed0) 그때 아무 테스트도 + /// 깨지지 않아 홈 로딩이 조용히 2~3배 느려졌다. 시간이 아니라 "같은 시각에 겹친 호출 수"를 세서 + /// 머신 부하에 흔들리지 않게 한다(병렬이면 3, 순차면 1). + @Test("세 가지를 동시에 불러온다") + func issuesThreeCallsConcurrently() async throws { + let probe = ConcurrencyProbeRepository() + let useCase = DefaultLoadHomeDataUseCase(repository: probe) - let usecase = DefaultLoadHomeDataUseCase(repository: mock) - let homeData = try await usecase.execute() + _ = try await useCase.execute() - #expect(homeData.todayDiscoveries.count == 1) - #expect(homeData.trendingFeeds.count == 1) + #expect(probe.peakConcurrentCalls == 3) } - @Test("로컬에 캐시된 닉네임을 함께 담는다") - func includesCachedNickname() async throws { - let mock = MockRecommendationRepository() - mock.cachedNickname = "웹소소" + /// 홈엔 관심글 섹션이 없다(#179). 관심글까지 부르면 그 하나가 실패할 때 홈 전체가 실패한다. + /// 그래서 관심글이 실패하게 해 두고, 홈 데이터가 그래도 오는지로 부르지 않았음을 확인한다. + @Test("홈은 관심글을 불러오지 않는다") + func doesNotLoadInterestFeeds() async { + let repository = MockRecommendationRepository() + repository.fetchInterestFeedsResult = .failure(.serverUnavailable) + let useCase = DefaultLoadHomeDataUseCase(repository: repository) - let usecase = DefaultLoadHomeDataUseCase(repository: mock) - let homeData = try await usecase.execute() - - #expect(homeData.nickname == "웹소소") + await #expect(throws: Never.self) { + try await useCase.execute() + } } - @Test("캐시된 닉네임이 없으면 nil을 담는다") - func includesNilWhenNicknameIsNotCached() async throws { - let mock = MockRecommendationRepository() - mock.cachedNickname = nil - - let usecase = DefaultLoadHomeDataUseCase(repository: mock) - let homeData = try await usecase.execute() + @Test("오늘의 발견을 불러오지 못하면 그 에러로 실패한다") + func failsWhenTodayDiscoveriesFail() async { + let repository = MockRecommendationRepository() + repository.fetchTodayDiscoveriesResult = .failure(.networkUnavailable) + let useCase = DefaultLoadHomeDataUseCase(repository: repository) - #expect(homeData.nickname == nil) + await #expect(throws: RepositoryError.networkUnavailable) { + try await useCase.execute() + } } - // MARK: - 실패 - - @Test("todayDiscoveries 실패 시 전체를 실패로 반환한다") - func throwsWhenTodayDiscoveriesFails() async { - let mock = MockRecommendationRepository() - mock.fetchTodayDiscoveriesResult = .failure(RepositoryError.unknown) + @Test("지금 뜨는 글을 불러오지 못하면 그 에러로 실패한다") + func failsWhenTrendingFeedsFail() async { + let repository = MockRecommendationRepository() + repository.fetchTrendingFeedsResult = .failure(.serverUnavailable) + let useCase = DefaultLoadHomeDataUseCase(repository: repository) - let usecase = DefaultLoadHomeDataUseCase(repository: mock) - - await #expect(throws: RepositoryError.unknown) { - try await usecase.execute() + await #expect(throws: RepositoryError.serverUnavailable) { + try await useCase.execute() } } - @Test("trendingFeeds 실패 시 전체를 실패로 반환한다") - func throwsWhenTrendingFeedsFails() async { - let mock = MockRecommendationRepository() - mock.fetchTodayDiscoveriesResult = .success([makeTodayDiscovery()]) - mock.fetchTrendingFeedsResult = .failure(RepositoryError.unknown) - mock.fetchRecommendedNovelsResult = .success(.noGenreSettings) - - let usecase = DefaultLoadHomeDataUseCase(repository: mock) + /// 이 실패를 삼키고 빈 값으로 채우면 서버 오류가 "선호 장르 미설정"처럼 보여 설정 유도 카드가 뜬다. + @Test("선호 장르 작품을 불러오지 못하면 그 에러로 실패한다") + func failsWhenPreferenceGenreNovelsFail() async { + let repository = MockRecommendationRepository() + repository.fetchRecommendedNovelsResult = .failure(.invalidData) + let useCase = DefaultLoadHomeDataUseCase(repository: repository) - await #expect(throws: RepositoryError.unknown) { - try await usecase.execute() + await #expect(throws: RepositoryError.invalidData) { + try await useCase.execute() } } +} - /// 마지막 호출까지 같은 규칙임을 못 박는다 — 여기만 `try?`로 눙치면 서버 오류가 - /// "선호 장르 미설정"으로 둔갑해 설정 유도 CTA가 뜬다. - @Test("preferenceGenreNovels 실패 시 전체를 실패로 반환한다") - func throwsWhenPreferenceGenreNovelsFails() async { - let mock = MockRecommendationRepository() - mock.fetchTodayDiscoveriesResult = .success([makeTodayDiscovery()]) - mock.fetchTrendingFeedsResult = .success([makeTrendingFeed()]) - mock.fetchRecommendedNovelsResult = .failure(RepositoryError.serverUnavailable) - - let usecase = DefaultLoadHomeDataUseCase(repository: mock) +// MARK: - Helper - await #expect(throws: RepositoryError.serverUnavailable) { - try await usecase.execute() - } - } +private func novelIDs(in state: PreferenceGenreNovelState) -> [NovelID]? { + guard case .novels(let novels) = state else { return nil } + return novels.map(\.novelID) +} - /// 세 호출은 `async let`으로 동시에 나가므로 하나가 실패해도 나머지는 이미 출발해 있다. - /// 대신 **닉네임 조회는 세 결과를 다 받은 뒤**라 실패 시 수행되지 않는다 — 로컬 캐시 조회라 - /// 굳이 당길 이유가 없고, 실패 경로에서 불필요한 부수효과를 남기지 않기 위해서다. - @Test("한 호출이 실패해도 나머지는 이미 나가 있고, 닉네임 조회는 하지 않는다") - func issuesAllCallsConcurrentlyAndSkipsNicknameOnFailure() async { - let mock = MockRecommendationRepository() - mock.fetchTodayDiscoveriesResult = .failure(RepositoryError.networkUnavailable) - - let usecase = DefaultLoadHomeDataUseCase(repository: mock) - _ = try? await usecase.execute() - - #expect(mock.fetchTodayDiscoveriesCallCount == 1) - #expect(mock.fetchTrendingFeedsCallCount == 1) - #expect(mock.fetchRecommendedNovelsCallCount == 1) - #expect(mock.fetchCachedNicknameCallCount == 0) - } +private func makeTodayDiscovery(id: Int) -> TodayDiscovery { + TodayDiscovery( + novelID: NovelID(id), + novelTitle: "오늘의 발견", + novelThumbnailImage: nil, + novelAuthor: "작가", + novelGenre: .romance, + publicationStatus: .onGoing, + keywords: [], + content: .novel, + contentDescription: "작품 소개" + ) } -extension LoadHomeDataUseCaseTests { - - private func makeTodayDiscovery() -> TodayDiscovery { - TodayDiscovery( - novelID: NovelID(1), - novelTitle: "오늘의 발견", - novelThumbnailImage: nil, - novelAuthor: "테스트작가", - novelGenre: .romance, - publicationStatus: .onGoing, - keywords: ["빙의"], - content: .novel, - contentDescription: "소설 설명" - ) - } +private func makeTrendingFeed(id: Int) -> TrendingFeed { + TrendingFeed( + feedID: FeedID(id), + novelTitle: "작품", + novelThumbnailImage: nil, + novelGenre: .romance, + description: "지금 뜨는 글", + isSpoiler: false, + likeCount: 0, + commentCount: 0 + ) +} - private func makeTrendingFeed() -> TrendingFeed { - TrendingFeed( - feedID: FeedID(1), - novelTitle: "테스트 작품", - novelThumbnailImage: nil, - novelGenre: .romance, - description: "뜨는 글 내용", - isSpoiler: false, - likeCount: 10, - commentCount: 3 - ) - } +private func makePreferenceGenreNovel(id: Int) -> PreferenceGenreNovel { + PreferenceGenreNovel( + novelID: NovelID(id), + novelTitle: "선호 장르 작품", + novelThumbnailImage: nil, + novelAuthors: [], + interestCount: 0, + ratingCount: 0, + rating: 0 + ) } -// MARK: - 동시성 계측용 Repository +// MARK: - 동시성 계측용 저장소 -/// 호출이 들어오고 나갈 때를 세어 **같은 시각에 몇 개가 겹쳐 있었는지**(`peakConcurrentCalls`)를 남긴다. -/// 벽시계 시간을 재면 머신 부하에 흔들리지만, 겹친 개수는 병렬이면 3 / 순차면 1로 결정적이다. +/// 호출이 들어오고 나갈 때를 세어 같은 시각에 몇 개가 겹쳐 있었는지(`peakConcurrentCalls`)를 남긴다. +/// 이 테스트 하나만 쓰는 계측 도구라 `Testing/`이 아니라 여기 둔다. private final class ConcurrencyProbeRepository: RecommendationRepository, @unchecked Sendable { private let lock = NSLock() @@ -222,23 +195,15 @@ private final class ConcurrencyProbeRepository: RecommendationRepository, @unche func fetchCachedNickname() -> String? { nil } - /// 겹칠 틈을 만들기 위해 잠깐 머문다 — 이 지연이 없으면 셋 다 시작 전에 끝나버려 겹침이 안 잡힌다. + /// 겹칠 틈을 만들려고 잠깐 머문다 — 이 지연이 없으면 다음 호출이 시작되기 전에 끝나 겹침이 안 잡힌다. private func overlapping(_ value: T) async -> T { - enter() - try? await Task.sleep(nanoseconds: 30_000_000) - leave() - return value - } - - private func enter() { withLock { inFlight += 1 peak = max(peak, inFlight) } - } - - private func leave() { + try? await Task.sleep(nanoseconds: 30_000_000) withLock { inFlight -= 1 } + return value } /// `NSLock`은 async 컨텍스트에서 직접 쓸 수 없어 동기 함수로 감싼다. diff --git a/Projects/Domain/RecommendationDomain/Tests/UseCase/LoadSosoPickUseCaseTests.swift b/Projects/Domain/RecommendationDomain/Tests/UseCase/LoadSosoPickUseCaseTests.swift deleted file mode 100644 index 685e21871..000000000 --- a/Projects/Domain/RecommendationDomain/Tests/UseCase/LoadSosoPickUseCaseTests.swift +++ /dev/null @@ -1,62 +0,0 @@ -// -// LoadSosoPickUseCaseTests.swift -// RecommendationDomain -// -// Created by Seoyeon Choi on 2/20/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing -@testable import RecommendationDomain -@testable import BaseDomain -@testable import RecommendationDomainTesting - -@Suite -struct LoadSosoPickUseCaseTests { - - @Test("소소픽을 성공적으로 불러온다") - func loadsSosoPickSuccessfully() async throws { - let mock = MockRecommendationRepository() - let expectedPicks = [makeSosoPick(novelID: NovelID(1)), makeSosoPick(novelID: NovelID(2))] - mock.fetchSosoPickResult = .success(expectedPicks) - - let usecase = DefaultLoadSosoPickUseCase(recommendationRepository: mock) - let result = try await usecase.execute() - - #expect(result.count == 2) - #expect(mock.fetchSosoPickCallCount == 1) - } - - @Test("소소픽 목록이 비어있어도 정상적으로 반환한다") - func returnsEmptySosoPickListNormally() async throws { - let mock = MockRecommendationRepository() - mock.fetchSosoPickResult = .success([]) - - let usecase = DefaultLoadSosoPickUseCase(recommendationRepository: mock) - let result = try await usecase.execute() - - #expect(result.isEmpty) - } - - @Test("소소픽 불러오기에 실패하면 에러를 던진다") - func throwsErrorWhenLoadSosoPickFails() async { - let mock = MockRecommendationRepository() - mock.fetchSosoPickResult = .failure(RepositoryError.networkUnavailable) - - let usecase = DefaultLoadSosoPickUseCase(recommendationRepository: mock) - - await #expect(throws: RepositoryError.networkUnavailable) { - try await usecase.execute() - } - } -} - -extension LoadSosoPickUseCaseTests { - private func makeSosoPick(novelID: NovelID = NovelID(1)) -> SosoPick { - SosoPick( - novelID: novelID, - novelTitle: "소소 픽 소설", - novelThumbnailimage: nil - ) - } -} diff --git a/Projects/Domain/SettingDomain/CLAUDE.md b/Projects/Domain/SettingDomain/CLAUDE.md index 0e1dec308..4f67a6a39 100644 --- a/Projects/Domain/SettingDomain/CLAUDE.md +++ b/Projects/Domain/SettingDomain/CLAUDE.md @@ -14,3 +14,4 @@ - **Repository 2개** (`AppUpdateRepository`, `TermsAgreementRepository`) — 영역이 다르다. - `AppVersionProviding`는 현재 버전을 주입받는 프로토콜 (Bundle 등 외부 의존을 도메인 밖으로 뺀 것). 테스트 시 여기에 가짜 버전 주입. +- **`Testing/Mock` 3개는 이 모듈 테스트가 아니라 `SplashData` 테스트(`DefaultLaunchGateRepositoryTests`)가 쓴다**(#308에서 넘기기 UseCase 테스트를 지운 뒤). 모듈 테스트에 안 보인다고 지우면 SplashData가 깨진다. diff --git a/Projects/Domain/SettingDomain/Sources/AppUpdate/Entity/AppVersion.swift b/Projects/Domain/SettingDomain/Sources/AppUpdate/Entity/AppVersion.swift index a3c8ff6d0..3827391a0 100644 --- a/Projects/Domain/SettingDomain/Sources/AppUpdate/Entity/AppVersion.swift +++ b/Projects/Domain/SettingDomain/Sources/AppUpdate/Entity/AppVersion.swift @@ -14,22 +14,20 @@ public struct AppVersion: Equatable, Comparable, Hashable, CustomStringConvertib public let minor: Int public let patch: Int - public static let zero = AppVersion(major: 0, minor: 0, patch: 0) - public var description: String { "\(major).\(minor).\(patch)" } public init(major: Int, minor: Int, patch: Int) { - self.major = max(0, major) - self.minor = max(0, minor) - self.patch = max(0, patch) + self.major = major + self.minor = minor + self.patch = patch } /// "1", "1.2", "1.2.3" 모두 허용. 그 외는 throw. + /// 빈 자리("1..2", "1.", ".1")도 throw — 빈 자리를 버리고 나누면 "1..2"가 1.2.0으로 조용히 읽힌다. + /// 빈 문자열은 `[""]`로 나뉘어 숫자 변환에서 throw되므로 따로 검사하지 않는다. public init(_ string: String) throws { let trimmed = string.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { throw ParseError.invalidFormat(string) } - - let parts = trimmed.split(separator: ".").map { String($0) } + let parts = trimmed.split(separator: ".", omittingEmptySubsequences: false).map { String($0) } guard (1...3).contains(parts.count) else { throw ParseError.invalidFormat(string) } func parse(_ idx: Int) throws -> Int { diff --git a/Projects/Domain/SettingDomain/TEST_SPEC.md b/Projects/Domain/SettingDomain/TEST_SPEC.md new file mode 100644 index 000000000..c4beccba6 --- /dev/null +++ b/Projects/Domain/SettingDomain/TEST_SPEC.md @@ -0,0 +1,65 @@ +# SettingDomain 테스트 명세 + + + +## 강제 업데이트 판단 + +`Tests/AppUpdate/Entity/AppUpdatePolicyTests.swift` + +- 앱 버전이 최소 버전보다 낮으면 강제 업데이트가 필요하다 +- 앱 버전이 최소 버전과 같거나 높으면 강제 업데이트가 필요 없다 + - `AppVersion(major: 1, minor: 0, patch: 0)` — 최소 버전과 딱 같음 + - `AppVersion(major: 1, minor: 0, patch: 1)` — patch 하나 위 + +## 앱 버전 + +`Tests/AppUpdate/Entity/AppVersionTests.swift` + +### 문자열 읽기 + +- 숫자가 하나나 둘이면 비어 있는 자리를 0으로 채운다 + - `("1", AppVersion(major: 1, minor: 0, patch: 0))` — minor·patch가 빔 + - `("1.2", AppVersion(major: 1, minor: 2, patch: 0))` — patch만 빔 +- 숫자가 셋이면 그대로 읽는다 +- 앞뒤 공백은 무시하고 읽는다 +- 버전 모양이 아니면 오류로 처리한다 + - `""` — 아무것도 없음 + - `" "` — 공백뿐 + - `"1.2.3.4"` — 숫자가 넷 + - `"a.b.c"` — 숫자가 아님 + - `"1.-2.3"` — 음수 + - `"v1.2.3"` — 앞에 글자가 붙음 + - `"1..2"` — 가운데 자리가 빔 + - `"1."` — 끝 자리가 빔 + - `".1"` — 첫 자리가 빔 + +### 비교 + +- 앞자리부터 차례로 비교해 처음 다른 자리로 크기를 정한다 + - `(AppVersion(major: 1, minor: 9, patch: 9), AppVersion(major: 2, minor: 0, patch: 0))` — major가 작으면 minor·patch가 커도 작다 + - `(AppVersion(major: 1, minor: 2, patch: 9), AppVersion(major: 1, minor: 3, patch: 0))` — major가 같으면 minor가 작은 쪽이 작다(patch가 커도) + - `(AppVersion(major: 1, minor: 2, patch: 3), AppVersion(major: 1, minor: 2, patch: 4))` — major·minor가 같으면 patch로 정한다 +- 세 자리가 모두 같으면 더 작다고 보지 않는다 + +## 약관 동의 + +`Tests/TermsAgreement/Entity/TermsAgreementDraftTests.swift` + +### 처음 상태 + +- 아무 값 없이 만들면 모든 약관이 미동의다 +- 값을 주지 않은 약관은 미동의로 채운다 + +### 동의 여부 편집 + +- 약관 하나에 동의하거나 철회하면 그 약관만 바뀐다 + - `true` — 전부 미동의인 상태에서 하나만 동의 + - `false` — 전부 동의한 상태에서 하나만 철회 +- 모두 동의하면 선택 약관까지 전부 동의가 된다 + +### 제출 + +- 필수 약관 중 하나라도 동의하지 않으면 제출할 수 없다 + - `[.serviceAgreement: false, .privacyPolicy: true, .marketingConsent: true]` — 서비스 이용약관만 빠짐 + - `[.serviceAgreement: true, .privacyPolicy: false, .marketingConsent: true]` — 개인정보 처리방침만 빠짐 +- 선택 약관인 마케팅 수신에 동의하지 않아도 제출할 수 있다 diff --git a/Projects/Domain/SettingDomain/Testing/Mock/MockAppUpdateRepository.swift b/Projects/Domain/SettingDomain/Testing/Mock/MockAppUpdateRepository.swift index a5e32a1cb..14507608c 100644 --- a/Projects/Domain/SettingDomain/Testing/Mock/MockAppUpdateRepository.swift +++ b/Projects/Domain/SettingDomain/Testing/Mock/MockAppUpdateRepository.swift @@ -12,15 +12,13 @@ import SettingDomain import BaseDomain public final class MockAppUpdateRepository: AppUpdateRepository { - public var loadCallCount = 0 public var result: Result = .success( - AppUpdatePolicy(minimumVersion: .zero, updateDate: nil) + AppUpdatePolicy(minimumVersion: AppVersion(major: 0, minor: 0, patch: 0), updateDate: nil) ) public init() {} public func loadAppUpdatePolicy() async throws(RepositoryError) -> AppUpdatePolicy { - loadCallCount += 1 - return try result.get() + try result.get() } } diff --git a/Projects/Domain/SettingDomain/Testing/Mock/MockTermsAgreementRepository.swift b/Projects/Domain/SettingDomain/Testing/Mock/MockTermsAgreementRepository.swift index d67a0ae79..5f5414f00 100644 --- a/Projects/Domain/SettingDomain/Testing/Mock/MockTermsAgreementRepository.swift +++ b/Projects/Domain/SettingDomain/Testing/Mock/MockTermsAgreementRepository.swift @@ -12,7 +12,6 @@ import SettingDomain import BaseDomain public final class MockTermsAgreementRepository: TermsAgreementRepository { - public var loadCallCount = 0 public var saveCallCount = 0 public var savedDrafts: [TermsAgreementDraft] = [] @@ -22,8 +21,7 @@ public final class MockTermsAgreementRepository: TermsAgreementRepository { public init() {} public func loadTermsAgreementDraft() async throws(RepositoryError) -> TermsAgreementDraft { - loadCallCount += 1 - return try loadResult.get() + try loadResult.get() } public func save(draft: TermsAgreementDraft) async throws(RepositoryError) { diff --git a/Projects/Domain/SettingDomain/Tests/AppUpdate/Entity/AppUpdatePolicyTests.swift b/Projects/Domain/SettingDomain/Tests/AppUpdate/Entity/AppUpdatePolicyTests.swift index 925b99bdf..f710865e6 100644 --- a/Projects/Domain/SettingDomain/Tests/AppUpdate/Entity/AppUpdatePolicyTests.swift +++ b/Projects/Domain/SettingDomain/Tests/AppUpdate/Entity/AppUpdatePolicyTests.swift @@ -6,46 +6,37 @@ // Copyright © 2026 kr.websoso.app. All rights reserved. // -import Foundation import Testing -@testable import SettingDomain -import SettingDomainTesting -import BaseDomain +import SettingDomain -@Suite("AppUpdatePolicy") +@Suite("강제 업데이트 판단") struct AppUpdatePolicyTests { - @Test("현재 버전이 최소 버전보다 낮으면 강제 업데이트가 필요하다") - func requiresForceUpdateWhenCurrentIsLower() { - let policy = AppUpdatePolicy( - minimumVersion: AppVersion(major: 1, minor: 0, patch: 0), - updateDate: nil - ) + private let policy = AppUpdatePolicy( + minimumVersion: AppVersion(major: 1, minor: 0, patch: 0), + updateDate: nil + ) + @Test("앱 버전이 최소 버전보다 낮으면 강제 업데이트가 필요하다") + func requiresUpdateBelowMinimum() { let current = AppVersion(major: 0, minor: 9, patch: 9) - #expect(policy.requiresForceUpdate(current: current) == true) - } - @Test("현재 버전이 최소 버전과 같으면 강제 업데이트가 필요하지 않다") - func doesNotRequireForceUpdateWhenCurrentEqualsMinimum() { - let policy = AppUpdatePolicy( - minimumVersion: AppVersion(major: 1, minor: 0, patch: 0), - updateDate: nil - ) + let requiresUpdate = policy.requiresForceUpdate(current: current) - let current = AppVersion(major: 1, minor: 0, patch: 0) - #expect(policy.requiresForceUpdate(current: current) == false) + #expect(requiresUpdate == true) } - @Test("현재 버전이 최소 버전보다 높으면 강제 업데이트가 필요하지 않다") - func doesNotRequireForceUpdateWhenCurrentIsGreater() { - let policy = AppUpdatePolicy( - minimumVersion: AppVersion(major: 1, minor: 0, patch: 0), - updateDate: nil - ) - - let current = AppVersion(major: 1, minor: 0, patch: 1) - #expect(policy.requiresForceUpdate(current: current) == false) + @Test( + "앱 버전이 최소 버전과 같거나 높으면 강제 업데이트가 필요 없다", + arguments: [ + AppVersion(major: 1, minor: 0, patch: 0), // 최소 버전과 딱 같음 + AppVersion(major: 1, minor: 0, patch: 1) // patch 하나 위 + ] + ) + func doesNotRequireUpdateAtOrAboveMinimum(current: AppVersion) { + let requiresUpdate = policy.requiresForceUpdate(current: current) + + #expect(requiresUpdate == false) } } diff --git a/Projects/Domain/SettingDomain/Tests/AppUpdate/Entity/AppVersionTests.swift b/Projects/Domain/SettingDomain/Tests/AppUpdate/Entity/AppVersionTests.swift index 472f90fc0..7bb9e1ce8 100644 --- a/Projects/Domain/SettingDomain/Tests/AppUpdate/Entity/AppVersionTests.swift +++ b/Projects/Domain/SettingDomain/Tests/AppUpdate/Entity/AppVersionTests.swift @@ -8,87 +8,89 @@ import Testing -@testable import SettingDomain -import SettingDomainTesting -import BaseDomain +import SettingDomain -@Suite("AppVersion") +@Suite("앱 버전") struct AppVersionTests { - @Test("버전 문자열이 한 자리일 경우 1.0.0 형태로 해석된다") - func parsesSingleComponentVersion() throws { - let v = try AppVersion("1") - #expect(v.major == 1) - #expect(v.minor == 0) - #expect(v.patch == 0) - #expect(v.description == "1.0.0") - } + @Suite("문자열 읽기") + struct Parsing { - @Test("버전 문자열이 두 자리일 경우 patch는 0으로 보정된다") - func parsesTwoComponentVersion() throws { - let v = try AppVersion("1.2") - #expect(v.major == 1) - #expect(v.minor == 2) - #expect(v.patch == 0) - #expect(v.description == "1.2.0") - } + @Test( + "숫자가 하나나 둘이면 비어 있는 자리를 0으로 채운다", + arguments: [ + ("1", AppVersion(major: 1, minor: 0, patch: 0)), // minor·patch가 빔 + ("1.2", AppVersion(major: 1, minor: 2, patch: 0)) // patch만 빔 + ] + ) + func fillsMissingComponentsWithZero(text: String, expected: AppVersion) throws { + let version = try AppVersion(text) - @Test("버전 문자열이 세 자리일 경우 그대로 해석된다") - func parsesThreeComponentVersion() throws { - let v = try AppVersion("1.2.3") - #expect(v.major == 1) - #expect(v.minor == 2) - #expect(v.patch == 3) - #expect(v.description == "1.2.3") - } + #expect(version == expected) + } - @Test("버전 문자열 앞뒤 공백은 무시된다") - func trimsWhitespace() throws { - let v = try AppVersion(" 2.0.1 ") - #expect(v == AppVersion(major: 2, minor: 0, patch: 1)) - } + @Test("숫자가 셋이면 그대로 읽는다") + func readsThreeComponents() throws { + let version = try AppVersion("1.2.3") - @Test("유효하지 않은 버전 문자열이면 파싱에 실패한다") - func throwsOnInvalidFormat() async { - #expect(throws: AppVersion.ParseError.invalidFormat("1.2.3.4")) { - _ = try AppVersion("1.2.3.4") + #expect(version == AppVersion(major: 1, minor: 2, patch: 3)) } - #expect(throws: AppVersion.ParseError.invalidFormat("a.b.c")) { - _ = try AppVersion("a.b.c") + @Test("앞뒤 공백은 무시하고 읽는다") + func ignoresSurroundingWhitespace() throws { + let version = try AppVersion(" 2.0.1\n") + + #expect(version == AppVersion(major: 2, minor: 0, patch: 1)) } - #expect(throws: AppVersion.ParseError.invalidFormat("")) { - _ = try AppVersion("") + @Test( + "버전 모양이 아니면 오류로 처리한다", + arguments: [ + "", // 아무것도 없음 + " ", // 공백뿐 + "1.2.3.4", // 숫자가 넷 + "a.b.c", // 숫자가 아님 + "1.-2.3", // 음수 + "v1.2.3", // 앞에 글자가 붙음 + "1..2", // 가운데 자리가 빔 + "1.", // 끝 자리가 빔 + ".1" // 첫 자리가 빔 + ] + ) + func rejectsMalformedText(text: String) { + #expect(throws: AppVersion.ParseError.invalidFormat(text)) { + try AppVersion(text) + } } } - @Test("patch 버전이 다르면 patch 값을 기준으로 비교한다") - func comparesPatchVersion() { - let a = AppVersion(major: 1, minor: 2, patch: 3) - let b = AppVersion(major: 1, minor: 2, patch: 4) - #expect(a < b) - #expect(b > a) - } + @Suite("비교") + struct Comparison { - @Test("minor 버전이 다르면 minor 값을 기준으로 비교한다") - func comparesMinorVersion() { - let a = AppVersion(major: 1, minor: 2, patch: 9) - let b = AppVersion(major: 1, minor: 3, patch: 0) - #expect(a < b) - } + @Test( + "앞자리부터 차례로 비교해 처음 다른 자리로 크기를 정한다", + arguments: [ + // major가 작으면 minor·patch가 커도 작다 + (AppVersion(major: 1, minor: 9, patch: 9), AppVersion(major: 2, minor: 0, patch: 0)), + // major가 같으면 minor가 작은 쪽이 작다(patch가 커도) + (AppVersion(major: 1, minor: 2, patch: 9), AppVersion(major: 1, minor: 3, patch: 0)), + // major·minor가 같으면 patch로 정한다 + (AppVersion(major: 1, minor: 2, patch: 3), AppVersion(major: 1, minor: 2, patch: 4)) + ] + ) + func higherComponentDecidesOrder(smaller: AppVersion, larger: AppVersion) { + let sorted = [larger, smaller].sorted() - @Test("major 버전이 다르면 major 값을 기준으로 비교한다") - func comparesMajorVersion() { - let a = AppVersion(major: 1, minor: 9, patch: 9) - let b = AppVersion(major: 2, minor: 0, patch: 0) - #expect(a < b) - } + #expect(sorted == [smaller, larger]) + } - @Test("1.2와 1.2.0은 같은 버전으로 취급된다") - func treatsNormalizedVersionsAsEqual() throws { - let a = try AppVersion("1.2") - let b = try AppVersion("1.2.0") - #expect(a == b) + @Test("세 자리가 모두 같으면 더 작다고 보지 않는다") + func sameComponentsAreNotSmaller() { + let version = AppVersion(major: 1, minor: 2, patch: 3) + + let isSmaller = version < AppVersion(major: 1, minor: 2, patch: 3) + + #expect(isSmaller == false) + } } } diff --git a/Projects/Domain/SettingDomain/Tests/AppUpdate/UseCase/CheckForceUpdateRequirementUseCaseTests.swift b/Projects/Domain/SettingDomain/Tests/AppUpdate/UseCase/CheckForceUpdateRequirementUseCaseTests.swift deleted file mode 100644 index 3789607ec..000000000 --- a/Projects/Domain/SettingDomain/Tests/AppUpdate/UseCase/CheckForceUpdateRequirementUseCaseTests.swift +++ /dev/null @@ -1,88 +0,0 @@ -// -// CheckForceUpdateRequirementUseCaseTests.swift -// SettingDomain -// -// Created by YunhakLee on 2/10/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation -import Testing - -@testable import SettingDomain -import SettingDomainTesting -import BaseDomain - -@Suite("CheckForceUpdateRequirementUseCase") -struct CheckForceUpdateRequirementUseCaseTests { - - // MARK: - Tests - @Test("현재 버전이 최소 버전보다 낮으면 강제 업데이트가 필요하다") - func returnsTrueWhenCurrentIsLower() async throws { - let repo = MockAppUpdateRepository() - repo.result = .success( - AppUpdatePolicy(minimumVersion: AppVersion(major: 2, minor: 0, patch: 0), - updateDate: nil) - ) - - let provider = MockAppVersionProvider(currentVersion: AppVersion(major: 1, minor: 9, patch: 9)) - let sut = DefaultCheckForceUpdateRequirementUseCase(repository: repo, versionProvider: provider) - - let required = try await sut.execute() - - #expect(repo.loadCallCount == 1) - #expect(required == true) - } - - @Test("현재 버전이 최소 버전과 같으면 강제 업데이트가 필요하지 않다") - func returnsFalseWhenCurrentEqualsMinimum() async throws { - let repo = MockAppUpdateRepository() - repo.result = .success( - AppUpdatePolicy(minimumVersion: AppVersion(major: 1, minor: 0, patch: 0), - updateDate: nil) - ) - - let provider = MockAppVersionProvider(currentVersion: AppVersion(major: 1, minor: 0, patch: 0)) - let sut = DefaultCheckForceUpdateRequirementUseCase(repository: repo, versionProvider: provider) - - let required = try await sut.execute() - - #expect(repo.loadCallCount == 1) - #expect(required == false) - } - - @Test("현재 버전이 최소 버전보다 높으면 강제 업데이트가 필요하지 않다") - func returnsFalseWhenCurrentIsGreater() async throws { - let repo = MockAppUpdateRepository() - repo.result = .success( - AppUpdatePolicy(minimumVersion: AppVersion(major: 1, minor: 0, patch: 0), - updateDate: nil) - ) - - let provider = MockAppVersionProvider(currentVersion: AppVersion(major: 1, minor: 0, patch: 1)) - let sut = DefaultCheckForceUpdateRequirementUseCase(repository: repo, versionProvider: provider) - - let required = try await sut.execute() - - #expect(repo.loadCallCount == 1) - #expect(required == false) - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockAppUpdateRepository() - repo.result = .failure(.networkUnavailable) - - let provider = MockAppVersionProvider(currentVersion: .zero) - let sut = DefaultCheckForceUpdateRequirementUseCase( - repository: repo, - versionProvider: provider - ) - - await #expect(throws: RepositoryError.networkUnavailable) { - _ = try await sut.execute() - } - - #expect(repo.loadCallCount == 1) - } -} diff --git a/Projects/Domain/SettingDomain/Tests/TermsAgreement/Entity/TermsAgreementDraftTests.swift b/Projects/Domain/SettingDomain/Tests/TermsAgreement/Entity/TermsAgreementDraftTests.swift index 1acd9d795..5630e8b60 100644 --- a/Projects/Domain/SettingDomain/Tests/TermsAgreement/Entity/TermsAgreementDraftTests.swift +++ b/Projects/Domain/SettingDomain/Tests/TermsAgreement/Entity/TermsAgreementDraftTests.swift @@ -8,111 +8,103 @@ import Testing -@testable import SettingDomain -import SettingDomainTesting -import BaseDomain +import SettingDomain -@Suite("TermsAgreementDraft") +@Suite("약관 동의") struct TermsAgreementDraftTests { - @Test("초기화 시 모든 약관 항목은 기본값 false로 채워진다") - func initFillsAllCasesWithFalseByDefault() throws { - let draft = TermsAgreementDraft() + @Suite("처음 상태") + struct Initial { - for t in TermsType.allCases { - #expect(draft.isAgreed(t) == false) - } - } - - @Test("초기값으로 전달한 항목은 반영되고, 나머지는 false로 채워진다") - func initAppliesInitialAndDefaultsTheRestToFalse() throws { - let some = TermsType.allCases.first! - let draft = TermsAgreementDraft(initial: [some: true]) + @Test("아무 값 없이 만들면 모든 약관이 미동의다") + func startsWithEverythingDisagreed() { + let draft = TermsAgreementDraft() - #expect(draft.isAgreed(some) == true) - - for t in TermsType.allCases where t != some { - #expect(draft.isAgreed(t) == false) + #expect(draft.agreements == [ + .serviceAgreement: false, + .privacyPolicy: false, + .marketingConsent: false + ]) } - } - - @Test("특정 약관 동의 여부를 조회할 수 있다") - func isAgreedReadsCurrentState() { - var draft = TermsAgreementDraft() - let t = TermsType.allCases[0] - #expect(draft.isAgreed(t) == false) + @Test("값을 주지 않은 약관은 미동의로 채운다") + func fillsUnspecifiedTermsAsDisagreed() { + let draft = TermsAgreementDraft(initial: [.marketingConsent: true]) - draft.setAgreed(true, for: t) - #expect(draft.isAgreed(t) == true) - } - - @Test("특정 약관 동의 여부를 설정할 수 있다") - func setAgreedUpdatesAgreementState() { - var draft = TermsAgreementDraft() - let t = TermsType.allCases[0] - - draft.setAgreed(true, for: t) - #expect(draft.isAgreed(t) == true) - - draft.setAgreed(false, for: t) - #expect(draft.isAgreed(t) == false) - } - - @Test("모두 동의 기능을 실행하면 모든 약관이 true가 된다") - func agreeToAllSetsAllToTrue() { - var draft = TermsAgreementDraft() - draft.agreeToAll() - - for t in TermsType.allCases { - #expect(draft.isAgreed(t) == true) + #expect(draft.agreements == [ + .serviceAgreement: false, + .privacyPolicy: false, + .marketingConsent: true + ]) } } - @Test("필수 약관이 모두 동의되면 제출 가능 상태가 된다") - func isSubmittableTrueWhenAllRequiredAreAgreed() { - var draft = TermsAgreementDraft() - - // 필수만 true로 - for t in TermsType.allCases where t.isRequired { - draft.setAgreed(true, for: t) + @Suite("동의 여부 편집") + struct Changing { + + @Test( + "약관 하나에 동의하거나 철회하면 그 약관만 바뀐다", + arguments: [ + true, // 전부 미동의인 상태에서 하나만 동의 + false // 전부 동의한 상태에서 하나만 철회 + ] + ) + func changesOnlyThatTerm(isAgreed: Bool) { + var draft = TermsAgreementDraft(initial: [ + .serviceAgreement: !isAgreed, + .privacyPolicy: !isAgreed, + .marketingConsent: !isAgreed + ]) + + draft.setAgreed(isAgreed, for: .privacyPolicy) + + #expect(draft.agreements == [ + .serviceAgreement: !isAgreed, + .privacyPolicy: isAgreed, + .marketingConsent: !isAgreed + ]) } - #expect(draft.isSubmittable == true) - } - - @Test("필수 약관 중 하나라도 미동의면 제출 불가 상태가 된다") - func isSubmittableFalseWhenAnyRequiredIsNotAgreed() { - var draft = TermsAgreementDraft() + @Test("모두 동의하면 선택 약관까지 전부 동의가 된다") + func agreeToAllIncludesOptionalTerms() { + var draft = TermsAgreementDraft() - // 필수 중 하나만 false로 유지 (나머지 필수는 true) - let required = TermsType.allCases.filter { $0.isRequired } - let firstRequired = required.first + draft.agreeToAll() - for t in required { - draft.setAgreed(true, for: t) + #expect(draft.agreements == [ + .serviceAgreement: true, + .privacyPolicy: true, + .marketingConsent: true + ]) } - if let firstRequired { - draft.setAgreed(false, for: firstRequired) - } - - #expect(draft.isSubmittable == false) } - @Test("선택 약관은 미동의여도 제출 가능 여부에 영향을 주지 않는다") - func optionalTermsDoNotAffectSubmittable() { - var draft = TermsAgreementDraft() - - // 필수는 전부 true - for t in TermsType.allCases where t.isRequired { - draft.setAgreed(true, for: t) + @Suite("제출") + struct Submission { + + @Test( + "필수 약관 중 하나라도 동의하지 않으면 제출할 수 없다", + // 선택 약관(마케팅)까지 동의해도 필수 하나가 빠지면 소용없다. + arguments: [ + [.serviceAgreement: false, .privacyPolicy: true, .marketingConsent: true], // 서비스 이용약관만 빠짐 + [.serviceAgreement: true, .privacyPolicy: false, .marketingConsent: true] // 개인정보 처리방침만 빠짐 + ] as [[TermsType: Bool]] + ) + func notSubmittableWithoutARequiredTerm(agreements: [TermsType: Bool]) { + let draft = TermsAgreementDraft(initial: agreements) + + #expect(draft.isSubmittable == false) } - // 선택은 전부 false로 유지해도 제출 가능 - for t in TermsType.allCases where !t.isRequired { - #expect(draft.isAgreed(t) == false) - } + @Test("선택 약관인 마케팅 수신에 동의하지 않아도 제출할 수 있다") + func submittableWithoutOptionalTerm() { + let draft = TermsAgreementDraft(initial: [ + .serviceAgreement: true, + .privacyPolicy: true, + .marketingConsent: false + ]) - #expect(draft.isSubmittable == true) + #expect(draft.isSubmittable == true) + } } } diff --git a/Projects/Domain/SettingDomain/Tests/TermsAgreement/UseCase/LoadTermsAgreementDraftUseCaseTests.swift b/Projects/Domain/SettingDomain/Tests/TermsAgreement/UseCase/LoadTermsAgreementDraftUseCaseTests.swift deleted file mode 100644 index ad321a9dd..000000000 --- a/Projects/Domain/SettingDomain/Tests/TermsAgreement/UseCase/LoadTermsAgreementDraftUseCaseTests.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// LoadTermsAgreementDraftUseCaseTests.swift -// SettingDomain -// -// Created by YunhakLee on 2/10/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import SettingDomain -import SettingDomainTesting -import BaseDomain - -@Suite("LoadTermsAgreementDraftUseCase") -struct LoadTermsAgreementDraftUseCaseTests { - - @Test("레포지토리에서 Draft를 불러와 그대로 반환한다") - func returnsDraftFromRepository() async throws { - let repo = MockTermsAgreementRepository() - - var expected = TermsAgreementDraft() - let any = TermsType.allCases.first! - expected.setAgreed(true, for: any) - repo.loadResult = .success(expected) - - let sut = DefaultLoadTermsAgreementDraftUseCase(repository: repo) - - let draft = try await sut.execute() - - #expect(repo.loadCallCount == 1) - #expect(draft == expected) - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockTermsAgreementRepository() - repo.loadResult = .failure(.networkUnavailable) - - let sut = DefaultLoadTermsAgreementDraftUseCase(repository: repo) - - await #expect(throws: RepositoryError.networkUnavailable) { - _ = try await sut.execute() - } - - #expect(repo.loadCallCount == 1) - } -} diff --git a/Projects/Domain/SettingDomain/Tests/TermsAgreement/UseCase/SaveTermsAgreementDraftUseCaseTests.swift b/Projects/Domain/SettingDomain/Tests/TermsAgreement/UseCase/SaveTermsAgreementDraftUseCaseTests.swift deleted file mode 100644 index f31c1785e..000000000 --- a/Projects/Domain/SettingDomain/Tests/TermsAgreement/UseCase/SaveTermsAgreementDraftUseCaseTests.swift +++ /dev/null @@ -1,52 +0,0 @@ -// -// SaveTermsAgreementDraftUseCaseTests.swift -// SettingDomain -// -// Created by YunhakLee on 2/10/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Testing - -@testable import SettingDomain -import SettingDomainTesting -import BaseDomain - -@Suite("SaveTermsAgreementDraftUseCase") -struct SaveTermsAgreementDraftUseCaseTests { - - @Test("Draft를 저장 요청하면 레포지토리에 그대로 전달한다") - func savesDraftToRepository() async throws - { - let repo = MockTermsAgreementRepository() - let sut = DefaultSaveTermsAgreementDraftUseCase(repository: repo) - - var draft = TermsAgreementDraft() - - for t in TermsType.allCases where t.isRequired { - draft.setAgreed(true, for: t) - } - - try await sut.execute(draft: draft) - - #expect(repo.saveCallCount == 1) - #expect(repo.savedDrafts == [draft]) - } - - @Test("레포지토리에서 에러가 발생하면 그대로 전달한다") - func propagatesRepositoryError() async { - let repo = MockTermsAgreementRepository() - repo.saveResult = .failure(.authenticationRequired) - - let sut = DefaultSaveTermsAgreementDraftUseCase(repository: repo) - - let draft = TermsAgreementDraft() - - await #expect(throws: RepositoryError.authenticationRequired) { - try await sut.execute(draft: draft) - } - - #expect(repo.saveCallCount == 1) - #expect(repo.savedDrafts == [draft]) - } -} diff --git a/Projects/Domain/SplashDomain/CLAUDE.md b/Projects/Domain/SplashDomain/CLAUDE.md index 577d5fb6d..2b3b5fd74 100644 --- a/Projects/Domain/SplashDomain/CLAUDE.md +++ b/Projects/Domain/SplashDomain/CLAUDE.md @@ -4,7 +4,7 @@ 런치 부트스트랩 정책 — 앱 진입 시 게이트 판정(강제 업데이트→세션→약관)과 부수 태스크 실행 순서·실패 분기를 전담한다(#225). 구성요소는 `Sources/`를 직접 보면 된다. - 식별자: `ModuleType.domain(.splash)` / 의존: `BaseDomain`뿐 -- **포트 2개는 Splash의 언어로 새로 선언한 것** — `LaunchGateRepository`(판정 질문) / `LaunchTaskRepository`(부수 태스크). 실제 답은 다른 도메인들(Profile·Setting·Notification·Base·Recommendation)에 있지만, **도메인 간 직접 의존 금지 규칙 때문에 여기선 프로토콜만 선언**하고 구현은 `SplashData`가 그 도메인들의 repo에 위임한다(구조 확정: 사용자, 2026-08-31). +- **포트 2개는 Splash의 언어로 새로 선언한 것** — `LaunchGateRepository`(판정 질문) / `LaunchTaskRepository`(부수 태스크). 실제 답은 다른 도메인들(Profile·Setting·Base·Recommendation)에 있지만, **도메인 간 직접 의존 금지 규칙 때문에 여기선 프로토콜만 선언**하고 구현은 `SplashData`가 그 도메인들의 repo에 위임한다(구조 확정: 사용자, 2026-08-31). ## 핵심 시나리오 @@ -23,7 +23,10 @@ 세션 게이트는 통과하나 프로필이 없다). 판정은 `LaunchGateRepository.isOnboardingCompleted()`(SplashData가 로컬 `isRegistered`를 `?? true`로 읽음 — 값 없으면 기존 유저로 보고 통과)에 위임하고, 순서·라우팅은 여기가 정한다. 부수 태스크·약관 게이트는 온보딩을 끝낸 세션에만 의미가 있어 이 게이트 뒤에 둔다. - - **부수 태스크 4종은 fire-and-forget** — 완료를 기다리지 않고 main을 반환(사용자 확정). 세션 없으면 시작조차 안 한다. + - **부수 태스크 3종은 fire-and-forget** — 완료를 기다리지 않고 main을 반환(사용자 확정). 세션 없으면 시작조차 안 한다. + - ⚠️ **FCM 토큰 등록은 부수 태스크에서 뺐다**(#287) — 런치 시점엔 APNs 토큰이 아직 없어 Firebase `token()`이 + 실기기에서 항상 실패했다(실측). 등록은 App의 푸시 허브(`PushNotificationCenter`)가 APNs 토큰 수신 직후에 한다 + (→ `App/CLAUDE.md` 푸시 배선). 여기에 되살리지 말 것. ## 주의사항 (작업 중 발견 시 누적) @@ -43,7 +46,7 @@ 만들거나 Networking에 request timeout을 두는 것 — 둘 다 Core 변경이라 이 모듈 밖이다. **완화(#236)**: App 조립이 재발급 전용 URLSession에 요청 타임아웃 10초를 걸어 최악 잠김을 60초→약 10초로 좁혔다(`App/CLAUDE.md` 주의사항). 예산 4초를 온전히 지키려면 여전히 위 근본 해결이 필요하다. -- `.intro`로 낙착해도 **이미 던진 부수 태스크는 되돌리지 않는다**. 죽은 세션에선 4종 전부 실패하고 끝나 +- `.intro`로 낙착해도 **이미 던진 부수 태스크는 되돌리지 않는다**. 죽은 세션에선 3종 전부 실패하고 끝나 무해하다 — 홈 프리페치 3종도 **전부 `requireToken`**이라(2026-08-31, today/trending을 `usesTokenIfAvailable`에서 전환) 익명 200으로 슬롯이 채워지는 일이 없다(fail-closed). 과거엔 today/trending이 익명으로도 채워져 "세션 소실 → 인트로 → 재로그인 뒤 첫 홈 로드가 런치 시점 diff --git a/Projects/Domain/SplashDomain/Sources/Repository/LaunchTaskRepository.swift b/Projects/Domain/SplashDomain/Sources/Repository/LaunchTaskRepository.swift index 858764c5d..aeb7b0566 100644 --- a/Projects/Domain/SplashDomain/Sources/Repository/LaunchTaskRepository.swift +++ b/Projects/Domain/SplashDomain/Sources/Repository/LaunchTaskRepository.swift @@ -16,8 +16,6 @@ import BaseDomain public protocol LaunchTaskRepository: Sendable { /// 유저 정보(`/users/me`)를 조회해 로컬 캐시(userId·nickname·gender·birth)를 갱신한다. func syncUserBasicInfo() async throws(RepositoryError) - /// FCM 디바이스 토큰을 서버에 등록한다(푸시 권한이 있을 때만). - func registerDeviceTokenIfNeeded() async throws(RepositoryError) /// 키워드 로컬 캐시를 서버와 동기화한다. func syncKeywords() async /// 홈 첫 화면 데이터(오늘의 발견·지금 뜨는 글)를 미리 받아 single-shot store를 채운다. diff --git a/Projects/Domain/SplashDomain/Sources/UseCase/BootstrapAppUseCase.swift b/Projects/Domain/SplashDomain/Sources/UseCase/BootstrapAppUseCase.swift index c949a22b7..1b702be0e 100644 --- a/Projects/Domain/SplashDomain/Sources/UseCase/BootstrapAppUseCase.swift +++ b/Projects/Domain/SplashDomain/Sources/UseCase/BootstrapAppUseCase.swift @@ -16,7 +16,7 @@ import BaseDomain /// 1. 강제 업데이트 게이트 — 조회 **실패는 통과**시킨다(서버 장애가 앱을 잠그면 안 된다). /// 2. 세션 게이트 — 저장된 세션이 없으면 인트로로, 부수 태스크는 시작하지 않는다. /// 2-1. 온보딩 게이트 — 세션은 있으나 온보딩(가입) 미완료면 인트로로(#257, 로컬 캐시가 없으면 완료로 간주). -/// 3. 부수 태스크 4종(users/me·FCM·키워드·프리페치) — **던지고 진입**(완료를 기다리지 않고, +/// 3. 부수 태스크 3종(users/me·키워드·프리페치) — **던지고 진입**(완료를 기다리지 않고, /// 실패·지연이 앱 진입을 막지 않는다). /// 4. 약관 게이트 — 조회 실패는 동의로 간주해 진입을 막지 않는다. 단 세션 소실만은 인트로로. /// @@ -82,14 +82,13 @@ public final class DefaultBootstrapAppUseCase: BootstrapAppUseCase { // 부수 태스크·약관 게이트는 온보딩을 끝낸 세션에만 의미가 있어 이 게이트 뒤에 둔다. guard gateRepository.isOnboardingCompleted() else { return .intro } - // 3. 부수 태스크 4종 — 던지고 진입(실패·지연이 앱 진입을 막지 않는다). + // 3. 부수 태스크 3종 — 던지고 진입(실패·지연이 앱 진입을 막지 않는다). let taskRepository = taskRepository launchInBackground { async let userSync: Void? = try? taskRepository.syncUserBasicInfo() - async let deviceToken: Void? = try? taskRepository.registerDeviceTokenIfNeeded() async let keywords: Void = taskRepository.syncKeywords() async let prefetch: Void = taskRepository.prefetchHomeData() - _ = await (userSync, deviceToken, keywords, prefetch) + _ = await (userSync, keywords, prefetch) } // 4. 약관 게이트 — 조회 실패·예산 초과는 동의로 간주해 진입을 막지 않는다. diff --git a/Projects/Domain/SplashDomain/Testing/Mock/MockLaunchTaskRepository.swift b/Projects/Domain/SplashDomain/Testing/Mock/MockLaunchTaskRepository.swift index 35b4f340f..4c843bda0 100644 --- a/Projects/Domain/SplashDomain/Testing/Mock/MockLaunchTaskRepository.swift +++ b/Projects/Domain/SplashDomain/Testing/Mock/MockLaunchTaskRepository.swift @@ -11,15 +11,13 @@ import Foundation import BaseDomain import SplashDomain -/// 부수 태스크 4종은 UseCase가 `async let`으로 **동시에** 부른다 — 카운터를 NSLock으로 지킨다. +/// 부수 태스크 3종은 UseCase가 `async let`으로 **동시에** 부른다 — 카운터를 NSLock으로 지킨다. public final class MockLaunchTaskRepository: LaunchTaskRepository, @unchecked Sendable { private struct State { var syncUserBasicInfoResult: Result = .success(()) - var registerDeviceTokenIfNeededResult: Result = .success(()) var syncUserBasicInfoCallCount = 0 - var registerDeviceTokenIfNeededCallCount = 0 var syncKeywordsCallCount = 0 var prefetchHomeDataCallCount = 0 } @@ -34,15 +32,9 @@ public final class MockLaunchTaskRepository: LaunchTaskRepository, @unchecked Se set { lock.withLock { state.syncUserBasicInfoResult = newValue } } } - public var registerDeviceTokenIfNeededResult: Result { - get { lock.withLock { state.registerDeviceTokenIfNeededResult } } - set { lock.withLock { state.registerDeviceTokenIfNeededResult = newValue } } - } - // MARK: - 호출 기록 public var syncUserBasicInfoCallCount: Int { lock.withLock { state.syncUserBasicInfoCallCount } } - public var registerDeviceTokenIfNeededCallCount: Int { lock.withLock { state.registerDeviceTokenIfNeededCallCount } } public var syncKeywordsCallCount: Int { lock.withLock { state.syncKeywordsCallCount } } public var prefetchHomeDataCallCount: Int { lock.withLock { state.prefetchHomeDataCallCount } } @@ -56,14 +48,6 @@ public final class MockLaunchTaskRepository: LaunchTaskRepository, @unchecked Se try result.get() } - public func registerDeviceTokenIfNeeded() async throws(RepositoryError) { - let result = lock.withLock { - state.registerDeviceTokenIfNeededCallCount += 1 - return state.registerDeviceTokenIfNeededResult - } - try result.get() - } - public func syncKeywords() async { lock.withLock { state.syncKeywordsCallCount += 1 } } diff --git a/Projects/Domain/SplashDomain/Tests/UseCase/BootstrapAppUseCaseTests.swift b/Projects/Domain/SplashDomain/Tests/UseCase/BootstrapAppUseCaseTests.swift index 143f88fc0..ae952a3cb 100644 --- a/Projects/Domain/SplashDomain/Tests/UseCase/BootstrapAppUseCaseTests.swift +++ b/Projects/Domain/SplashDomain/Tests/UseCase/BootstrapAppUseCaseTests.swift @@ -179,9 +179,9 @@ struct BootstrapAppUseCaseTests { #expect(outcome == .main(needsTermsAgreement: false)) } - // MARK: - 3. 부수 태스크 4종 — 던지고 진입(fire-and-forget), 실패·지연이 진입을 막지 않는다 + // MARK: - 3. 부수 태스크 3종 — 던지고 진입(fire-and-forget), 실패·지연이 진입을 막지 않는다 - @Test("세션이 있으면 부수 태스크 4종을 모두 시작한다") + @Test("세션이 있으면 부수 태스크 3종을 모두 시작한다") func sessionStartsAllLaunchTasks() async { let task = MockLaunchTaskRepository() let spy = BackgroundWorkSpy() @@ -191,7 +191,6 @@ struct BootstrapAppUseCaseTests { await spy.runAll() #expect(task.syncUserBasicInfoCallCount == 1) - #expect(task.registerDeviceTokenIfNeededCallCount == 1) #expect(task.syncKeywordsCallCount == 1) #expect(task.prefetchHomeDataCallCount == 1) } @@ -213,7 +212,6 @@ struct BootstrapAppUseCaseTests { func launchTaskFailuresDoNotAffectOutcome() async { let task = MockLaunchTaskRepository() task.syncUserBasicInfoResult = .failure(.serverUnavailable) - task.registerDeviceTokenIfNeededResult = .failure(.unknown) let spy = BackgroundWorkSpy() let sut = makeSUT(task: task, spy: spy) diff --git a/Projects/Feature/CollectionFeature/CLAUDE.md b/Projects/Feature/CollectionFeature/CLAUDE.md index dce150741..7fb962cac 100644 --- a/Projects/Feature/CollectionFeature/CLAUDE.md +++ b/Projects/Feature/CollectionFeature/CLAUDE.md @@ -99,8 +99,8 @@ `onRoute(.collectionDetail(CollectionID))`로 App에 알리면 App이 push한다(#201부터 로컬 `.navigationDestination(item:)`이 아니라 App의 `NavigationPath`). 히어로 배경은 `representativeNovelID`로 `novels` 배열에서 찾은 표지 위에 다크 그라데이션(상단 투명→하단 36% 블랙, `NovelDetailFeature`처럼 - 블러는 없음). `LoadCollectionDetailUseCase.execute(id:sortType:)`로 1회 로드(push 화면 — 재진입 시 - 재로드 안 함)하고, 정렬 토글(`WSSSortButton`, "최신순"↔"오래된순")은 가드 없이 매번 새로 조회한다. + 블러는 없음). `LoadCollectionDetailUseCase.execute(id:sortType:)`로 진입 시 1회 로드하고(자식 화면에서 + 돌아오면 `.reloadAfterReturn`으로 다시 부른다 — 아래 화면 동작 계약의 "컬렉션 수정" 항목), 정렬 토글(`WSSSortButton`, "최신순"↔"오래된순")은 가드 없이 매번 새로 조회한다. 좋아요는 `CollectionDetail.toggleLike()` 낙관 반영 + 실패 롤백(`UserPageFeature` 피드 좋아요와 동일 패턴). 복귀 시 `CollectionListView`는 무조건 그 탭을 재로드한다(위 `hasAppearedOnce`/`reloadAfterReturn` 경로 — 좋아요·삭제로 카드가 바뀌었을 수 있어서, `CreateCollectionView` 복귀와 동일 판단). @@ -166,6 +166,13 @@ **`MypageRootView`가 이 콜백을 받아 `NovelDetailAssembly`로 push한다**(#201에서 해소된 옛 TODO 항목) — 다른 탭(`LibraryRootView` 등)과 동일하게 작품 상세가 다시 여는 리뷰·피드 작성·피드 상세· 유저 프로필·일반 검색까지 그 서브트리 전체를 `MypageRootView`도 갖는다. + - **히어로의 작성자(프로필 사진·닉네임)를 탭하면 그 유저의 프로필로 간다**(#311) — 피드 상세 작성자 탭과 + 같은 계약: `onRoute(.userProfile(UserID))`를 올리면 4탭 Root가 내 ID 가드 후 `Destination.userPage`를 + push한다. **내 컬렉션(`isMine`)이면 `Button`을 아예 안 그린다**(이동할 곳이 없는 죽은 탭 영역 방지), + **탈퇴 유저(`owner.accessibleUserId == nil`)면 이동 대신 `.unknownUser` 토스트**. 서버 명세엔 "알 수 없는 + 사용자 프로필로 내려간다"고만 있고 값이 안 적혀 있지만, dev 서버 실측(2026-11-27, 컬렉션 63·49)으로 상세·공개 + 목록 둘 다 피드와 같은 `userId: -1`, 닉네임 `"(알 수 없음)"`, 기본 아바타로 오는 걸 확인했다 — 그래서 + `Author.accessibleUserId`의 `-1` 센티널 판정을 그대로 쓴다. - **"공유하기"는 카카오 공유 카드 하나다 — 카카오톡이 있으면 카카오톡 앱, 없으면 카카오 웹 공유(Safari). 시스템 공유 시트는 쓰지 않는다**(#228, 사용자 확정 2026-08-29). 목표가 "받은 사람이 카톡에서 탭해 앱의 이 화면으로 들어오는 것"인데, 커스텀 스킴(`websoso://…`)을 텍스트로 보내면 **카카오톡이 링크로 인식하지 않아** @@ -218,9 +225,15 @@ - **"컬렉션 수정"은 `CreateCollectionView`를 수정 모드로 재사용하는 별도 Factory 진입점 (`makeEditCollectionView`)이다** — 더보기 메뉴 탭 → `onRoute(.editCollection)`으로 App에 알리면 App이 push한다 (#201부터, 로컬 push 아님). 이 화면도 `CollectionListView`와 같은 `hasAppearedOnce` 플래그로 복귀를 - 감지한다(App 경로의 자식이 수정 화면 하나뿐이라 최초 이후 재발화는 곧 "수정에서 돌아옴") — - 성공/취소 구분 없이 무조건 `.reloadAfterEdit`로 다시 불러온다(이미 `state.detail`이 있어 전면 - 로딩으로 안 덮인다, 정렬 변경과 동일 UX). + 감지한다 — 최초 이후 재발화는 자식 화면(수정·작품 상세·작성자 프로필)에서의 복귀이고, 어디서 왔는지 + 구분 없이 무조건 `.reloadAfterReturn`(구 `reloadAfterEdit`)으로 다시 불러온다(이미 `state.detail`이 + 있어 전면 로딩으로 안 덮인다, 정렬 변경과 동일 UX). + - ⚠️ **이미 보던 상세를 다시 불러왔는데 `.forbidden`/`.notFound`면 실패 뷰 대신 화면을 닫는다**(#311, 사용자 + 확정 2026-11-27 — `closeIfNoLongerViewable`). 작성자 프로필에서 그 유저를 **차단하고 돌아오면 서버가 403 + `BLOCK-007`**("차단 관계인 사용자에게 접근할 수 없습니다")을 준다(dev 실측 2026-11-27, 공개 목록에서도 그 + 작성자의 컬렉션이 빠진다). 실패 뷰로 덮으면 재시도해도 같은 403이라 갇히고 "일시적 오류" 문구도 틀린다. + 삭제 성공과 같은 exit(`close()` + `shouldDismiss`)이고, "차단했어요" 토스트는 App 컨테이너 오버레이라 + 직전 화면 위에 그대로 남는다. 첫 로드(`detail == nil`)는 대상이 아니다(보여준 적 없는 화면을 말없이 닫지 않음). - 삭제는 확인 알럿(`WSSAlertType.deleteCollection`, "삭제한 컬렉션은 되돌릴 수 없어요") 필수 — Figma엔 알럿이 없지만 파괴적 액션은 항상 확인을 거치는 프로젝트 관례를 따른다(`deleteMyFeed`/ `deleteMyComment`와 동일 패턴). 성공 시 `shouldDismiss`로 화면을 닫는다(삭제된 컬렉션은 더 볼 수 @@ -313,7 +326,7 @@ 그대로 유효하다 — `MypageRootView`가 같은 `NavigationPath`에 "컬렉션 수정"을 push하면, 그 push가 App 소유든 예전처럼 Feature 로컬 소유든 상관없이 **push되는 순간 이전 화면(`CollectionDetailView`)의 `.onDisappear`가 SwiftUI 표준 동작으로 함께 발화한다.** 그 시점에 `isClosing`이 `true`로 굳고 - 되돌리는 코드가 없으면, 수정 화면에서 복귀한 뒤 재조회(`.reloadAfterEdit`)는 물론 정렬 변경·좋아요· + 되돌리는 코드가 없으면, 수정 화면에서 복귀한 뒤 재조회(`.reloadAfterReturn`)는 물론 정렬 변경·좋아요· 삭제까지 전부 조용히 무반응이 된다(alert도 안 닫힘, 콘솔 로그도 안 찍힘 — 겉보기엔 화면이 "고장"). `onDisappear` 기반 변형은 **같은 `NavigationPath`에서 자기 위로 뭔가 push될 일이 없는 리프 화면 (시트 등)에서만** 안전하다 — 이 화면처럼 같은 스택 위에 다른 화면이 push되면(App이 하든 Feature가 @@ -532,7 +545,11 @@ 아무것도 없는 첫 로드"일 때만** 전면 로딩을 보여줄 것 — `FeedFeature.SosoFeedView`의 `isLoading && currentFeeds.isEmpty` 판단과 동일 패턴이다. 재조회 실패는 여전히 `hasLoadError`로 전면 실패 뷰가 뜬다(`Feature/CLAUDE.md`의 "로드 실패 표현 계약"대로 갱신 실패도 첫 로드와 동일하게 - 다룸 — 이건 의도한 동작이라 건드리지 않았다). + 다룸 — 이건 의도한 동작이라 건드리지 않았다). 단 `.forbidden`/`.notFound`면 실패 뷰 대신 화면을 닫는다(#311, + 위 "컬렉션 수정" 항목의 차단 복귀). + ⚠️ **실패 뷰의 재시도는 `.load`가 아니라 `.retry`다**(#311) — `.load`는 진입 1회 가드(`hasLoaded`)가 있어, + 한 번이라도 성공한 뒤의 재조회 실패(정렬 변경·복귀)에서 재시도를 눌러도 가드에 막혀 무반응이었다(리뷰에서 발견). + `.retry`는 `.reloadAfterReturn`과 같은 강제 재조회(`reload()`)를 탄다 — 첫 로드 실패의 재시도도 이걸로 충분하다. - **`CollectionListView`의 `isOwnCollections: Bool`(기본 `true`, #201 후속·2026-08-28)은 타유저 프로필(`UserPageFeature`)의 "컬렉션" 헤더 탭이 이 화면을 재사용할 수 있게 연 스위치다** — "좋아요한 컬렉션" 탭이 세션 토큰=로그인 사용자 자신 기준이라, 애초에 이 화면 전체가 "로그인 사용자 자신 diff --git a/Projects/Feature/CollectionFeature/Demo/CollectionFeatureDemoApp.swift b/Projects/Feature/CollectionFeature/Demo/CollectionFeatureDemoApp.swift index fc8c309f9..ca917bbb8 100644 --- a/Projects/Feature/CollectionFeature/Demo/CollectionFeatureDemoApp.swift +++ b/Projects/Feature/CollectionFeature/Demo/CollectionFeatureDemoApp.swift @@ -270,6 +270,8 @@ private struct DemoRootView: View { switch route { case .novelDetail(let novelID): handleNovelTapped(novelID) case .editCollection: path.append(Destination.edit(id)) + // 타유저 프로필은 UserPageFeature 화면이라 이 Demo에선 조립할 수 없다 — 요청만 찍는다. + case .userProfile(let userID): print("유저 프로필 이동 요청: \(userID)") } }, kakaoCollectionShareTemplateID1: NetworkingConfig.kakaoCollectionShareTemplateID1, @@ -656,7 +658,12 @@ private struct DemoLoadCollectionDetailUseCase: LoadCollectionDetailUseCase { id: id, name: "컬렉션 \(id.value)", description: id.value.isMultiple(of: 3) ? nil : "존잼 수준이 정도를 넘음", - owner: Author(nickname: "판소덕", profileImage: nil), + // 작성자 탭(#311) 시연 — 3의 배수 id는 탈퇴 유저(-1, 안내 토스트), 그 외 타인 컬렉션은 프로필 이동 요청. + owner: Author( + userId: UserID(id.value.isMultiple(of: 3) ? -1 : 1000 + id.value), + nickname: "판소덕", + profileImage: nil + ), isMine: isMine, isPrivate: isPrivate, representativeNovelID: novels[0].id, diff --git a/Projects/Feature/CollectionFeature/Sources/CollectionDetail/CollectionDetailView.swift b/Projects/Feature/CollectionFeature/Sources/CollectionDetail/CollectionDetailView.swift index 9ec642a1f..e4c4f4940 100644 --- a/Projects/Feature/CollectionFeature/Sources/CollectionDetail/CollectionDetailView.swift +++ b/Projects/Feature/CollectionFeature/Sources/CollectionDetail/CollectionDetailView.swift @@ -28,8 +28,9 @@ struct CollectionDetailView: View { @State private var navBarBottomY: CGFloat = 0 /// 스티키 정렬 바 — 스크롤 콘텐츠 안 "원본" 정렬 바의 상단 y(화면 좌상단 기준). 측정 전엔 안 뜨도록 무한대. @State private var sortBarMinY: CGFloat = .greatestFiniteMagnitude - /// 이 화면의 유일한 자식은 "컬렉션 수정"(App이 push)뿐이라, 두 번째 이후의 `onAppear`는 항상 - /// "수정 화면에서 복귀"를 뜻한다 — 그때만 무조건 재로드한다(`CollectionListView`의 + /// 두 번째 이후의 `onAppear`는 자식 화면(컬렉션 수정·작품 상세·작성자 프로필, 모두 App이 push)에서의 + /// 복귀다 — 어디서 돌아왔는지 구분하지 않고 무조건 재로드한다(작성자를 차단하고 돌아와 403이면 VM이 + /// 화면을 닫는다 — `closeIfNoLongerViewable`. `CollectionListView`의 /// `hasAppearedOnce` 패턴과 동일 이유, App이 소유한 `NavigationPath`로 옮기며 로컬 /// `isEditPresented`/`onChange` 대신 이 방식으로 바뀌었다). @State private var hasAppearedOnce = false @@ -76,7 +77,7 @@ struct CollectionDetailView: View { Group { if let error = viewModel.state.hasLoadError { NetworkErrorView(error: error) { - viewModel.handle(.load) + viewModel.handle(.retry) } } else { ScrollView { @@ -142,6 +143,7 @@ struct CollectionDetailView: View { ) .showWSSToast(isPresented: actionErrorToastBinding, type: .unknownError) .showWSSToast(isPresented: $isShareErrorToastPresented, type: .unknownError) + .showWSSToast(isPresented: unavailableUserToastBinding, type: .unknownUser) .onChange(of: viewModel.state.shouldDismiss) { _, shouldDismiss in if shouldDismiss { dismiss() } } @@ -151,11 +153,11 @@ struct CollectionDetailView: View { if needsAuth { onAuthenticationRequired() } } .onAppear { - // 이 화면의 유일한 자식(컬렉션 수정)에서 복귀한 뒤의 재진입만 무조건 재로드한다 — - // `CreateCollectionView`가 성공 콜백 없는 자기완결 dismiss 계약이라 복귀했다는 사실만으로 - // 판단한다(`CollectionListView`와 동일 이유). + // 자식 화면(수정·작품 상세·작성자 프로필)에서 복귀한 뒤의 재진입은 무조건 재로드한다 — + // 자식들이 성공 콜백 없는 자기완결 dismiss 계약이라 복귀했다는 사실만으로 판단한다 + // (`CollectionListView`와 동일 이유). 차단 등으로 더는 볼 수 없게 됐으면 VM이 화면을 닫는다. if hasAppearedOnce { - viewModel.handle(.reloadAfterEdit) + viewModel.handle(.reloadAfterReturn) } else { hasAppearedOnce = true viewModel.track(.detailViewed) @@ -178,8 +180,8 @@ private extension CollectionDetailView { HStack(spacing: 0) { Button { - // 이 화면은 "컬렉션 수정"을 같은 스택에 로컬 push하므로 `.onDisappear`로 닫힘을 - // 감지하면 그 push에도 함께 발화해버린다(`CollectionFeature/CLAUDE.md` 참고) — + // App이 같은 스택에 자식 화면(수정·작품 상세·작성자 프로필)을 push하므로 `.onDisappear`로 + // 닫힘을 감지하면 그 push에도 함께 발화해버린다(`CollectionFeature/CLAUDE.md` 참고) — // 그래서 진짜 뒤로가기인 여기서 명시적으로 알린다. viewModel.handle(.backTapped) dismiss() @@ -336,15 +338,7 @@ private extension CollectionDetailView { func heroInfo(_ detail: CollectionDetail) -> some View { VStack(alignment: .leading, spacing: 0) { - HStack(spacing: 10) { - WSSProfileImage(url: detail.owner.profileImage) - .frame(width: 32, height: 32) - .clipShape(RoundedRectangle(cornerRadius: 10)) - - Text(detail.owner.nickname) - .applyWSSFont(.title4) - .foregroundStyle(Color.wssWhite) - } + ownerProfile(detail) Spacer().frame(height: 8) @@ -369,6 +363,42 @@ private extension CollectionDetailView { .padding(.horizontal, 16) } + /// 작성자(프로필 사진·닉네임) — 탭하면 그 유저의 프로필로 간다(#311, 피드 상세 작성자 탭과 동일 계약). + /// 내 컬렉션이면 내 프로필로 "이동"할 곳이 없어 `Button`을 아예 안 그린다(죽은 탭 영역을 만들지 않음 + /// — `WSSFeadHeaderView.isProfileTappable`과 같은 판단). 탈퇴 유저(`accessibleUserId == nil`)면 이동 + /// 대신 안내 토스트만 띄운다. + @ViewBuilder + func ownerProfile(_ detail: CollectionDetail) -> some View { + if detail.isMine { + ownerProfileLabel(detail.owner) + } else { + Button { + guard let userID = detail.owner.accessibleUserId else { + viewModel.handle(.userProfileUnavailableTapped) + return + } + onRoute(.userProfile(userID)) + } label: { + ownerProfileLabel(detail.owner) + .contentShape(Rectangle()) + } + // 라벨의 프로필 이미지·닉네임이 accent 색으로 물들지 않게(`WSSFeadHeaderView`와 동일). + .buttonStyle(.plain) + } + } + + func ownerProfileLabel(_ owner: Author) -> some View { + HStack(spacing: 10) { + WSSProfileImage(url: owner.profileImage) + .frame(width: 32, height: 32) + .clipShape(RoundedRectangle(cornerRadius: 10)) + + Text(owner.nickname) + .applyWSSFont(.title4) + .foregroundStyle(Color.wssWhite) + } + } + func heroButtons(_ detail: CollectionDetail) -> some View { HStack(spacing: 8) { likeButton(detail) @@ -645,6 +675,13 @@ private extension CollectionDetailView { set: { if !$0 { viewModel.handle(.dismissActionErrorToast) } } ) } + + var unavailableUserToastBinding: Binding { + Binding( + get: { viewModel.state.isUnavailableUserToastPresented }, + set: { if !$0 { viewModel.handle(.dismissUnavailableUserToast) } } + ) + } } // MARK: - Preview diff --git a/Projects/Feature/CollectionFeature/Sources/CollectionDetail/CollectionDetailViewModel.swift b/Projects/Feature/CollectionFeature/Sources/CollectionDetail/CollectionDetailViewModel.swift index 0ffdc9817..981cddb3b 100644 --- a/Projects/Feature/CollectionFeature/Sources/CollectionDetail/CollectionDetailViewModel.swift +++ b/Projects/Feature/CollectionFeature/Sources/CollectionDetail/CollectionDetailViewModel.swift @@ -30,12 +30,15 @@ final class CollectionDetailViewModel { var isMenuPresented = false var isDeleteAlertPresented = false var isDeleting = false - /// 삭제 성공 신호. View가 `onChange`로 소비해 dismiss한다(`UserPageFeature`의 차단 성공과 동일 패턴) - /// — 삭제된 컬렉션은 더 볼 수 없어 화면에 남아있을 이유가 없다. + /// 화면 닫기 신호 — 삭제 성공, 또는 보던 컬렉션을 다시 불러왔더니 더는 볼 수 없게 됐을 때(403/404, + /// `closeIfNoLongerViewable`). View가 `onChange`로 소비해 dismiss한다(`UserPageFeature`의 차단 성공과 + /// 동일 패턴) — 볼 수 없는 컬렉션은 화면에 남아있을 이유가 없다. var shouldDismiss = false /// 좋아요·삭제 실패 공통 에러 토스트 — 둘 다 같은 카피(`WSSToastType.unknownError`)라 하나로 묶는다. var hasActionError = false + /// 탈퇴 유저의 작성자 영역을 탭했을 때 "알 수 없는 유저" 안내 토스트(피드 상세와 동일 계약, #311). + var isUnavailableUserToastPresented = false var requiresAuthentication = false } @@ -43,22 +46,29 @@ final class CollectionDetailViewModel { // MARK: - Action enum Action { + /// 진입 시 첫 `onAppear` 1회 전용 — `hasLoaded` 가드가 있어 재시도·복귀 재조회엔 쓰지 않는다(`.retry`/`.reloadAfterReturn`). case load case changeSortType(SortType) case toggleLike case menuTapped case dismissMenu case editTapped - /// 수정 화면(로컬 push, `CollectionDetailView`가 소유)에서 돌아왔을 때 — 성공 콜백 없는 - /// 자기완결 dismiss 계약이라 성공/취소 구분 없이 무조건 다시 로드한다(`CollectionListView`의 - /// `reloadAfterDetail`과 동일 판단). - case reloadAfterEdit + /// 자식 화면(수정·작품 상세·작성자 프로필 — App이 같은 스택에 push)에서 돌아왔을 때 — 어디서 + /// 왔는지·성공/취소 구분 없이 무조건 다시 로드한다(`CollectionListView`의 `reloadAfterReturn`과 + /// 동일 판단). + case reloadAfterReturn + /// 실패 뷰의 "페이지 다시 불러오기" — 진입 1회 가드(`hasLoaded`)를 우회해 항상 다시 부른다. + /// `.load`로 보내면 한 번이라도 성공한 뒤의 재조회 실패(정렬 변경·복귀)에서 가드에 막혀 무반응이 된다. + case retry case deleteTapped case dismissDeleteAlert case confirmDelete case dismissActionErrorToast + /// 작성자가 탈퇴 유저라 프로필로 갈 수 없을 때 — 이동 대신 안내 토스트만 띄운다(#311). + case userProfileUnavailableTapped + case dismissUnavailableUserToast /// 뒤로가기 버튼 탭 — `dismiss()` 직전에 View가 함께 호출한다. `.onDisappear`로는 못 쓴다 - /// — 이 화면은 "컬렉션 수정"을 같은 스택에 로컬 push하는데, push되는 순간 부모도 + /// — App이 같은 `NavigationPath`에 자식 화면(수정·작품 상세·작성자 프로필)을 push하는 순간 부모도 /// `.onDisappear`가 발화해(SwiftUI 표준 동작) `isClosing`이 영구히 굳어버린다(실측 확인, /// 수정 복귀 후 재조회·정렬·좋아요·삭제 전부 무반응이 되는 회귀였다) — 그래서 /// `NovelDetailViewModel.close()`처럼 **명시적 사용자 액션**으로만 세운다. @@ -74,7 +84,7 @@ final class CollectionDetailViewModel { @ObservationIgnored private var hasLoaded = false @ObservationIgnored private var loadTask: Task? @ObservationIgnored private var likeTask: Task? - /// 화면이 닫히는 중 — 뒤로가기(`.backTapped`)나 삭제 성공이 세운다(아래 `close()`). + /// 화면이 닫히는 중 — 뒤로가기(`.backTapped`)·삭제 성공·재조회 403/404가 세운다(아래 `close()`). @ObservationIgnored private var isClosing = false // MARK: - Dependency @@ -127,12 +137,12 @@ final class CollectionDetailViewModel { case .dismissMenu: state.isMenuPresented = false case .editTapped: - // 메뉴만 닫는다(delete와 대칭) — 실제 화면 전환(isEditPresented)은 View가 로컬 상태로 - // 소유한다("작품 추가"/"서재에서 추가"와 같은 위상, `CollectionFeature/CLAUDE.md` 참고). + // 메뉴만 닫는다(delete와 대칭) — 실제 화면 전환은 View가 `onRoute(.editCollection)`으로 + // App에 알리고 App이 push한다(#201부터, `CollectionFeature/CLAUDE.md` 참고). track(.editTapped) state.isMenuPresented = false - case .reloadAfterEdit: - reloadAfterEdit() + case .reloadAfterReturn, .retry: + reload() case .deleteTapped: state.isMenuPresented = false state.isDeleteAlertPresented = true @@ -142,6 +152,10 @@ final class CollectionDetailViewModel { confirmDelete() case .dismissActionErrorToast: state.hasActionError = false + case .userProfileUnavailableTapped: + state.isUnavailableUserToastPresented = true + case .dismissUnavailableUserToast: + state.isUnavailableUserToastPresented = false case .backTapped: close() } @@ -168,10 +182,10 @@ private extension CollectionDetailViewModel { loadTask = Task { await loadDetail() } } - /// 수정 화면 복귀 재조회 — 진입 1회 가드(`hasLoaded`)를 우회해 강제로 다시 불러온다. 이미 - /// `state.detail`이 있는 상태라 View의 `isLoading && detail == nil` 오버레이 조건상 전면 로딩으로 - /// 덮이지 않는다(정렬 변경과 동일 UX, `CollectionDetailView`의 그 조건 그대로 재사용). - func reloadAfterEdit() { + /// 자식 화면 복귀·실패 뷰 재시도 공용 재조회 — 진입 1회 가드(`hasLoaded`)를 우회해 강제로 다시 + /// 불러온다. 이미 `state.detail`이 있으면 View의 `isLoading && detail == nil` 오버레이 조건상 전면 + /// 로딩으로 덮이지 않고(정렬 변경과 동일 UX), 첫 로드 실패 후 재시도(`detail == nil`)면 전면 로딩이 뜬다. + func reload() { guard loadTask == nil, !isClosing else { return } state.isLoading = true state.hasLoadError = nil @@ -227,6 +241,7 @@ private extension CollectionDetailViewModel { guard !isClosing, !Task.isCancelled else { return } if routeToLoginIfAuthenticationRequired(error) { return } logger?.error("컬렉션 상세 로드 실패: \(String(describing: error))") + if closeIfNoLongerViewable(error) { return } state.hasLoadError = (error as? RepositoryError) ?? .unknown } } @@ -277,4 +292,22 @@ private extension CollectionDetailViewModel { state.requiresAuthentication = true return true } + + /// 이미 보고 있던 컬렉션을 다시 불러왔더니 더는 볼 수 없게 됐으면(`.forbidden`/`.notFound`) 실패 뷰 대신 + /// 화면을 닫는다(#311) — 작성자 프로필에서 그 유저를 차단하고 돌아오면 서버가 403 `BLOCK-007`을 준다 + /// (dev 실측 2026-11-27). 실패 뷰로 덮으면 재시도해도 같은 403이라 탈출구가 안 되고, "일시적 오류" + /// 문구도 틀린다. 삭제 성공과 같은 exit(`close()` + `shouldDismiss`)이고, "차단했어요" 토스트는 App의 + /// 컨테이너 오버레이라 이 화면이 닫혀도 직전 화면 위에 남는다. 첫 로드(`detail == nil`)는 대상이 아니다 — + /// 보여준 적 없는 화면을 말없이 닫으면 무슨 일인지 알 수 없어 기존대로 실패 뷰를 띄운다. + func closeIfNoLongerViewable(_ error: Error) -> Bool { + guard state.detail != nil else { return false } + switch error as? RepositoryError { + case .forbidden, .notFound: + close() + state.shouldDismiss = true + return true + default: + return false + } + } } diff --git a/Projects/Feature/CollectionFeature/Sources/Navigation/CollectionRoutes.swift b/Projects/Feature/CollectionFeature/Sources/Navigation/CollectionRoutes.swift index 403be603b..539dcdd9a 100644 --- a/Projects/Feature/CollectionFeature/Sources/Navigation/CollectionRoutes.swift +++ b/Projects/Feature/CollectionFeature/Sources/Navigation/CollectionRoutes.swift @@ -41,6 +41,9 @@ public enum CollectionDetailRoute { case novelDetail(NovelID) /// 더보기 "컬렉션 수정" 탭 — 수정 화면이 `id`로 대상을 스스로 다시 불러오므로 payload가 없다. case editCollection + /// 히어로의 작성자(프로필 사진·닉네임) 탭 → 그 유저의 프로필(#311). 내 컬렉션이면 탭 자체가 없고, + /// 탈퇴 유저면 이 라우트 대신 안내 토스트를 띄운다(피드 상세 작성자 탭과 동일 계약). + case userProfile(UserID) } /// 전체 컬렉션뷰(`PublicCollectionListView`, #283). diff --git a/Projects/Feature/FeedFeature/Sources/SosoFeed/SosoFeedView.swift b/Projects/Feature/FeedFeature/Sources/SosoFeed/SosoFeedView.swift index 61fb4d79f..3468342fb 100644 --- a/Projects/Feature/FeedFeature/Sources/SosoFeed/SosoFeedView.swift +++ b/Projects/Feature/FeedFeature/Sources/SosoFeed/SosoFeedView.swift @@ -497,6 +497,8 @@ struct SosoFeedView: View { viewModel.handle(.toggleLike(feed.feedId)) }, isSpoiler: feed.isSpoiler, + // 내 글이면 스포일러여도 본문을 펼치고 작은 표시만 붙인다. + revealsSpoiler: feed.isMyFeed, isPrivate: !feed.isPublic ) } diff --git a/Projects/Feature/HomeFeature/CLAUDE.md b/Projects/Feature/HomeFeature/CLAUDE.md index d838b2354..50173e64c 100644 --- a/Projects/Feature/HomeFeature/CLAUDE.md +++ b/Projects/Feature/HomeFeature/CLAUDE.md @@ -10,7 +10,7 @@ `DesignSystem`, `WSSComponent`, `Logger`, `PushAuthorization`(#193 — 알림 벨 탭 시 시스템 권한 확인용) - 진입점: `HomeFeatureFactory.makeView(loadHomeDataUseCase:loadUnreadNotificationStatusUseCase: - loadPublicCollectionsUseCase:pushAuthorizationChecker:logger:onRoute:onAuthenticationRequired:)` — + loadRandomPublicCollectionsUseCase:pushAuthorizationChecker:logger:onRoute:onAuthenticationRequired:)` — **탭 콘텐츠만** 반환(탭바·화면 전환은 App 몫). 화면 전환 의도는 `onRoute: (HomeRoute) -> Void` 하나 (#253 — `.novelDetail`/`.feedDetail`/`.search`/`.detailSearch`/`.notification`/`.preferenceGenreSetting`/ `.publicCollectionList`/`.collectionDetail`, @@ -18,8 +18,8 @@ ## 핵심 시나리오 -- **로드**: `onAppear`마다 `.load` → `LoadHomeDataUseCase`(추천 3종)·`LoadUnreadNotificationStatusUseCase` - (알림 배지)·`LoadPublicCollectionsUseCase`(컬렉션 섹션, #283)를 **`async let`으로 동시에** 부른다. +- **로드**: `onAppear`마다 `.load`(push 화면에서 pop 복귀면 컬렉션만 건너뛰는 `.reloadAfterPop` — 아래 컬렉션 섹션) → `LoadHomeDataUseCase`(추천 3종)·`LoadUnreadNotificationStatusUseCase` + (알림 배지)·`LoadRandomPublicCollectionsUseCase`(컬렉션 섹션, #283)를 **`async let`으로 동시에** 부른다. 추천 3종도 UseCase 안에서 동시 호출이라, 홈 진입 시 **총 5건이 한꺼번에 나간다**(순차로 펴지 말 것 → [RecommendationDomain](../../Domain/RecommendationDomain/CLAUDE.md)에 퇴행 이력과 컴파일 함정이 있다). - **수확은 콘텐츠·배지 따로다(2026-08-31)** — 콘텐츠(추천 3종)는 성공 즉시 그리고, 배지는 도착하는 대로 @@ -82,8 +82,17 @@ 한 장은 `hidden="true"`이고, 모양이 아래 그리드 셀(거긴 `/novels/taste`가 실제로 내려줌)과 동일해 **복사 잔재로 확인**했다. **시안에 있다는 이유로 되살리지 말 것.** - **오늘의 발견 카드 탭 → 작품 상세**(유저 한마디 카드도 마찬가지, 유저 프로필로 가지 않는다). -- **"컬렉션 모음.zip" 섹션(#283, 사용자 확정 2026-09-28)** — 모든 사용자의 공개 컬렉션을 최신순(왼쪽이 최신)으로 - 최대 10개(`size=10` 첫 페이지만, 더보기 없음). 제목 줄(`>` 포함) 탭 → 전체 컬렉션뷰(`.publicCollectionList`), +- **"컬렉션 모음.zip" 섹션(#283, 사용자 확정 2026-09-28)** — 모든 사용자의 공개 컬렉션을 **무작위로** + 최대 10개(`sort=random&size=10`, 더보기 없음 — #311에서 최신순 → 랜덤, 서버 명세가 홈은 random으로 부르라고 지정). + 전체 컬렉션뷰는 그대로 최신순이라 둘은 다른 UseCase다(랜덤은 페이지네이션이 없어 cursor를 받지 않는다). + **첫 진입·탭 복귀·재시도에만 새로 섞고, push한 화면(컬렉션 상세 등)에서 pop하면 직전 카드를 유지한다**(사용자 확정 + 2026-11-28, #311 — 처음엔 pop마다 섞였는데 방금 본 카드가 사라져 바꿨다). 둘 다 `onAppear`라 VM은 구분 못 한다 → + View가 `route(_:)`에서 `isReturningFromPush`를 세우고 다음 `onAppear`가 `.reloadAfterPop`을 보낸다(추천 3종·배지는 + 그대로 갱신, 컬렉션만 건너뜀 — 섹션이 비어 있으면 받는다). ⚠️ **화면 전환은 `onRoute`를 직접 부르지 말고 `route(_:)`로** — + 빠뜨리면 그 경로만 pop 복귀에 카드가 다시 섞인다. 홈의 Route는 전부 push라 성립하는 설계다(sheet·무시하는 Route가 생기면 + 표시가 남아 다음 탭 복귀가 안 섞인다 — 그때 다시 볼 것). + 대가: 상세에서 그 컬렉션을 삭제하거나 작성자를 차단하고 돌아와도 **탭 복귀 전까지 카드가 남는다**(누르면 403/404 → + 상세가 스스로 닫힘, `CollectionFeature` 참고). 사용자가 알고 수용했다. 제목 줄(`>` 포함) 탭 → 전체 컬렉션뷰(`.publicCollectionList`), 카드 탭 → 컬렉션 상세(`.collectionDetail`), 작성자 라벨은 탭 없음. 카드는 표지 **4칸 고정**(모자라면 기본 표지). 카드는 공용 `CollectionCard`라 `owner`가 옵셔널이다 — owner가 없으면 작성자 라벨과 그 위 간격을 함께 생략한다(공개 목록은 항상 온다). - **부수 콘텐츠라 실패해도 홈을 실패 뷰로 덮지 않는다** — 배지와 같은 lane: 로그만, 토스트 없음, 직전 카드 유지, diff --git a/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift b/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift index 90107aede..d34741337 100644 --- a/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift +++ b/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift @@ -139,7 +139,7 @@ private struct DemoRootView: View { makeHomeView( loadHomeDataUseCase: DemoLoadHomeDataUseCase(scenario: scenario), loadUnreadNotificationStatusUseCase: DemoLoadUnreadNotificationStatusUseCase(scenario: scenario), - loadPublicCollectionsUseCase: DemoLoadPublicCollectionsUseCase(scenario: scenario) + loadRandomPublicCollectionsUseCase: DemoLoadRandomPublicCollectionsUseCase(scenario: scenario) ) case .live: makeLiveView() @@ -152,12 +152,12 @@ private struct DemoRootView: View { private func makeHomeView( loadHomeDataUseCase: LoadHomeDataUseCase, loadUnreadNotificationStatusUseCase: LoadUnreadNotificationStatusUseCase, - loadPublicCollectionsUseCase: LoadPublicCollectionsUseCase + loadRandomPublicCollectionsUseCase: LoadRandomPublicCollectionsUseCase ) -> some View { HomeFeatureFactory.makeView( loadHomeDataUseCase: loadHomeDataUseCase, loadUnreadNotificationStatusUseCase: loadUnreadNotificationStatusUseCase, - loadPublicCollectionsUseCase: loadPublicCollectionsUseCase, + loadRandomPublicCollectionsUseCase: loadRandomPublicCollectionsUseCase, pushAuthorizationChecker: DemoPushAuthorizationChecker(status: pushAuthorizationScenario.status), logger: consoleLogger, onRoute: { route in @@ -198,7 +198,7 @@ private struct DemoRootView: View { loadUnreadNotificationStatusUseCase: DefaultLoadUnreadNotificationStatusUseCase( repository: notificationRepository ), - loadPublicCollectionsUseCase: DefaultLoadPublicCollectionsUseCase( + loadRandomPublicCollectionsUseCase: DefaultLoadRandomPublicCollectionsUseCase( collectionRepository: CollectionDataFactory.makeRepository( network: client, appStorage: UserDefaultsStorage(), @@ -360,12 +360,12 @@ private enum DemoHomeData { /// "컬렉션 모음.zip" 섹션 — 정상 시나리오는 10개(작품 수 0~7개로 빈 표지 슬롯 확인), 빈 데이터 시나리오는 0개로 /// 섹션이 통째로 숨는 레이아웃을 본다. 나머지 실패 시나리오는 홈 전체가 실패 뷰라 무관하다. -private struct DemoLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { +private struct DemoLoadRandomPublicCollectionsUseCase: LoadRandomPublicCollectionsUseCase { let scenario: DemoHomeScenario - func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { + func execute(size: Int) async throws(RepositoryError) -> [CollectionCard] { guard scenario != .empty else { - return CursorPaginated(items: [], hasNext: false, nextCursor: nil) + return [] } let cards = (0.. Void private let onAuthenticationRequired: () -> Void + /// 홈의 `onRoute`는 전부 push라, 발화했으면 다음 `onAppear`는 pop 복귀다 — 그땐 컬렉션 카드를 다시 섞지 않는다 + /// (방금 본 카드가 돌아왔을 때 그 자리에 있어야 한다, 사용자 확정 2026-11-28). 탭 복귀·첫 진입은 false라 새로 섞인다. + @State private var isReturningFromPush = false private enum Metric { static let searchToCollection: CGFloat = 24 @@ -51,7 +54,8 @@ struct HomeView: View { var body: some View { content .onAppear { - viewModel.handle(.load) + viewModel.handle(isReturningFromPush ? .reloadAfterPop : .load) + isReturningFromPush = false viewModel.handle(.checkPushAuthorizationOnEntry) } .onChange(of: viewModel.state.requiresAuthentication) { _, requiresAuthentication in @@ -63,10 +67,16 @@ struct HomeView: View { .onChange(of: viewModel.state.shouldNavigateToNotifications) { _, shouldNavigate in guard shouldNavigate else { return } viewModel.handle(.consumeNotificationNavigation) - onRoute(.notification) + route(.notification) } } + /// 모든 화면 전환은 여기를 거친다 — `onRoute`를 직접 부르면 pop 복귀 표시가 빠져 카드가 다시 섞인다. + private func route(_ route: HomeRoute) { + isReturningFromPush = true + onRoute(route) + } + /// 헤더만 고정이고 그 아래가 통째로 스크롤/로딩/실패로 갈린다(구 WSSiOS와 같은 경계). private var content: some View { VStack(spacing: 0) { @@ -108,11 +118,11 @@ private extension HomeView { HomeSearchSection( onSearchTapped: { viewModel.track(.searchBarTapped) - onRoute(.search) + route(.search) }, onDetailSearchTapped: { viewModel.track(.detailSearchBannerTapped) - onRoute(.detailSearch) + route(.detailSearch) } ) @@ -124,11 +134,11 @@ private extension HomeView { collections: state.publicCollections, onTitleTapped: { viewModel.track(.publicCollectionTitleTapped) - onRoute(.publicCollectionList) + route(.publicCollectionList) }, onCollectionSelected: { collectionID in viewModel.track(.publicCollectionSelected) - onRoute(.collectionDetail(collectionID)) + route(.collectionDetail(collectionID)) } ) } @@ -149,7 +159,7 @@ private extension HomeView { feeds: state.trendingFeeds, onFeedSelected: { feedID in viewModel.track(.trendingFeedSelected) - onRoute(.feedDetail(feedID)) + route(.feedDetail(feedID)) } ) } @@ -163,11 +173,11 @@ private extension HomeView { state: preferenceGenreNovelState, onNovelSelected: { novelID in viewModel.track(.preferenceGenreNovelSelected) - onRoute(.novelDetail(novelID)) + route(.novelDetail(novelID)) }, onSettingTapped: { viewModel.track(.preferenceGenreSettingTapped) - onRoute(.preferenceGenreSetting) + route(.preferenceGenreSetting) } ) } @@ -193,7 +203,7 @@ private extension HomeView { ForEach(discoveries, id: \.novelID) { discovery in TodayDiscoveryCard(discovery: discovery) { viewModel.track(.todayDiscoverySelected) - onRoute(.novelDetail(discovery.novelID)) + route(.novelDetail(discovery.novelID)) } } } @@ -211,7 +221,7 @@ private extension HomeView { viewModel: HomeViewModel( loadHomeDataUseCase: PreviewLoadHomeDataUseCase(), loadUnreadNotificationStatusUseCase: PreviewLoadUnreadNotificationStatusUseCase(), - loadPublicCollectionsUseCase: PreviewLoadPublicCollectionsUseCase(), + loadRandomPublicCollectionsUseCase: PreviewLoadRandomPublicCollectionsUseCase(), pushAuthorizationChecker: PreviewPushAuthorizationChecker() ), onRoute: { print("화면 전환 요청: \($0)") }, @@ -285,8 +295,8 @@ private struct PreviewLoadUnreadNotificationStatusUseCase: LoadUnreadNotificatio } } -private struct PreviewLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { - func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { +private struct PreviewLoadRandomPublicCollectionsUseCase: LoadRandomPublicCollectionsUseCase { + func execute(size: Int) async throws(RepositoryError) -> [CollectionCard] { let cards = (0..<3).map { index in CollectionCard( id: CollectionID(index), @@ -298,7 +308,7 @@ private struct PreviewLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase owner: Author(userId: UserID(index), nickname: "코띠", profileImage: nil) ) } - return CursorPaginated(items: cards, hasNext: false, nextCursor: nil) + return cards } } diff --git a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift index 57be5d447..b6049a203 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift @@ -60,8 +60,12 @@ final class HomeViewModel { // MARK: - Action enum Action { - /// 진입·탭 복귀마다 발화한다(홈은 밖에서 바뀐 값을 다시 비춰야 해서 1회 가드를 두지 않는다). + /// 진입·탭 복귀·재시도마다 발화한다(홈은 밖에서 바뀐 값을 다시 비춰야 해서 1회 가드를 두지 않는다). + /// 컬렉션 섹션도 새로 섞는다. case load + /// push한 화면에서 pop으로 돌아왔을 때 — `.load`와 같되 **컬렉션 카드는 다시 받지 않는다**(랜덤이라 받으면 + /// 방금 본 카드가 사라진다, 사용자 확정 2026-11-28). 단 섹션이 비어 있으면(첫 로드 실패) 받아서 채운다. + case reloadAfterPop case consumeAuthenticationRequired case notificationBellTapped case consumeNotificationNavigation @@ -100,7 +104,7 @@ final class HomeViewModel { private let loadUnreadNotificationStatusUseCase: LoadUnreadNotificationStatusUseCase // CollectionDomain - private let loadPublicCollectionsUseCase: LoadPublicCollectionsUseCase + private let loadRandomPublicCollectionsUseCase: LoadRandomPublicCollectionsUseCase // PushAuthorization private let pushAuthorizationChecker: PushAuthorizationChecker @@ -110,14 +114,14 @@ final class HomeViewModel { init( loadHomeDataUseCase: LoadHomeDataUseCase, loadUnreadNotificationStatusUseCase: LoadUnreadNotificationStatusUseCase, - loadPublicCollectionsUseCase: LoadPublicCollectionsUseCase, + loadRandomPublicCollectionsUseCase: LoadRandomPublicCollectionsUseCase, pushAuthorizationChecker: PushAuthorizationChecker, logger: Logger? = nil, analyticsTracker: AnalyticsTracker? = nil ) { self.loadHomeDataUseCase = loadHomeDataUseCase self.loadUnreadNotificationStatusUseCase = loadUnreadNotificationStatusUseCase - self.loadPublicCollectionsUseCase = loadPublicCollectionsUseCase + self.loadRandomPublicCollectionsUseCase = loadRandomPublicCollectionsUseCase self.pushAuthorizationChecker = pushAuthorizationChecker self.logger = logger self.analyticsTracker = analyticsTracker @@ -136,7 +140,8 @@ final class HomeViewModel { func handle(_ action: Action) { switch action { - case .load: load() + case .load: load(reshufflesCollections: true) + case .reloadAfterPop: load(reshufflesCollections: false) case .consumeAuthenticationRequired: state.requiresAuthentication = false case .notificationBellTapped: state.shouldNavigateToNotifications = true case .consumeNotificationNavigation: state.shouldNavigateToNotifications = false @@ -149,7 +154,7 @@ final class HomeViewModel { private extension HomeViewModel { - func load() { + func load(reshufflesCollections: Bool) { guard loadTask == nil else { return } // 재조회 자체엔 최초 1회 가드를 두지 않지만(탭 복귀마다 갱신), 화면 진입 트래킹만은 최초 1회로 좁힌다. if !hasLoadedContent { @@ -157,7 +162,7 @@ private extension HomeViewModel { } loadTask = Task { [weak self] in - await self?.loadHome() + await self?.loadHome(reshufflesCollections: reshufflesCollections) self?.loadTask = nil } } @@ -185,7 +190,7 @@ private extension HomeViewModel { /// 끝나는 콘텐츠가 배지 네트워크 왕복까지 기다렸다가 그려진다(첫 런치의 프리페치 이득이 죽는다). /// 실패도 분리다: 콘텐츠 실패만 전면 실패 뷰, 배지·컬렉션 실패는 조용히 무시(로그만 — 이유는 아래 /// `presentBadgeFailure`·`presentPublicCollectionsFailure` 주석). - func loadHome() async { + func loadHome(reshufflesCollections: Bool) async { state.isLoading = true // 재시도·재진입 시작 시점에 함께 내린다 — 성공할 때만 내리면 "페이지 다시 불러오기"를 눌러도 // 로드가 끝날 때까지 실패 뷰가 그대로라 아무 반응이 없어 보인다. @@ -196,17 +201,18 @@ private extension HomeViewModel { // 홈은 탭 복귀마다 갱신하는 화면이라 그 비용을 매번 낸다. async let homeData = loadHomeDataUseCase.execute() async let notificationStatus = loadUnreadNotificationStatusUseCase.execute() - async let publicCollections = loadPublicCollectionsUseCase.execute( - cursor: nil, - size: Self.publicCollectionCount - ) + // 조건은 미리 계산한다 — `async let` 초기식은 MainActor 밖이라 `state`를 직접 못 읽는다. + let shouldLoadCollections = reshufflesCollections || state.publicCollections.isEmpty + async let publicCollections = loadPublicCollections(when: shouldLoadCollections) // 1) 컬렉션 섹션 — 콘텐츠 성패와 무관하게 수확한다. **콘텐츠보다 먼저** 꺼낸다: 홈 최상단(검색 영역 바로 // 아래) 섹션이라 콘텐츠 뒤에 들어오면 그 아래 섹션 전부가 밀리는 점프가 생긴다. 먼저 state에 넣어도 // `hasLoadedContent`가 아직 false라 로딩 뷰가 덮고 있다가 콘텐츠와 같은 프레임에 함께 그려진다. // 둘은 동시에 요청했으니 총 대기시간은 max(콘텐츠, 컬렉션) 그대로다. do { - state.publicCollections = try await publicCollections.items + if let loadedCollections = try await publicCollections { + state.publicCollections = loadedCollections + } } catch let error as RepositoryError { presentPublicCollectionsFailure(error) } catch { @@ -244,6 +250,12 @@ private extension HomeViewModel { presentBadgeFailure(.unknown) } } + + /// nil = 이번엔 받지 않는다(직전 카드 유지). `async let` 초기식엔 조건부 `try await`를 못 써서 함수로 뺐다. + func loadPublicCollections(when shouldLoad: Bool) async throws(RepositoryError) -> [CollectionCard]? { + guard shouldLoad else { return nil } + return try await loadRandomPublicCollectionsUseCase.execute(size: Self.publicCollectionCount) + } } // MARK: - Error Mapping diff --git a/Projects/Feature/NovelDetailFeature/Sources/NovelDetail/NovelDetailFeedTab.swift b/Projects/Feature/NovelDetailFeature/Sources/NovelDetail/NovelDetailFeedTab.swift index 2b5000212..e1c338f2e 100644 --- a/Projects/Feature/NovelDetailFeature/Sources/NovelDetail/NovelDetailFeedTab.swift +++ b/Projects/Feature/NovelDetailFeature/Sources/NovelDetail/NovelDetailFeedTab.swift @@ -155,6 +155,8 @@ struct NovelDetailFeedTab: View { isLiked: feed.isLiked, likeButtonTapped: { onToggleLike(feed.feedId) }, isSpoiler: feed.isSpoiler, + // 내 글이면 스포일러여도 본문을 펼치고 작은 표시만 붙인다. + revealsSpoiler: feed.isMyFeed, isPrivate: !feed.isPublic ) } diff --git a/Projects/Feature/OnboardingFeature/V1_BEHAVIOR_CONTRACT.md b/Projects/Feature/OnboardingFeature/V1_BEHAVIOR_CONTRACT.md index 7131fe6b8..5b8ea4111 100644 --- a/Projects/Feature/OnboardingFeature/V1_BEHAVIOR_CONTRACT.md +++ b/Projects/Feature/OnboardingFeature/V1_BEHAVIOR_CONTRACT.md @@ -46,7 +46,7 @@ 3. **v1.4.0 재로그인 확인 액션시트** — V1 로그인 화면은 `didEnterLoginV140` 플래그가 없고 이미 로그인된 상태면 "로그인 확인이 필요합니다" 액션시트를 띄운다(업데이트 후 1회). V2엔 없다. 위와 같은 마이그레이션 성격. → [1.5](#15-v140-마이그레이션-워크어라운드) - **🗑 확정(2026-08-28): 의도된 제거(마이그레이션 잔재).** #2와 동일 — v1.4.0 업데이트 후 1회 재로그인 유도, V2엔 불필요. 4. **로그인 성공 시 FCM 토큰 발급** — V1 `loginSuccess`는 토큰 저장 직후 `NotificationHelper.fetchFCMToken()`을 부른다. V2 인트로 흐름엔 안 보인다(푸시 권한은 "Home 진입 시점 별도"라고 문서화 — FCM 등록 시점이 어디로 옮겨졌는지 확인). → [1.6](#16-로그인-성공-라우팅) - - **✅ 확정(2026-08-28, 조사): 인프라 존재·App 배선 대기(삭제 아님).** FCM 등록이 V1의 인라인 로그인 부수효과 → V2는 `NotificationDomain.RegisterDeviceTokenUseCase`(+`DefaultPushRepository`·엔드포인트 `/users/fcm-token`)로 분리됨. **호출부는 아직 미배선**(Feature·App grep 0) = App 부트스트랩 몫. + - **✅ 유지 — 배선 완료(#287, 2026-10-08).** FCM 등록이 V1의 인라인 로그인 부수효과 → V2는 `NotificationDomain.RegisterDeviceTokenUseCase`(+`DefaultPushRepository`·엔드포인트 `/users/fcm-token`)로 분리됐고, 호출은 App의 푸시 허브가 맡는다: 로그인·가입 완료 → 메인 탭 진입 → APNs 등록 → `token()` 조회 → 서버 등록(알림 권한과 무관). 온보딩 Feature는 관여하지 않는다. #243의 부트스트랩 경로는 런치 시점에 APNs 토큰이 없어 항상 실패해 #287에서 제거했다. 정본: `App/CLAUDE.md` 푸시 알림(FCM/APNs) 배선 절. 5. **온보딩 진입 분석 이벤트** — V1은 "둘러보기" 탭 시 `AmplitudeManager.track(...nonLogin)`을 남긴다. V2는 Amplitude 의존이 없고(외부 의존성 없음 원칙) 게스트 경로 자체가 없어 이벤트도 사라졌다. 분석 계측을 어디서 이어받는지 별개 확인. → [1.2](#12-둘러보기비로그인) - **➡️ 확정(2026-08-28): Amplitude 횡단 재도입으로 흡수.** 화면별 계약이 아니라 앱 전반 애널리틱스 부재 사안 → `docs/TODO.md` 12절(Amplitude 횡단 재도입, 별도 이슈 승격)로 이관. @@ -120,9 +120,9 @@ V2: `Sources/Intro/OnboardingIntroView.swift`, `.../OnboardingIntroViewModel.swi - ✅ **Keep** — 토큰 영속화(accessToken·refreshToken·isRegister). V1은 VM이 직접 `UserDefaults`에 쓴다. - V2: **저장 책임이 Data/UseCase 레이어로** 내려감(Feature는 `NeedOnboarding`만 받음). 관찰 동작(로그인 후 세션 유지) 동일. - 근거: V1 `LoginViewModel.swift:186-191` · V2 `OnboardingIntroViewModel.swift:102`(UseCase 경유), `AuthDomain` -- ✅ **Keep 확정** (2026-08-28: 인프라 존재·App 배선 대기 — 삭제 아님) — **FCM 토큰 발급**. V1 `loginSuccess`는 토큰 저장 직후 `NotificationHelper.shared.fetchFCMToken()`을 호출한다. V2 인트로 흐름엔 안 보인다. - - V2: 푸시 권한 요청은 "Home 진입 시점 별도"라 문서화(`CLAUDE.md:64`) — FCM **등록** 시점이 어디로 이동했는지 확인 필요. - - 근거: V1 `LoginViewModel.swift:192`(`fetchFCMToken`) · V2 `CLAUDE.md`(푸시 권한은 모듈 범위 밖) +- ✅ **Keep 확정** (2026-10-08: 배선 완료, #287) — **FCM 토큰 발급**. V1 `loginSuccess`는 토큰 저장 직후 `NotificationHelper.shared.fetchFCMToken()`을 호출한다. V2 인트로 흐름엔 없다. + - V2: 등록은 로그인 부수효과가 아니라 **메인 탭 진입**에서 한다 — 로그인·가입 완료 → 메인 탭 → APNs 등록 → `token()` 조회 → 서버 등록(알림 권한과 무관). 로그인 완료 시 등록 기록을 비워 같은 토큰이라도 새 계정으로 다시 보낸다. 관찰 동작(로그인한 기기가 서버에 등록됨) 동일. + - 근거: V1 `LoginViewModel.swift:192`(`fetchFCMToken`) · V2 `App/Sources/Push/PushNotificationCenter.swift`, `App/Sources/Main/MainTabView.swift`, `App/CLAUDE.md`(푸시 알림(FCM/APNs) 배선 절) ### 1.7 로그인 재진입 가드 diff --git a/Projects/Feature/UserPageFeature/CLAUDE.md b/Projects/Feature/UserPageFeature/CLAUDE.md index 3bfdc2533..c34dc3427 100644 --- a/Projects/Feature/UserPageFeature/CLAUDE.md +++ b/Projects/Feature/UserPageFeature/CLAUDE.md @@ -259,6 +259,7 @@ ### 주의사항 (작업 중 발견 시 누적) +- ⚠️ **이 화면의 `feed.isMyFeed`는 항상 `false`다** — `FeedData.fetchUserFeeds`가 "타 유저 전용"을 전제로 `isMyFeed: false`를 하드코딩한다(응답에 그 필드가 없음). 그래서 피드 셀에 넘기는 `revealsSpoiler: feed.isMyFeed`(#311, 내 스포일러 글 펼치기)는 여기선 늘 꺼져 스포일러가 가려진다 — 지금은 의도대로다. **이 화면이 내 프로필도 띄우게 되면** 이 값이 거짓말을 하게 되니, 스포일러 표시·threedots 메뉴(내 글/남의 글) 분기를 함께 다시 볼 것. - **`other_block`("타유저 차단 버튼 클릭") 이벤트는 `.blockUserTapped` 액션(확인 알럿을 띄우는 시점)에서 트래킹한다**(#249) — 실제 차단 API 성공(`confirmBlockUser`)이 아니라 "차단하기" 버튼을 누른 시점 그 자체다. CSV 설명이 "버튼 클릭"이라 확인 알럿의 최종 확정까지는 기다리지 않는다. diff --git a/Projects/Feature/UserPageFeature/Sources/UserPage/UserFeedList/UserFeedListView.swift b/Projects/Feature/UserPageFeature/Sources/UserPage/UserFeedList/UserFeedListView.swift index a7cf1ec69..2277ac5ad 100644 --- a/Projects/Feature/UserPageFeature/Sources/UserPage/UserFeedList/UserFeedListView.swift +++ b/Projects/Feature/UserPageFeature/Sources/UserPage/UserFeedList/UserFeedListView.swift @@ -159,6 +159,8 @@ struct UserFeedListView: View { viewModel.handle(.toggleFeedLike(feed.feedId)) }, isSpoiler: feed.isSpoiler, + // 내 글이면 스포일러여도 본문을 펼치고 작은 표시만 붙인다. + revealsSpoiler: feed.isMyFeed, isPrivate: !feed.isPublic ) } diff --git a/Projects/Feature/UserPageFeature/Sources/UserPage/UserPageView.swift b/Projects/Feature/UserPageFeature/Sources/UserPage/UserPageView.swift index a886d0916..ba81e39c6 100644 --- a/Projects/Feature/UserPageFeature/Sources/UserPage/UserPageView.swift +++ b/Projects/Feature/UserPageFeature/Sources/UserPage/UserPageView.swift @@ -588,6 +588,8 @@ struct UserPageView: View { viewModel.handle(.toggleFeedLike(feed.feedId)) }, isSpoiler: feed.isSpoiler, + // 내 글이면 스포일러여도 본문을 펼치고 작은 표시만 붙인다. + revealsSpoiler: feed.isMyFeed, isPrivate: !feed.isPublic ) } diff --git a/Projects/UI/WSSComponent/CLAUDE.md b/Projects/UI/WSSComponent/CLAUDE.md index cf698940a..a2b09faef 100644 --- a/Projects/UI/WSSComponent/CLAUDE.md +++ b/Projects/UI/WSSComponent/CLAUDE.md @@ -144,7 +144,8 @@ - `WSSFeadView`는 `isLiked`/`likeButtonTapped`를 자체 파라미터로 받아 `WSSFeedReactView`에 그대로 넘긴다(둘 다 기본값 없는 필수 파라미터 — 호출부가 실제 좋아요 상태/토글을 직접 채워야 한다). - raw `AsyncImage`의 여러 `phase`(`.success`/`.failure`)에 이미지를 그릴 땐 **각 phase의 이미지마다 개별적으로 `.resizable()`을 걸어야** 바깥에 얹은 `.scaledToFill()`/`.frame`이 실제로 적용된다 — 하나라도 빠뜨리면 그 phase(예: 로드 실패 placeholder)만 조용히 원본 크기로 나온다(`WSSFeedImageView`가 실제로 이 함정이었다가 #237에서 `WSSAsyncImage`로 옮겨지며 사라짐 — 남은 raw `AsyncImage` 호출부에 새 phase 분기를 추가할 때 여전히 주의). - `WSSSortButton`처럼 `Button` 라벨 안의 값(예: `sortType`에 따른 텍스트/아이콘)이 바뀌는 경우, 호출부에 별도 `.animation`이 없어도 탭 트랜잭션에 얹혀 암시적으로 크로스페이드된다. 즉시 전환을 원하면 그 값에 `.animation(nil, value:)`를 명시해야 한다. -- `WSSFeadView`의 `isSpoiler`/`isPrivate`는 단순 배지가 아니라 **하위 콘텐츠를 통째로 대체**한다: `isSpoiler: true`면 `content` 텍스트가 "스포일러가 포함된 글 보기"로, `feedImage`가 있어도 이미지 자체가 렌더링되지 않는다. `isPrivate: true`면 `react`(좋아요/댓글) 섹션이 아예 안 뜨고 "나만 보는 기록이에요." 행으로 대체된다 — 호출부가 `react`를 넘겨도 private일 땐 좋아요/댓글 버튼에 접근할 수 없다. +- `WSSFeadView`의 `isSpoiler`/`isPrivate`는 단순 배지가 아니라 **하위 콘텐츠를 통째로 대체**한다: `isSpoiler: true`면 `content` 텍스트가 "스포일러가 포함된 글 보기"로, `feedImage`가 있어도 이미지 자체가 렌더링되지 않는다. + **단 `revealsSpoiler: true`(내 글 — `isLiked`처럼 기본값 없는 필수 인자, 기본값을 두면 새 호출부가 빠뜨려도 내 글이 조용히 가려진다)면 가리지 않는다**(#311) — 본문·이미지를 그대로 보여주고 리액션 줄(좋아요/댓글 또는 비공개 행) **오른쪽 끝에 작은 "스포일러가 포함된 글"**(`label1`·`wssSecondary100`)만 붙인다. 내 글인지 판단은 호출부가 `TotalFeed.isMyFeed`로 넘긴다(`isProfileTappable`과 같은 결 — 뜻이 달라 그 값을 재사용하지 않았다). ⚠️ `UserPageFeature`는 `fetchUserFeeds`가 `isMyFeed`를 항상 `false`로 매핑하므로(타 유저 전용 화면) 거기선 늘 가려진다. 비공개+스포일러 조합은 Figma에 없어 비공개 행 오른쪽에 같은 표시를 두기로 정했다. `isPrivate: true`면 `react`(좋아요/댓글) 섹션이 아예 안 뜨고 "나만 보는 기록이에요." 행으로 대체된다 — 호출부가 `react`를 넘겨도 private일 땐 좋아요/댓글 버튼에 접근할 수 없다. - `HapticManager`(`Sources/Haptic/`)는 Core가 아니라 여기 있다 — 도메인 지식이 없는 순수 기술이라 Core 기준(재사용 가능한 기반 기술)에도 맞지만, 등록된 `CoreModule`에 범용 유틸 모듈이 없고(`Keychain`/`Networking`/`Logger`만 존재) 이걸 위해 새 Core 모듈을 만들 정도는 아니라고 판단해 WSSComponent에 뒀다. 호출은 자동 적용되지 않고 **각 콜사이트가 상황에 맞는 스타일을 직접 골라 명시적으로 호출**해야 한다(예: `WSSSortButton` action 클로저 안에서 `HapticManager.selection()`). - Capsule 모양 칩/버튼의 배경·테두리는 `.background(Color).clipShape(Capsule()).overlay(Capsule().stroke(...))` 대신 `.background { Capsule().fill(...) }.overlay { Capsule().strokeBorder(...) }` 패턴을 쓰면 clipShape가 불필요해지고(도형이 이미 캡슐로만 그려짐) `strokeBorder`는 테두리가 프레임 안쪽으로만 그려져 `stroke`처럼 경계 밖으로 살짝 번지지 않는다. `WhiteRemovableKeywordChip`은 이 패턴으로 전환됨, `PrimaryRemovableKeywordChip`/`WSSFilterButton`은 아직 구 패턴 — 새로 만들 때는 신 패턴을 우선한다. - ⚠️ **`CapsuleSelectableKeywordChip`·`RectangleSelectableKeywordChip`(선택형 칩)은 색만 애니메이트하고 위치는 즉시 스냅한다 — 미러(`animatedSelected`) 방식**(#221). 선택 색/배경/테두리를 `isSelected`에 `.animation(.spring, value: isSelected)`로 **직접** 걸면, 이 칩이 상위 레이아웃 변화로 **위치가 밀릴 때**(예: 서재 필터 시트에서 첫 선택으로 위쪽에 선택 칩 행이 생겨 아래로 밀림) 색뿐 아니라 **위치까지 함께 애니메이트돼 방금 누른 칩만 뒤늦게 미끄러지는 잔상**이 생긴다. 그래서 `@State private var animatedSelected`(init에서 `isSelected`로 시딩)를 두고 색·배경·테두리는 전부 이 미러로 그리며, `.animation(value: animatedSelected)` + `.onChange(of: isSelected) { animatedSelected = $0 }`로 **위치가 이미 확정된 다음 프레임에 색만** spring시킨다. **이 칩들에 `.animation(value: isSelected)`를 다시 직접 걸지 말 것**(잔상 재발). 공개 init 시그니처는 그대로라 호출부(온보딩 성별/출생년도·설정 성별나이·상세탐색 필터·서재 필터 등)는 무변경 — 위치가 안 밀리는 화면에선 색만 부드럽게 전환되는 nicety, 밀리는 화면에선 잔상 제거. diff --git a/Projects/UI/WSSComponent/Demo/WSSFeedDemoView.swift b/Projects/UI/WSSComponent/Demo/WSSFeedDemoView.swift index c290c3a73..1f12c443f 100644 --- a/Projects/UI/WSSComponent/Demo/WSSFeedDemoView.swift +++ b/Projects/UI/WSSComponent/Demo/WSSFeedDemoView.swift @@ -13,6 +13,56 @@ struct WSSFeedDemoView: View { var body: some View { ScrollView { VStack(spacing: 0) { + // 내 스포일러 글 — 본문·이미지를 펼치고 리액션 줄 오른쪽에 작은 표시 + SectionHeader("내 스포일러 글 (revealsSpoiler)") + WSSFeadView( + header: FeedHeader( + profileImageURL: nil, + nickname: "판소덕", + createdDate: "3월 21일", + isEdited: true + ), + profileImageTapped: {}, + isProfileTappable: false, + threeDotsButtonTapped: {}, + content: "대학원생이 환생에서 대학원생이 됨. 주인공 완전 갓갓! 일단 작가가 세계관이나 마법에 대해서 진지하게 생각해보고 설정을 짠게 느껴져서 좋아요.", + feedImage: WSSFeedImage( + thumbnailImageURL: URL(string: "https://i.pinimg.com/736x/66/0a/11/660a1122583033a20cf90ce9dccbe2c2.jpg"), + imageCount: 2 + ), + react: WSSFeedReact(likeCount: 23, commentCount: 7), + isLiked: false, + likeButtonTapped: {}, + isSpoiler: true, + revealsSpoiler: true, + isPrivate: false + ) + + Divider() + + // 내 비공개 스포일러 글 — "나만 보는 기록이에요." 줄 오른쪽에 작은 표시 + SectionHeader("내 비공개 스포일러 글") + WSSFeadView( + header: FeedHeader( + profileImageURL: nil, + nickname: "판소덕", + createdDate: "3월 21일", + isEdited: false + ), + profileImageTapped: {}, + isProfileTappable: false, + threeDotsButtonTapped: {}, + content: "나만 보려고 남기는 스포일러 기록.", + react: WSSFeedReact(likeCount: 0, commentCount: 0), + isLiked: false, + likeButtonTapped: {}, + isSpoiler: true, + revealsSpoiler: true, + isPrivate: true + ) + + Divider() + // 이미지 + 연결 작품 모두 있는 경우 SectionHeader("이미지 + 연결 작품") WSSFeadView( @@ -42,6 +92,7 @@ struct WSSFeedDemoView: View { isLiked: true, likeButtonTapped: { print("좋아요 버튼 탭!") }, isSpoiler: false, + revealsSpoiler: false, isPrivate: false ) @@ -70,6 +121,7 @@ struct WSSFeedDemoView: View { isLiked: false, likeButtonTapped: { print("좋아요 버튼 탭!") }, isSpoiler: true, + revealsSpoiler: false, isPrivate: false ) @@ -100,6 +152,7 @@ struct WSSFeedDemoView: View { isLiked: true, likeButtonTapped: { print("좋아요 버튼 탭!") }, isSpoiler: false, + revealsSpoiler: false, isPrivate: true ) @@ -124,6 +177,7 @@ struct WSSFeedDemoView: View { isLiked: false, likeButtonTapped: { print("좋아요 버튼 탭!") }, isSpoiler: true, + revealsSpoiler: false, isPrivate: true ) } diff --git a/Projects/UI/WSSComponent/Sources/FeedCell/WSSFeadView.swift b/Projects/UI/WSSComponent/Sources/FeedCell/WSSFeadView.swift index d158a2a3d..d0004aa77 100644 --- a/Projects/UI/WSSComponent/Sources/FeedCell/WSSFeadView.swift +++ b/Projects/UI/WSSComponent/Sources/FeedCell/WSSFeadView.swift @@ -35,8 +35,17 @@ public struct WSSFeadView: View { let likeButtonTapped: () -> Void let isSpoiler: Bool + /// 내 글이면 `true` — 스포일러 글이어도 본문·이미지를 가리지 않고, 리액션 줄 오른쪽에 작은 + /// "스포일러가 포함된 글" 표시만 붙인다. `false`(남의 글)면 본문 대신 "스포일러가 포함된 글 보기"로 가린다. + /// `isLiked`처럼 기본값 없는 필수 인자다 — 기본값을 두면 새 호출부가 빠뜨려도 내 글이 조용히 가려진다. + let revealsSpoiler: Bool let isPrivate: Bool + /// 스포일러 본문을 가려야 하는가 — 남의 스포일러 글일 때만. + private var hidesSpoilerContent: Bool { isSpoiler && !revealsSpoiler } + /// 리액션 줄 오른쪽 작은 스포일러 표시 — 내 스포일러 글일 때만. + private var showsSpoilerBadge: Bool { isSpoiler && revealsSpoiler } + public init( header: FeedHeader, profileImageTapped: @escaping () -> Void, @@ -49,6 +58,7 @@ public struct WSSFeadView: View { isLiked: Bool, likeButtonTapped: @escaping () -> Void, isSpoiler: Bool, + revealsSpoiler: Bool, isPrivate: Bool ) { self.header = header @@ -62,6 +72,7 @@ public struct WSSFeadView: View { self.isLiked = isLiked self.likeButtonTapped = likeButtonTapped self.isSpoiler = isSpoiler + self.revealsSpoiler = revealsSpoiler self.isPrivate = isPrivate } @@ -81,7 +92,7 @@ public struct WSSFeadView: View { // 피드 글 HStack(spacing: 0) { - if isSpoiler { + if hidesSpoilerContent { Text("스포일러가 포함된 글 보기") .applyWSSFont(.body2) .foregroundStyle(Color.wssSecondary100) @@ -100,7 +111,7 @@ public struct WSSFeadView: View { Spacer().frame(height: 20) // 피드 첨부 이미지 - if let feedImage, !isSpoiler { + if let feedImage, !hidesSpoilerContent { WSSFeedImageView(feedImage: feedImage) .padding(.horizontal, 12.5) @@ -120,18 +131,28 @@ public struct WSSFeadView: View { Spacer().frame(height: 10) } - // 피드 리액션 - if isPrivate { - privateSection - .padding(.horizontal, 20) - } else { - WSSFeedReactView( - react: react, - isLiked: isLiked, - likeButtonTapped: likeButtonTapped - ) - .padding(.horizontal, 20) + // 피드 리액션 (+ 내 스포일러 글이면 오른쪽 끝에 작은 표시) + // 두 리액션 뷰 모두 끝에 Spacer가 있어 표시가 오른쪽 끝으로 밀린다. + HStack(spacing: 0) { + if isPrivate { + privateSection + } else { + WSSFeedReactView( + react: react, + isLiked: isLiked, + likeButtonTapped: likeButtonTapped + ) + } + + if showsSpoilerBadge { + Text("스포일러가 포함된 글") + .applyWSSFont(.label1) + .foregroundStyle(Color.wssSecondary100) + .lineLimit(1) + .fixedSize() + } } + .padding(.horizontal, 20) } .padding(.top, 20) .padding(.bottom, 10) @@ -181,6 +202,7 @@ public struct WSSFeadView: View { isLiked: true, likeButtonTapped: { print("좋아요 클릭!") }, isSpoiler: true, + revealsSpoiler: false, isPrivate: true ) } 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..4f5663ddc --- /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", "SettingDomain", "NotificationDomain", "RecommendationDomain", "NovelDomain", "ProfileDomain"] + + /// 경로에서 `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..0b0802058 --- /dev/null +++ b/Tooling/ArchLint/Tests/ArchLintCoreTests/TestSpecRuleTests.swift @@ -0,0 +1,685 @@ +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" +// 실제 모듈 이름을 쓰면 그 모듈을 적용 범위에 넣는 순간 이 테스트가 깨진다(#308에서 NovelDomain으로 실제 발생) — 없는 모듈로 둔다. +private let outOfScopeTestPath = "/Projects/Domain/OutOfScopeSampleDomain/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 OutOfScopeSampleDomain\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..0f5087b0e 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -1,99 +1,155 @@ # 테스트 가이드 -> **테스트는 필수다.** 새 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?)]`처럼 타입을 붙인다(검사기·목록 파일은 그대로 읽는다). +- 경계값은 "딱 그 값"과 "하나 넘는 값"을 둘 다 둔다. 위 예처럼 넘는 쪽은 어디가 잘렸는지까지 보이게 만든다. +- 켜기/끄기처럼 **양쪽으로 바뀌는 동작은 양쪽 다** 테스트한다(꺼짐→켜짐, 켜짐→꺼짐). 한쪽만 보면 `isPrivate.toggle()`이 + `isPrivate = true`로 바뀌어도 통과한다. 뮤테이션 도구는 동작을 고정값으로 바꾸는 버그를 심지 않아 이 구멍은 + "다 잡힘"이 떠도 남는다 — 목록 단계에서 사람이 본다(#308, `CollectionDraft` 나만 보기에서 실제로 빠졌다). +- 에러는 case를 적어 확인한다: `#expect(throws: CollectionDraft.ValidationError.nameOverLimit(max: 20)) { … }` (타입만 적으면 다른 case도 통과). +- 공개 API로만 테스트한다(`@testable import` ❌) — internal에 기대면 리팩터링마다 깨진다. + +## 가짜 객체: Stub과 Mock + +용어는 둘만 쓴다(클래스 이름은 `Mock…Repository`로 통일). + +- **Stub — 조회(`fetch…`·`load…`·`search…`)**: 정해 둔 값을 돌려줄 뿐 호출을 기록하지 않는다. + 조회 입력이 맞는지는 Stub이 입력마다 다른 값을 돌려주게 해서 **결과로** 확인한다. + "몇 번 불렀나"를 확인하면 캐시를 붙이는 것 같은 정상 리팩터링에도 깨진다. +- **Mock — 명령(저장·삭제·전송)**: 호출 자체가 결과라 보낸 값을 기록하고 확인한다. +- 중복 요청 금지처럼 조회 횟수가 진짜 요구사항이면 allow 주석에 그 이유를 적는다. +- Entity 테스트에는 가짜 객체를 쓰지 않는다 — 값과 규칙뿐이라 결과로 확인한다. +- 가짜 객체는 `Testing/` 타깃(`DomainTesting`)에 둔다. 다른 모듈의 Testing 타깃을 쓰려면 그 모듈 + `Project.swift`에 `testDependencies: [.module(.domain(.base), type: .testing)]`처럼 선언해야 import 된다(없으면 "No such module"). + +## 위치 -- **Swift Testing** (`@Test` / `#expect` / `@Suite`). **XCTest 금지.** ``` Projects/Domain/Domain/ -├── Testing/Mock/Mock[Protocol].swift # Mock — 별도 타깃 DomainTesting +├── TEST_SPEC.md # 자동 생성 테스트 목록(손으로 고치지 않는다) +├── Testing/Mock/Mock[Protocol].swift # 가짜 객체 — 필요한 모듈만 └── 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`를 재사용. -## 작성 규칙 +- **Swift Testing**(`@Test`·`#expect`·`@Suite`). XCTest ❌. -- 함수명: **`@Test("한글 설명") func englishName()`** — 한글은 설명에, 함수명은 영어로. (CI 호환, backtick 한글 함수명 금지) -- helper는 `make~` prefix, 보통 `extension XxxTests`에 `private func`로 분리. 파라미터 기본값으로 변형 케이스를 만든다. -- 에러 검증: `await #expect(throws: RepositoryError.unknown) { try await sut.execute(...) }`. -- **커버리지 4종 필수 고려**: 정상 / 경계값 / 정책 위반 / 상태 변화. +## 적용 범위 (일부 모듈만 — 재작성 진행 중) -### 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) -} -``` - -## Mock 패턴 (tracking array + Result) - -```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`)에 둔다 (테스트와 분리, 다른 모듈도 재사용 가능). +- 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 +157,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 심사 제출)