Files
2nd/10_Wiki/Topic_Programming/Architecture/Testability_Architecture.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

6.2 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-testability-architecture Testability Architecture 10_Wiki/Topics verified self
Test-Friendly Architecture
Design for Testability
none A 0.9 applied
testing
architecture
dependency-injection
seams
2026-05-10 pending
language framework
TypeScript Vitest

Testability Architecture

매 한 줄

"매 testable design 은 testing 의 byproduct 가 아니라 cause". Michael Feathers 의 Working Effectively with Legacy Code 의 seam 개념 + Dependency Inversion 의 결합. 매 unit test 의 어려움 = 매 design problem 의 signal.

매 핵심

매 testability dimensions (Robert Binder 1994)

  • Observability: 매 internal state 의 inspection.
  • Controllability: 매 input 의 injection.
  • Isolability: 매 unit 의 independent execution.
  • Predictability: 매 deterministic output.

매 seam types (Feathers)

  • Object seam: 매 polymorphism (interface + implementation swap).
  • Preprocessor seam: 매 macro / build flag.
  • Link seam: 매 link-time symbol 의 replacement.

매 응용

  1. 매 hard-to-test code = refactor signal — 매 hidden coupling.
  2. Dependency injection 의 systematic 적용.
  3. Pure function core + I/O shell (functional core, imperative shell).

💻 패턴

Dependency injection

// 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 ...');
  }
}

// Good: injected, testable
interface PaymentGateway { charge(amount: number): Promise<ChargeResult>; }
interface OrderRepo { save(order: Order): Promise<void>; }

class OrderService {
  constructor(private payments: PaymentGateway, private repo: OrderRepo) {}
  async placeOrder(order: Order) {
    await this.payments.charge(order.total);
    await this.repo.save(order);
  }
}

// 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();
});

Functional core, imperative shell

// 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 };
}

// 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);
}

Hexagonal port for time

interface Clock { now(): Date; }

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); }
}

class TokenService {
  constructor(private clock: Clock) {}
  isExpired(token: { expiresAt: Date }) {
    return this.clock.now() > token.expiresAt;
  }
}

Test data builder

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)

// 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

// 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

🤖 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