d3ro-voice/scripts/ci/lib/test-files.mjs
Yun Chan 42583cc96b 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
2026-11-08 21:08:35 +09:00

77 lines
2.7 KiB
JavaScript

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