test(infra): add test-system metrics baseline (TDD 2.0 Phase 0)
docs/tdd-red/07-revamp-plan.md Phase 0 — "측정 없는 개편은 없다"의 첫 단계.
게이트가 아니라 지표다 (05 §9: 커버리지·강도는 지표, 완료 조건 아님).
추가:
- scripts/ci/test-metrics.mjs — 스위트별 파일/케이스/단정/약한 단정/ambient/스킵,
i18n 로케일 수·키 수를 markdown 또는 JSON 으로 산출 (--write 로 날짜 문서 생성)
- scripts/ci/lib/test-files.mjs — 테스트 파일 판정·계수 공용 헬퍼
(test:hygiene 과 같은 패턴을 쓰도록 한 곳에 모음)
- docs/tdd-red/metrics/2026-11-08.md — 오늘 기준선
측정 결과 (기준선):
- 파일 407 · 케이스 3,498 · 단정 8,958
- 약한 단정(toBeDefined/toBeTruthy/toBeFalsy/toBeNull) 128
- ambient 시계/난수(Date.now/Math.random/performance.now) 203
- skip/todo 3 · i18n 2,753키 × 12로케일
문서:
- 07-revamp-plan.md: 상태를 "Phase 0 완료"로 갱신, 측정치를 추정치(3,380/106/169)에서
실측치로 교정
- REFACTOR_WAVE5_AUDIT.md: Wave 5 감사 결과(실행 입력) 편입
검증: node scripts/ci/test-metrics.mjs --write / --json GREEN,
npm run test:metrics GREEN
This commit is contained in:
parent
f95bc9cdeb
commit
42583cc96b
7 changed files with 648 additions and 0 deletions
77
scripts/ci/lib/test-files.mjs
Normal file
77
scripts/ci/lib/test-files.mjs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
// scripts/ci/lib/test-files.mjs
|
||||
// 테스트 파일 판정·계수 공용 헬퍼 — test-metrics / check-test-quality 가 같은 규칙을 공유한다.
|
||||
// 규칙을 늘릴 때는 이 파일 한 곳만 고치고, 두 스크립트의 --self-test 를 함께 확인한다.
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/** test:hygiene 과 동일한 패턴 (의도적 동일 — 게이트 3개가 같은 파일을 보게 한다). */
|
||||
export const TEST_FILE =
|
||||
/(?:^|\/)(?:tests?|__tests__|e2e)\/.*\.(?:test|spec)\.[cm]?[jt]sx?$|\.(?:test|spec)\.[cm]?[jt]sx?$/
|
||||
export const EXCLUDED_PATH =
|
||||
/(?:^|\/)(?:node_modules|dist|build|out|coverage|playwright-report|test-results|scratch)(?:\/|$)/
|
||||
|
||||
/** 약한 단정 — "값이 있다"만 확인하고 결함을 잡지 못하는 형태. */
|
||||
export const WEAK_ASSERTION =
|
||||
/\bexpect\s*\([^)]*\)\s*\.\s*(?:not\s*\.\s*)?(?:toBeDefined|toBeTruthy|toBeFalsy|toBeNull)\s*\(/g
|
||||
|
||||
/** 테스트 안의 직접 시계/난수 호출 (주입·고정 줄은 제외). */
|
||||
export const AMBIENT_TIME = /\b(?:Date\.now|Math\.random|performance\.now)\s*\(\s*\)/g
|
||||
export const AMBIENT_ALLOW =
|
||||
/(?:setSystemTime|useFakeTimers|advanceTimersByTime|advanceTimers|withMockedNow|randomSeed|mkdtemp|vi\.spyOn\()/
|
||||
|
||||
export function gitLsFiles(cwd = process.cwd()) {
|
||||
return execFileSync('git', ['ls-files'], { cwd, maxBuffer: 1 << 28, encoding: 'utf8' })
|
||||
.split('\n')
|
||||
.map((line) => line.trim().replaceAll('\\', '/'))
|
||||
.filter(Boolean)
|
||||
}
|
||||
|
||||
export function isTestFile(path) {
|
||||
if (EXCLUDED_PATH.test(path)) return false
|
||||
if (path.endsWith('.cs')) return path.startsWith('apps/api-server.Tests/') && /Tests?\.cs$/.test(path)
|
||||
if (/\.(?:mjs|js)$/.test(path) && path.includes('__tests__')) return true
|
||||
return TEST_FILE.test(path)
|
||||
}
|
||||
|
||||
export function countMatches(text, re) {
|
||||
re.lastIndex = 0
|
||||
let count = 0
|
||||
while (re.exec(text)) count += 1
|
||||
return count
|
||||
}
|
||||
|
||||
/** 줄 단위로 세어 주입/고정 줄은 제외한다. */
|
||||
export function countAmbient(text) {
|
||||
let count = 0
|
||||
for (const line of text.split('\n')) {
|
||||
if (AMBIENT_ALLOW.test(line)) continue
|
||||
AMBIENT_TIME.lastIndex = 0
|
||||
while (AMBIENT_TIME.exec(line)) count += 1
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
export function readRepoFile(path, cwd = process.cwd()) {
|
||||
return readFileSync(join(cwd, path), 'utf8')
|
||||
}
|
||||
|
||||
/** test 파일 경로 → { path, weak, ambient } */
|
||||
export function scanQuality(cwd = process.cwd()) {
|
||||
const rows = []
|
||||
for (const path of gitLsFiles(cwd).filter(isTestFile)) {
|
||||
let text
|
||||
try {
|
||||
text = readRepoFile(path, cwd)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
rows.push({
|
||||
path,
|
||||
weak: countMatches(text, WEAK_ASSERTION),
|
||||
ambient: countAmbient(text),
|
||||
})
|
||||
}
|
||||
return rows
|
||||
}
|
||||
172
scripts/ci/test-metrics.mjs
Normal file
172
scripts/ci/test-metrics.mjs
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
#!/usr/bin/env node
|
||||
// scripts/ci/test-metrics.mjs
|
||||
// TDD 2.0 Phase 0 — 테스트 체계 지표 산출 (게이트 아님).
|
||||
//
|
||||
// 정책 정본: docs/tdd-red/07-revamp-plan.md §3-2
|
||||
// - 커버리지% 가 아니라 "무엇을 얼마나/얼마나 강하게" 검증하는지의 추세를 본다.
|
||||
// - 이 스크립트는 실패를 만들지 않는다. 회귀 차단은 check-test-quality.mjs 가 한다.
|
||||
//
|
||||
// 사용:
|
||||
// node scripts/ci/test-metrics.mjs # 표준출력으로 markdown
|
||||
// node scripts/ci/test-metrics.mjs --write # docs/tdd-red/metrics/YYYY-MM-DD.md 로 저장
|
||||
// node scripts/ci/test-metrics.mjs --json # 기계 판독용
|
||||
|
||||
import { mkdirSync, writeFileSync } from 'node:fs'
|
||||
import { dirname } from 'node:path'
|
||||
import {
|
||||
countAmbient,
|
||||
countMatches,
|
||||
gitLsFiles,
|
||||
isTestFile,
|
||||
readRepoFile,
|
||||
WEAK_ASSERTION,
|
||||
} from './lib/test-files.mjs'
|
||||
|
||||
const CWD = process.cwd()
|
||||
|
||||
const SUITES = [
|
||||
{ key: 'desktop', label: '데스크톱 (Vitest)', prefix: 'apps/desktop/' },
|
||||
{ key: 'core', label: 'packages/core (Vitest)', prefix: 'packages/core/' },
|
||||
{ key: 'api-client', label: 'packages/api-client (Vitest)', prefix: 'packages/api-client/' },
|
||||
{ key: 'web', label: '웹 (Vitest + Playwright)', prefix: 'apps/web/' },
|
||||
{ key: 'mobile', label: '모바일 (Jest)', prefix: 'apps/mobile-rn/' },
|
||||
{ key: 'edge', label: 'Supabase Edge (Deno)', prefix: 'server/supabase/' },
|
||||
{ key: 'cloudflare', label: 'Cloudflare Worker (Deno)', prefix: 'server/cloudflare-worker/' },
|
||||
{ key: 'dotnet', label: 'API 서버 (xUnit)', prefix: 'apps/api-server.Tests/' },
|
||||
]
|
||||
|
||||
const TEST_CASE = /(?:^|\n)\s*(?:it|test)(?:\.(?:each|skip|only|todo|concurrent)(?:\([^\n]*?\))?)?\s*\(/g
|
||||
// Deno(.test) 와 xUnit([Fact]/[Theory]) 는 vitest/jest 문법이 아니다.
|
||||
const DENO_TEST = /^\s*Deno\s*\.\s*test\s*\(/gm
|
||||
const DOTNET_FACT = /^\s*\[(?:Fact|Theory)[^\]]*\]/gm
|
||||
const ASSERTION = /\bexpect\s*\(|\bassert(?:\.\w+)?\s*\(|\bDeno\s*\.\s*assert\w*\s*\(|\bAssert\.\w+\s*\(/g
|
||||
const SKIP = /\.(?:skip|todo)\s*\(/g
|
||||
|
||||
function read(path) {
|
||||
return readRepoFile(path, CWD)
|
||||
}
|
||||
|
||||
export function collectMetrics() {
|
||||
const files = gitLsFiles(CWD).filter(isTestFile)
|
||||
const suites = new Map(
|
||||
SUITES.map((s) => [s.key, { ...s, files: 0, cases: 0, assertions: 0, weak: 0, ambient: 0, skips: 0 }]),
|
||||
)
|
||||
const offenders = { weak: [], ambient: [] }
|
||||
|
||||
for (const path of files) {
|
||||
const suite = SUITES.find((s) => path.startsWith(s.prefix))
|
||||
if (!suite) continue
|
||||
let text
|
||||
try {
|
||||
text = read(path)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const row = suites.get(suite.key)
|
||||
const cases =
|
||||
countMatches(text, TEST_CASE) + countMatches(text, DENO_TEST) + countMatches(text, DOTNET_FACT)
|
||||
const weak = countMatches(text, WEAK_ASSERTION)
|
||||
const ambient = countAmbient(text)
|
||||
row.files += 1
|
||||
row.cases += cases
|
||||
row.assertions += countMatches(text, ASSERTION)
|
||||
row.weak += weak
|
||||
row.ambient += ambient
|
||||
row.skips += countMatches(text, SKIP)
|
||||
if (weak > 0) offenders.weak.push({ path, weak })
|
||||
if (ambient > 0) offenders.ambient.push({ path, ambient })
|
||||
}
|
||||
|
||||
const localeDir = 'packages/i18n/src/locales'
|
||||
let localeKeys = 0
|
||||
let localeFiles = 0
|
||||
try {
|
||||
localeFiles = gitLsFiles(CWD).filter((f) => f.startsWith(localeDir) && f.endsWith('.json')).length
|
||||
localeKeys = Object.keys(JSON.parse(read(`${localeDir}/ko.json`))).length
|
||||
} catch {
|
||||
// 로케일이 없으면 0 (게이트 아님)
|
||||
}
|
||||
|
||||
offenders.weak.sort((a, b) => b.weak - a.weak)
|
||||
offenders.ambient.sort((a, b) => b.ambient - a.ambient)
|
||||
|
||||
const rows = [...suites.values()].filter((s) => s.files > 0)
|
||||
const total = (key) => rows.reduce((n, s) => n + s[key], 0)
|
||||
|
||||
return {
|
||||
generatedAt: new Date().toISOString().slice(0, 10),
|
||||
totals: {
|
||||
files: total('files'),
|
||||
cases: total('cases'),
|
||||
assertions: total('assertions'),
|
||||
weak: total('weak'),
|
||||
ambient: total('ambient'),
|
||||
skips: total('skips'),
|
||||
localeFiles,
|
||||
localeKeys,
|
||||
},
|
||||
suites: rows,
|
||||
offenders,
|
||||
}
|
||||
}
|
||||
|
||||
export function toMarkdown(metrics) {
|
||||
const t = metrics.totals
|
||||
const lines = []
|
||||
lines.push(`# 테스트 체계 지표 — ${metrics.generatedAt}`)
|
||||
lines.push('')
|
||||
lines.push('> `node scripts/ci/test-metrics.mjs --write` 로 생성된다. 손으로 고치지 않는다.')
|
||||
lines.push('> 정책: `docs/tdd-red/07-revamp-plan.md` §3-2 (지표는 게이트가 아니다)')
|
||||
lines.push('')
|
||||
lines.push('## 합계')
|
||||
lines.push('')
|
||||
lines.push('| 항목 | 값 |')
|
||||
lines.push('|---|---|')
|
||||
lines.push(`| 테스트 파일 | ${t.files} |`)
|
||||
lines.push(`| 테스트 케이스 | ${t.cases} |`)
|
||||
lines.push(`| 단정(expect/assert) | ${t.assertions} |`)
|
||||
lines.push(`| 약한 단정 (toBeDefined/toBeTruthy/toBeFalsy/toBeNull) | ${t.weak} |`)
|
||||
lines.push(`| 시간·난수 직접 호출 (ambient) | ${t.ambient} |`)
|
||||
lines.push(`| skip/todo | ${t.skips} |`)
|
||||
lines.push(`| i18n 로케일 파일 | ${t.localeFiles} |`)
|
||||
lines.push(`| i18n 키 (ko 기준) | ${t.localeKeys} |`)
|
||||
lines.push('')
|
||||
lines.push('## 스위트별')
|
||||
lines.push('')
|
||||
lines.push('| 스위트 | 파일 | 케이스 | 단정 | 약한 단정 | ambient |')
|
||||
lines.push('|---|---:|---:|---:|---:|---:|')
|
||||
for (const s of metrics.suites) {
|
||||
lines.push(`| ${s.label} | ${s.files} | ${s.cases} | ${s.assertions} | ${s.weak} | ${s.ambient} |`)
|
||||
}
|
||||
lines.push('')
|
||||
lines.push('## 약한 단정 상위 파일')
|
||||
lines.push('')
|
||||
lines.push('| 파일 | 개수 |')
|
||||
lines.push('|---|---:|')
|
||||
for (const row of metrics.offenders.weak.slice(0, 15)) lines.push(`| \`${row.path}\` | ${row.weak} |`)
|
||||
lines.push('')
|
||||
lines.push('## ambient 시간·난수 상위 파일')
|
||||
lines.push('')
|
||||
lines.push('| 파일 | 개수 |')
|
||||
lines.push('|---|---:|')
|
||||
for (const row of metrics.offenders.ambient.slice(0, 15)) lines.push(`| \`${row.path}\` | ${row.ambient} |`)
|
||||
lines.push('')
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
const args = new Set(process.argv.slice(2))
|
||||
const metrics = collectMetrics()
|
||||
|
||||
if (args.has('--json')) {
|
||||
process.stdout.write(JSON.stringify(metrics, null, 2) + '\n')
|
||||
} else if (args.has('--write')) {
|
||||
const target = `docs/tdd-red/metrics/${metrics.generatedAt}.md`
|
||||
mkdirSync(dirname(target), { recursive: true })
|
||||
writeFileSync(target, toMarkdown(metrics), 'utf8')
|
||||
process.stdout.write(`[test-metrics] wrote ${target}\n`)
|
||||
process.stdout.write(
|
||||
`[test-metrics] ${metrics.totals.files} files / ${metrics.totals.cases} cases / weak ${metrics.totals.weak} / ambient ${metrics.totals.ambient}\n`,
|
||||
)
|
||||
} else {
|
||||
process.stdout.write(toMarkdown(metrics))
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue