[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
@@ -2,125 +2,223 @@
id: wiki-2026-0508-characterization-tests-특성화-테스트
title: Characterization Tests (특성화 테스트)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [Golden Master Tests, Approval Tests, Pinning Tests, Snapshot Tests]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [uncategorized]
confidence_score: 0.9
verification_status: applied
tags: [testing, legacy-code, feathers, refactoring]
raw_sources: []
last_reinforced: 2026-05-08
last_reinforced: 2026-05-10
github_commit: pending
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
tech_stack:
language: unspecified
framework: unspecified
language: typescript-python
framework: jest-pytest-approvaltests
---
# [[Characterization Tests (특성화 테스트)]]
# Characterization Tests (특성화 테스트)
## 📌 한 줄 통찰 (The Karpathy Summary)
캐릭터리제이션 테스트(특성화 테스트)는 코드가 '무엇을 해야 하는지'가 아니라 '실제로 무엇을 하는지' 현재의 동작을 그대로 캡처하고 기록하는 테스트 기법이다 [1, 2]. 주로 테스트가 없는 난해한 레거시 코드(Legacy Code)에 빠르고 효과적으로 안전망(Safety net)을 구축하여, 코드를 안전하게 리팩토링할 수 있도록 돕는 데 사용된다 [1, 2].
## 한 줄
> **"매 legacy code 의 actual behavior 의 capture — 매 spec 이 X, 매 photo 가 O."**. Michael Feathers 의 *Working Effectively with Legacy Code* (2004) 에서 정립. 매 untested legacy 의 refactoring 시작점. 매 "what should it do" X — 매 "what does it do right now" 의 lock down. 2026년 snapshot tests, ApprovalTests, golden master tests 모두 같은 family.
## 📖 구조화된 지식 (Synthesized Content)
* **현재 동작의 캡처 (Capturing Current Behavior):**
포괄적인 단위 테스트(Comprehensive Unit Tests)를 작성하여 기대하는 결과를 검증하는 대신, 기존 코드의 현재 동작 상태에 대한 스냅샷(Snapshot)을 찍어 특성화한다 [1].
* **실제 동작의 우선성:**
대부분의 레거시 시스템에서는 코드가 '어떻게 동작해야 하는가(what it should do)'보다 '실제로 어떻게 동작하고 있는가(what it actually does)'가 훨씬 더 중요하게 취급된다 [2]. 이 테스트는 이러한 실제 동작이 변경되지 않았음을 강력하게 보장한다 [2].
* **실무적 대체 용어:**
현업 및 개발 생태계에서는 이 기법을 승인 테스트(Approval Testing), 스냅샷 테스트(Snapshot Testing) 또는 골든 마스터(Golden Master)라는 이름으로도 부른다 [2, 3].
* **리팩토링을 위한 빠르고 든든한 안전망:**
테스트가 없고 코드를 이해하기조차 어려운 상황에서, 개발자는 이 테스트를 통해 레거시 코드를 빠르게 커버하고 리팩토링을 시작하기 위한 1차적인 안전망을 확보할 수 있다 [2].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
* **의도된 로직의 올바름을 검증하지 않음:** 캐릭터리제이션 테스트는 코드의 현재 동작을 그대로 기록(Snapshot)하여 그것이 변하지 않았는지를 확인하는 데 목적이 있다 [1, 2]. 즉, 코드가 논리적으로 올바르게 작성되었는지 검증하는 것이 아니며, 기존 코드에 버그가 있다면 그 버그가 포함된 동작 자체를 정상 기준으로 삼아 캡처하게 된다는 제약이 있다 [2].
* **단위 테스트의 완벽한 대체재가 아님:** 이 테스트는 코드를 이해하기 어렵거나 시간이 부족할 때 안전하게 리팩토링을 수행하기 위한 수단(Safety net)으로 사용된다 [1, 2]. 시스템의 개별 컴포넌트를 설계적 관점에서 고립시켜 검증하는 전통적인 포괄적 단위 테스트(Unit Tests)를 완전히 대체하는 것은 아니다 [1].
* 그 외 캐릭터리제이션 테스트의 구체적인 부작용이나 최적화 시 발생할 수 있는 기술적 반대 급부(Trade-off)에 대해서는 **소스에 관련 정보가 부족합니다.** (단지 도입을 위한 휴리스틱 등이 목차 수준에서만 언급됨 [4]).
### 매 정의 (Feathers)
> "A characterization test is a test that characterizes the actual behavior of a piece of code. There's no 'correct'... it just records what the system does."
## 🔗 지식 연결 (Graph)
### Related Concepts
### 매 vs unit/spec test
| 측면 | Spec Test | Characterization Test |
|---|---|---|
| Source of truth | Requirements / spec | Actual current behavior |
| Failing means | Code has bug | Behavior changed (maybe intended) |
| When to write | TDD, before code | Before refactoring legacy code |
| Update on change | Fix code | Review diff, accept if intended |
#### [레거시 코드 제어 (Legacy Code Control)]
- [[Legacy Code (레거시 코드)]]
- 연결 이유: 캐릭터리제이션 테스트는 본질적으로 '테스트가 없는 코드'인 레거시 코드를 안전하게 다루고 리팩토링하기 위해 고안된 기법이다 [2, 5].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 피드백(자동화된 테스트) 없이 코드를 변경하는 것이 왜 위험하며, 리팩토링에 앞서 안전망 구축이 왜 필수적인지 그 당위성을 깊이 이해할 수 있다.
### 매 procedure (Feathers)
1. Pick code 의 region.
2. Write test 가 invokes the code with realistic inputs.
3. Assert with **placeholder** (e.g. `assert result == "FILL_ME"`).
4. Run, capture actual output.
5. Replace placeholder with actual output.
6. Now test pins behavior — refactor with confidence.
- [[Seam (접점)]]
- 연결 이유: 레거시 코드에 캐릭터리제이션 테스트를 적용하려면, 소스 코드를 직접 편집하지 않고도 프로그램의 동작을 변경하거나 의존성을 끊을 수 있는 '접점(Seam)'을 먼저 식별해야 한다 [6, 7].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 테스트 불가능해 보이는 복잡한 의존성을 가진 코드를 어떻게 테스트 가능한 상태로 격리하는지 원리를 파악할 수 있다.
### 매 variants
- **Snapshot test** (Jest, Vitest): serialize output, compare next run.
- **Approval test** (ApprovalTests): write to `.approved.txt`, manual review on diff.
- **Golden master**: large input/output pair, often UI screenshot.
- **Property-based regression**: random inputs, save outputs as golden.
#### [유사 테스트 기법 (Similar Testing Techniques)]
- [[Approval Testing / Snapshot Testing (승인/스냅샷 테스트)]]
- 연결 이유: 캐릭터리제이션 테스트와 동일한 목적(기존 동작의 보존)과 방식(결과값 캡처 및 비교)을 공유하는 실무적 동의어이다 [2, 3].
- 이 개념을 통해 더 깊게 이해할 수 있는 부분: 소프트웨어의 현재 동작을 스냅샷으로 저장하고, 변경 후의 상태와 비교하는 구체적인 구현 패턴 및 생태계의 도구들을 이해할 수 있다.
### 매 응용
1. Refactoring legacy monolith without specs.
2. Migration (framework upgrade, language port).
3. Compiler / parser output stability.
4. Report generation (PDFs, CSVs).
5. UI visual regression (Percy, Chromatic).
### Deeper Research Questions
- 캐릭터리제이션 테스트(Characterization Tests)와 일반적인 단위 테스트(Unit Tests)의 본질적인 목적과 구현 방식의 가장 큰 차이는 무엇인가?
- 레거시 코드 환경에서 캐릭터리제이션 테스트를 적용하기 위해 의존성을 끊고 접점(Seam)을 식별하는 구체적인 과정은 어떻게 진행되는가?
- 시스템의 '실제 동작(what it actually does)'을 캡처할 때, 기존 코드에 내재된 버그나 비효율성은 어떻게 취급하고 이후에 어떻게 수정해야 하는가?
- 승인 테스트(Approval Testing)나 스냅샷 테스트(Snapshot Testing) 도구를 실제 복잡하고 거대한 레거시 시스템에 적용할 때 발생하는 한계점은 무엇인가?
- 마이클 페더스(Michael Feathers)가 제안한 '캐릭터리제이션 테스트 작성을 위한 휴리스틱(Heuristic)'은 구체적으로 어떤 기준과 절차로 구성되어 있는가?
## 💻 패턴
### Practical Application Contexts
- **Implementation:** 복잡하고 이해하기 힘든 레거시 시스템의 함수나 클래스의 현재 반환값(상태)을 스냅샷 파일로 저장하고, 리팩토링을 수행한 뒤 변경 후의 결과가 저장된 스냅샷과 완벽히 일치하는지 비교하는 테스트 코드를 작성한다 [1, 2].
- **System Design:** 강하게 결합되어 테스트가 불가능한 시스템에 대해 1차적인 캐릭터리제이션 안전망을 씌운 뒤, 객체 지향적이고 독립적인 모듈로 점진적인 아키텍처 재설계(Refactoring)를 진행하는 발판으로 사용한다 [2, 6].
- **Operation / Maintenance:** 기존 기능의 변경 없이 버그 수정이나 성능 개선(유지보수)을 수행해야 할 때, 기존 시스템의 '실제 동작'이 훼손되지 않았음(회귀 버그가 발생하지 않았음)을 빠르고 확실하게 보장하는 용도로 활용한다 [2, 8].
- **Learning Path:** 단위 테스트 작성법 학습 -> 레거시 코드의 문제점(의존성) 이해 -> 접점(Seam) 식별을 통한 의존성 분리 -> 캐릭터리제이션 테스트를 통한 안전망 구축 -> 본격적인 구조적 리팩토링 기법 적용의 순서로 학습한다 [1, 8].
- **My Project Relevance:** 마감 기한이 촉박하고 기존 코드가 복잡하여 정규 단위 테스트를 면밀히 작성할 수 없는 프로젝트 모듈에서, 빠르고 신뢰할 수 있는 보호벽을 쳐 놓고 기능 추가나 코드 정리를 수행하고자 할 때 적용할 수 있다 [1, 2].
### Feathers procedure (TypeScript + Jest)
```typescript
import { calculateInvoice } from './legacy';
### Adjacent Topics
- [[Sprout & Wrap Techniques (스프라우트 & 랩 기법)]]
- 확장 방향: 레거시 코드에 캐릭터리제이션 테스트조차 작성할 시간이 부족하거나 클래스가 너무 거대할 때, 기존 코드를 직접 수정하지 않고 완전히 분리된 위치에 새로운 테스트 가능한 코드를 싹 틔우거나(Sprout), 기존 메서드를 감싸서(Wrap) 새 로직을 안전하게 추가하는 우회 기법으로 확장이 가능하다 [9-11].
describe('calculateInvoice — characterization', () => {
it('records current behavior for typical input', () => {
const result = calculateInvoice({
items: [
{ sku: 'A', qty: 2, price: 19.99 },
{ sku: 'B', qty: 1, price: 5.00 },
],
customerType: 'premium',
country: 'KR',
});
---
*Last updated: 2026-05-03*
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (Validation)
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
## 🧬 중복 검사 (Duplicate Check)
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
// Step 1: write `expect(result).toBe('PLACEHOLDER')`
// Step 2: run, observe actual:
// { subtotal: 44.98, discount: 4.50, vat: 4.05, total: 44.53 }
// Step 3: paste it as expected
expect(result).toEqual({
subtotal: 44.98,
discount: 4.50,
vat: 4.05,
total: 44.53,
});
});
});
```
## 🤔 의사결정 기준 (Decision Criteria)
### Jest snapshot
```typescript
import { renderInvoiceHtml } from './render';
**선택 A를 써야 할 때:**
- *(TODO)*
test('invoice html — characterized', () => {
const html = renderInvoiceHtml(SAMPLE_INVOICE);
expect(html).toMatchSnapshot();
});
// First run: writes __snapshots__/invoice.test.ts.snap
// Future runs: diffs. Use `--update-snapshot` after intentional change.
```
**선택 B를 써야 할 때:**
- *(TODO)*
### ApprovalTests (Python)
```python
from approvaltests import verify
**기본값:**
> *(TODO)*
def test_pdf_layout():
pdf_text = render_pdf(sample_data)
verify(pdf_text)
# Writes `test_pdf_layout.received.txt`, compares to `.approved.txt`.
# CI fails on diff; dev reviews then renames received→approved.
```
## ❌ 안티패턴 (Anti-Patterns)
### Golden master with multiple inputs
```python
import json
from pathlib import Path
from legacy_pricing import compute_price
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
def test_pricing_golden_master():
cases = json.loads(Path("fixtures/cases.json").read_text())
actual = [compute_price(c["input"]) for c in cases]
expected = json.loads(Path("fixtures/expected.json").read_text())
assert actual == expected
```
### Generating the golden initially
```python
# tools/regenerate_golden.py — run once, then commit
import json
from pathlib import Path
from legacy_pricing import compute_price
cases = json.loads(Path("fixtures/cases.json").read_text())
out = [compute_price(c["input"]) for c in cases]
Path("fixtures/expected.json").write_text(json.dumps(out, indent=2))
```
### Differential testing (old vs refactored)
```typescript
import { computePriceLegacy } from './pricing-legacy';
import { computePriceNew } from './pricing-new';
import fc from 'fast-check';
test('refactor preserves behavior', () => {
fc.assert(
fc.property(
fc.record({
qty: fc.integer({ min: 1, max: 100 }),
unitPrice: fc.float({ min: 0.01, max: 9999 }),
}),
(input) => {
expect(computePriceNew(input))
.toBeCloseTo(computePriceLegacy(input), 2);
},
),
{ numRuns: 1000 },
);
});
```
### Capture I/O of legacy via instrumentation
```python
# Wrap legacy fn, log all inputs+outputs in production for a week,
# then replay as test fixtures
from functools import wraps
import json, time
def record(path):
def deco(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
with open(path, "a") as f:
f.write(json.dumps({
"ts": time.time(),
"args": args, "kwargs": kwargs,
"result": result,
}, default=str) + "\n")
return result
return wrapper
return deco
@record("fixtures/legacy_calls.jsonl")
def legacy_compute(...): ...
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Pure function legacy | Inline assertion (Feathers procedure) |
| Large structured output | Snapshot or ApprovalTests |
| Visual UI | Storybook + Chromatic / Percy |
| Two impls (refactor) | Differential testing + property-based |
| Production behavior unknown | Record-replay from instrumentation |
**기본값**: Snapshot test for serializable output, ApprovalTests for human-reviewed diffs (PDF, HTML), differential test during refactor.
## 🔗 Graph
- 부모: [[Software Testing]] · [[Legacy Code]]
- 변형: [[Snapshot Testing]] · [[Approval Tests]] · [[Golden Master]]
- 응용: [[Refactoring]] · [[Visual Regression]] · [[Migration Testing]]
- Adjacent: [[Property-Based Testing]] · [[TDD]] · [[Test Doubles]]
## 🤖 LLM 활용
**언제**: legacy code refactor 시작, untested codebase 첫 test net, framework migration, output-shape stability (PDF/CSV/JSON).
**언제 X**: greenfield TDD (use spec tests), rapidly evolving design (snapshots churn), security-critical (need real spec).
## ❌ 안티패턴
- **Treating snapshot as spec**: 매 snapshot fail — auto-update without review. 매 bug 의 silent merge.
- **Huge unreadable snapshot**: 1000-line JSON — split into focused snapshots.
- **No fixture review process**: golden master changes auto-merge — require reviewer.
- **Characterization without refactor goal**: tests forever pin "legacy bug" 의 behavior — note bugs explicitly, fix later.
- **Time/random in capture**: nondeterministic snapshots — freeze clock/seed.
## 🧪 검증 / 중복
- Verified (Feathers "Working Effectively with Legacy Code" 2004 / Jest docs / ApprovalTests / Beck "Test Driven Development").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Feathers procedure + snapshot/approval/differential 패턴 |