docs/tdd-red/07-revamp-plan.md Phase 1 — v1.1이 문서로만 선언한 것을 게이트로 옮긴다. 보호 수용 경로 게이트 (check-protected-tests.mjs): - 06 §5 의 보호 6경로를 base revision 과 비교한다. - 실패 조건: 테스트/스텝 블록 감소, expect 감소, .only 추가, skip/todo 추가, 보호 파일 삭제. - 정당한 스펙 변경은 커밋 본문 `allow-protected-change: <사유>` 또는 --reason 으로만 통과한다(사람 리뷰 대체 아님). CI quality 잡이 --base HEAD^ 로 실행하며 체크아웃이 depth 2 로 바뀐다. 얕은 클론에서는 SKIP 사유를 출력한다. 품질 래칫 (check-test-quality.mjs + test-quality-baseline.json): - 파일별 weak-assertion(toBeDefined/toBeTruthy/toBeFalsy/toBeNull)과 ambient-time(Date.now/Math.random/performance.now) 수치를 동결하고 증가만 막는다. - 128 / 203 건을 한 번에 고치지 않고 회귀만 차단한다. --update 는 리뷰 후 실행. 배선: verify:all 에 두 게이트 편입, CI quality 잡 단계 추가, map/02 §10 · tdd-red/06 §5·§6 · 07 Phase 0-1 상태 갱신. 검증: - self-test: check-protected-tests 6케이스, check-test-quality 6케이스 통과 - 실제 약화 주입 시 두 게이트가 exit 1 (smoke.spec.ts .only, 약한 단정 추가) 후 원복 - npm run test:hygiene / check:design GREEN, npm test GREEN (2800+605+31+24)
181 lines
6.4 KiB
JavaScript
181 lines
6.4 KiB
JavaScript
#!/usr/bin/env node
|
|
// scripts/ci/check-test-quality.mjs
|
|
// TDD 2.0 Phase 1 — 테스트 품질 래칫(ratchet) 게이트.
|
|
//
|
|
// 정책 정본: docs/tdd-red/02-meaningful-vs-meaningless-red.md (의미 없는 RED)
|
|
// docs/tdd-red/07-revamp-plan.md §3-1 (약한 단정 · 결정성)
|
|
//
|
|
// 왜 래칫인가: 오늘 128건의 약한 단정과 203건의 ambient 시계/난수를 한 번에 고치면
|
|
// 회귀 위험이 크다. 그래서 "현재 수치를 동결"하고 **증가만** 막는다.
|
|
// (파일별 기준선 = scripts/ci/test-quality-baseline.json, --update 로만 갱신)
|
|
//
|
|
// 규칙:
|
|
// weak-assertion expect(...).toBeDefined/toBeTruthy/toBeFalsy/toBeNull 만으로 끝나는 단정
|
|
// → 관찰 가능한 값(문자열·개수·상태)을 단정하라
|
|
// ambient-time 테스트 안에서 Date.now()/Math.random()/performance.now() 직접 호출
|
|
// → 주입된 clock/rand 또는 vi.setSystemTime/vi.useFakeTimers 를 쓰라
|
|
//
|
|
// 사용:
|
|
// node scripts/ci/check-test-quality.mjs # 기준선 대비 증가 시 실패
|
|
// node scripts/ci/check-test-quality.mjs --update # 기준선 재생성(리뷰 필수)
|
|
// node scripts/ci/check-test-quality.mjs --self-test
|
|
|
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
import { join } from 'node:path'
|
|
import { scanQuality } from './lib/test-files.mjs'
|
|
|
|
const CWD = process.cwd()
|
|
const BASELINE_PATH = 'scripts/ci/test-quality-baseline.json'
|
|
|
|
const RULES = [
|
|
{
|
|
key: 'weak-assertion',
|
|
field: 'weak',
|
|
hint: 'toBeDefined/toBeTruthy/toBeNull 대신 관찰 결과(값·개수·상태)를 단정하세요.',
|
|
},
|
|
{
|
|
key: 'ambient-time',
|
|
field: 'ambient',
|
|
hint: '시간·난수는 주입하세요 (clock/rand 포트, vi.setSystemTime, vi.useFakeTimers).',
|
|
},
|
|
]
|
|
|
|
export function compareToBaseline(rows, baseline) {
|
|
const violations = []
|
|
for (const rule of RULES) {
|
|
const frozen = baseline.rules?.[rule.key] ?? {}
|
|
for (const row of rows) {
|
|
const current = row[rule.field]
|
|
const allowed = frozen[row.path] ?? 0
|
|
if (current > allowed) {
|
|
violations.push({ rule: rule.key, path: row.path, current, allowed })
|
|
}
|
|
}
|
|
}
|
|
return violations.sort((a, b) => b.current - b.allowed - (a.current - a.allowed))
|
|
}
|
|
|
|
export function buildBaseline(rows, date) {
|
|
const rules = {}
|
|
for (const rule of RULES) {
|
|
const frozen = {}
|
|
for (const row of rows) {
|
|
if (row[rule.field] > 0) frozen[row.path] = row[rule.field]
|
|
}
|
|
rules[rule.key] = frozen
|
|
}
|
|
return { generatedAt: date, note: 'TDD 2.0 래칫 기준선 — 증가만 막는다. --update 로만 갱신.', rules }
|
|
}
|
|
|
|
function loadBaseline() {
|
|
const full = join(CWD, BASELINE_PATH)
|
|
if (!existsSync(full)) return { generatedAt: null, rules: {} }
|
|
return JSON.parse(readFileSync(full, 'utf8'))
|
|
}
|
|
|
|
function runSelfTest() {
|
|
const baseline = {
|
|
generatedAt: 'test',
|
|
rules: { 'weak-assertion': { 'a.test.ts': 2 }, 'ambient-time': { 'b.test.ts': 1 } },
|
|
}
|
|
const fixtures = [
|
|
{
|
|
name: '기준선과 같으면 통과',
|
|
rows: [
|
|
{ path: 'a.test.ts', weak: 2, ambient: 0 },
|
|
{ path: 'b.test.ts', weak: 0, ambient: 1 },
|
|
],
|
|
expected: 0,
|
|
},
|
|
{
|
|
name: '약한 단정 증가 → 위반',
|
|
rows: [{ path: 'a.test.ts', weak: 3, ambient: 0 }],
|
|
expected: 1,
|
|
},
|
|
{
|
|
name: '줄었으면 통과 (래칫은 증가만 막는다)',
|
|
rows: [{ path: 'a.test.ts', weak: 1, ambient: 0 }],
|
|
expected: 0,
|
|
},
|
|
{
|
|
name: '기준선에 없는 파일에서 새 약한 단정 → 위반',
|
|
rows: [{ path: 'c.test.ts', weak: 1, ambient: 0 }],
|
|
expected: 1,
|
|
},
|
|
{
|
|
name: 'ambient 증가 → 위반',
|
|
rows: [{ path: 'b.test.ts', weak: 0, ambient: 2 }],
|
|
expected: 1,
|
|
},
|
|
]
|
|
|
|
let failures = 0
|
|
for (const fixture of fixtures) {
|
|
const got = compareToBaseline(fixture.rows, baseline).length
|
|
if (got !== fixture.expected) {
|
|
failures += 1
|
|
process.stdout.write(`FAIL ${fixture.name} — 기대 ${fixture.expected}, 실제 ${got}\n`)
|
|
} else {
|
|
process.stdout.write(`ok ${fixture.name}\n`)
|
|
}
|
|
}
|
|
|
|
const rebuilt = buildBaseline([{ path: 'a.test.ts', weak: 2, ambient: 0 }], 'test')
|
|
if (rebuilt.rules['weak-assertion']['a.test.ts'] !== 2 || rebuilt.rules['ambient-time']['a.test.ts']) {
|
|
failures += 1
|
|
process.stdout.write('FAIL 기준선 생성 규칙\n')
|
|
} else {
|
|
process.stdout.write('ok 기준선 생성 규칙\n')
|
|
}
|
|
|
|
if (failures > 0) {
|
|
process.stdout.write(`\ncheck-test-quality self-test 실패 ${failures}건\n`)
|
|
process.exit(1)
|
|
}
|
|
process.stdout.write('\ncheck-test-quality self-test 통과\n')
|
|
}
|
|
|
|
function main() {
|
|
const args = new Set(process.argv.slice(2))
|
|
if (args.has('--self-test')) {
|
|
runSelfTest()
|
|
return
|
|
}
|
|
|
|
const rows = scanQuality(CWD)
|
|
const today = new Date().toISOString().slice(0, 10)
|
|
|
|
if (args.has('--update')) {
|
|
const baseline = buildBaseline(rows, today)
|
|
writeFileSync(join(CWD, BASELINE_PATH), JSON.stringify(baseline, null, 2) + '\n', 'utf8')
|
|
const weak = Object.values(baseline.rules['weak-assertion']).reduce((a, b) => a + b, 0)
|
|
const ambient = Object.values(baseline.rules['ambient-time']).reduce((a, b) => a + b, 0)
|
|
process.stdout.write(`[test-quality] 기준선 갱신: ${BASELINE_PATH} (weak ${weak} / ambient ${ambient})\n`)
|
|
return
|
|
}
|
|
|
|
const violations = compareToBaseline(rows, loadBaseline())
|
|
if (violations.length === 0) {
|
|
process.stdout.write(`[test-quality] GREEN (${rows.length} test files, 기준선 대비 증가 없음)\n`)
|
|
return
|
|
}
|
|
|
|
const byRule = new Map()
|
|
for (const v of violations) byRule.set(v.rule, (byRule.get(v.rule) ?? 0) + 1)
|
|
process.stdout.write('[test-quality] 테스트 품질이 기준선보다 나빠졌습니다.\n')
|
|
for (const v of violations.slice(0, 20)) {
|
|
process.stdout.write(` ✗ ${v.path} · ${v.rule} ${v.allowed} → ${v.current}\n`)
|
|
}
|
|
if (violations.length > 20) process.stdout.write(` … 외 ${violations.length - 20}건\n`)
|
|
for (const rule of RULES) {
|
|
if (byRule.has(rule.key)) process.stdout.write(`\n${rule.key}: ${rule.hint}\n`)
|
|
}
|
|
process.stdout.write(
|
|
'\n정당한 사유(예: 기존 테스트를 캐릭터라이제이션으로 교체)가 있으면 사람 리뷰 후\n' +
|
|
' npm run test:quality:update\n' +
|
|
'로 기준선을 갱신하고 커밋 본문에 이유를 적으세요.\n',
|
|
)
|
|
process.exit(1)
|
|
}
|
|
|
|
main()
|