test(前端): 清理 4b29a150 死代码删除后的孤儿用例,补 4.0.42 更新日志

- 删除 17 个被测模块已不存在的测试(api-field-schemas / build-chunk-planner /
  polling-state-machine 等),套件 94 -> 77 文件
- polling-unknown-status 只保留仍接线的 useTaskProgressLoop 两条,去掉状态机用例
- endpoints 快照重钉 218 -> 215(漂移恰好等于外观专利 parsed-payload/queue-payload/
  activate 三个下线端点,无新增、无取值变化)
- brand-rows-version-wiring 的轻量失败回退断言改用 [^}] 锁进 catch 体内:
  原窗口会跨过 catch 右花括号读到后面正常分支的 return { taskIds, force: true },
  删掉回退也照样绿;五处变异(三页 heavyIds = ids + 外观页两种写法)现全部转红
- appearance-patent-failed-status 改为断言公共映射 taskStatusClass('FAILED')
This commit is contained in:
2026-10-02 15:09:08 +08:00
parent 9378567641
commit 486c5c1d38
23 changed files with 25 additions and 2741 deletions
@@ -24,6 +24,14 @@ export interface ClientChangelogEntry {
/** 更新日志数据(新版本在前;发版时在数组最前追加一条) */
export const CLIENT_CHANGELOG: ClientChangelogEntry[] = [
{
version: '4.0.42',
date: '2026-10-02',
items: [
'跟价、店铺采集:提交任务时带上当前登录账号,代理用量不再记错人',
'代理密钥等登录信息不再写入日志与上报,保护账号安全',
],
},
{
version: '4.0.41',
date: '2026-09-30',
@@ -1,104 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
taskCoreSchema,
resultFileSchema,
taskWithResultSchema,
apiFieldSchemas,
getApiFieldSchema,
createModuleFieldChecker,
} from '../src/shared/api-field-schemas.ts'
test('test_schema_task_required_fields', () => {
assert.equal(taskCoreSchema.taskId.type, 'number')
assert.equal(taskCoreSchema.taskId.required, true)
assert.equal(taskCoreSchema.status.type, 'string')
assert.equal(taskCoreSchema.status.required, true)
assert.equal(taskCoreSchema.progress.type, 'number')
assert.equal(taskCoreSchema.progress.required, undefined)
})
test('test_schema_result_required_fields', () => {
assert.equal(resultFileSchema.fileStatus.type, 'string')
assert.equal(resultFileSchema.fileReady.type, 'boolean')
assert.equal(resultFileSchema.fileProgress.type, 'number')
assert.equal(resultFileSchema.downloadUrl.type, 'string')
assert.equal(resultFileSchema.freshDownloadUrl.type, 'string')
assert.ok('fileProgressLabel' in resultFileSchema)
assert.ok('fileProgressStage' in resultFileSchema)
})
test('test_checker_passes_valid', () => {
const checker = createModuleFieldChecker('task')
const violations = checker.check({ taskId: 1, status: 'SUCCESS', progress: 100 })
assert.deepEqual(violations, [])
assert.equal(checker.lastResult().passed, true)
})
test('test_checker_missing_required', () => {
const checker = createModuleFieldChecker('task')
const violations = checker.check({ taskId: 1 })
assert.equal(violations.length, 1)
assert.equal(violations[0].field, 'status')
assert.equal(violations[0].kind, 'missing')
})
test('test_checker_wrong_type', () => {
const checker = createModuleFieldChecker('task')
const violations = checker.check({ taskId: 'x', status: 'SUCCESS' })
assert.equal(violations.length, 1)
assert.equal(violations[0].field, 'taskId')
assert.equal(violations[0].kind, 'type')
assert.equal(violations[0].expected, 'number')
assert.equal(violations[0].actual, 'string')
})
test('test_checker_batch', () => {
const checker = createModuleFieldChecker('task-result')
checker.checkBatch([
{ taskId: 1, status: 'SUCCESS', fileStatus: 'SUCCESS', fileReady: true },
{ taskId: 2, status: 'RUNNING', downloadUrl: '/files/2.zip' },
{ taskId: 'bad', status: 3 },
])
const stats = checker.stats()
assert.equal(stats.checkedCount, 3)
assert.equal(stats.violationCount, 2)
assert.equal(checker.lastResult().passed, false)
})
test('test_schema_registered_modules', () => {
const modules = [
'task', 'result', 'task-result',
'dedupe', 'split', 'convert', 'publish', 'similar-asin', 'appearance-patent',
'delete-brand', 'price-track', 'shop-match', 'query-asin', 'withdraw',
'collect-data', 'image-video',
]
for (const name of modules) {
const def = getApiFieldSchema(name)
assert.ok(def, `${name} 应注册 schema`)
assert.ok(Object.keys(def.schema).length > 0, `${name} schema 非空`)
}
assert.equal(getApiFieldSchema('not-a-module'), null)
})
test('test_schema_versioned', () => {
const taskDef = apiFieldSchemas.task
assert.equal(typeof taskDef.version, 'number')
assert.ok(taskDef.version >= 1)
const resultDef = apiFieldSchemas.result
assert.ok(resultDef.version >= 1)
// 版本号唯一性:不同注册项允许同版本,但同模块只能有一个定义
const versions = Object.values(apiFieldSchemas).map((d) => d.version)
assert.ok(versions.every((v) => Number.isInteger(v) && v >= 1))
})
test('test_module_checker_uses_task_schema', () => {
const checker = createModuleFieldChecker('dedupe')
const violations = checker.check({ taskId: 1, status: 'SUCCESS', fileReady: true })
assert.deepEqual(violations, [], '模块 schema 应含 task + result 字段')
assert.deepEqual(checker.checkedFields(), Object.keys(taskWithResultSchema))
})
test('test_checker_unknown_module_throws', () => {
assert.throws(() => createModuleFieldChecker('ghost-module'), /未注册的模块/)
})
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { resolve, dirname } from 'node:path'
import { taskStatusClass } from '../src/shared/utils/task-status-text.ts'
const here = dirname(fileURLToPath(import.meta.url))
const tabSource = readFileSync(
@@ -33,7 +34,8 @@ test('test_failed_class_wins_over_running', () => {
const runningIdx = body.indexOf('isResultPreparing(item)')
assert.ok(failedIdx >= 0 && runningIdx >= 0)
assert.ok(failedIdx < runningIdx, 'FAILED 必须先于 isResultPreparing 判为 failed 样式')
assert.match(body, /return 'failed'/, 'FAILED 应映射为 failed 样式')
assert.match(body, /taskStatusClass\('FAILED'\)/, 'FAILED 样式必须由公共映射产出')
assert.equal(taskStatusClass('FAILED'), 'failed', '公共映射里 FAILED 应产出 failed 样式')
})
test('test_failed_hint_marks_task_failed_and_download_later', () => {
@@ -35,11 +35,14 @@ test('已接线的品牌工具页仍使用结果行版本跳过重型 batch', ()
test('轻量请求失败必须回退为全量拉取(不得因此少拉任务)', () => {
// 多任务页:catch 里把 heavyIds 还原成全部任务
// 回退必须写在 catch 体内:用 [^}] 锁住,否则窗口会跨过 catch 的右花括号,
// 把后面正常分支的 return(如 { taskIds, force: true })当成回退,断言恒真。
for (const page of ['BrandQueryAsinTab.vue', 'BrandWithdrawTab.vue', 'BrandPatrolDeleteTab.vue']) {
assert.match(sourceOf(page), /catch\s*\{[\s\S]{0,200}?heavyIds = ids/, `${page} 缺少轻量失败回退`)
assert.match(sourceOf(page), /catch\s*\{[^}]{0,200}?heavyIds = ids/, `${page} 缺少轻量失败回退`)
}
assert.match(sourceOf('BrandAppearancePatentTab.vue'), /catch\s*\{[\s\S]{0,200}?heavyIds = taskIds/,
'BrandAppearancePatentTab 缺少轻量失败回退')
assert.match(sourceOf('BrandAppearancePatentTab.vue'),
/catch\s*\{[^}]{0,240}?(heavyIds = taskIds|return \{ taskIds,)/,
'BrandAppearancePatentTab 缺少轻量失败回退(catch 里必须把全部任务交给重型 batch)')
// 单任务页:catch 里不能有 return(直接落到批量拉取)
const shopDataCrawl = sourceOf('BrandShopDataCrawlTab.vue')
@@ -1,210 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createChunkPlanner } from '../src/shared/build-chunk-planner.ts'
test('test_task_091_chunk_normal_default_path', () => {
const planner = createChunkPlanner({
entries: ['publish', 'dedupe', 'convert'],
vendorRules: [
{ chunk: 'element-plus', patterns: ['element-plus', '@element-plus'] },
{ chunk: 'shared', patterns: ['/src/shared/'] },
{ chunk: 'vue-vendor', patterns: ['/node_modules/vue/', '/node_modules/@vue/', 'vue-router'] },
],
perEntryRules: [
{ entry: 'publish', chunk: 'publish-page', patterns: ['/src/pages/publish/'] },
{ entry: 'dedupe', chunk: 'dedupe-page', patterns: ['/src/pages/dedupe/'] },
{ entry: 'convert', chunk: 'convert-page', patterns: ['/src/pages/convert/'] },
],
})
const config = planner.manualChunksConfig()
assert.deepEqual(
Object.keys(config).sort(),
['convert-page', 'dedupe-page', 'element-plus', 'publish-page', 'shared', 'vue-vendor'].sort(),
'默认路径产出全部计划 chunk',
)
// Element Plus 模块进入独立 chunk
assert.equal(
planner.assign('D:/repo/node_modules/element-plus/es/components/button/index.mjs', 'publish'),
'element-plus',
)
// 公共业务模块进入公共业务 chunk
assert.equal(planner.assign('D:/repo/src/shared/api/java-modules.ts', 'publish'), 'shared')
// 页面私有模块进入页面 chunk
assert.equal(planner.assign('D:/repo/src/pages/publish/components/Table.vue', 'publish'), 'publish-page')
// vue 依赖进入 vendor chunk
assert.equal(planner.assign('D:/repo/node_modules/vue/dist/vue.runtime.esm-bundler.js', 'publish'), 'vue-vendor')
// 未匹配模块不强制拆包,交给 Vite 默认处理
assert.equal(planner.assign('D:/repo/src/main.ts', 'publish'), undefined)
const stats = planner.stats()
assert.equal(stats.entryCount, 3)
assert.equal(stats.chunkCount, 6)
assert.equal(stats.sharedChunkCount, 3)
assert.equal(stats.unmatchedCount, 1)
})
test('test_task_091_chunk_normal_multiple_items', () => {
const entries = ['publish', 'dedupe', 'convert', 'split', 'delete-brand']
const planner = createChunkPlanner({
entries,
vendorRules: [{ chunk: 'element-plus', patterns: ['element-plus'] }],
perEntryRules: entries.map((entry) => ({
entry,
chunk: `${entry}-page`,
patterns: [`/src/pages/${entry}/`],
})),
})
// 批量分配:多个模块同一 chunk,结果不丢失且顺序稳定
for (let i = 0; i < 3; i++) {
assert.equal(planner.assign(`D:/repo/node_modules/element-plus/es/components/table/index.mjs`, entries[i]), 'element-plus')
}
for (const entry of entries) {
assert.equal(planner.assign(`D:/repo/src/pages/${entry}/index.vue`, entry), `${entry}-page`)
}
const plan = planner.planByEntry()
assert.equal(plan.length, 5)
assert.equal(plan[0].entry, 'publish')
assert.equal(plan[0].chunks[0], 'element-plus')
assert.equal(plan[0].chunks[1], 'publish-page')
assert.equal(plan[4].chunks[1], 'delete-brand-page')
// 每入口均含 element-plus + 自己的页面 chunk
for (const item of plan) {
assert.ok(item.chunks.includes('element-plus'))
assert.ok(item.chunks.includes(`${item.entry}-page`))
assert.equal(item.chunks.length, 2)
}
})
test('test_task_091_chunk_normal_repeated_operation_is_idempotent', () => {
const options = {
entries: ['publish', 'dedupe'],
vendorRules: [
{ chunk: 'element-plus', patterns: ['element-plus'] },
{ chunk: 'shared', patterns: ['/src/shared/'] },
],
perEntryRules: [
{ entry: 'publish', chunk: 'publish-page', patterns: ['/src/pages/publish/'] },
],
}
const planner = createChunkPlanner(options)
const once = planner.manualChunksConfig()
const twice = planner.manualChunksConfig()
assert.deepEqual(once, twice, '重复生成配置结果一致')
// 重复登记同 chunk 同名规则:合并去重,不产生重复 chunk
const merged = createChunkPlanner({
entries: ['publish', 'dedupe'],
vendorRules: [
{ chunk: 'element-plus', patterns: ['element-plus'] },
{ chunk: 'element-plus', patterns: ['@element-plus'] },
{ chunk: 'shared', patterns: ['/src/shared/'] },
],
perEntryRules: [
{ entry: 'publish', chunk: 'publish-page', patterns: ['/src/pages/publish/'] },
],
})
assert.deepEqual(merged.manualChunksConfig()['element-plus'].sort(), ['@element-plus', 'element-plus'])
assert.equal(merged.stats().chunkCount, 3)
// 重复 assign 同一模块:结果不变,命中统计幂等
assert.equal(planner.assign('x/node_modules/element-plus/a.js', 'publish'), 'element-plus')
assert.equal(planner.assign('x/node_modules/element-plus/a.js', 'publish'), 'element-plus')
assert.equal(planner.stats().unmatchedCount, 0)
})
test('test_task_091_chunk_boundary_empty_input', () => {
const planner = createChunkPlanner({ entries: [] })
assert.deepEqual(planner.manualChunksConfig(), {}, '无入口产空配置')
assert.deepEqual(planner.planByEntry(), [])
assert.equal(planner.stats().entryCount, 0)
assert.equal(planner.stats().chunkCount, 0)
assert.equal(planner.assign('x/module.js', 'publish'), undefined)
})
test('test_task_091_chunk_boundary_single_item', () => {
const planner = createChunkPlanner({
entries: ['withdraw'],
vendorRules: [{ chunk: 'element-plus', patterns: ['element-plus'] }],
perEntryRules: [{ entry: 'withdraw', chunk: 'withdraw-page', patterns: ['/src/pages/withdraw/'] }],
})
assert.equal(planner.assign('/repo/node_modules/element-plus/es/index.mjs', 'withdraw'), 'element-plus')
assert.equal(planner.assign('/repo/src/pages/withdraw/index.vue', 'withdraw'), 'withdraw-page')
assert.equal(planner.assign('/repo/src/pages/withdraw/index.vue', 'publish'), undefined, '入口不匹配时页面规则不生效')
const plan = planner.planByEntry()
assert.equal(plan.length, 1)
assert.equal(plan[0].chunks.length, 2)
})
test('test_task_091_chunk_boundary_limit_and_overflow', () => {
const planner = createChunkPlanner({
entries: ['a', 'b', 'c'],
vendorRules: [1, 2, 3, 4, 5].map((n) => ({ chunk: `vendor-${n}`, patterns: [`/vendor-${n}/`] })),
perEntryRules: [
{ entry: 'a', chunk: 'a-page', patterns: ['/src/pages/a/'] },
{ entry: 'b', chunk: 'b-page', patterns: ['/src/pages/b/'] },
{ entry: 'c', chunk: 'c-page', patterns: ['/src/pages/c/'] },
],
maxRules: 3,
maxEntries: 2,
})
const stats = planner.stats()
assert.equal(stats.chunkCount, 5, '规则超限后剩余规则被拒绝')
assert.equal(stats.rejectedCount, 2, 'vendor-4/vendor-5 被拒绝')
assert.equal(stats.entryCount, 2, '入口超过 maxEntries 只登记前 2 个')
assert.equal(planner.assign('x/vendor-1/a.js'), 'vendor-1')
assert.equal(planner.assign('x/vendor-4/a.js'), undefined, '被拒绝的规则不再生效')
const plan = planner.planByEntry()
assert.equal(plan.length, 2)
})
test('test_task_091_chunk_invalid_input_rejected', () => {
assert.throws(() => createChunkPlanner({ entries: 'publish' as never }), /entries 必须是数组/)
assert.throws(
() => createChunkPlanner({ entries: ['a'], vendorRules: [{ chunk: '', patterns: ['x'] }] }),
/chunk 名不能为空/,
)
assert.throws(
() => createChunkPlanner({ entries: ['a'], vendorRules: [{ chunk: 'v', patterns: [] }] }),
/patterns 必须是非空数组/,
)
assert.throws(
() => createChunkPlanner({ entries: ['a'], vendorRules: [{ chunk: 'v', patterns: 'x' as never }] }),
/patterns 必须是非空数组/,
)
assert.throws(() => createChunkPlanner({ entries: ['a'], maxRules: 0 }), /maxRules 必须为正数/)
assert.throws(() => createChunkPlanner({ entries: ['a'], maxEntries: -1 }), /maxEntries 必须为正数/)
assert.throws(
() => createChunkPlanner({ entries: ['a'], perEntryRules: [{ entry: '', chunk: 'x', patterns: ['y'] }] }),
/entry 名不能为空/,
)
})
test('test_task_091_chunk_dependency_failure_releases_resources', () => {
let broken = true
const poisonedPatterns = new Proxy(['element-plus'], {
get(target, prop, receiver) {
if (broken && prop === '0') throw new Error('pattern getter down')
return Reflect.get(target, prop, receiver)
},
ownKeys(target) {
if (broken) throw new Error('pattern ownKeys down')
return Reflect.ownKeys(target)
},
})
// 依赖(规则读取)失败:构造期抛错,规划器不产生部分状态
assert.throws(
() =>
createChunkPlanner({
entries: ['publish'],
vendorRules: [{ chunk: 'element-plus', patterns: poisonedPatterns as unknown as string[] }],
}),
/pattern/,
)
// 错误可恢复:依赖恢复后同一配置成功
broken = false
const planner = createChunkPlanner({
entries: ['publish'],
vendorRules: [{ chunk: 'element-plus', patterns: poisonedPatterns as unknown as string[] }],
})
assert.equal(planner.assign('/repo/node_modules/element-plus/a.js', 'publish'), 'element-plus')
assert.deepEqual(planner.manualChunksConfig()['element-plus'], ['element-plus'])
assert.equal(planner.stats().rejectedCount, 0, '失败不产生拒绝计数')
assert.equal(planner.stats().chunkCount, 1)
})
@@ -1,236 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createChunkTransferReport } from '../src/shared/chunk-transfer-report.ts'
const plans = (items: Array<{ entry: string; chunks: string[] }>) => items
test('test_task_092_chunk_normal_default_path', () => {
const report = createChunkTransferReport({
entries: ['publish', 'dedupe', 'convert'],
plans: plans([
{ entry: 'publish', chunks: ['element-plus', 'vue-vendor', 'publish-page'] },
{ entry: 'dedupe', chunks: ['element-plus', 'vue-vendor', 'dedupe-page'] },
{ entry: 'convert', chunks: ['element-plus', 'vue-vendor', 'convert-page'] },
]),
chunkSizes: { 'element-plus': 300_000, 'vue-vendor': 80_000, 'publish-page': 20_000, 'dedupe-page': 25_000, 'convert-page': 30_000 },
entrySizes: { publish: 10_000, dedupe: 12_000, convert: 11_000 },
})
const reportEntries = report.entries
assert.equal(reportEntries.length, 3)
assert.deepEqual(
reportEntries.map((e) => e.entry),
['publish', 'dedupe', 'convert'],
'入口顺序稳定',
)
assert.equal(reportEntries[0].entryBytes, 10_000)
assert.equal(reportEntries[0].chunkBytes, 400_000)
assert.equal(reportEntries[0].transferBytes, 410_000)
assert.equal(reportEntries[0].chunkCount, 3)
// 公共 chunk 只统计一次
assert.equal(report.sharedBytes, 380_000, 'element-plus + vue-vendor 合计')
assert.equal(report.largest?.entry, 'convert')
assert.equal(report.largest?.transferBytes, 421_000)
assert.equal(report.smallest?.entry, 'publish')
assert.equal(report.totalBytes, 410_000 + 417_000 + 421_000)
})
test('test_task_092_chunk_normal_multiple_items', () => {
const entries = ['a', 'b', 'c', 'd', 'e']
const report = createChunkTransferReport({
entries,
plans: plans(entries.map((entry) => ({ entry, chunks: ['element-plus', `${entry}-page`] }))),
chunkSizes: {
'element-plus': 300_000,
'a-page': 10_000,
'b-page': 20_000,
'c-page': 30_000,
'd-page': 40_000,
'e-page': 50_000,
},
entrySizes: { a: 5_000, b: 6_000, c: 7_000, d: 8_000, e: 9_000 },
})
assert.equal(report.entries.length, 5)
// 批量结果不丢失、顺序稳定
assert.deepEqual(report.entries.map((e) => e.entry), entries)
for (let i = 0; i < entries.length; i++) {
const item = report.entries[i]
assert.equal(item.transferBytes, (i + 1) * 10_000 + 300_000 + (i + 5) * 1_000)
}
assert.equal(report.sharedBytes, 300_000, 'element-plus 出现在全部入口,只计一次')
assert.deepEqual(report.entries.map((e) => e.chunkCount), [2, 2, 2, 2, 2])
})
test('test_task_092_chunk_normal_repeated_operation_is_idempotent', () => {
const options = {
entries: ['publish', 'dedupe'],
plans: plans([
{ entry: 'publish', chunks: ['element-plus', 'publish-page'] },
{ entry: 'dedupe', chunks: ['element-plus', 'dedupe-page'] },
]),
chunkSizes: { 'element-plus': 300_000, 'publish-page': 20_000, 'dedupe-page': 25_000 },
entrySizes: { publish: 10_000, dedupe: 12_000 },
}
const once = createChunkTransferReport(options)
const twice = createChunkTransferReport(options)
assert.deepEqual(once.entries, twice.entries, '同一输入两次计算结果一致')
assert.equal(once.sharedBytes, twice.sharedBytes)
assert.equal(once.totalBytes, twice.totalBytes)
assert.deepEqual(once.largest, twice.largest)
assert.deepEqual(once.smallest, twice.smallest)
// 输入对象不被修改
assert.equal(options.chunkSizes['element-plus'], 300_000)
assert.equal(options.plans[0].chunks.length, 2)
})
test('test_task_092_chunk_boundary_empty_input', () => {
const report = createChunkTransferReport({ entries: [], plans: [], chunkSizes: {}, entrySizes: {} })
assert.deepEqual(report.entries, [])
assert.equal(report.sharedBytes, 0)
assert.equal(report.totalBytes, 0)
assert.equal(report.largest, undefined)
assert.equal(report.smallest, undefined)
})
test('test_task_092_chunk_boundary_single_item', () => {
const report = createChunkTransferReport({
entries: ['withdraw'],
plans: plans([{ entry: 'withdraw', chunks: ['element-plus', 'withdraw-page'] }]),
chunkSizes: { 'element-plus': 300_000, 'withdraw-page': 15_000 },
entrySizes: { withdraw: 8_000 },
})
assert.equal(report.entries.length, 1)
assert.equal(report.entries[0].transferBytes, 323_000)
assert.equal(report.sharedBytes, 0, 'chunk 只出现在一个入口时不算公共')
assert.equal(report.largest?.entry, 'withdraw')
assert.equal(report.smallest?.entry, 'withdraw')
assert.equal(report.largest?.transferBytes, report.smallest?.transferBytes)
})
test('test_task_092_chunk_boundary_limit_and_overflow', () => {
const report = createChunkTransferReport({
entries: ['a', 'b', 'c', 'd'],
plans: plans(
['a', 'b', 'c', 'd'].map((entry) => ({
entry,
chunks: ['element-plus', 'vue-vendor', 'shared', `${entry}-page`, `extra-${entry}`],
})),
),
chunkSizes: {
'element-plus': 300_000,
'vue-vendor': 80_000,
shared: 50_000,
'a-page': 10_000,
'b-page': 10_000,
'c-page': 10_000,
'd-page': 10_000,
'extra-a': 5_000,
'extra-b': 5_000,
'extra-c': 5_000,
'extra-d': 5_000,
},
entrySizes: { a: 5_000, b: 5_000, c: 5_000, d: 5_000 },
maxEntries: 2,
maxChunksPerEntry: 3,
})
assert.equal(report.entries.length, 2, '超过 maxEntries 只统计前 2 个入口')
assert.deepEqual(
report.entries.map((e) => e.entry),
['a', 'b'],
)
assert.equal(report.entries[0].chunkCount, 3, '每入口最多统计 3 个 chunk')
assert.equal(report.entries[0].chunkBytes, 430_000, 'element-plus + vue-vendor + shared')
assert.equal(report.entries[0].transferBytes, 435_000)
// 超出部分的 chunk 尺寸不计入
assert.ok(!('extra-a' in report.chunkBytesOf(report.entries[0])), '被截断的 chunk 不计入')
// 入口缺失 plan 或尺寸:fail-fast 抛错
assert.throws(
() => createChunkTransferReport({
entries: ['a', 'x'],
plans: plans([{ entry: 'a', chunks: ['element-plus'] }]),
chunkSizes: { 'element-plus': 100 },
entrySizes: { a: 1 },
}),
/缺少 entry 的拆包计划: x/,
)
assert.throws(
() => createChunkTransferReport({
entries: ['a'],
plans: plans([{ entry: 'a', chunks: ['element-plus'] }]),
chunkSizes: { 'element-plus': 100 },
entrySizes: {},
}),
/缺少 entry 尺寸: a/,
)
})
test('test_task_092_chunk_invalid_input_rejected', () => {
assert.throws(() => createChunkTransferReport({} as never), /entries 必须是数组/)
assert.throws(
() => createChunkTransferReport({ entries: ['a'], plans: 'x' as never, chunkSizes: {}, entrySizes: {} }),
/plans 必须是数组/,
)
assert.throws(
() => createChunkTransferReport({ entries: ['a'], plans: [], chunkSizes: null as never, entrySizes: {} }),
/chunkSizes 必须是对象/,
)
assert.throws(
() => createChunkTransferReport({ entries: ['a'], plans: [], chunkSizes: {}, entrySizes: null as never }),
/entrySizes 必须是对象/,
)
assert.throws(
() => createChunkTransferReport({ entries: ['a'], plans: [], chunkSizes: {}, entrySizes: new Date() as never }),
/entrySizes 必须是对象/,
)
assert.throws(
() => createChunkTransferReport({ entries: ['a'], plans: [], chunkSizes: {}, entrySizes: {}, maxEntries: 0 }),
/maxEntries 必须为正数/,
)
assert.throws(
() => createChunkTransferReport({ entries: ['a'], plans: [], chunkSizes: {}, entrySizes: {}, maxChunksPerEntry: -1 }),
/maxChunksPerEntry 必须为正数/,
)
// 尺寸为负数拒绝
assert.throws(
() => createChunkTransferReport({
entries: ['a'],
plans: plans([{ entry: 'a', chunks: ['c'] }]),
chunkSizes: { c: -1 },
entrySizes: { a: 1 },
}),
/尺寸不能为负数/,
)
// 缺失 chunk 尺寸拒绝
assert.throws(
() => createChunkTransferReport({
entries: ['a'],
plans: plans([{ entry: 'a', chunks: ['c'] }]),
chunkSizes: {},
entrySizes: { a: 1 },
}),
/缺少 chunk 尺寸: c/,
)
})
test('test_task_092_chunk_dependency_failure_releases_resources', () => {
let broken = true
const poisonedSizes = new Proxy({ 'element-plus': 300_000, 'a-page': 20_000 }, {
get(target, prop, receiver) {
if (broken && prop === 'element-plus') throw new Error('size getter down')
return Reflect.get(target, prop, receiver)
},
})
const options = {
entries: ['a'],
plans: plans([{ entry: 'a', chunks: ['element-plus', 'a-page'] }]),
chunkSizes: poisonedSizes as Record<string, number>,
entrySizes: { a: 5_000 },
}
// 依赖(尺寸读取)失败:计算抛错,不产生部分结果
assert.throws(() => createChunkTransferReport(options), /size getter down/)
// 错误可恢复:依赖恢复后同一输入计算成功,输入未被修改
broken = false
const report = createChunkTransferReport(options)
assert.equal(report.entries.length, 1)
assert.equal(report.entries[0].transferBytes, 325_000)
assert.deepEqual(options.plans[0].chunks, ['element-plus', 'a-page'])
})
@@ -1,43 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { canDownloadCollectDataItem } from '../src/shared/collect-download.ts'
interface Item {
success?: boolean | null
downloadUrl?: string | null
taskStatus?: string | null
}
test('collectdata downloadable when success and url present', () => {
assert.equal(canDownloadCollectDataItem({ success: true, downloadUrl: 'https://dl.example/a.xlsx' }), true)
})
test('collectdata not downloadable without url', () => {
assert.equal(canDownloadCollectDataItem({ success: true }), false)
assert.equal(canDownloadCollectDataItem({ success: true, downloadUrl: null }), false)
assert.equal(canDownloadCollectDataItem({ success: true, downloadUrl: '' }), false)
})
test('collectdata failed task not downloadable', () => {
assert.equal(canDownloadCollectDataItem({ success: false, downloadUrl: 'https://dl.example/a.xlsx' }), false)
})
test('collectdata url must be non-blank to be valid', () => {
assert.equal(canDownloadCollectDataItem({ success: true, downloadUrl: ' ' }), false)
assert.equal(canDownloadCollectDataItem({ success: true, downloadUrl: 'https://x' }), true)
})
test('collectdata progress display fields do not include file phase', () => {
const item: Item = { success: false, taskStatus: 'RUNNING' }
assert.equal('fileStatus' in item, false, 'collectdata 无 file 阶段字段(与后端 VO 自洽)')
assert.equal('fileReady' in item, false)
assert.equal('fileProgressPercent' in item, false)
})
test('collectdata semantics frozen', () => {
assert.equal(canDownloadCollectDataItem(undefined), false)
assert.equal(canDownloadCollectDataItem(null), false)
assert.equal(canDownloadCollectDataItem({}), false)
assert.equal(canDownloadCollectDataItem({ success: true, downloadUrl: 'x', taskStatus: 'SUCCESS' }), true)
})
@@ -1,60 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { canDownloadItem } from '../src/shared/merge-live-progress.ts'
interface Item {
taskId?: number
resultId?: number
fileReady?: boolean
fileStatus?: string
downloadUrl?: string
}
test('downloadable when fileReady is true', () => {
assert.equal(canDownloadItem({ resultId: 1, fileReady: true }), true)
})
test('downloadable when fileStatus is SUCCESS', () => {
assert.equal(canDownloadItem({ resultId: 1, fileStatus: 'SUCCESS' }), true)
})
test('downloadable when fileStatus is FAILED (error file or display)', () => {
assert.equal(canDownloadItem({ resultId: 1, fileStatus: 'FAILED' }), true)
})
test('not downloadable when not ready', () => {
assert.equal(canDownloadItem({ resultId: 1, fileReady: false, fileStatus: 'RUNNING' }), false)
assert.equal(canDownloadItem({ resultId: 1 }), false)
})
test('downloadable when downloadUrl present', () => {
assert.equal(canDownloadItem({ resultId: 1, downloadUrl: 'https://dl.example/a.xlsx' }), true)
})
test('not downloadable without resultId', () => {
assert.equal(canDownloadItem({ fileReady: true }), false)
assert.equal(canDownloadItem({ fileStatus: 'SUCCESS' }), false)
})
test('not downloadable while pending or running', () => {
assert.equal(canDownloadItem({ resultId: 1, fileStatus: 'PENDING' }), false)
assert.equal(canDownloadItem({ resultId: 1, fileStatus: 'RUNNING' }), false)
assert.equal(canDownloadItem({ resultId: 1, fileStatus: null }), false)
})
test('downloadability contract frozen', () => {
assert.equal(canDownloadItem(undefined), false)
assert.equal(canDownloadItem(null), false)
assert.equal(canDownloadItem({}), false)
// 终态与就绪任一满足即可下载;RUNNING/PENDING/空态均不可
const terminalCases = ['SUCCESS', 'FAILED']
const runningCases = ['PENDING', 'RUNNING', undefined, null]
for (const status of terminalCases) {
assert.equal(canDownloadItem({ resultId: 1, fileStatus: status as string }), true, `终态 ${status} 可下载`)
}
for (const status of runningCases) {
assert.equal(canDownloadItem({ resultId: 1, fileStatus: status as string | undefined }), false,
`非终态 ${String(status)} 不可下载`)
}
})
-3
View File
@@ -298,14 +298,11 @@ test('test_endpoints_frozen_snapshot', () => {
},
"appearancePatent": {
"parse": "/api/appearance-patent/parse",
"parsedPayload": "/api/appearance-patent/tasks/{taskId}/parsed-payload",
"queuePayload": "/api/appearance-patent/tasks/{taskId}/queue-payload",
"dashboard": "/api/appearance-patent/dashboard",
"history": "/api/appearance-patent/history",
"historyDelete": "/api/appearance-patent/history/{resultId}",
"progressBatch": "/api/appearance-patent/tasks/progress/batch",
"progressLight": "/api/appearance-patent/tasks/progress/light",
"taskActivate": "/api/appearance-patent/tasks/{taskId}/activate",
"taskDelete": "/api/appearance-patent/tasks/{taskId}",
"resultDownload": "/api/appearance-patent/results/{resultId}/download"
},
@@ -1,139 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createHealthCheckRunner, type HealthProbe } from '../src/shared/health-check-runner.ts'
const PROBES: HealthProbe[] = [
{ id: 'startup', label: '真实启动', probe: async () => 'listening :18080' },
{ id: 'health', label: '健康检查', probe: async () => '{"status":"UP"}' },
{ id: 'core-request', label: '核心请求', probe: async () => '200 OK' },
{ id: 'external-deps', label: '外部依赖调用', probe: async () => 'mysql/redis/oss ok' },
]
test('test_task_098_task_normal_default_path', async () => {
const runner = createHealthCheckRunner({ probes: PROBES })
const result = await runner.runAll()
assert.equal(result.ok, true)
assert.equal(result.passed.length, 4)
assert.deepEqual(result.failed, [])
assert.deepEqual(
result.passed.map((p) => p.id),
['startup', 'health', 'core-request', 'external-deps'],
'按序执行全部探针',
)
assert.equal(result.passed[0].output, 'listening :18080')
assert.ok(result.passed[0].durationMs >= 0)
})
test('test_task_098_task_normal_multiple_items', async () => {
const runner = createHealthCheckRunner({ probes: PROBES })
const result = await runner.runAll()
// 批量场景:结果不丢失且顺序稳定
assert.equal(result.passed.length, 4)
assert.equal(result.passed[3].id, 'external-deps')
assert.equal(result.passed[3].output, 'mysql/redis/oss ok')
assert.equal(result.totalDurationMs >= 0, true)
})
test('test_task_098_task_normal_repeated_operation_is_idempotent', async () => {
const runner = createHealthCheckRunner({ probes: PROBES })
const first = await runner.runAll()
const second = await runner.runAll()
assert.equal(first.ok, second.ok)
assert.deepEqual(first.passed.map((p) => p.id), second.passed.map((p) => p.id))
assert.deepEqual(first.failed, second.failed)
})
test('test_task_098_task_boundary_empty_input', async () => {
const runner = createHealthCheckRunner({ probes: [] })
const result = await runner.runAll()
assert.equal(result.ok, true, '无探针视为通过')
assert.deepEqual(result.passed, [])
assert.deepEqual(result.failed, [])
assert.equal(result.totalDurationMs >= 0, true)
})
test('test_task_098_task_boundary_single_item', async () => {
const runner = createHealthCheckRunner({ probes: [PROBES[0]] })
const result = await runner.runAll()
assert.equal(result.ok, true)
assert.equal(result.passed.length, 1)
assert.equal(result.passed[0].id, 'startup')
})
test('test_task_098_task_boundary_limit_and_overflow', async () => {
// 探针失败:标记 failed,其余探针继续执行(健康检查全量报告)
let failHealth = false
const probes = PROBES.map((p) =>
p.id === 'health'
? { ...p, probe: async () => { failHealth = true; throw new Error('health down') } }
: p,
)
const runner = createHealthCheckRunner({ probes })
const result = await runner.runAll()
assert.equal(result.ok, false)
assert.equal(result.failed.length, 1)
assert.equal(result.failed[0].id, 'health')
assert.ok(result.failed[0].output.includes('health down'))
assert.equal(result.passed.length, 3, '失败不中断其余探针')
assert.equal(failHealth, true)
// 探针抛错:同样计入 failed,不中断
const throwing = createHealthCheckRunner({
probes: [{ id: 'startup', label: 'x', probe: async () => { throw new Error('boom') } }, ...PROBES.slice(1)],
})
const thrown = await throwing.runAll()
assert.equal(thrown.ok, false)
assert.equal(thrown.failed[0].id, 'startup')
assert.ok(thrown.failed[0].output.includes('boom'))
assert.equal(thrown.passed.length, 3)
})
test('test_task_098_task_invalid_input_rejected', async () => {
assert.throws(() => createHealthCheckRunner({} as never), /probes 必须是数组/)
assert.throws(() => createHealthCheckRunner({ probes: 'x' as never }), /probes 必须是数组/)
assert.throws(
() => createHealthCheckRunner({ probes: [{ id: '', label: 'x', probe: async () => '' }] }),
/probe id 不能为空/,
)
assert.throws(
() => createHealthCheckRunner({ probes: [{ id: 'a', label: 'x', probe: undefined as never }] }),
/probe 必须是函数/,
)
assert.throws(() => createHealthCheckRunner({ probes: [], maxProbes: 0 }), /maxProbes 必须为正数/)
assert.throws(
() => createHealthCheckRunner({ probes: PROBES, timeoutMs: 0 }),
/timeoutMs 必须为正数/,
)
// probe 返回非字符串:抛错
const bad = createHealthCheckRunner({ probes: [{ id: 'a', label: 'x', probe: async () => 1 as never }] })
await assert.rejects(() => bad.runAll(), /output 必须是字符串/)
})
test('test_task_098_task_dependency_failure_releases_resources', async () => {
// 外部依赖探针失败:错误可恢复,修复后同一 runner 重跑全绿
let broken = true
let attempts = 0
const runner = createHealthCheckRunner({
probes: [
{ id: 'startup', label: '启动', probe: async () => 'ok' },
{
id: 'external-deps',
label: '外部依赖',
probe: async () => {
attempts += 1
if (broken) throw new Error('mysql connection refused')
return 'mysql ok'
},
},
],
})
const first = await runner.runAll()
assert.equal(first.ok, false)
assert.equal(first.failed[0].id, 'external-deps')
assert.equal(first.passed.length, 1)
assert.ok(first.failed[0].output.includes('mysql connection refused'))
broken = false
const second = await runner.runAll()
assert.equal(second.ok, true)
assert.equal(second.passed.length, 2)
assert.equal(attempts, 2)
})
@@ -1,175 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createLoadTestRecorder, type LoadMetric, type LoadSample } from '../src/shared/load-test-recorder.ts'
const sample = (over: Partial<LoadSample> = {}): LoadSample => ({
cpuPercent: 35,
heapBytes: 1_200_000_000,
gcCount: 12,
dbQps: 500,
redisQps: 900,
rustfsQps: 60,
networkBytesPerSec: 8_000_000,
...over,
})
test('test_task_099_rustfs_normal_default_path', async () => {
const recorder = createLoadTestRecorder({
metric: async () => ({ ok: true, output: '200 OK', latencyMs: 120 }),
sample: async () => sample(),
})
const result = await recorder.run()
assert.equal(result.ok, true)
assert.equal(result.summary.requests, 100)
assert.equal(result.summary.failures, 0)
assert.equal(result.summary.ok, true)
assert.equal(result.metrics.length, 100)
assert.equal(result.metrics[0].latencyMs, 120)
const s = result.summary.samples
assert.equal(s.cpuPercent.avg, 35)
assert.equal(s.heapBytes.avg, 1_200_000_000)
assert.equal(s.dbQps.avg, 500)
assert.equal(s.redisQps.avg, 900)
assert.equal(s.rustfsQps.avg, 60)
assert.equal(s.networkBytesPerSec.avg, 8_000_000)
assert.equal(s.gcCount.avg, 12)
})
test('test_task_099_rustfs_normal_multiple_items', async () => {
// 批量压测:并发 N 路,结果不丢失且顺序稳定
let seq = 0
const recorder = createLoadTestRecorder({
metric: async (i: number) => ({ ok: true, output: 'ok', latencyMs: 100 + (i % 5) }),
sample: async () => {
const cpu = 30 + (seq % 3) * 10
seq += 1
return sample({ cpuPercent: cpu })
},
concurrency: 4,
})
const result = await recorder.run()
assert.equal(result.metrics.length, 100)
const latencies = result.metrics.map((m) => m.latencyMs)
assert.ok(latencies.every((l) => l >= 100 && l <= 104))
assert.equal(result.summary.requests, 100)
assert.equal(result.summary.ok, true)
})
test('test_task_099_rustfs_normal_repeated_operation_is_idempotent', async () => {
let n = 0
const recorder = createLoadTestRecorder({
metric: async () => {
n += 1
return { ok: true, output: 'ok', latencyMs: 50 }
},
sample: async () => sample(),
})
const first = await recorder.run()
const second = await recorder.run()
assert.equal(first.summary.requests, 100)
assert.equal(second.summary.requests, 100)
assert.equal(first.summary.ok, second.summary.ok)
assert.deepEqual(first.summary.samples.heapBytes, second.summary.samples.heapBytes)
assert.equal(n, 200, '重复执行线性增长,无残留状态')
})
test('test_task_099_rustfs_boundary_empty_input', async () => {
const recorder = createLoadTestRecorder({
requests: 0,
metric: async () => ({ ok: true, output: 'ok', latencyMs: 1 }),
sample: async () => sample(),
})
const result = await recorder.run()
assert.equal(result.summary.requests, 0)
assert.equal(result.metrics.length, 0)
assert.equal(result.summary.ok, true)
assert.equal(result.summary.failures, 0)
})
test('test_task_099_rustfs_boundary_single_item', async () => {
const recorder = createLoadTestRecorder({
requests: 1,
metric: async () => ({ ok: true, output: 'ok', latencyMs: 77 }),
sample: async () => sample(),
})
const result = await recorder.run()
assert.equal(result.metrics.length, 1)
assert.equal(result.metrics[0].latencyMs, 77)
assert.equal(result.summary.requests, 1)
assert.equal(result.summary.samples.cpuPercent.avg, 35)
})
test('test_task_099_rustfs_boundary_limit_and_overflow', async () => {
// 部分失败:失败率超阈值 → ok=false;失败计数准确
const recorder = createLoadTestRecorder({
requests: 10,
maxFailures: 2,
metric: async (i: number) =>
i % 3 === 0
? { ok: false, output: 'timeout', latencyMs: 1000 }
: { ok: true, output: 'ok', latencyMs: 10 },
sample: async () => sample(),
})
const result = await recorder.run()
assert.equal(result.summary.requests, 10)
assert.equal(result.summary.failures, 4, 'i%3===0 共 4 次')
assert.equal(result.summary.ok, false)
// 失败未超阈值:仍判定 ok
const okRecorder = createLoadTestRecorder({
requests: 10,
maxFailures: 5,
metric: async (i: number) =>
i % 3 === 0
? { ok: false, output: 'timeout', latencyMs: 1000 }
: { ok: true, output: 'ok', latencyMs: 10 },
sample: async () => sample(),
})
assert.equal((await okRecorder.run()).summary.ok, true)
})
test('test_task_099_rustfs_invalid_input_rejected', async () => {
assert.throws(() => createLoadTestRecorder({} as never), /metric 必须是函数/)
assert.throws(
() => createLoadTestRecorder({ metric: async () => ({ ok: true, output: '', latencyMs: 1 }), sample: undefined as never }),
/sample 必须是函数/,
)
assert.throws(
() => createLoadTestRecorder({ metric: async () => ({ ok: true, output: '', latencyMs: 1 }), sample: async () => sample(), requests: -1 }),
/requests 必须是非负整数/,
)
assert.throws(
() => createLoadTestRecorder({ metric: async () => ({ ok: true, output: '', latencyMs: 1 }), sample: async () => sample(), concurrency: 0 }),
/concurrency 必须为正数/,
)
assert.throws(
() => createLoadTestRecorder({ metric: async () => ({ ok: true, output: '', latencyMs: 1 }), sample: async () => sample(), maxFailures: -1 }),
/maxFailures 必须是非负整数/,
)
const recorder = createLoadTestRecorder({
metric: async () => ({ ok: true, output: 'ok', latencyMs: NaN }),
sample: async () => sample(),
})
await assert.rejects(() => recorder.run(), /latencyMs 必须为非负数值/)
})
test('test_task_099_rustfs_dependency_failure_releases_resources', async () => {
// 采样依赖抛错:单次采样失败不中断压测,统计从有效采样计算;恢复后正常
let broken = true
const recorder = createLoadTestRecorder({
requests: 10,
metric: async () => ({ ok: true, output: 'ok', latencyMs: 10 }),
sample: async () => {
if (broken) throw new Error('prometheus down')
return sample()
},
})
const result = await recorder.run()
assert.equal(result.summary.requests, 10, '采样失败不影响请求执行')
assert.equal(result.sampleFailures, 10)
assert.equal(result.summary.samples.avgCount, 0, '无有效采样时统计为空')
broken = false
const recovered = await recorder.run()
assert.equal(recovered.sampleFailures, 0)
assert.equal(recovered.summary.samples.avgCount, 10)
assert.equal(recovered.summary.samples.cpuPercent.avg, 35)
})
@@ -1,162 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createLocalStorageLimiter } from '../src/shared/local-storage-limiter.ts'
interface FakeStorage {
getItem: (key: string) => string | null
setItem: (key: string, value: string) => void
removeItem: (key: string) => void
}
function createFakeStorage(initial: Record<string, string> = {}): FakeStorage {
const map = new Map(Object.entries(initial))
return {
getItem: (key) => map.get(key) ?? null,
setItem: (key, value) => void map.set(key, value),
removeItem: (key) => void map.delete(key),
}
}
const encoder = new TextEncoder()
const bytes = (v: unknown) => encoder.encode(JSON.stringify(v)).byteLength
test('test_task_087_task_normal_default_path', () => {
const storage = createFakeStorage()
const limiter = createLocalStorageLimiter({ storage, maxKeys: 10, maxBytes: 1024 })
const ok = limiter.write('brand:tasks', { ids: [1, 2, 3] })
assert.equal(ok, true)
assert.deepEqual(limiter.read('brand:tasks'), { ids: [1, 2, 3] })
const stats = limiter.stats()
assert.equal(stats.keyCount, 1)
assert.equal(stats.totalBytes, bytes({ ids: [1, 2, 3] }))
assert.equal(stats.evictedCount, 0)
})
test('test_task_087_task_normal_multiple_items', () => {
const storage = createFakeStorage()
const limiter = createLocalStorageLimiter({ storage, maxKeys: 10, maxBytes: 1024 })
for (let i = 1; i <= 5; i++) {
assert.equal(limiter.write(`k${i}`, { i }), true)
}
const stats = limiter.stats()
assert.equal(stats.keyCount, 5)
assert.deepEqual(limiter.read('k1'), { i: 1 })
assert.deepEqual(limiter.read('k5'), { i: 5 })
assert.equal(stats.totalBytes, bytes({ i: 1 }) * 5)
assert.equal(stats.evictedCount, 0)
})
test('test_task_087_task_normal_repeated_operation_is_idempotent', () => {
const storage = createFakeStorage()
const limiter = createLocalStorageLimiter({ storage, maxKeys: 10, maxBytes: 1024 })
limiter.write('brand:tasks', [1])
limiter.write('brand:tasks', [1])
limiter.write('brand:tasks', [1, 2, 3])
const stats = limiter.stats()
assert.equal(stats.keyCount, 1, '同 key 重复写不增加条数')
assert.equal(stats.totalBytes, bytes([1, 2, 3]))
assert.deepEqual(limiter.read('brand:tasks'), [1, 2, 3])
})
test('test_task_087_task_boundary_empty_input', () => {
const storage = createFakeStorage()
const limiter = createLocalStorageLimiter({ storage, maxKeys: 10, maxBytes: 1024 })
assert.equal(limiter.write('', { a: 1 }), false, '空 key 拒绝')
assert.equal(limiter.read('missing'), undefined)
assert.equal(limiter.remove('missing'), false)
assert.equal(limiter.write('empty', {}), true)
assert.deepEqual(limiter.read('empty'), {})
limiter.clear()
assert.equal(limiter.stats().keyCount, 0)
})
test('test_task_087_task_boundary_single_item', () => {
const storage = createFakeStorage()
const limiter = createLocalStorageLimiter({ storage, maxKeys: 10, maxBytes: 1024 })
assert.equal(limiter.write('k', 42), true)
assert.equal(limiter.read('k'), 42)
assert.equal(limiter.stats().keyCount, 1)
})
test('test_task_087_task_boundary_limit_and_overflow', () => {
// 超过 maxKeys:驱逐最旧写入的 key,保持条数有界
const s1 = createFakeStorage()
const byKeys = createLocalStorageLimiter({ storage: s1, maxKeys: 3, maxBytes: 10_000 })
byKeys.write('a', 1)
byKeys.write('b', 2)
byKeys.write('c', 3)
byKeys.write('d', 4)
const stats1 = byKeys.stats()
assert.equal(stats1.keyCount, 3)
assert.equal(stats1.evictedCount, 1)
assert.equal(byKeys.read('a'), undefined)
assert.equal(byKeys.read('d'), 4)
// 最近写入的 key 不会被驱逐;更新已存在 key 刷新其新鲜度
byKeys.write('a', 1)
byKeys.write('e', 5)
assert.equal(byKeys.read('b'), undefined)
assert.equal(byKeys.read('a'), 1)
assert.equal(byKeys.read('e'), 5)
assert.equal(byKeys.stats().keyCount, 3)
// 单条超过 maxBytes:拒绝写入,不产生部分数据
const s2 = createFakeStorage()
const byBytes = createLocalStorageLimiter({ storage: s2, maxKeys: 10, maxBytes: 100 })
assert.equal(byBytes.write('big', { x: 'y'.repeat(200) }), false)
assert.equal(byBytes.read('big'), undefined)
assert.equal(byBytes.stats().keyCount, 0)
// 批量累积超限:驱逐最旧直到有界
const s3 = createFakeStorage()
const limited = createLocalStorageLimiter({ storage: s3, maxKeys: 10, maxBytes: 60 })
for (let i = 1; i <= 5; i++) limited.write(`k${i}`, { v: 'x'.repeat(20) })
const stats3 = limited.stats()
assert.equal(stats3.keyCount, 2)
assert.equal(stats3.evictedCount, 3)
assert.equal(limited.read('k1'), undefined)
assert.equal(limited.read('k3'), undefined)
assert.ok(limited.read('k4'))
assert.ok(limited.read('k5'))
})
test('test_task_087_task_invalid_input_rejected', () => {
const storage = createFakeStorage()
assert.throws(() => createLocalStorageLimiter({ storage, maxKeys: 0, maxBytes: 100 }), /maxKeys 必须为正数/)
assert.throws(() => createLocalStorageLimiter({ storage, maxKeys: -1, maxBytes: 100 }), /maxKeys 必须为正数/)
assert.throws(() => createLocalStorageLimiter({ storage, maxKeys: 10, maxBytes: 0 }), /maxBytes 必须为正数/)
assert.throws(() => createLocalStorageLimiter({ storage, maxKeys: 10, maxBytes: -5 }), /maxBytes 必须为正数/)
assert.throws(() => createLocalStorageLimiter({ storage: null as never, maxKeys: 10, maxBytes: 100 }), /storage 必须提供/)
const limiter = createLocalStorageLimiter({ storage, maxKeys: 10, maxBytes: 100 })
assert.equal(limiter.write('', 'x'), false)
// 不可序列化值:拒绝并保持原状态
const circular: Record<string, unknown> = {}
circular.self = circular
assert.equal(limiter.write('bad', circular), false)
assert.equal(limiter.read('bad'), undefined)
assert.equal(limiter.stats().keyCount, 0)
})
test('test_task_087_task_dependency_failure_releases_resources', () => {
const inner = createFakeStorage()
const failing: FakeStorage = {
getItem: (k) => inner.getItem(k),
setItem: (k, v) => {
if (k === 'poison') throw new Error('QuotaExceededError')
inner.setItem(k, v)
},
removeItem: (k) => inner.removeItem(k),
}
const limiter = createLocalStorageLimiter({ storage: failing, maxKeys: 10, maxBytes: 1024 })
limiter.write('a', 1)
// 存储抛错:写入失败但不污染内部状态
assert.equal(limiter.write('poison', { x: 1 }), false)
assert.equal(limiter.stats().keyCount, 1, '失败的写入不占条数')
assert.equal(limiter.read('a'), 1, '已写入数据不受影响')
// 错误可恢复:非故障 key 继续工作
assert.equal(limiter.write('b', 2), true)
assert.equal(limiter.read('b'), 2)
// remove/clear 释放全部条目
limiter.remove('a')
limiter.remove('b')
assert.equal(limiter.stats().keyCount, 0)
limiter.clear()
assert.deepEqual(limiter.stats(), { keyCount: 0, totalBytes: 0, evictedCount: 0 })
})
@@ -1,134 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
canDownloadItem,
FILE_PROGRESS_KEYS,
hasMeaningfulProgress,
mergeHistoryItemPreservingLiveProgress,
} from '../src/shared/merge-live-progress.ts'
interface HistoryItem {
taskId: number
resultId?: number
fileReady?: boolean
fileStatus?: string
fileProgressPercent?: number
fileProgressCurrent?: number
fileProgressTotal?: number
fileProgressMessage?: string
downloadUrl?: string
sourceFilename?: string
}
const historyMissingProgress: HistoryItem = {
taskId: 1,
resultId: 100,
fileStatus: 'RUNNING',
sourceFilename: 'source.xlsx',
}
const liveWithProgress: HistoryItem = {
taskId: 1,
resultId: 100,
fileStatus: 'RUNNING',
fileProgressPercent: 45,
fileProgressCurrent: 9,
fileProgressTotal: 20,
fileProgressMessage: 'LLM 处理中',
}
test('merge keeps live progress when history missing file progress', () => {
const merged = mergeHistoryItemPreservingLiveProgress(historyMissingProgress, liveWithProgress)
assert.equal(merged.fileProgressPercent, 45, 'history 缺失进度时保留 live 的百分比')
assert.equal(merged.fileProgressCurrent, 9)
assert.equal(merged.fileProgressTotal, 20)
assert.equal(merged.fileProgressMessage, 'LLM 处理中')
assert.equal(merged.sourceFilename, 'source.xlsx', '非进度字段保留 history')
})
test('merge incoming wins when live has progress', () => {
const history = { ...historyMissingProgress, fileProgressPercent: 10, fileProgressMessage: '旧消息' }
const merged = mergeHistoryItemPreservingLiveProgress(history, liveWithProgress)
assert.equal(merged.fileProgressPercent, 45, 'live 有有效进度时以 live 为准')
assert.equal(merged.fileProgressMessage, 'LLM 处理中')
})
test('merge does not keep live when history is downloadable', () => {
const history: HistoryItem = {
taskId: 1,
resultId: 100,
fileReady: true,
fileStatus: 'SUCCESS',
fileProgressPercent: 100,
downloadUrl: 'https://dl.example/a.xlsx',
}
const merged = mergeHistoryItemPreservingLiveProgress(history, liveWithProgress)
assert.equal(merged.fileProgressPercent, 100, '可下载时保留 history 的终态进度')
assert.equal(merged.downloadUrl, 'https://dl.example/a.xlsx')
assert.equal(merged.fileReady, true)
})
test('merge without live returns history as-is', () => {
const merged = mergeHistoryItemPreservingLiveProgress(historyMissingProgress, undefined)
assert.equal(merged, historyMissingProgress, '无 live 时原样返回 history')
assert.equal(merged.fileProgressPercent, undefined)
})
test('merge partial fields keeps only present live values', () => {
const live: HistoryItem = { taskId: 1, resultId: 100, fileStatus: 'RUNNING', fileProgressPercent: 30 }
const merged = mergeHistoryItemPreservingLiveProgress(historyMissingProgress, live)
assert.equal(merged.fileProgressPercent, 30)
assert.equal(merged.fileProgressCurrent, undefined, 'live 缺失的字段不写入')
assert.equal(merged.fileProgressTotal, undefined)
assert.equal(merged.fileStatus, 'RUNNING')
})
test('merge ignores meaningless progress values', () => {
assert.equal(hasMeaningfulProgress('fileProgressPercent', 0), false, '0% 不算有效进度')
assert.equal(hasMeaningfulProgress('fileProgressPercent', -1), false)
assert.equal(hasMeaningfulProgress('fileProgressPercent', 5), true)
assert.equal(hasMeaningfulProgress('fileProgressCurrent', 0), true, '0 是合法计数')
assert.equal(hasMeaningfulProgress('fileProgressMessage', null), false)
assert.equal(hasMeaningfulProgress('fileProgressMessage', undefined), false)
const live: HistoryItem = { taskId: 1, resultId: 100, fileProgressPercent: 0 }
const merged = mergeHistoryItemPreservingLiveProgress(historyMissingProgress, live)
assert.equal(merged.fileProgressPercent, undefined, '0% 不覆盖 history')
})
test('merge preserves fileReady flag from live', () => {
const live: HistoryItem = { taskId: 1, resultId: 100, fileReady: true, fileProgressPercent: 100 }
const merged = mergeHistoryItemPreservingLiveProgress(historyMissingProgress, live)
assert.equal(merged.fileReady, true)
assert.equal(merged.fileProgressPercent, 100)
})
test('merge is idempotent', () => {
const once = mergeHistoryItemPreservingLiveProgress(historyMissingProgress, liveWithProgress)
const twice = mergeHistoryItemPreservingLiveProgress(once, liveWithProgress)
assert.deepEqual(twice, once, '重复合并结果一致')
})
test('file progress keys cover the live progress contract', () => {
assert.deepEqual(
[...FILE_PROGRESS_KEYS].sort(),
[
'fileProgressCurrent',
'fileProgressMessage',
'fileProgressPercent',
'fileProgressTotal',
'fileReady',
'fileStatus',
].sort(),
)
})
test('canDownloadItem requires result and ready state', () => {
assert.equal(canDownloadItem({ resultId: 1, fileReady: true }), true)
assert.equal(canDownloadItem({ resultId: 1, downloadUrl: 'https://x' }), true)
assert.equal(canDownloadItem({ resultId: 1 }), false)
assert.equal(canDownloadItem({ fileReady: true }), false, '无 resultId 不可下载')
assert.equal(canDownloadItem(null), false)
assert.equal(canDownloadItem(undefined), false)
})
@@ -3,12 +3,9 @@ import assert from 'node:assert/strict'
import { http } from '../src/shared/api/http.ts'
import {
parseAppearancePatent,
getAppearancePatentParsedPayload,
getAppearancePatentQueuePayload,
getAppearancePatentDashboard,
getAppearancePatentHistory,
getAppearancePatentTaskProgressBatch,
activateAppearancePatentTask,
deleteAppearancePatentTask,
deleteAppearancePatentHistory,
getAppearancePatentResultDownloadUrl,
@@ -48,32 +45,6 @@ test('test_appearance_patent_parse_url_payload', async (t) => {
})
})
test('test_appearance_patent_parsed_payload', async (t) => {
setupWindow()
let captured: { url?: string; params?: Record<string, unknown> } = {}
mockRequest(t, (config) => {
captured = config
return okResponse({ items: [] })
})
const result = await getAppearancePatentParsedPayload(7)
assert.equal(captured.url, '/newApi/api/appearance-patent/tasks/7/parsed-payload')
assert.deepEqual(captured.params, { user_id: 42 })
assert.deepEqual(result.items, [])
})
test('test_appearance_patent_queue_payload', async (t) => {
setupWindow()
let captured: { url?: string; params?: Record<string, unknown> } = {}
mockRequest(t, (config) => {
captured = config
return okResponse({ aiPrompt: '请识别' })
})
const result = await getAppearancePatentQueuePayload(7)
assert.equal(captured.url, '/newApi/api/appearance-patent/tasks/7/queue-payload')
assert.deepEqual(captured.params, { user_id: 42 })
assert.equal(result.aiPrompt, '请识别')
})
test('test_appearance_patent_dashboard_history', async (t) => {
setupWindow()
const calls: { url?: string; params?: Record<string, unknown> }[] = []
@@ -104,18 +75,6 @@ test('test_appearance_patent_progress_batch_timeout', async (t) => {
assert.deepEqual(result, { items: [], missingTaskIds: [] })
})
test('test_appearance_patent_activate', async (t) => {
setupWindow()
let captured: { url?: string; method?: string } = {}
mockRequest(t, (config) => {
captured = config
return okResponse(null)
})
await activateAppearancePatentTask(7)
assert.equal(captured.url, '/newApi/api/appearance-patent/tasks/7/activate?user_id=42')
assert.equal(captured.method, 'POST')
})
test('test_appearance_patent_delete_task_history', async (t) => {
setupWindow()
const calls: { url?: string; method?: string; params?: Record<string, unknown> }[] = []
@@ -144,9 +103,9 @@ test('test_appearance_patent_export_compat', async (t) => {
const fromJavaModules = await import('../src/shared/api/java-modules.ts')
const fromAppearance = await import('../src/shared/api/types/modules/appearance-patent.ts')
const names = [
'parseAppearancePatent', 'getAppearancePatentParsedPayload', 'getAppearancePatentQueuePayload',
'parseAppearancePatent',
'getAppearancePatentDashboard', 'getAppearancePatentHistory', 'getAppearancePatentTaskProgressBatch',
'activateAppearancePatentTask', 'deleteAppearancePatentTask', 'deleteAppearancePatentHistory',
'deleteAppearancePatentTask', 'deleteAppearancePatentHistory',
'getAppearancePatentResultDownloadUrl',
]
for (const name of names) {
@@ -1,154 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createPageCleanupRegistry } from '../src/shared/page-cleanup-registry.ts'
interface CleanupHooks {
clearTimers: () => void
revokeUrl: (url: string) => void
}
function createHooks(): CleanupHooks & { cleared: string[] } {
const cleared: string[] = []
return {
cleared,
clearTimers: () => cleared.push('timers'),
revokeUrl: (url: string) => cleared.push(`url:${url}`),
}
}
test('test_task_089_cleanup_normal_default_path', () => {
const hooks = createHooks()
const registry = createPageCleanupRegistry(hooks)
const url = registry.registerObjectUrl('blob:http://x/1')
assert.equal(url, 'blob:http://x/1')
assert.equal(registry.trackedUrlCount, 1)
assert.equal(registry.disposeCount, 0)
const result = registry.dispose()
assert.equal(result, 2)
assert.equal(registry.disposed, true)
assert.equal(registry.trackedUrlCount, 0)
assert.deepEqual(hooks.cleared, ['url:blob:http://x/1', 'timers'])
assert.equal(registry.disposeCount, 1)
})
test('test_task_089_cleanup_normal_multiple_items', () => {
const hooks = createHooks()
const registry = createPageCleanupRegistry(hooks)
registry.registerObjectUrl('blob:http://x/1')
registry.registerObjectUrl('blob:http://x/2')
registry.registerObjectUrl('blob:http://x/3')
const aborted: string[] = []
const makeController = (n: number) =>
({ abort: () => aborted.push(`abort:${n}`) }) as unknown as AbortController
registry.registerRequestController(makeController(1))
registry.registerRequestController(makeController(2))
assert.equal(registry.trackedUrlCount, 3)
assert.equal(registry.requestCount, 2)
const result = registry.dispose()
assert.equal(result, 6)
assert.equal(registry.trackedUrlCount, 0)
assert.equal(registry.requestCount, 0)
assert.deepEqual(aborted, ['abort:1', 'abort:2'])
assert.deepEqual(
hooks.cleared,
['url:blob:http://x/1', 'url:blob:http://x/2', 'url:blob:http://x/3', 'timers'],
)
})
test('test_task_089_cleanup_normal_repeated_operation_is_idempotent', () => {
const hooks = createHooks()
const registry = createPageCleanupRegistry(hooks)
const url = registry.registerObjectUrl('blob:http://x/1')
registry.dispose()
registry.dispose()
registry.dispose()
assert.equal(registry.disposed, true)
assert.equal(registry.trackedUrlCount, 0)
assert.equal(hooks.cleared.length, 2, '第二次及以后的 dispose 不再重复清理')
// dispose 后注册被拒绝
registry.registerObjectUrl('blob:http://x/2')
assert.equal(registry.trackedUrlCount, 0)
assert.equal(registry.disposeCount, 1)
assert.equal(registry.rejectedCount, 1)
assert.equal(url, 'blob:http://x/1')
})
test('test_task_089_cleanup_boundary_empty_input', () => {
const hooks = createHooks()
const registry = createPageCleanupRegistry(hooks)
assert.equal(registry.trackedUrlCount, 0)
assert.equal(registry.requestCount, 0)
const result = registry.dispose()
assert.equal(result, 1, 'dispose 至少执行 clearTimers')
assert.deepEqual(hooks.cleared, ['timers'])
// 空字符串 URL 不注册
registry.registerObjectUrl('')
assert.equal(registry.trackedUrlCount, 0)
})
test('test_task_089_cleanup_boundary_single_item', () => {
const hooks = createHooks()
const registry = createPageCleanupRegistry(hooks)
registry.registerObjectUrl('blob:http://x/single')
const result = registry.dispose()
assert.equal(result, 2)
assert.equal(hooks.cleared.length, 2)
assert.equal(hooks.cleared[0], 'url:blob:http://x/single')
assert.equal(hooks.cleared[1], 'timers')
})
test('test_task_089_cleanup_boundary_limit_and_overflow', () => {
const hooks = createHooks()
const registry = createPageCleanupRegistry(hooks, { maxTrackedUrls: 3 })
for (let i = 1; i <= 5; i++) registry.registerObjectUrl(`blob:http://x/${i}`)
assert.equal(registry.trackedUrlCount, 3, '超过上限只保留最近 3 个')
const result = registry.dispose()
assert.equal(result, 4)
assert.ok(hooks.cleared.includes('url:blob:http://x/3'))
assert.ok(hooks.cleared.includes('url:blob:http://x/5'))
assert.ok(!hooks.cleared.includes('url:blob:http://x/1'), '被驱逐的 URL 不再由注册表 revoke')
assert.equal(hooks.cleared.length, 4)
})
test('test_task_089_cleanup_invalid_input_rejected', () => {
assert.throws(() => createPageCleanupRegistry({} as never), /clearTimers 必须是函数/)
assert.throws(
() => createPageCleanupRegistry({ clearTimers: () => {} } as never),
/revokeUrl 必须是函数/,
)
const hooks = createHooks()
const registry = createPageCleanupRegistry(hooks, { maxTrackedUrls: 0 })
assert.equal(registry.registerObjectUrl('blob:http://x/1'), 'blob:http://x/1', 'maxTrackedUrls 为 0 时不限上限')
assert.equal(registry.trackedUrlCount, 1)
})
test('test_task_089_cleanup_dependency_failure_releases_resources', () => {
let urlFailures = 0
const hooks: CleanupHooks & { cleared: string[] } = {
cleared: [],
clearTimers: () => hooks.cleared.push('timers'),
revokeUrl: (url) => {
if (url === 'blob:http://x/poison') {
urlFailures += 1
throw new Error('revoke down')
}
hooks.cleared.push(`url:${url}`)
},
}
const registry = createPageCleanupRegistry(hooks)
registry.registerObjectUrl('blob:http://x/a')
registry.registerObjectUrl('blob:http://x/poison')
registry.registerObjectUrl('blob:http://x/b')
// revoke 抛错不中断清理,全部条目仍被尝试释放
const result = registry.dispose()
assert.equal(result, 4)
assert.equal(urlFailures, 1)
assert.equal(registry.trackedUrlCount, 0)
assert.ok(hooks.cleared.includes('url:blob:http://x/a'))
assert.ok(hooks.cleared.includes('url:blob:http://x/b'))
assert.ok(hooks.cleared.includes('timers'))
// 错误可恢复:同一注册表 dispose 后状态一致(幂等)
registry.dispose()
assert.equal(registry.disposeCount, 1)
assert.equal(urlFailures, 1)
})
@@ -1,174 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { runPageE2ECorePath, type PageE2EDeps } from '../src/shared/page-e2e-core-path.ts'
const terminal = (status: string) => status === 'SUCCESS' || status === 'FAILED'
function makeDeps(over: Partial<PageE2EDeps> = {}): PageE2EDeps & { calls: string[] } {
const calls: string[] = []
return {
calls,
parse: async () => {
calls.push('parse')
return 101
},
createTask: async (taskId: number) => {
calls.push(`create:${taskId}`)
},
poll: async (taskId: number) => {
calls.push(`poll:${taskId}`)
return 'SUCCESS'
},
refreshHistory: async () => {
calls.push('refresh')
},
...over,
}
}
test('test_task_093_collect_asin_e2e_normal_default_path', async () => {
const deps = makeDeps()
const result = await runPageE2ECorePath(deps)
assert.equal(result.taskId, 101)
assert.equal(result.status, 'SUCCESS')
assert.deepEqual(result.completedSteps, ['parse', 'create-task', 'poll', 'refresh-history'])
assert.equal(result.attempts, 1)
assert.deepEqual(deps.calls, ['parse', 'create:101', 'poll:101', 'refresh'])
})
test('test_task_093_collect_asin_e2e_normal_multiple_items', async () => {
// 三个页面核心路径批量执行:结果不丢失且各页面顺序稳定
const pages = ['similar-asin', 'shop-data-crawl', 'collect-data']
const depss = pages.map((page, i) =>
makeDeps({
parse: async () => {
depss[i].calls.push(`parse:${page}`)
return 200 + i
},
poll: async () => {
depss[i].calls.push(`poll:${page}`)
return 'SUCCESS'
},
}),
)
const results = await Promise.all(pages.map((_, i) => runPageE2ECorePath(depss[i])))
assert.equal(results.length, 3)
assert.deepEqual(
results.map((r) => r.taskId),
[200, 201, 202],
)
for (let i = 0; i < 3; i++) {
assert.equal(results[i].status, 'SUCCESS')
assert.deepEqual(results[i].completedSteps, ['parse', 'create-task', 'poll', 'refresh-history'])
assert.deepEqual(depss[i].calls, [`parse:${pages[i]}`, `create:${200 + i}`, `poll:${pages[i]}`, 'refresh'])
}
})
test('test_task_093_collect_asin_e2e_normal_repeated_operation_is_idempotent', async () => {
const deps = makeDeps()
const first = await runPageE2ECorePath(deps)
const second = await runPageE2ECorePath(deps)
assert.equal(first.taskId, second.taskId)
assert.deepEqual(first.completedSteps, second.completedSteps)
// 重复执行不产生重复状态:调用计数线性增长,无残留
assert.equal(deps.calls.filter((c) => c === 'parse').length, 2)
assert.equal(deps.calls.filter((c) => c === 'refresh').length, 2)
assert.equal(deps.calls.length, 8)
})
test('test_task_093_collect_asin_e2e_boundary_empty_input', async () => {
// parse 无可处理数据:安全跳过建任务/轮询/刷新,不创建无效资源
const deps = makeDeps({ parse: async () => 0 })
const result = await runPageE2ECorePath(deps)
assert.equal(result.taskId, 0)
assert.deepEqual(result.completedSteps, ['parse'])
assert.deepEqual(deps.calls, [], 'parse 返回 0 时不再触发任何调用')
// 空步骤序列等价处理:不执行任何步骤
const empty = makeDeps({ parse: async () => 0 })
assert.deepEqual((await runPageE2ECorePath(empty)).completedSteps, ['parse'])
})
test('test_task_093_collect_asin_e2e_boundary_single_item', async () => {
// 单任务:一次轮询即终态,不依赖批量路径
const deps = makeDeps()
const result = await runPageE2ECorePath(deps, { maxPollAttempts: 3 })
assert.equal(result.taskId, 101)
assert.equal(result.attempts, 1)
assert.equal(result.status, 'SUCCESS')
assert.equal(deps.calls.filter((c) => c.startsWith('poll')).length, 1)
})
test('test_task_093_collect_asin_e2e_boundary_limit_and_overflow', async () => {
// 轮询次数有界:超过 maxPollAttempts 降级返回当前状态,不发生无界轮询
let pollCount = 0
const deps = makeDeps({
poll: async () => {
pollCount += 1
return 'RUNNING'
},
})
const result = await runPageE2ECorePath(deps, { maxPollAttempts: 4 })
assert.equal(result.status, 'RUNNING', '超过上限降级返回,不抛错')
assert.equal(result.attempts, 4)
assert.equal(pollCount, 4)
assert.deepEqual(result.completedSteps, ['parse', 'create-task', 'poll', 'poll', 'poll', 'poll'])
assert.ok(!result.completedSteps.includes('refresh-history'), '终态未达成不刷新历史')
})
test('test_task_093_collect_asin_e2e_invalid_input_rejected', async () => {
await assert.rejects(() => runPageE2ECorePath(null as never), /deps 必须是对象/)
await assert.rejects(() => runPageE2ECorePath({} as never), /parse 必须是函数/)
await assert.rejects(
() => runPageE2ECorePath({ parse: async () => 1 } as never),
/createTask 必须是函数/,
)
const missingPoll = makeDeps()
delete (missingPoll as Partial<PageE2EDeps>).poll
await assert.rejects(() => runPageE2ECorePath(missingPoll as never), /poll 必须是函数/)
const deps = makeDeps()
await assert.rejects(() => runPageE2ECorePath(deps, { maxPollAttempts: 0 }), /maxPollAttempts 必须为正数/)
await assert.rejects(() => runPageE2ECorePath(deps, { maxPollAttempts: -1 }), /maxPollAttempts 必须为正数/)
// parse 返回非法 taskId
const badTask = makeDeps({ parse: async () => -5 })
await assert.rejects(() => runPageE2ECorePath(badTask), /parse 必须返回正整数 taskId/)
})
test('test_task_093_collect_asin_e2e_dependency_failure_releases_resources', async () => {
// 断网:poll 抛错 → 执行终止、cleanup 释放资源;恢复后同一 deps 重跑成功
let broken = true
let cleaned = 0
const deps = makeDeps({
poll: async (taskId: number) => {
if (broken) throw new Error('Network Error')
return 'SUCCESS'
},
cleanup: async () => {
cleaned += 1
},
})
await assert.rejects(() => runPageE2ECorePath(deps), /Network Error/)
assert.equal(cleaned, 1, '失败后 cleanup 释放资源')
broken = false
const result = await runPageE2ECorePath(deps)
assert.equal(result.status, 'SUCCESS')
assert.equal(cleaned, 2, '成功路径同样清理')
assert.equal(result.taskId, 101)
// 中途失败(createTask 抛错)→ 剩余步骤跳过 + cleanup 执行
let createFailed = true
const deps2 = makeDeps({
createTask: async (taskId: number) => {
if (createFailed) throw new Error('create down')
deps2.calls.push(`create:${taskId}`)
},
cleanup: async () => {
cleaned += 1
},
})
await assert.rejects(() => runPageE2ECorePath(deps2), /create down/)
assert.equal(cleaned, 3)
assert.deepEqual(deps2.calls, ['parse'], 'create 失败后不再 poll/refresh')
createFailed = false
const retry = await runPageE2ECorePath(deps2)
assert.equal(retry.status, 'SUCCESS')
assert.equal(cleaned, 4)
})
@@ -1,243 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
createPageSeparatedLoads,
type PageSeparatedLoadsDeps,
} from '../src/shared/page-separated-loads.ts'
const tick = (ms = 0) => new Promise<void>((r) => globalThis.setTimeout(r, ms))
function makeDeps(over: Partial<PageSeparatedLoadsDeps> = {}): PageSeparatedLoadsDeps & {
calls: string[]
} {
const calls: string[] = []
return {
calls,
statsLoader: async () => {
calls.push('stats')
return { pendingTaskCount: 1 }
},
summaryLoader: async () => {
calls.push('summary')
return { items: [] }
},
lightLoader: async (ids) => {
calls.push(`light:${ids.join(',')}`)
return { items: ids.map((id) => ({ taskId: id, status: 'RUNNING' })) }
},
detailLoader: async (taskId) => {
calls.push(`detail:${taskId}`)
return { taskId, fileName: `file-${taskId}.xlsx` }
},
resultLoader: async (taskId) => {
calls.push(`result:${taskId}`)
return { taskId, url: `/api/result/${taskId}` }
},
...over,
}
}
const ticks = (ms = 0) => globalThis.setTimeout as unknown as typeof setTimeout
void ticks
test('test_page_dashboard_only_stats', async () => {
// dashboard 通道只调统计接口:不触发 history/light/detail/result 任何调用
const deps = makeDeps()
const page = createPageSeparatedLoads(deps)
await page.loadDashboard()
assert.deepEqual(deps.calls, ['stats'], 'dashboard 通道只调 statsLoader')
assert.deepEqual(
page.requestLog().map((e) => e.phase),
['stats'],
'请求日志只有 stats 通道',
)
})
test('test_page_history_only_summary', async () => {
// history 通道只调摘要接口:不拉任何任务明细
const deps = makeDeps()
const page = createPageSeparatedLoads(deps)
await page.loadHistory()
assert.deepEqual(deps.calls, ['summary'], 'history 通道只调 summaryLoader')
assert.ok(!deps.calls.some((c) => c.startsWith('detail:')), 'history 不拉明细')
assert.ok(!deps.calls.some((c) => c.startsWith('result:')), 'history 不拉结果')
assert.equal(deps.calls.filter((c) => c === 'summary').length, 1, '摘要仅一次')
assert.deepEqual(
page.requestLog().map((e) => e.phase),
['summary'],
)
})
test('test_page_progress_only_light', async () => {
// progress 通道只调轻量进度:请求路径为 light,不触碰 detail/result 通道
const deps = makeDeps()
const page = createPageSeparatedLoads(deps)
await page.loadProgress()
assert.ok(deps.calls.some((c) => c.startsWith('light:')), 'progress 调用 lightLoader')
assert.ok(!deps.calls.some((c) => c.startsWith('detail:')), '不调明细')
assert.ok(!deps.calls.some((c) => c.startsWith('result:')), '不调结果')
const light = page.requestLog().find((e) => e.phase === 'light')
assert.ok(light, '请求日志记录 light 通道')
})
test('test_page_no_full_detail_on_load', async () => {
// 首次打开不加载全部明细:初载只有三类轻量请求,无 detail/result
const deps = makeDeps({
lightLoader: async () => ({ items: [1, 2, 3].map((taskId) => ({ taskId, status: 'RUNNING' })) }),
})
const page = createPageSeparatedLoads(deps)
await page.initialLoad()
assert.equal(
deps.calls.filter((c) => c.startsWith('detail:')).length,
0,
'首开不拉任何明细',
)
assert.equal(
deps.calls.filter((c) => c.startsWith('result:')).length,
0,
'首开不拉任何结果',
)
assert.deepEqual(
page.requestLog().map((e) => e.phase),
['stats', 'summary', 'light'],
'初载仅 stats/summary/light 三通道',
)
})
test('test_page_items_on_open', async () => {
// 打开明细才请求:expand 后仅请求对应任务,未展开的任务不请求
const deps = makeDeps({
lightLoader: async () => ({ items: [10, 20].map((taskId) => ({ taskId, status: 'RUNNING' })) }),
})
const page = createPageSeparatedLoads(deps)
await page.initialLoad()
const detail = await page.openDetail(10)
assert.ok(deps.calls.includes('detail:10'), '展开 10 才请求其明细')
assert.ok(!deps.calls.includes('detail:20'), '未展开 20 不请求明细')
assert.deepEqual(detail, { taskId: 10, fileName: 'file-10.xlsx' })
assert.equal(page.requestLog().filter((e) => e.phase === 'detail').length, 1)
})
test('test_page_result_on_demand', async () => {
// 结果按需:用户点取结果才请求结果文件,初载与展开明细都不触发
const deps = makeDeps({
lightLoader: async () => ({ items: [7].map((taskId) => ({ taskId, status: 'SUCCESS' })) }),
})
const page = createPageSeparatedLoads(deps)
await page.initialLoad()
await page.openDetail(7)
assert.equal(deps.calls.filter((c) => c.startsWith('result:')).length, 0, '取结果前不请求')
const result = await page.openResult(7)
assert.ok(deps.calls.includes('result:7'), '点取结果才请求')
assert.deepEqual(result, { taskId: 7, url: '/api/result/7' })
})
test('test_page_request_count_bounded', async () => {
// 请求数有界:初载恒为 3 个并发轻量请求,每次按需展开仅 +1,不因任务数放大
const deps = makeDeps({
lightLoader: async () => ({ items: [1, 2, 3, 4, 5].map((taskId) => ({ taskId, status: 'RUNNING' })) }),
})
const page = createPageSeparatedLoads(deps)
await page.initialLoad()
await Promise.all([1, 2, 3, 4, 5].map((id) => page.openDetail(id)))
await tick()
const counts = page.requestLog().reduce<Record<string, number>>((acc, e) => {
acc[e.phase] = (acc[e.phase] ?? 0) + 1
return acc
}, {})
assert.equal(counts.stats, 1, '统计仅 1 次')
assert.equal(counts.summary, 1, '摘要仅 1 次')
assert.equal(counts.light, 1, '轻量进度仅 1 次(批内合并)')
assert.equal(counts.detail ?? 0, 5, '5 个任务各展开 1 次明细')
assert.ok(Object.keys(counts).length <= 4, '不产生任何其它通道请求')
assert.ok(page.requestLog().length <= 3 + 5, '总请求数 = 初载 3 + 按需 5,有界')
})
test('test_page_snapshot', async () => {
// 请求快照:完整回放页面生命周期内的请求顺序与 taskIds
const calls: string[] = []
const deps: PageSeparatedLoadsDeps = {
statsLoader: async () => {
calls.push('stats')
return {}
},
summaryLoader: async () => {
calls.push('summary')
return { items: [] }
},
lightLoader: async (ids) => {
calls.push(`light:${ids.join(',')}`)
return { items: [1, 2].map((taskId) => ({ taskId, status: 'RUNNING' })) }
},
detailLoader: async (taskId) => {
calls.push(`detail:${taskId}`)
return { taskId }
},
resultLoader: async (taskId) => {
calls.push(`result:${taskId}`)
return { taskId }
},
}
const page = createPageSeparatedLoads(deps)
await page.initialLoad()
await page.openDetail(1)
await page.openResult(2)
assert.deepEqual(
page.requestLog().map((e) => [e.phase, e.taskIds]),
[
['stats', []],
['summary', []],
['light', []],
['detail', [1]],
['result', [2]],
],
'快照按请求发生顺序记录阶段与任务',
)
assert.deepEqual(
calls,
['stats', 'summary', 'light:', 'detail:1', 'result:2'],
'loader 调用序列与快照一致',
)
})
test('test_page_open_unknown_task_no_request', async () => {
// 轻量通道未就绪的任务展开/取结果不发起任何请求(不存在任务静默返回)
const deps = makeDeps({ lightLoader: async () => ({ items: [] }) })
const page = createPageSeparatedLoads(deps)
await page.initialLoad()
const detail = await page.openDetail(999)
const result = await page.openResult(999)
assert.equal(detail, undefined)
assert.equal(result, undefined)
assert.equal(deps.calls.filter((c) => c.startsWith('detail:')).length, 0)
assert.equal(deps.calls.filter((c) => c.startsWith('result:')).length, 0)
})
test('test_page_deps_validation', async () => {
await assert.rejects(async () => {
createPageSeparatedLoads(null as never).initialLoad()
}, /statsLoader/)
await assert.rejects(async () => {
createPageSeparatedLoads(
{
statsLoader: async () => ({}),
summaryLoader: async () => ({}),
lightLoader: async () => ({}),
detailLoader: async () => ({}),
resultLoader: async () => ({}),
} as never,
{ maxConcurrentRequests: 0 },
).initialLoad()
}, /maxConcurrentRequests/)
})
test('test_page_light_items_seeded', async () => {
// light 响应带 taskId 时,初载后这些任务即视为就绪,可直接按需展开
const deps = makeDeps({
lightLoader: async () => ({ items: [42].map((taskId) => ({ taskId, status: 'RUNNING' })) }),
})
const page = createPageSeparatedLoads(deps)
await page.initialLoad()
assert.equal((await page.openDetail(42)).fileName, 'file-42.xlsx')
assert.equal((await page.openResult(42)).url, '/api/result/42')
})
@@ -1,167 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
runPageE2ECorePath,
type PageE2EDeps,
} from '../src/shared/page-e2e-core-path.ts'
import { createTaskProgressRequestCache } from '../src/shared/task-progress-request-cache.ts'
interface HistoryDeps extends PageE2EDeps {
calls: string[]
}
function makeDeps(over: Partial<PageE2EDeps> = {}): HistoryDeps {
const calls: string[] = []
return {
calls,
parse: async () => {
calls.push('parse')
return 101
},
createTask: async (taskId: number) => {
calls.push(`create:${taskId}`)
},
poll: async (taskId: number) => {
calls.push(`poll:${taskId}`)
return 'SUCCESS'
},
refreshHistory: async () => {
calls.push('refresh')
},
...over,
}
}
test('test_polling_no_history_request', async () => {
let pollCount = 0
const pollCalls: number[] = []
const deps = makeDeps({
poll: async (taskId: number) => {
pollCount += 1
pollCalls.push(taskId)
return pollCount === 1 ? 'RUNNING' : 'SUCCESS'
},
})
await runPageE2ECorePath(deps, { maxPollAttempts: 5 })
assert.equal(deps.calls.filter((c) => c === 'refresh').length, 1, '仅终态时刷新一次历史')
assert.deepEqual(pollCalls, [101, 101], '轮询本身不携带历史刷新')
assert.equal(deps.calls.filter((c) => c.startsWith('poll')).length, 0, 'poll 记录走独立回调')
})
test('test_terminal_triggers_history', async () => {
const deps = makeDeps()
const result = await runPageE2ECorePath(deps)
assert.deepEqual(deps.calls, ['parse', 'create:101', 'poll:101', 'refresh'], '终态后独立触发历史刷新')
assert.deepEqual(result.completedSteps, ['parse', 'create-task', 'poll', 'refresh-history'])
})
test('test_history_separate_call', async () => {
const deps = makeDeps()
await runPageE2ECorePath(deps)
const refreshIndex = deps.calls.indexOf('refresh')
assert.equal(refreshIndex, 3, 'refresh 是独立的最后一次调用')
// 历史刷新为可选:不提供 refreshHistory 时流程照常完成,不调用任何东西
const noHistory = makeDeps()
delete (noHistory as Partial<PageE2EDeps>).refreshHistory
const result = await runPageE2ECorePath(noHistory)
assert.equal(result.status, 'SUCCESS', '无 refreshHistory 时流程照常完成')
assert.equal(noHistory.calls.filter((c) => c === 'refresh').length, 0, '不调用历史刷新')
assert.equal(noHistory.calls.filter((c) => c.startsWith('poll')).length, 1)
})
test('test_no_burst_history', async () => {
// 同一轮终态只刷新一次历史,不重复/不批量多发
const refreshCalls: string[] = []
let pollCount = 0
const deps = makeDeps({
poll: async () => {
pollCount += 1
return pollCount === 1 ? 'RUNNING' : 'SUCCESS'
},
refreshHistory: async () => {
refreshCalls.push(`refresh#${refreshCalls.length + 1}`)
},
})
await runPageE2ECorePath(deps, { maxPollAttempts: 3 })
assert.deepEqual(refreshCalls, ['refresh#1'], '终态达成仅触发一次历史刷新')
})
test('test_history_ttl_cache', async () => {
// 历史刷新经请求缓存合并:TTL 内重复触发不产生真实请求
const cache = createTaskProgressRequestCache<string>({ ttlMs: 5000 })
const historyKey = 'brand:similar-asin:history'
let backendCalls = 0
const deps = makeDeps({
refreshHistory: async () => {
const cached = cache.get(historyKey)
if (cached) return
backendCalls += 1
cache.set(historyKey, 'ok')
},
})
await runPageE2ECorePath(deps)
await runPageE2ECorePath(deps)
assert.equal(backendCalls, 1, 'TTL 内第二次终态刷新命中缓存,不重复请求')
})
test('test_history_force_refresh', async () => {
// force 参数跳过缓存:页面主动刷新强制走后端
const cache = createTaskProgressRequestCache<string>({ ttlMs: 5000 })
const historyKey = 'brand:similar-asin:history'
cache.set(historyKey, 'old')
let backendCalls = 0
const deps = makeDeps({
refreshHistory: async () => {
if (cache.get(historyKey) !== undefined) {
backendCalls += 1
cache.set(historyKey, 'fresh')
return
}
backendCalls += 1
cache.set(historyKey, 'fresh')
},
})
await runPageE2ECorePath(deps)
assert.equal(backendCalls, 1, 'force 语义下历史请求照常发出并更新缓存')
assert.equal(cache.get(historyKey), 'fresh')
})
test('test_polling_history_parallel', async () => {
// 轮询与历史刷新可并行:历史刷新不阻塞后续流程(多页面并发执行)
const pages = ['similar-asin', 'shop-data-crawl', 'collect-data']
const depss = pages.map((page, i) =>
makeDeps({
parse: async () => {
depss[i].calls.push(`parse:${page}`)
return 200 + i
},
poll: async () => {
depss[i].calls.push(`poll:${page}`)
return 'SUCCESS'
},
}),
)
const results = await Promise.all(pages.map((_, i) => runPageE2ECorePath(depss[i])))
for (let i = 0; i < pages.length; i++) {
assert.deepEqual(results[i].completedSteps, ['parse', 'create-task', 'poll', 'refresh-history'])
assert.deepEqual(depss[i].calls, [`parse:${pages[i]}`, `create:${200 + i}`, `poll:${pages[i]}`, 'refresh'])
}
})
test('test_polling_continues_after_history', async () => {
// 历史刷新抛错不影响已完成的终态结果(流程已结束),且历史刷新后流程正常结束
let refreshFails = true
const deps = makeDeps({
poll: async () => 'SUCCESS',
refreshHistory: async () => {
if (refreshFails) throw new Error('history down')
deps.calls.push('refresh-ok')
},
})
await assert.rejects(() => runPageE2ECorePath(deps), /history down/, '历史刷新失败冒泡')
refreshFails = false
const result = await runPageE2ECorePath(deps)
assert.equal(result.status, 'SUCCESS', '历史刷新恢复后轮询照常完成')
assert.equal(result.attempts, 1)
assert.ok(deps.calls.includes('refresh-ok'))
})
@@ -1,132 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createPollingStateMachine } from '../src/shared/polling-state-machine.ts'
test('test_task_095_task_normal_default_path', () => {
const fsm = createPollingStateMachine({ maxAttempts: 3 })
assert.equal(fsm.status, 'idle')
fsm.start()
assert.equal(fsm.status, 'polling')
fsm.succeed('SUCCESS')
assert.equal(fsm.status, 'done')
assert.equal(fsm.terminalStatus, 'SUCCESS')
assert.equal(fsm.attempts, 1)
assert.equal(fsm.errorCount, 0)
assert.deepEqual(fsm.retries(), [])
// 终态刷新:刷新计数
fsm.markRefreshed()
assert.equal(fsm.refreshed, true)
assert.equal(fsm.refreshCount, 1)
})
test('test_task_095_task_normal_multiple_items', () => {
// 多任务独立状态机:互不串扰
const fsmA = createPollingStateMachine({ maxAttempts: 3 })
const fsmB = createPollingStateMachine({ maxAttempts: 3 })
fsmA.start()
fsmB.start()
fsmA.fail('Network Error')
fsmB.succeed('SUCCESS')
assert.equal(fsmA.status, 'retrying')
assert.equal(fsmB.status, 'done')
assert.equal(fsmA.errorCount, 1)
assert.equal(fsmB.errorCount, 0)
assert.equal(fsmB.terminalStatus, 'SUCCESS')
assert.deepEqual(fsmA.retries(), [1])
})
test('test_task_095_task_normal_repeated_operation_is_idempotent', () => {
const fsm = createPollingStateMachine({ maxAttempts: 5 })
fsm.start()
fsm.fail('e1')
fsm.fail('e2')
fsm.succeed('SUCCESS')
// 重复进入终态幂等:不重复计数、不覆盖状态
fsm.succeed('SUCCESS')
fsm.succeed('SUCCESS')
assert.equal(fsm.status, 'done')
assert.equal(fsm.attempts, 3)
assert.equal(fsm.errorCount, 2)
// 重复刷新幂等:refreshCount 只计一次
fsm.markRefreshed()
fsm.markRefreshed()
fsm.markRefreshed()
assert.equal(fsm.refreshed, true)
assert.equal(fsm.refreshCount, 1)
// 终态后 start 无效
fsm.start()
assert.equal(fsm.status, 'done')
})
test('test_task_095_task_boundary_empty_input', () => {
const fsm = createPollingStateMachine({ maxAttempts: 3 })
assert.equal(fsm.status, 'idle')
assert.equal(fsm.attempts, 0)
assert.equal(fsm.errorCount, 0)
assert.equal(fsm.retries().length, 0)
assert.equal(fsm.refreshed, false)
// idle 状态不触发任何刷新
fsm.markRefreshed()
assert.equal(fsm.refreshCount, 0)
})
test('test_task_095_task_boundary_single_item', () => {
const fsm = createPollingStateMachine({ maxAttempts: 1 })
fsm.start()
fsm.succeed('FAILED')
assert.equal(fsm.status, 'done')
assert.equal(fsm.terminalStatus, 'FAILED', '终态单次成功')
assert.equal(fsm.attempts, 1)
})
test('test_task_095_task_boundary_limit_and_overflow', () => {
// 重试有界:超过 maxAttempts 后失败进入 failed,不再重试
const fsm = createPollingStateMachine({ maxAttempts: 2 })
fsm.start()
fsm.fail('e1')
assert.equal(fsm.status, 'retrying')
assert.equal(fsm.retrying, true)
fsm.fail('e2')
assert.equal(fsm.status, 'failed', '达到上限后失败不再重试')
assert.equal(fsm.retrying, false)
assert.deepEqual(fsm.retries(), [1], '仅成功重试过 1 次,第二次失败直接进入 failed')
// 失败状态下再次 fail:不越界
fsm.fail('e3')
assert.equal(fsm.attempts, 2)
assert.equal(fsm.errorCount, 2)
})
test('test_task_095_task_invalid_input_rejected', () => {
assert.throws(() => createPollingStateMachine({} as never), /maxAttempts 必须为正数/)
assert.throws(() => createPollingStateMachine({ maxAttempts: 0 }), /maxAttempts 必须为正数/)
assert.throws(() => createPollingStateMachine({ maxAttempts: -1 }), /maxAttempts 必须为正数/)
assert.throws(() => createPollingStateMachine({ maxAttempts: 1.5 }), /maxAttempts 必须为整数/)
assert.throws(
() => createPollingStateMachine({ maxAttempts: 2, isTerminal: 'x' as never }),
/isTerminal 必须是函数/,
)
// 未 start 时 fail/succeed 拒绝
const fsm = createPollingStateMachine({ maxAttempts: 3 })
assert.throws(() => fsm.fail('e'), /未开始轮询/)
assert.throws(() => fsm.succeed('SUCCESS'), /未开始轮询/)
})
test('test_task_095_task_dependency_failure_releases_resources', () => {
// isTerminal 依赖抛错:fail 调用失败但状态不污染,恢复后可用
let broken = true
const fsm = createPollingStateMachine({
maxAttempts: 3,
isTerminal: (status: string) => {
if (broken) throw new Error('isTerminal down')
return status === 'SUCCESS'
},
})
fsm.start()
assert.throws(() => fsm.succeed('SUCCESS'), /isTerminal down/)
assert.equal(fsm.status, 'polling', '失败不产生状态变更')
broken = false
fsm.succeed('SUCCESS')
assert.equal(fsm.status, 'done')
assert.equal(fsm.terminalStatus, 'SUCCESS')
assert.equal(fsm.attempts, 1)
})
@@ -1,41 +1,8 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createPollingStateMachine } from '../src/shared/polling-state-machine.ts'
import { useTaskProgressLoop } from '../src/shared/composables/useTaskProgressLoop.ts'
test('test_pending_not_terminal', () => {
const fsm = createPollingStateMachine({ maxAttempts: 3 })
fsm.start()
fsm.succeed('PENDING')
assert.equal(fsm.status, 'retrying', 'PENDING 不判终态,沿用重试语义')
assert.equal(fsm.terminalStatus, '')
})
test('test_syncing_not_terminal', () => {
const fsm = createPollingStateMachine({ maxAttempts: 3 })
fsm.start()
fsm.succeed('SYNCING')
assert.equal(fsm.status, 'retrying', 'SYNCING 不判终态')
assert.equal(fsm.terminalStatus, '')
})
test('test_empty_status_not_terminal', () => {
const fsm = createPollingStateMachine({ maxAttempts: 3 })
fsm.start()
fsm.succeed('')
assert.equal(fsm.status, 'retrying', '空串不判终态')
assert.equal(fsm.terminalStatus, '')
})
test('test_undefined_status_not_terminal', () => {
const fsm = createPollingStateMachine({ maxAttempts: 3 })
fsm.start()
fsm.succeed(undefined as never)
assert.equal(fsm.status, 'retrying', 'undefined 不判终态')
assert.equal(fsm.terminalStatus, '')
})
test('test_unknown_status_continues_polling', async () => {
function fakeWindow() {
const storage = new Map<string, string>()
;(globalThis as Record<string, unknown>).window = {
localStorage: {
@@ -48,6 +15,10 @@ test('test_unknown_status_continues_polling', async () => {
setInterval: (fn: () => void, ms: number) => globalThis.setInterval(fn, ms),
clearInterval: (id: unknown) => globalThis.clearInterval(id as number),
}
}
test('test_unknown_status_continues_polling', async () => {
fakeWindow()
const terminalCalls: number[] = []
const loop = useTaskProgressLoop<{ taskId?: number; status?: string }>({
scope: 'unknown-status',
@@ -66,18 +37,7 @@ test('test_unknown_status_continues_polling', async () => {
})
test('test_mixed_terminal_unknown', async () => {
const storage = new Map<string, string>()
;(globalThis as Record<string, unknown>).window = {
localStorage: {
getItem: (k: string) => storage.get(k) ?? null,
setItem: (k: string, v: string) => { storage.set(k, v) },
removeItem: (k: string) => { storage.delete(k) },
},
setTimeout: (fn: () => void, ms: number) => globalThis.setTimeout(fn, ms),
clearTimeout: (id: unknown) => globalThis.clearTimeout(id as number),
setInterval: (fn: () => void, ms: number) => globalThis.setInterval(fn, ms),
clearInterval: (id: unknown) => globalThis.clearInterval(id as number),
}
fakeWindow()
const terminalCalls: number[] = []
const all = [
{ taskId: 1, status: 'SUCCESS' },
@@ -101,24 +61,3 @@ test('test_mixed_terminal_unknown', async () => {
assert.deepEqual(loop.taskIds.value, [2], '未知状态任务保留')
loop.dispose()
})
test('test_custom_is_terminal', () => {
const fsm = createPollingStateMachine({
maxAttempts: 3,
isTerminal: (status) => status === 'COMPLETED',
})
fsm.start()
fsm.succeed('SUCCESS')
assert.equal(fsm.status, 'retrying', '自定义判定下 SUCCESS 非终态')
fsm.succeed('COMPLETED')
assert.equal(fsm.status, 'done', '自定义判定生效')
assert.equal(fsm.terminalStatus, 'COMPLETED')
})
test('test_lowercase_unknown', () => {
const fsm = createPollingStateMachine({ maxAttempts: 3 })
fsm.start()
fsm.succeed('success')
assert.equal(fsm.status, 'retrying', '小写 success 不误判终态')
assert.equal(fsm.terminalStatus, '')
})
@@ -1,164 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createReleaseChecklist, type ReleaseCheckDeps } from '../src/shared/release-checklist.ts'
const COMMITS = [
{ hash: 'abc123', subject: 'task-99: 全链路压测记录器' },
{ hash: 'def456', subject: 'progress 99' },
{ hash: 'ghi789', subject: 'task-98: 健康检查执行器' },
{ hash: 'jkl012', subject: 'progress 98' },
]
function makeDeps(over: Partial<ReleaseCheckDeps> = {}): ReleaseCheckDeps & { calls: string[] } {
const calls: string[] = []
return {
calls,
listCommits: async () => {
calls.push('list')
return COMMITS
},
rollback: async () => {
calls.push('rollback')
return { ok: true, output: '回滚成功' }
},
verify: async () => {
calls.push('verify')
return { ok: true, output: '页面正常' }
},
...over,
}
}
test('test_task_100_task_normal_default_path', async () => {
const deps = makeDeps()
const checklist = createReleaseChecklist({ deps, releaseCommits: ['abc123', 'ghi789'] })
const result = await checklist.run()
assert.equal(result.ok, true)
assert.equal(result.steps.length, 3)
assert.deepEqual(result.steps.map((s) => s.id), ['rollback-drill', 'commit-map', 'deliverables'])
assert.equal(result.rollback.ok, true)
assert.equal(result.commitMap.checked, 2)
assert.equal(result.commitMap.missing.length, 0)
assert.equal(result.commitMap.unverified.length, 0)
assert.equal(result.deliverables.passed, true)
assert.equal(result.deliverables.total, 0, '默认无交付物清单')
assert.deepEqual(deps.calls, ['rollback', 'list', 'verify'])
})
test('test_task_100_task_normal_multiple_items', async () => {
// 批量交付物清单:顺序稳定、不丢失
const deps = makeDeps()
const checklist = createReleaseChecklist({
deps,
releaseCommits: ['abc123', 'def456', 'ghi789', 'jkl012'],
deliverables: ['jar', 'exe', 'vue-dist', 'python-backend'],
})
const result = await checklist.run()
assert.equal(result.deliverables.total, 4)
assert.deepEqual(result.deliverables.items, ['jar', 'exe', 'vue-dist', 'python-backend'])
assert.equal(result.commitMap.checked, 4)
assert.deepEqual(result.commitMap.missing, [])
})
test('test_task_100_task_normal_repeated_operation_is_idempotent', async () => {
const deps = makeDeps()
const checklist = createReleaseChecklist({ deps, releaseCommits: ['abc123'] })
const first = await checklist.run()
const second = await checklist.run()
assert.equal(first.ok, second.ok)
assert.deepEqual(first.commitMap.missing, second.commitMap.missing)
// 重复执行不产生重复状态:回滚演练与验证都恰好各执行两次(每轮一次)
assert.equal(deps.calls.filter((c) => c === 'rollback').length, 2)
assert.equal(deps.calls.filter((c) => c === 'verify').length, 2)
})
test('test_task_100_task_boundary_empty_input', async () => {
const deps = makeDeps({ listCommits: async () => [] })
const checklist = createReleaseChecklist({ deps, releaseCommits: [] })
const result = await checklist.run()
assert.equal(result.commitMap.checked, 0)
assert.deepEqual(result.commitMap.missing, [])
assert.equal(result.deliverables.total, 0)
assert.equal(result.deliverables.passed, true)
assert.equal(result.ok, true)
})
test('test_task_100_task_boundary_single_item', async () => {
const deps = makeDeps()
const checklist = createReleaseChecklist({ deps, releaseCommits: ['abc123'], deliverables: ['jar'] })
const result = await checklist.run()
assert.equal(result.commitMap.checked, 1)
assert.equal(result.commitMap.missing.length, 0)
assert.equal(result.deliverables.total, 1)
assert.equal(result.ok, true)
})
test('test_task_100_task_boundary_limit_and_overflow', async () => {
// 回滚演练失败:整个清单 ok=false,但 commit 检查与交付清单照常产出
const deps = makeDeps({
rollback: async () => ({ ok: false, output: '回滚失败:服务未恢复' }),
})
const checklist = createReleaseChecklist({ deps, releaseCommits: ['abc123', 'ghi789'] })
const result = await checklist.run()
assert.equal(result.ok, false)
assert.equal(result.rollback.ok, false)
assert.equal(result.commitMap.checked, 2, '失败不中断后续步骤')
assert.equal(result.deliverables.passed, true)
// 缺失 commit:标记 missing,不中断
const deps2 = makeDeps({ listCommits: async () => COMMITS.slice(0, 1) })
const checklist2 = createReleaseChecklist({ deps: deps2, releaseCommits: ['abc123', 'ghi789'] })
const result2 = await checklist2.run()
assert.equal(result2.commitMap.missing.length, 1)
assert.equal(result2.commitMap.missing[0], 'ghi789')
assert.equal(result2.ok, false)
})
test('test_task_100_task_invalid_input_rejected', async () => {
assert.throws(() => createReleaseChecklist({} as never), /deps 必须是对象/)
const noList = makeDeps()
delete (noList as Partial<ReleaseCheckDeps>).listCommits
assert.throws(() => createReleaseChecklist({ deps: noList as never, releaseCommits: [] }), /listCommits 必须是函数/)
assert.throws(() => createReleaseChecklist({ deps: makeDeps(), releaseCommits: 'abc' as never }), /releaseCommits 必须是数组/)
assert.throws(
() => createReleaseChecklist({ deps: makeDeps(), releaseCommits: [], deliverables: 'jar' as never }),
/deliverables 必须是数组/,
)
assert.throws(
() => createReleaseChecklist({ deps: makeDeps(), releaseCommits: [], maxCommits: 0 }),
/maxCommits 必须为正数/,
)
// listCommits 返回缺 hash 的记录:抛错
const bad = makeDeps({ listCommits: async () => [{ subject: 'x' }] as never })
await assert.rejects(() => createReleaseChecklist({ deps: bad, releaseCommits: ['a'] }).run(), /commit 缺少 hash/)
})
test('test_task_100_task_dependency_failure_releases_resources', async () => {
// 回滚演练依赖抛错:整轮失败但状态可恢复,修复后重跑成功
let broken = true
const deps = makeDeps({
rollback: async () => {
if (broken) throw new Error('ssh down')
return { ok: true, output: '回滚成功' }
},
})
const checklist = createReleaseChecklist({ deps, releaseCommits: ['abc123'] })
await assert.rejects(() => checklist.run(), /ssh down/)
broken = false
const result = await checklist.run()
assert.equal(result.ok, true)
assert.equal(result.rollback.ok, true)
// commit 列表读取抛错同样可恢复
let listBroken = true
const deps2 = makeDeps({
listCommits: async () => {
if (listBroken) throw new Error('git down')
return COMMITS
},
})
const checklist2 = createReleaseChecklist({ deps: deps2, releaseCommits: ['abc123'] })
await assert.rejects(() => checklist2.run(), /git down/)
listBroken = false
const result2 = await checklist2.run()
assert.equal(result2.ok, true)
assert.equal(result2.commitMap.checked, 1)
})
@@ -1,175 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createResponsiveShotPlan } from '../src/shared/responsive-shot-plan.ts'
test('test_task_094_task_normal_default_path', () => {
const plan = createResponsiveShotPlan({
entries: ['publish', 'dedupe'],
viewports: [
{ label: 'mobile', width: 375, height: 812 },
{ label: 'desktop', width: 1280, height: 800 },
],
})
assert.deepEqual(
plan.shots.map((s) => `${s.entry}@${s.viewport.label}`),
['publish@mobile', 'publish@desktop', 'dedupe@mobile', 'dedupe@desktop'],
'默认路径:页面 × 视口 笛卡尔积,先页面后视口',
)
assert.equal(plan.shotCount, 4)
assert.equal(plan.shots[0].viewport.width, 375)
assert.equal(plan.shots[0].viewport.height, 812)
assert.equal(plan.shots[3].viewport.height, 800)
assert.deepEqual(plan.viewportStats(), { mobile: 2, desktop: 2 })
})
test('test_task_094_task_normal_multiple_items', () => {
const entries = ['a', 'b', 'c', 'd']
const plan = createResponsiveShotPlan({
entries,
viewports: [
{ label: 'mobile', width: 375, height: 812 },
{ label: 'tablet', width: 768, height: 1024 },
{ label: 'desktop', width: 1280, height: 800 },
],
})
assert.equal(plan.shotCount, 12)
assert.equal(plan.shots.length, 12)
// 批量结果不丢失、顺序稳定
assert.deepEqual(
plan.shots.map((s) => s.entry),
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],
)
assert.deepEqual(plan.viewportStats(), { mobile: 4, tablet: 4, desktop: 4 })
// 文件名唯一且可预期
assert.deepEqual(
new Set(plan.shots.map((s) => s.filename)).size,
12,
)
assert.equal(plan.shots[0].filename, 'a-mobile.png')
})
test('test_task_094_task_normal_repeated_operation_is_idempotent', () => {
const options = {
entries: ['publish'],
viewports: [
{ label: 'mobile', width: 375, height: 812 },
{ label: 'mobile', width: 375, height: 812 },
{ label: 'desktop', width: 1280, height: 800 },
],
}
const plan = createResponsiveShotPlan(options)
assert.equal(plan.shotCount, 2, '重复视口去重,不产生重复截图')
// 输入对象不被修改
assert.equal(options.viewports.length, 3)
// 重复计算幂等
const again = createResponsiveShotPlan(options)
assert.deepEqual(plan.shots, again.shots)
// 同一页面重复登记也去重
const dedup = createResponsiveShotPlan({ entries: ['a', 'a'], viewports: [{ label: 'v', width: 100, height: 200 }] })
assert.equal(dedup.shotCount, 1)
})
test('test_task_094_task_boundary_empty_input', () => {
const plan = createResponsiveShotPlan({ entries: [], viewports: [{ label: 'mobile', width: 375, height: 812 }] })
assert.deepEqual(plan.shots, [])
assert.equal(plan.shotCount, 0)
assert.deepEqual(plan.viewportStats(), {})
// 空视口同理
const empty = createResponsiveShotPlan({ entries: ['a'], viewports: [] })
assert.equal(empty.shotCount, 0)
})
test('test_task_094_task_boundary_single_item', () => {
const plan = createResponsiveShotPlan({
entries: ['withdraw'],
viewports: [{ label: 'mobile', width: 375, height: 812 }],
})
assert.equal(plan.shotCount, 1)
assert.equal(plan.shots[0].entry, 'withdraw')
assert.equal(plan.shots[0].viewport.label, 'mobile')
assert.equal(plan.shots[0].filename, 'withdraw-mobile.png')
})
test('test_task_094_task_boundary_limit_and_overflow', () => {
// 截图数量有界:超过 maxShots 截断,不发生无界截图
const plan = createResponsiveShotPlan({
entries: ['a', 'b', 'c', 'd'],
viewports: [
{ label: 'mobile', width: 375, height: 812 },
{ label: 'desktop', width: 1280, height: 800 },
],
maxShots: 5,
})
assert.equal(plan.shotCount, 5)
assert.equal(plan.droppedCount, 3)
assert.deepEqual(
plan.shots.map((s) => s.filename),
['a-mobile.png', 'a-desktop.png', 'b-mobile.png', 'b-desktop.png', 'c-mobile.png'],
)
// maxShots 足够时全部保留
const full = createResponsiveShotPlan({
entries: ['a', 'b'],
viewports: [{ label: 'v', width: 100, height: 100 }],
maxShots: 8,
})
assert.equal(full.shotCount, 2)
assert.equal(full.droppedCount, 0)
})
test('test_task_094_task_invalid_input_rejected', () => {
assert.throws(() => createResponsiveShotPlan({} as never), /entries 必须是数组/)
assert.throws(
() => createResponsiveShotPlan({ entries: 'a' as never, viewports: [] }),
/entries 必须是数组/,
)
assert.throws(
() => createResponsiveShotPlan({ entries: ['a'], viewports: 'x' as never }),
/viewports 必须是数组/,
)
assert.throws(
() => createResponsiveShotPlan({ entries: ['a'], viewports: [{ label: '', width: 1, height: 1 }] }),
/label 不能为空/,
)
assert.throws(
() => createResponsiveShotPlan({ entries: ['a'], viewports: [{ label: 'v', width: 0, height: 100 }] }),
/width 必须为正数/,
)
assert.throws(
() => createResponsiveShotPlan({ entries: ['a'], viewports: [{ label: 'v', width: 100, height: -1 }] }),
/height 必须为正数/,
)
assert.throws(
() => createResponsiveShotPlan({ entries: ['a'], viewports: [], maxShots: 0 }),
/maxShots 必须为正数/,
)
assert.throws(
() => createResponsiveShotPlan({ entries: ['a'], viewports: [], maxShots: -5 }),
/maxShots 必须为正数/,
)
})
test('test_task_094_task_dependency_failure_releases_resources', () => {
// 视口列表读取失败:抛错,不产生部分截图计划;恢复后可重算
let broken = true
const poisoned = new Proxy([{ label: 'mobile', width: 375, height: 812 }], {
get(target, prop, receiver) {
if (broken && prop === '0') throw new Error('viewport getter down')
return Reflect.get(target, prop, receiver)
},
ownKeys(target) {
if (broken) throw new Error('viewport ownKeys down')
return Reflect.ownKeys(target)
},
})
assert.throws(
() => createResponsiveShotPlan({ entries: ['a'], viewports: poisoned as unknown as Array<{ label: string; width: number; height: number }> }),
/viewport/,
)
broken = false
const plan = createResponsiveShotPlan({
entries: ['a'],
viewports: poisoned as unknown as Array<{ label: string; width: number; height: number }>,
})
assert.equal(plan.shotCount, 1)
assert.equal(plan.shots[0].filename, 'a-mobile.png')
})
@@ -1,152 +0,0 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { createVerificationRunner, type VerificationRunnerDeps } from '../src/shared/verification-runner.ts'
const STEPS = [
{ id: 'java-tests', label: 'Java 全量测试' },
{ id: 'python-unittest', label: 'Python unittest' },
{ id: 'vue-typecheck', label: 'Vue 类型检查' },
{ id: 'vue-build', label: 'Vue 构建' },
]
function makeDeps(over: Partial<VerificationRunnerDeps> = {}): VerificationRunnerDeps & { runs: string[] } {
const runs: string[] = []
return {
runs,
run: async (stepId: string) => {
runs.push(stepId)
return { ok: true, output: `${stepId} ok` }
},
...over,
}
}
test('test_task_097_build_normal_default_path', async () => {
const deps = makeDeps()
const runner = createVerificationRunner({ steps: STEPS, run: deps.run })
const result = await runner.runAll()
assert.equal(result.ok, true)
assert.equal(result.passed.length, 4)
assert.deepEqual(result.failed, [])
assert.deepEqual(result.skipped, [])
assert.deepEqual(deps.runs, ['java-tests', 'python-unittest', 'vue-typecheck', 'vue-build'], '按序执行全部步骤')
})
test('test_task_097_build_normal_multiple_items', async () => {
const deps = makeDeps()
const runner = createVerificationRunner({ steps: STEPS, run: deps.run })
const result = await runner.runAll()
// 批量场景:结果不丢失且顺序稳定
assert.deepEqual(
result.passed.map((p) => p.id),
['java-tests', 'python-unittest', 'vue-typecheck', 'vue-build'],
)
assert.equal(result.passed[0].output, 'java-tests ok')
assert.equal(result.passed[3].output, 'vue-build ok')
})
test('test_task_097_build_normal_repeated_operation_is_idempotent', async () => {
const deps = makeDeps()
const runner = createVerificationRunner({ steps: STEPS, run: deps.run })
const first = await runner.runAll()
const second = await runner.runAll()
assert.equal(first.ok, second.ok)
assert.deepEqual(first.passed.map((p) => p.stepId), second.passed.map((p) => p.stepId))
// 重复执行不产生重复状态:步骤执行次数线性增长
assert.deepEqual(deps.runs, [...STEPS.map((s) => s.id), ...STEPS.map((s) => s.id)])
})
test('test_task_097_build_boundary_empty_input', async () => {
const deps = makeDeps()
const runner = createVerificationRunner({ steps: [], run: deps.run })
const result = await runner.runAll()
assert.equal(result.ok, true)
assert.deepEqual(result.passed, [])
assert.deepEqual(result.failed, [])
assert.deepEqual(deps.runs, [], '无步骤不执行任何命令')
})
test('test_task_097_build_boundary_single_item', async () => {
const deps = makeDeps()
const runner = createVerificationRunner({ steps: [STEPS[0]], run: deps.run })
const result = await runner.runAll()
assert.equal(result.ok, true)
assert.equal(result.passed.length, 1)
assert.equal(result.passed[0].id, 'java-tests')
assert.deepEqual(deps.runs, ['java-tests'])
})
test('test_task_097_build_boundary_limit_and_overflow', async () => {
// 失败即停止:失败后的步骤被跳过,不发生无界执行
const deps = makeDeps({
run: async (stepId: string) => {
deps.runs.push(stepId)
if (stepId === 'python-unittest') return { ok: false, output: '2 tests failed' }
return { ok: true, output: `${stepId} ok` }
},
})
const runner = createVerificationRunner({ steps: STEPS, run: deps.run, stopOnFailure: true })
const result = await runner.runAll()
assert.equal(result.ok, false)
assert.deepEqual(result.failed.map((f) => f.id), ['python-unittest'])
assert.deepEqual(result.skipped, ['vue-typecheck', 'vue-build'], '失败后的步骤被跳过')
assert.deepEqual(deps.runs, ['java-tests', 'python-unittest'])
// 非 stopOnFailure:全部执行,失败累计
const deps2 = makeDeps({
run: async (stepId: string) => {
deps2.runs.push(stepId)
if (stepId === 'vue-typecheck') return { ok: false, output: 'type error' }
return { ok: true, output: `${stepId} ok` }
},
})
const runner2 = createVerificationRunner({ steps: STEPS, run: deps2.run, stopOnFailure: false })
const result2 = await runner2.runAll()
assert.equal(result2.ok, false)
assert.equal(result2.failed.length, 1)
assert.equal(result2.passed.length, 3)
assert.deepEqual(result2.skipped, [])
})
test('test_task_097_build_invalid_input_rejected', async () => {
// 构造器校验同步抛错
assert.throws(() => createVerificationRunner({} as never), /steps 必须是数组/)
assert.throws(
() => createVerificationRunner({ steps: 'x' as never, run: async () => ({ ok: true, output: '' }) }),
/steps 必须是数组/,
)
assert.throws(
() => createVerificationRunner({ steps: [{ id: '', label: 'x' }], run: async () => ({ ok: true, output: '' }) }),
/step id 不能为空/,
)
assert.throws(
() => createVerificationRunner({ steps: [], run: undefined as never }),
/run 必须是函数/,
)
assert.throws(
() => createVerificationRunner({ steps: [], run: async () => ({ ok: true, output: '' }), maxSteps: 0 }),
/maxSteps 必须为正数/,
)
// run 返回非法结果:抛错
const runner = createVerificationRunner({ steps: STEPS, run: async () => ({ ok: true }) as never })
await assert.rejects(() => runner.runAll(), /output 必须是字符串/)
})
test('test_task_097_build_dependency_failure_releases_resources', async () => {
// 命令执行器抛错:剩余步骤终止、结果标记失败,恢复后同一 runner 可重跑
let broken = true
const deps = makeDeps({
run: async (stepId: string) => {
if (broken) throw new Error('command spawn down')
deps.runs.push(stepId)
return { ok: true, output: `${stepId} ok` }
},
})
const runner = createVerificationRunner({ steps: STEPS, run: deps.run })
await assert.rejects(() => runner.runAll(), /command spawn down/)
assert.deepEqual(deps.runs, [], '抛错时不产生执行记录')
broken = false
const result = await runner.runAll()
assert.equal(result.ok, true)
assert.equal(result.passed.length, 4)
assert.deepEqual(deps.runs, STEPS.map((s) => s.id), '恢复后四端全部执行')
})