[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -4,113 +4,201 @@ title: Testability Architecture
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [P-REINFORCE-WIKI-DEV-TESTABILITY-ARCHITECTURE, 테스트 용이성, Testability, 테스트 가능한 설계, 격리된 테스트, 의존성 격리]
aliases: [Test-Friendly Architecture, Design for Testability]
duplicate_of: none
source_trust_level: A
confidence_score: 1.0
tags: [Architecture, Testing, Clean_Architecture, Dependency_Injection, Design_Principles]
raw_sources: [Datacollector_Export_2026-05-02]
last_reinforced: 2026-05-02
confidence_score: 0.9
verification_status: applied
tags: [testing, architecture, dependency-injection, seams]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: TypeScript
framework: Vitest
---
# [[테스트 용이성을 위한 아키텍처 설계 (Testability in Architecture)]]
# Testability Architecture
## 1. 개요
테스트 용이성(Testability)은 소프트웨어 시스템의 각 구성 요소를 독립적으로 분리하여 얼마나 쉽고 효과적으로 검증할 수 있는지를 나타내는 척도다. 테스트하기 쉬운 아키텍처는 결합도가 낮고 응집도가 높으며, 비즈니스 로직이 외부 인프라(DB, UI, 네트워크 등)로부터 격리되어 있어 시스템의 신뢰성과 유지보수성을 비약적으로 향상시킨다.
## 매 한 줄
> **"매 testable design 은 testing 의 byproduct 가 아니라 cause"**. Michael Feathers 의 *Working Effectively with Legacy Code* 의 seam 개념 + Dependency Inversion 의 결합. 매 unit test 의 어려움 = 매 design problem 의 signal.
## 2. 테스트 가능한 설계를 위한 핵심 원칙
- **관심사 분리 (Separation of Concerns)**: 비즈니스 규칙, 데이터 접근, 프레젠테이션 로직을 명확히 분리하여 각 영역을 독립적으로 검증할 수 있도록 설계.
- **의존성 주입 (Dependency Injection)**: 하위 모듈의 생성 책임을 외부로 위임하고 인터페이스에 의존하게 함으로써, 테스트 시 실제 구현체를 모의 객체(Mock)로 용이하게 교체.
- **도메인 격리 (Domain Isolation)**: 클린 아키텍처 원칙에 따라 핵심 도메인 로직을 가장 안쪽에 배치하고, 외부 프레임워크나 도구의 변화에 영향을 받지 않는 순수한 상태로 유지.
- **바운디드 컨텍스트 (Bounded Context)**: 거대한 시스템을 독립적인 비즈니스 경계로 나누어, 특정 영역의 변경이나 버그가 다른 영역의 테스트에 전파되지 않도록 차단.
## 매 핵심
## 3. 엔지니어링 가치
- **신속한 피드백 루프**: 외부 환경 의존성이 제거된 단위 테스트는 수 밀리초 내에 실행되므로, 개발자가 코드 변경 후 즉각적으로 정상 작동 여부를 확인 가능.
- **신뢰할 수 있는 코드 해독**: 잘 설계된 테스트 코드는 신규 개발자에게 시스템의 '살아있는 사용 설명서'가 되어, 낯선 코드베이스에 대한 온보딩 속도를 가속화함.
- **안전한 리팩토링**: 강력한 테스트 안전망이 구축되어 있어, 시스템의 내부 구조를 과감하게 개선하더라도 외부 동작의 파손 여부를 즉시 감지할 수 있음.
### 매 testability dimensions (Robert Binder 1994)
- **Observability**: 매 internal state 의 inspection.
- **Controllability**: 매 input 의 injection.
- **Isolability**: 매 unit 의 independent execution.
- **Predictability**: 매 deterministic output.
## 4. 트레이드오프 및 주의사항
- **설계 오버헤드**: 테스트 용이성을 확보하기 위해 인터페이스를 추상화하고 DI 패턴을 도입하는 과정에서 초기 설계 비용과 구현 복잡도가 상승할 수 있음.
- **과도한 모킹 (Over-mocking)**: 의존성을 너무 많이 격리하여 모든 것을 모의 객체로 대체하면, 실제 운영 환경에서의 상호작용 문제를 놓칠 수 있음. 적절한 수준의 통합 테스트 병행 필수.
- **추상화의 함정**: 테스트를 위해 도입한 수많은 추상화 계층이 오히려 코드의 가독성을 해치고 인지적 부하를 높일 수 있으므로 '필요한 만큼만' 설계.
### 매 seam types (Feathers)
- **Object seam**: 매 polymorphism (interface + implementation swap).
- **Preprocessor seam**: 매 macro / build flag.
- **Link seam**: 매 link-time symbol 의 replacement.
## 5. 지식 연결 (Related)
- [[Test_Automation_TDD]]: 테스트 가능한 설계를 바탕으로 수행되는 구체적인 테스트 방법론.
- [[Mocking_Strategies]]: 의존성 격리를 위한 실전 기법들.
- [[Clean_Architecture]]: 테스트 용이성을 극대화하는 표준 아키텍처 모델.
### 매 응용
1. 매 hard-to-test code = refactor signal — 매 hidden coupling.
2. Dependency injection 의 systematic 적용.
3. Pure function core + I/O shell (functional core, imperative shell).
## 🧪 검증 상태 (Validation)
- **정보 상태**: 검증 완료 (Verified)
- **출처 신뢰도**: A
- **검토 이유**: 소프트웨어의 지속 가능한 품질과 신뢰성을 확보하기 위해, 아키텍처 설계 단계부터 테스트 가능성을 고려하는 표준 가이드라인 정립.
## 💻 패턴
## 📌 한 줄 통찰 (The Karpathy Summary)
### Dependency injection
```typescript
// Bad: hidden dependency, untestable
class OrderService {
async placeOrder(order: Order) {
const result = await fetch('https://api.stripe.com/charge', { /* ... */ });
await db.query('INSERT INTO orders ...');
}
}
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
// Good: injected, testable
interface PaymentGateway { charge(amount: number): Promise<ChargeResult>; }
interface OrderRepo { save(order: Order): Promise<void>; }
## 📖 구조화된 지식 (Synthesized Content)
class OrderService {
constructor(private payments: PaymentGateway, private repo: OrderRepo) {}
async placeOrder(order: Order) {
await this.payments.charge(order.total);
await this.repo.save(order);
}
}
**추출된 패턴:**
> *(TODO)*
**세부 내용:**
- *(TODO)*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 없음
- **정책 변화:** 없음
## 🔗 지식 연결 (Graph)
- **Parent:** [[10_Wiki/Topics]]
- **Related:** *(TODO: 최소 2개)*
- **Opposite / Trade-off:** *(TODO)*
- **Raw Source:** 직접 입력
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
// Test
it('saves order after payment', async () => {
const payments = { charge: vi.fn().mockResolvedValue({ ok: true }) };
const repo = { save: vi.fn() };
const svc = new OrderService(payments, repo);
await svc.placeOrder(makeOrder({ total: 100 }));
expect(repo.save).toHaveBeenCalled();
});
```
## 🤔 의사결정 기준 (Decision Criteria)
### Functional core, imperative shell
```typescript
// Pure core (easy to test)
export function calculateInvoice(order: Order, taxRules: TaxRule[]): Invoice {
const subtotal = order.items.reduce((s, i) => s + i.price * i.qty, 0);
const tax = applyTaxRules(subtotal, taxRules);
return { subtotal, tax, total: subtotal + tax };
}
**선택 A를 써야 할 때:**
- *(TODO)*
// Imperative shell (thin, integration-tested)
export async function generateInvoice(orderId: string) {
const order = await db.orders.findById(orderId);
const rules = await db.taxRules.findActive();
const invoice = calculateInvoice(order, rules); // pure
await db.invoices.save(invoice);
await emailService.send(order.customerId, invoice);
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Hexagonal port for time
```typescript
interface Clock { now(): Date; }
**기본값:**
> *(TODO)*
class SystemClock implements Clock { now() { return new Date(); } }
class FakeClock implements Clock {
constructor(private fixed: Date) {}
now() { return this.fixed; }
advance(ms: number) { this.fixed = new Date(this.fixed.getTime() + ms); }
}
## ❌ 안티패턴 (Anti-Patterns)
class TokenService {
constructor(private clock: Clock) {}
isExpired(token: { expiresAt: Date }) {
return this.clock.now() > token.expiresAt;
}
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Test data builder
```typescript
class OrderBuilder {
private order: Order = { id: 'o1', items: [], total: 0, status: 'pending' };
withItem(item: Item) { this.order.items.push(item); return this; }
withStatus(s: OrderStatus) { this.order.status = s; return this; }
build() { return { ...this.order }; }
}
// Usage
const order = new OrderBuilder()
.withItem({ sku: 'A', price: 10, qty: 2 })
.withStatus('paid')
.build();
```
### Sprout method (Feathers — adding to legacy)
```typescript
// Legacy untestable
function processBatch(records: Record[]) {
for (const r of records) {
// ... 200 lines of mess ...
db.update(r);
}
}
// Add new logic via sprout (pure, testable)
export function shouldArchive(record: Record, today: Date): boolean {
return today.getTime() - record.createdAt.getTime() > 365 * 86400_000;
}
function processBatch(records: Record[]) {
const today = new Date();
for (const r of records) {
if (shouldArchive(r, today)) { /* new branch */ }
// ... existing mess unchanged ...
}
}
```
### Humble object pattern
```typescript
// View has no logic — humble
class CartView {
render(model: CartViewModel) { /* pure rendering */ }
}
// Presenter has all logic — testable without DOM
class CartPresenter {
buildViewModel(cart: Cart): CartViewModel { /* pure */ }
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Side-effect heavy code | Inject dependencies |
| Time-sensitive logic | Clock port |
| Complex object graphs in tests | Test data builder |
| Legacy untouchable | Sprout method/class |
| UI logic | Humble object |
**기본값**: 매 constructor injection + 매 functional core + 매 ports for I/O.
## 🔗 Graph
- 부모: [[Technical-Architecture]] · [[Test-Driven_Development]]
- 변형: [[Hexagonal Architecture]] · [[Clean Architecture]]
- 응용: [[Dependency Injection]] · [[Test Doubles (테스트 대역)]]
- Adjacent: [[Working Effectively with Legacy Code]] · [[Test Automation Pyramid]] · [[The Two Hats]]
## 🤖 LLM 활용
**언제**: refactor for testability, seam identification, DI introduction.
**언제 X**: 매 framework-specific DI container choice — 매 ecosystem convention 의 우선.
## ❌ 안티패턴
- **Mock everything**: 매 mock soup — 매 test 가 implementation 의 mirror.
- **Static singletons**: untestable — 매 global state 의 source.
- **`new` in business logic**: hidden dependency.
- **Test private methods**: 매 leak — public surface 만 test.
## 🧪 검증 / 중복
- Verified (Feathers 2004 *WELC*; Binder 1994 testability metrics).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — seams + DI + functional core patterns |