217 lines
12 KiB
TypeScript
217 lines
12 KiB
TypeScript
// 终态集合只能有一套。这一份判据从"源码正则"升级成 AST(四面9分口径 §2 用户端「判据尺子失明」)。
|
||
// 跑法:npm test
|
||
import { test } from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
import { fileURLToPath } from 'node:url'
|
||
import { dirname, resolve, relative, sep } from 'node:path'
|
||
|
||
import { TERMINAL_TASK_STATUSES } from '../src/shared/utils/task-terminal.ts'
|
||
import {
|
||
findNarrowTerminalSets,
|
||
findWaitFunctions,
|
||
listSourceFiles,
|
||
readSource,
|
||
} from './helpers/task-terminal-ast-ruler.ts'
|
||
|
||
const here = dirname(fileURLToPath(import.meta.url))
|
||
const root = resolve(here, '..')
|
||
const rel = (p: string) => relative(root, p).split(sep).join('/')
|
||
const SRC_FILES = listSourceFiles(resolve(root, 'src')).map(rel)
|
||
|
||
const TABS = [
|
||
'BrandPatrolDeleteTab.vue',
|
||
'BrandPriceTrackTab.vue',
|
||
'BrandProductRiskTab.vue',
|
||
'BrandQueryAsinTab.vue',
|
||
'BrandShopMatchTab.vue',
|
||
'BrandWithdrawTab.vue',
|
||
].map((f) => `src/pages/brand/components/${f}`)
|
||
|
||
/**
|
||
* 迁移后仍留在库里的窄集合(本轮只消掉任务终态那两处:useTaskProgressLoop 的默认词表、
|
||
* BrandShopMatchTab 的自写阶段等待)。这一份台账是**只许减**的基线,逐文件钉死:
|
||
* 新增一处、或在别处新写一份窄集合,都会红。
|
||
*
|
||
* 口径:单位=处(一条 `||` 链或一个数组词表算一处),分母=src 下全部 .ts/.vue(.d.ts 除外),
|
||
* 命令=`npm test`,尺子=tests/helpers/task-terminal-ast-ruler.ts。
|
||
* STOPPED 那几处是巡店/循环跑自己的运行态词表(文档 10-08 口径里旧判据也放过它),不是任务终态;
|
||
* fileStatus 那几处是结果文件维度——两处都还没跟后端对过账,所以留在台账里而不是当场改宽。
|
||
*/
|
||
const NARROW_LEDGER: Record<string, number> = {
|
||
'src/pages/brand/components/BrandAppearancePatentTab.vue': 3,
|
||
'src/pages/brand/components/BrandCollectDataTab.vue': 2,
|
||
'src/pages/brand/components/BrandDeleteBrandTab.vue': 2,
|
||
'src/pages/brand/components/BrandPatrolDeleteTab.vue': 1,
|
||
'src/pages/brand/components/BrandPriceTrackTab.vue': 6,
|
||
'src/pages/brand/components/BrandProductRiskTab.vue': 2,
|
||
'src/pages/brand/components/BrandSimilarAsinTab.vue': 1,
|
||
'src/pages/jd/JdCollectTab.vue': 1,
|
||
'src/shared/composables/useLiveTaskBoard.ts': 2,
|
||
}
|
||
const NARROW_BASELINE_TOTAL = Object.values(NARROW_LEDGER).reduce((a, b) => a + b, 0)
|
||
|
||
/** 本轮已经迁到共用词表上的文件:这里必须是 0 处,不给"只许减"留讨价还价的余地。 */
|
||
const MIGRATED_ZERO_TOLERANCE = [
|
||
'src/shared/utils/task-terminal.ts',
|
||
'src/shared/composables/useTaskProgressLoop.ts',
|
||
'src/pages/brand/components/BrandShopMatchTab.vue',
|
||
]
|
||
|
||
/** 上一版尺子的原文(留在测试里当反面对照,不是留着用):变量名不叫 status 就整个看不见。 */
|
||
const OLD_NARROW_REGEX = /===\s*'SUCCESS'\s*\|\|\s*status\s*===\s*'FAILED'\s*\)/
|
||
|
||
/** 任务里点名要能抓到的三个形状。全部走内存字符串,主树一个字节都不动。 */
|
||
const COUNTER_EXAMPLES: Array<{ name: string; source: string }> = [
|
||
{ name: '同形异名(箭头函数 + 变量叫 s)', source: "const x = (s: string) => s === 'SUCCESS' || s === 'FAILED'" },
|
||
{ name: '变量叫 st 的 if 判定', source: "if (st === 'SUCCESS' || st === 'FAILED') return true" },
|
||
{ name: '数组 + 枚举 + as any 的 includes', source: '[TaskStatus.SUCCESS, TaskStatus.FAILED].includes(status as any)' },
|
||
]
|
||
|
||
test('尺子先在内存反例上自证:三种同形写法都要变红', () => {
|
||
for (const { name, source } of COUNTER_EXAMPLES) {
|
||
const hits = findNarrowTerminalSets(source, '<内存反例>')
|
||
assert.ok(hits.length > 0, `${name} 没被抓到 ⇒ 尺子对这一形状恒绿:${source}`)
|
||
assert.deepEqual([...hits[0].words].sort(), ['FAILED', 'SUCCESS'])
|
||
}
|
||
})
|
||
|
||
test('反例同时对照旧正则:证明这次升级真的补上了洞', () => {
|
||
for (const { name, source } of COUNTER_EXAMPLES) {
|
||
assert.equal(OLD_NARROW_REGEX.test(source), false, `${name} 若被旧正则抓到,那这条对照就失去意义了`)
|
||
}
|
||
// 非零对照:旧正则能吃的那口(变量名恰好叫 status)新尺子也必须吃得到,不许升级成漏判
|
||
assert.ok(findNarrowTerminalSets("if (status === 'SUCCESS' || status === 'FAILED') { return }", '<内存对照>').length > 0)
|
||
})
|
||
|
||
test('宽集合与非终态写法不得误报(判据误红一次就没人再信它)', () => {
|
||
const wide = [
|
||
"if (status === 'SUCCESS' || status === 'FAILED' || status === 'COMPLETED') return true",
|
||
"return ['SUCCESS', 'FAILED', 'COMPLETED', 'CANCELLED'].includes(normalizeStatus(status))",
|
||
"st === 'SUCCESS' || st === 'FAILED' || st === 'RUNNING' ? '执行中' : '已完成'",
|
||
'isTerminalTaskStatus(status)',
|
||
"TERMINAL_TASK_STATUSES.includes(status.trim().toUpperCase())",
|
||
]
|
||
for (const source of wide) {
|
||
assert.deepEqual(findNarrowTerminalSets(source, '<内存宽集合>'), [], `宽/非终态写法被误报了:${source}`)
|
||
}
|
||
})
|
||
|
||
test('语法坏掉与 .vue 没有 script 段都必须抛,不许静默返回空清单', () => {
|
||
assert.throws(() => findNarrowTerminalSets('const a = (((', '<坏语法>.ts'), /解析失败/)
|
||
// 文件名后缀要如实带上:尺子就是靠它决定"要不要先取 <script> 段"
|
||
assert.throws(() => findNarrowTerminalSets('<template><div/></template>', '<没script的段>.vue'), /<script> 段数/)
|
||
// 两段 script 也要抛:尺子只取一段就是漏判
|
||
assert.throws(() => findNarrowTerminalSets('<script>const a = 1</script><script>const b = 2</script>', '<两段script>.vue'), /<script> 段数/)
|
||
})
|
||
|
||
test('终态面这三个文件必须一条窄集合都没有', () => {
|
||
const offenders: string[] = []
|
||
for (const file of MIGRATED_ZERO_TOLERANCE) {
|
||
const hits = findNarrowTerminalSets(readSource(file, root), file)
|
||
if (hits.length) offenders.push(`${file}\n ${hits.map((h) => `${h.line}: ${h.snippet}`).join('\n ')}`)
|
||
}
|
||
assert.deepEqual(offenders, [], `这些地方又在各写一份 SUCCESS|FAILED —— 收到 COMPLETED 就空转:\n${offenders.join('\n')}`)
|
||
})
|
||
|
||
test('useTaskProgressLoop 的默认终态判定确实指向骨架符号', () => {
|
||
const source = readSource('src/shared/composables/useTaskProgressLoop.ts', root)
|
||
assert.match(source, /import\s*\{\s*isTerminalTaskStatus\s*\}\s*from\s*'\.\.\/utils\/task-terminal\.ts'/,
|
||
'没从骨架引判定,DEFAULT_TERMINAL 就是又起了一套词表')
|
||
assert.match(source.replace(/\r\n/g, '\n'), /const DEFAULT_TERMINAL = isTerminalTaskStatus\n/,
|
||
'DEFAULT_TERMINAL 必须直接指向骨架判定,不许再包一层自写比较')
|
||
})
|
||
|
||
test('把迁移前那两处原样拼回内存里的源码,尺子必须当场变红(不是拼回去改主树)', () => {
|
||
// ① useTaskProgressLoop 的第二套词表本体
|
||
const loopFile = 'src/shared/composables/useTaskProgressLoop.ts'
|
||
const loopSource = readSource(loopFile, root).replace(/\r\n/g, '\n')
|
||
const anchor = 'const DEFAULT_TERMINAL = isTerminalTaskStatus'
|
||
assert.equal(loopSource.split(anchor).length - 1, 1, '锚点不唯一,这条自证不作数')
|
||
const splicedLoop = loopSource.replace(anchor, "const DEFAULT_TERMINAL = (status: string) => status === 'SUCCESS' || status === 'FAILED'")
|
||
assert.notEqual(splicedLoop, loopSource, '注入没生效')
|
||
assert.ok(findNarrowTerminalSets(splicedLoop, loopFile).length > 0,
|
||
'把迁移前那行拼回去,零容忍清单却没变红 ⇒ 这条判据是恒绿的')
|
||
|
||
// ② BrandShopMatchTab 的自写阶段等待循环
|
||
const tabFile = 'src/pages/brand/components/BrandShopMatchTab.vue'
|
||
const tabSource = readSource(tabFile, root).replace(/\r\n/g, '\n')
|
||
const tabAnchor = 'async function waitForScheduledTaskStageExit(taskId: number) {'
|
||
assert.equal(tabSource.split(tabAnchor).length - 1, 1, '锚点不唯一,这条自证不作数')
|
||
const splicedTab = tabSource.replace(tabAnchor, `${tabAnchor}
|
||
let transientErrorCount = 0
|
||
while (true) {
|
||
if (disposed) return 'STOPPED'
|
||
transientErrorCount += 1
|
||
if (transientErrorCount > 30) return 'FAILED'
|
||
await sleep(getPollIntervalMs())
|
||
}`)
|
||
const shapes = findWaitFunctions(splicedTab, tabFile)
|
||
const stage = shapes.find((f) => f.name === 'waitForScheduledTaskStageExit')
|
||
assert.ok(stage, '拼了自写循环却没扫到这个函数')
|
||
assert.ok(stage!.hasWhileTrue || stage!.declaresTransientCounter,
|
||
'自写 while(true) + 瞬断计数没被抓到 ⇒ "都上骨架"那条判据是恒绿的')
|
||
})
|
||
|
||
test('全 src 窄集合只许减:逐文件台账 + 分母自证', () => {
|
||
// 分母自证:文件遍历坏掉会让所有尺子恒绿
|
||
assert.ok(SRC_FILES.length > 100, `src 只扫到 ${SRC_FILES.length} 个文件,分母不对,判据不可信`)
|
||
assert.ok(SRC_FILES.some((f) => f.endsWith('.vue')) && SRC_FILES.some((f) => f.endsWith('.ts')))
|
||
|
||
const perFile: Record<string, number> = {}
|
||
const unexpected: string[] = []
|
||
for (const file of SRC_FILES) {
|
||
const hits = findNarrowTerminalSets(readSource(file, root), file)
|
||
if (!hits.length) continue
|
||
perFile[file] = hits.length
|
||
const allowed = NARROW_LEDGER[file]
|
||
if (allowed === undefined) unexpected.push(`${file} 是新增窄集合的文件:\n ${hits.map((h) => `${h.line}: ${h.snippet}`).join('\n ')}`)
|
||
else if (hits.length > allowed) unexpected.push(`${file} 从 ${allowed} 处涨到 ${hits.length} 处:\n ${hits.map((h) => `${h.line}: ${h.snippet}`).join('\n ')}`)
|
||
}
|
||
assert.deepEqual(unexpected, [], unexpected.join('\n\n'))
|
||
|
||
const total = Object.values(perFile).reduce((a, b) => a + b, 0)
|
||
assert.ok(total <= NARROW_BASELINE_TOTAL, `全 src 窄集合 ${total} 处,超基线 ${NARROW_BASELINE_TOTAL} 处;台账只许减:\n${JSON.stringify(perFile, null, 1)}`)
|
||
|
||
// 台账里的文件必须真的还在命中:悄悄改了别处、把账目改成"0"也是绕过
|
||
for (const [file, count] of Object.entries(NARROW_LEDGER)) {
|
||
assert.equal(perFile[file], count, `${file} 的窄集合处数与台账不符(实测 ${perFile[file]},台账 ${count})——要么改了代码要么改了台账,两者要一起`)
|
||
}
|
||
})
|
||
|
||
test('六个 Tab 的每条等待函数都真的走骨架(按 AST 认函数,不靠签名切字符串)', () => {
|
||
const offenders: string[] = []
|
||
const seen: string[] = []
|
||
for (const tab of TABS) {
|
||
const source = readSource(tab, root)
|
||
const fns = findWaitFunctions(source, tab)
|
||
assert.ok(fns.length >= 1, `${tab} 里一个 waitFor* 函数都没有,判据无从下手`)
|
||
for (const fn of fns) {
|
||
seen.push(`${relative(root, tab) || tab}#${fn.name}`)
|
||
if (!fn.calls.includes('waitForTaskTerminalShared')) offenders.push(`${tab}#${fn.name} 没调共用骨架`)
|
||
if (fn.hasWhileTrue) offenders.push(`${tab}#${fn.name} 仍自己写 while (true)`)
|
||
if (fn.declaresTransientCounter) offenders.push(`${tab}#${fn.name} 仍自己数瞬断`)
|
||
}
|
||
}
|
||
assert.deepEqual(offenders, [], `这些等待循环还在各写一份:${offenders}`)
|
||
// 排期那条链(waitForScheduledTaskStageExit)也必须在名单里——上一期就是漏了它才有第二份循环
|
||
assert.ok(seen.some((s) => s.includes('waitForScheduledTaskStageExit')), `没扫到 waitForScheduledTaskStageExit:${seen.join(', ')}`)
|
||
})
|
||
|
||
test('被改宽的两页确实改用共用判定了', () => {
|
||
for (const tab of ['BrandPriceTrackTab.vue', 'BrandProductRiskTab.vue']) {
|
||
const source = readSource(`src/pages/brand/components/${tab}`, root)
|
||
assert.match(source, /from '@\/shared\/utils\/task-terminal'/, `${tab} 没引共用终态判定`)
|
||
assert.ok(source.includes('isTerminalTaskStatus('), `${tab} 引了但没用`)
|
||
}
|
||
})
|
||
|
||
test('COMPLETED 与 SUCCESS 同类的口径两头都有出处', () => {
|
||
// 前端显示表:两个状态都是「已完成」/success 样式
|
||
const display = readSource('src/shared/utils/task-status-text.ts', root)
|
||
for (const key of TERMINAL_TASK_STATUSES) {
|
||
assert.ok(display.includes(`${key}:`), `显示表里没有 ${key},统一集合就成了无源之水`)
|
||
}
|
||
assert.equal(display.includes("SUCCESS: '已完成'") && display.includes("COMPLETED: '已完成'"), true,
|
||
'COMPLETED≡SUCCESS 的前提是这张表,它变了就得重新对账')
|
||
})
|