fix(phase-5.2): 消项 CR 第二轮 P1/P2/P3(通道/证据链/交付时序/后管证据页)
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
||||
"totals": {
|
||||
"files": 251,
|
||||
"cases": 1750,
|
||||
"pins": 453,
|
||||
"reads": 646
|
||||
"files": 252,
|
||||
"cases": 1753,
|
||||
"pins": 456,
|
||||
"reads": 651
|
||||
},
|
||||
"files": {
|
||||
"admin-scaffold.test.ts": {
|
||||
@@ -1247,6 +1247,11 @@
|
||||
"pins": 3,
|
||||
"reads": 5
|
||||
},
|
||||
"task-evidence-page.test.ts": {
|
||||
"cases": 3,
|
||||
"pins": 3,
|
||||
"reads": 5
|
||||
},
|
||||
"timer-cleanup-pairing.test.ts": {
|
||||
"cases": 5,
|
||||
"pins": 3,
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// P2-10(后管 AC/user-notice「只把中文给用户看」口径)。
|
||||
//
|
||||
// 评审实录:`RecordsSoftwareVersionPage.vue`/`RecordsTutorialPage.vue` 的 catch 直接写
|
||||
// `error instanceof Error ? error.message : '上传失败'`,而 `src/api/http.ts` 的响应拦截器
|
||||
// **不做 sanitize**(只挑 401/403/4011)⇒ `Broken pipe`、`Request failed with status code 403`
|
||||
// 这类英文异常原文整段上屏。收口方式沿用本仓既有出口 `components/load-failure-model`
|
||||
// 的 `loadFailureMessage(error, 本页兜底句)`(去重页四条写路径同一写法)。
|
||||
//
|
||||
// 跑法:npm run test:mount(tests/mount/**,vitest+jsdom)。
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import RecordsSoftwareVersionPage from '@/pages/records/RecordsSoftwareVersionPage.vue'
|
||||
import RecordsTutorialPage from '@/pages/records/RecordsTutorialPage.vue'
|
||||
import { loadFailureMessage } from '@/components/load-failure-model'
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const root = resolve(here, '../..')
|
||||
|
||||
const versionApi = vi.hoisted(() => ({
|
||||
fetchSoftwareVersions: vi.fn(),
|
||||
uploadSoftwareVersion: vi.fn(),
|
||||
deleteSoftwareVersions: vi.fn(),
|
||||
}))
|
||||
const tutorialApi = vi.hoisted(() => ({
|
||||
fetchTutorialPackages: vi.fn(),
|
||||
uploadTutorialPackage: vi.fn(),
|
||||
deleteTutorialPackages: vi.fn(),
|
||||
}))
|
||||
const confirmMock = vi.hoisted(() => vi.fn())
|
||||
const feedbackMock = vi.hoisted(() => vi.fn())
|
||||
const messageMock = vi.hoisted(() => ({ success: vi.fn() }))
|
||||
|
||||
vi.mock('@/pages/records/version-api.ts', () => versionApi)
|
||||
vi.mock('@/pages/records/tutorial-api.ts', () => tutorialApi)
|
||||
vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock }))
|
||||
vi.mock('@/components/admin-feedback-ui', () => ({ showAdminFeedback: feedbackMock }))
|
||||
vi.mock('element-plus', () => ({ ElMessage: messageMock }))
|
||||
|
||||
/** el-upload 的桩:把页面传进来的 on-change 回调顶出来,等价于用户选了一个 .zip。 */
|
||||
const uploadStub = {
|
||||
props: ['onChange'],
|
||||
template: '<button class="pick-zip" @click="onChange({ raw: fake })">选择文件</button>',
|
||||
data: () => ({ fake: new File([new Uint8Array(16)], 'pkg.zip', { type: 'application/zip' }) }),
|
||||
}
|
||||
|
||||
const stubs = {
|
||||
'el-dialog': { template: '<div><slot /><slot name="footer" /></div>' },
|
||||
'el-form': { template: '<form><slot /></form>' },
|
||||
'el-form-item': { template: '<div><slot /></div>' },
|
||||
'el-input': {
|
||||
props: ['modelValue'],
|
||||
emits: ['update:modelValue'],
|
||||
template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />',
|
||||
},
|
||||
'el-upload': uploadStub,
|
||||
'el-button': { template: '<button><slot /></button>' },
|
||||
'el-progress': true,
|
||||
'el-alert': { props: ['title'], template: '<div class="upload-msg">{{ title }}</div>' },
|
||||
}
|
||||
|
||||
/** 后端/驱动层原文:一句中文都没有,正是过去直接上屏的那种。 */
|
||||
const RAW_ENGLISH = 'Broken pipe: java.io.IOException at sun.nio.ch.FileDispatcherImpl.write0'
|
||||
|
||||
function clickButtonByText(wrapper: ReturnType<typeof mount>, text: string, last = false) {
|
||||
const matches = wrapper.findAll('button').filter((node) => node.text().trim() === text)
|
||||
const button = last ? matches[matches.length - 1] : matches[0]
|
||||
if (!button) throw new Error(`找不到文案为「${text}」的按钮`)
|
||||
return button
|
||||
}
|
||||
|
||||
async function submitZipUpload(component: typeof RecordsSoftwareVersionPage, versionPlaceholder: string, submitText: string, openText = '上传新版本') {
|
||||
const wrapper = mount(component, { global: { stubs } })
|
||||
await flushPromises()
|
||||
|
||||
clickButtonByText(wrapper, openText)
|
||||
const versionInput = wrapper.find(`input[placeholder="${versionPlaceholder}"]`)
|
||||
if (versionInput.exists()) await versionInput.setValue('9.9.9')
|
||||
await wrapper.get('.pick-zip').trigger('click')
|
||||
await clickButtonByText(wrapper, submitText, true).trigger('click')
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
describe('P2-10 后管上传/加载失败只把中文交给界面', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
versionApi.fetchSoftwareVersions.mockResolvedValue({ items: [] })
|
||||
tutorialApi.fetchTutorialPackages.mockResolvedValue({ items: [] })
|
||||
confirmMock.mockResolvedValue(true)
|
||||
})
|
||||
|
||||
it('真实出口对照:英文原文一律被换成中文,原因段不拼半截句', () => {
|
||||
expect(loadFailureMessage(new Error(RAW_ENGLISH), '上传失败')).toBe('上传失败')
|
||||
expect(loadFailureMessage(new Error('分片会话不存在或已过期'), '上传失败'))
|
||||
.toBe('上传失败:分片会话不存在或已过期')
|
||||
})
|
||||
|
||||
it('安装包上传失败:界面文案不含英文原文,原文只进 console', async () => {
|
||||
const warned = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
versionApi.uploadSoftwareVersion.mockRejectedValue(new Error(RAW_ENGLISH))
|
||||
|
||||
const wrapper = await submitZipUpload(RecordsSoftwareVersionPage, '例如:1.0.0', '上传软件版本')
|
||||
|
||||
const shown = wrapper.get('.upload-msg').text()
|
||||
expect(shown, '英文异常原文仍在上屏').not.toContain('Broken pipe')
|
||||
expect(shown).toContain('上传失败')
|
||||
expect(
|
||||
warned.mock.calls.some((call) => String(call.join(' ')).includes(RAW_ENGLISH)),
|
||||
'原文要留在 console,否则支持同学对着后端日志无从核对',
|
||||
).toBe(true)
|
||||
warned.mockRestore()
|
||||
})
|
||||
|
||||
it('教程包上传失败:同一条中文出口,不得再直落 error.message', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
tutorialApi.uploadTutorialPackage.mockRejectedValue(new Error(RAW_ENGLISH))
|
||||
|
||||
const wrapper = await submitZipUpload(RecordsTutorialPage, '例如:v2026.09 或留空', '上传教程包', '上传教程包')
|
||||
|
||||
const shown = wrapper.get('.upload-msg').text()
|
||||
expect(shown, '英文异常原文仍在上屏').not.toContain('Broken pipe')
|
||||
expect(shown).toContain('上传失败')
|
||||
})
|
||||
|
||||
it('列表加载失败:LoadFailureBar 的文案也是中文', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||
versionApi.fetchSoftwareVersions.mockRejectedValue(new Error('Internal Server Error'))
|
||||
|
||||
const wrapper = mount(RecordsSoftwareVersionPage, { global: { stubs } })
|
||||
await flushPromises()
|
||||
|
||||
const shown = wrapper.text()
|
||||
expect(shown).not.toContain('Internal Server Error')
|
||||
expect(shown).toContain('版本列表加载失败')
|
||||
expect(feedbackMock).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
// 写法收口的台账:两页四条 catch(列表/删除×2/上传)都必须把错误交给同一个出口。
|
||||
it('两页不得再留 error instanceof Error ? error.message 那套写法', () => {
|
||||
for (const file of [
|
||||
'src/pages/records/RecordsSoftwareVersionPage.vue',
|
||||
'src/pages/records/RecordsTutorialPage.vue',
|
||||
]) {
|
||||
const source = readFileSync(resolve(root, file), 'utf-8')
|
||||
expect(source, `${file} 仍直落 error.message`).not.toMatch(/error instanceof Error \? error\.message/)
|
||||
expect(source.match(/loadFailureMessage\(error,/g)?.length ?? 0, `${file} 的失败出口没接上`)
|
||||
.toBeGreaterThanOrEqual(4)
|
||||
expect(source).toMatch(/import \{ loadFailureMessage \} from '@\/components\/load-failure-model'/)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,13 @@
|
||||
// AC-11(R4):后管版本/教程大档上传接线的「源码尺子」那一半。
|
||||
//
|
||||
// Pending Phase 4 激活。今天 `src/pages/records/version-api.ts` 与 `tutorial-api.ts`
|
||||
// 都是 presign → 一次 PUT 直传(512MB 级也一样,蓝图 §1.2 R4 实读);本文件要求两条
|
||||
// 路径接上既有 `/api/files/chunk/**` 分片通道(断点续传/按片重试)。
|
||||
// Pending Phase 4 激活。本尺子的前身只断言 `files/chunk` 出现在非注释行,而那一句匹配来自
|
||||
// `version-api.ts`/`tutorial-api.ts` 里一对**全仓零引用的死常量**(SOFTWARE_VERSION_CHUNK_ENDPOINT/
|
||||
// TUTORIAL_CHUNK_ENDPOINT)——把真调用 `uploadFileInChunks(…)` 删掉,尺子照样绿(评审 P2-6 假绿形状)。
|
||||
// 现在判据钉在**真调用点**上:被接线的那个函数体里必须出现 `uploadFileInChunks(`,
|
||||
// 且死常量不许回来(`CHUNK_ENDPOINT =` 一出现即红)。删调用必判红,加死常量也判红。
|
||||
//
|
||||
// 行为口径在 tests/pure/pending-phase4-大档上传接线.test.ts(vitest 真调 uploadSoftwareVersion/
|
||||
// uploadTutorialPackage,删掉调用同一刻那一边也红);本文件只补"接线没被搬空"这一层。
|
||||
//
|
||||
// 跑法:npm test(node --test tests/*.test.ts)。
|
||||
import { test } from 'node:test'
|
||||
@@ -14,29 +19,75 @@ import { fileURLToPath } from 'node:url'
|
||||
const here = dirname(fileURLToPath(import.meta.url))
|
||||
const root = resolve(here, '..')
|
||||
|
||||
const LARGE_UPLOAD_FILES = [
|
||||
'src/pages/records/version-api.ts',
|
||||
'src/pages/records/tutorial-api.ts',
|
||||
]
|
||||
/** 把注释整段涂白(保行数):接线只写在注释里不算数。 */
|
||||
function blankComments(source: string): string {
|
||||
return source
|
||||
.replace(/\/\*[\s\S]*?\*\//g, (block) => block.replace(/[^\n]/g, ' '))
|
||||
.replace(/\/\/[^\n]*/g, (line) => ' '.repeat(line.length))
|
||||
}
|
||||
|
||||
test('后管版本/教程大档必须接分片通道', () => {
|
||||
for (const file of LARGE_UPLOAD_FILES) {
|
||||
const source = readFileSync(resolve(root, file), 'utf-8')
|
||||
assert.match(
|
||||
source,
|
||||
/files\/chunk/,
|
||||
`AC-11:${file} 仍是 presign 直传(512MB 断网从 0 重来,没有分片续传)`,
|
||||
)
|
||||
/** 取 `function <name>(…) {…}` 的函数体:大括号配对,跳过字符串与模板串里的括号。 */
|
||||
function functionBodyOf(source: string, name: string): string {
|
||||
const code = blankComments(source)
|
||||
const head = code.indexOf(`function ${name}(`)
|
||||
assert.notEqual(head, -1, `找不到函数 ${name}()——接线被删了还是改名了?`)
|
||||
const open = code.indexOf('{', head)
|
||||
assert.notEqual(open, -1, `${name}() 没有函数体`)
|
||||
let depth = 0
|
||||
let index = open
|
||||
let quote = ''
|
||||
for (; index < code.length; index += 1) {
|
||||
const char = code[index]
|
||||
if (quote) {
|
||||
if (char === '\\') index += 1
|
||||
else if (char === quote) quote = ''
|
||||
continue
|
||||
}
|
||||
if (char === '"' || char === "'" || char === '`') { quote = char; continue }
|
||||
if (char === '{') depth += 1
|
||||
else if (char === '}') {
|
||||
depth -= 1
|
||||
if (depth === 0) return code.slice(open + 1, index)
|
||||
}
|
||||
}
|
||||
return code.slice(open + 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* 两格共同判据(读盘点留在用例体内:把 readFileSync 挪进 helper 是本仓 source-pin 棘轮点名的"搬家不算改进"):
|
||||
* ① 从 @/api/chunk-upload 把分片函数引进来;② 被接线的函数体里真的调它;
|
||||
* ③ 阈值同源;④ 死常量不得回来。
|
||||
*/
|
||||
function assertChunkedWiring(source: string, file: string, wiredFunction: string): void {
|
||||
assert.match(
|
||||
source,
|
||||
/import\s*\{[^}]*uploadFileInChunks[^}]*\}\s*from\s*'@\/api\/chunk-upload'/,
|
||||
`AC-11:${file} 没有从 @/api/chunk-upload 引入分片函数`,
|
||||
)
|
||||
const body = functionBodyOf(source, wiredFunction)
|
||||
assert.match(
|
||||
body,
|
||||
/uploadFileInChunks\s*\(/,
|
||||
`AC-11:${file}::${wiredFunction}() 里没有真调用 uploadFileInChunks(…)(大档仍走一次 PUT 直传,512MB 断网从 0 重来)`,
|
||||
)
|
||||
assert.match(
|
||||
body,
|
||||
/CHUNK_UPLOAD_THRESHOLD/,
|
||||
`AC-11:${wiredFunction}() 的选路阈值必须与 chunk-upload 同源,不得各自写死 8MB`,
|
||||
)
|
||||
assert.doesNotMatch(
|
||||
source,
|
||||
/CHUNK_ENDPOINT\s*=/,
|
||||
`AC-11:${file} 又立了一个没人引用的 CHUNK_ENDPOINT 常量——它会顶掉本尺子的匹配来源,正是 P2-6 的假绿形状`,
|
||||
)
|
||||
}
|
||||
|
||||
test('后管安装包上传必须真的调分片通道', () => {
|
||||
const file = 'src/pages/records/version-api.ts'
|
||||
assertChunkedWiring(readFileSync(resolve(root, file), 'utf-8'), file, 'uploadSoftwareVersion')
|
||||
})
|
||||
|
||||
test('分片接线不得只落注释', () => {
|
||||
for (const file of LARGE_UPLOAD_FILES) {
|
||||
const source = readFileSync(resolve(root, file), 'utf-8')
|
||||
const codeLines = source
|
||||
.split('\n')
|
||||
.filter((line) => !line.trim().startsWith('//') && !line.trim().startsWith('*'))
|
||||
.join('\n')
|
||||
assert.match(codeLines, /files\/chunk/, `AC-11:${file} 的分片引用只出现在注释里`)
|
||||
}
|
||||
test('后管教程包上传必须真的调分片通道', () => {
|
||||
const file = 'src/pages/records/tutorial-api.ts'
|
||||
assertChunkedWiring(readFileSync(resolve(root, file), 'utf-8'), file, 'uploadTutorialPackage')
|
||||
})
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// P2-7/P2-8/P3-5(后管分片通道 AC-9/AC-11 精神)。
|
||||
//
|
||||
// 评审实录:`src/api/chunk-upload.ts` 每次调用都新 init 一个 upload_id ⇒ 紧随的 GET 必空、
|
||||
// 放弃时又把会话 DELETE 掉,**等于根本没有续传**;逐片超时还按整包体积算(120s + MB×15s),
|
||||
// 8MB 的片能拿到约 130 分钟。本文件按用户端 `shared/api/upload.ts` 的同一口径钉四件事:
|
||||
// ① 同一文件身份复用 upload_id(不重新 init);② 瞬态失败不 DELETE、会话留在本地供下次续传;
|
||||
// ③ 只有服务端确实说会话没了(404/「不存在或已过期」)才重开;④ 逐片超时按本片体积给。
|
||||
//
|
||||
// 跑法:npm run test:mount(tests/pure/** 与 tests/mount/** 同走 vitest)。
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
post: vi.fn(),
|
||||
get: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
}))
|
||||
|
||||
// 只顶掉 http 实例,unwrap 用真的:会话回收在后端是 HTTP 200+success:false,
|
||||
// 判因逻辑要吃真实解包语义(含中文文案把关),换桩会把这一半形状测漏。
|
||||
vi.mock('@/api/http', async (importOriginal) => {
|
||||
const actual = await importOriginal<{ unwrap: <T>(payload: unknown) => T }>()
|
||||
return {
|
||||
...actual,
|
||||
http: { post: mocks.post, get: mocks.get, delete: mocks.delete },
|
||||
}
|
||||
})
|
||||
|
||||
import {
|
||||
CHUNK_UPLOAD_PART_SIZE,
|
||||
CHUNK_UPLOAD_THRESHOLD,
|
||||
chunkSessionKeyOf,
|
||||
partTimeoutOf,
|
||||
uploadFileInChunks,
|
||||
} from '@/api/chunk-upload'
|
||||
|
||||
const RESUMED_ID = 'r'.repeat(32)
|
||||
const FRESH_ID = 'n'.repeat(32)
|
||||
|
||||
function axiosResponse(status: number, body: unknown) {
|
||||
return { status, data: body }
|
||||
}
|
||||
|
||||
function javaOk(body: unknown) {
|
||||
return axiosResponse(200, { success: true, message: '', data: body })
|
||||
}
|
||||
|
||||
function makeFile(name: string, bytes: number): File {
|
||||
return new File([new Uint8Array(bytes)], name, { type: 'application/octet-stream' })
|
||||
}
|
||||
|
||||
function seedSession(file: File, uploadId: string): void {
|
||||
localStorage.setItem(chunkSessionKeyOf(file.name, file), JSON.stringify({
|
||||
uploadId,
|
||||
size: file.size,
|
||||
lastModified: file.lastModified,
|
||||
}))
|
||||
}
|
||||
|
||||
function storedUploadId(file: File): string {
|
||||
const raw = localStorage.getItem(chunkSessionKeyOf(file.name, file))
|
||||
if (!raw) return ''
|
||||
return String((JSON.parse(raw) as { uploadId?: unknown }).uploadId ?? '')
|
||||
}
|
||||
|
||||
function postedUrls(): string[] {
|
||||
return mocks.post.mock.calls.map(([url]) => String(url))
|
||||
}
|
||||
|
||||
function partPosts(): Array<{ url: string; timeout: number }> {
|
||||
return mocks.post.mock.calls
|
||||
.filter(([url]) => /\/part\/\d+$/.test(String(url)))
|
||||
.map(([url, , config]) => ({
|
||||
url: String(url),
|
||||
timeout: Number((config as { timeout?: unknown } | undefined)?.timeout ?? -1),
|
||||
}))
|
||||
}
|
||||
|
||||
function initCount(): number {
|
||||
return postedUrls().filter((url) => url.includes('/chunk/init')).length
|
||||
}
|
||||
|
||||
/** init/逐片/complete 一律成功;complete 返回拼装后的 fileKey。 */
|
||||
function routePosts(uploadId: string) {
|
||||
mocks.post.mockImplementation((url: string) => Promise.resolve(
|
||||
String(url).includes('/chunk/init')
|
||||
? javaOk({ upload_id: uploadId, total_parts: 2 })
|
||||
: String(url).includes('/complete')
|
||||
? javaOk({ fileKey: 'tmp/pkg.zip', originalFilename: 'pkg.zip', size: 1 })
|
||||
: javaOk({ upload_id: String(url).split('/')[5], received_parts: 1 }),
|
||||
))
|
||||
}
|
||||
|
||||
describe('P2-7 后管分片必须真的续传', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
routePosts(FRESH_ID)
|
||||
})
|
||||
|
||||
it('同一文件身份复用 upload_id:探测成功就一条 init 都不许发', async () => {
|
||||
const file = makeFile('pkg.zip', CHUNK_UPLOAD_PART_SIZE * 2)
|
||||
seedSession(file, RESUMED_ID)
|
||||
mocks.get.mockResolvedValue(javaOk({ upload_id: RESUMED_ID, uploaded_parts: [0] }))
|
||||
|
||||
await uploadFileInChunks(file, file.name)
|
||||
|
||||
expect(initCount(), '会话还在服务端,重开 init 就是作废已传片').toBe(0)
|
||||
expect(
|
||||
partPosts().map((part) => part.url),
|
||||
'第 0 片服务端已有,只补第 1 片',
|
||||
).toEqual([`/api/files/chunk/${RESUMED_ID}/part/1`])
|
||||
})
|
||||
|
||||
it('瞬态失败(分片打不出去):不 DELETE 会话,且本地仍留着 upload_id', async () => {
|
||||
const file = makeFile('pkg.zip', CHUNK_UPLOAD_PART_SIZE * 2)
|
||||
seedSession(file, RESUMED_ID)
|
||||
mocks.get.mockResolvedValue(javaOk({ upload_id: RESUMED_ID, uploaded_parts: [] }))
|
||||
mocks.post.mockRejectedValue(new Error('Network Error'))
|
||||
|
||||
await expect(uploadFileInChunks(file, file.name)).rejects.toThrow(/Network Error/)
|
||||
|
||||
expect(mocks.delete.mock.calls, 'DELETE 会把已达片号一起清掉,下次只能从 0').length(0)
|
||||
expect(storedUploadId(file), '会话要留给下一次(含刷新后)续传').toBe(RESUMED_ID)
|
||||
})
|
||||
|
||||
it('探测 503:瞬态 ⇒ 保留原会话,不重开', async () => {
|
||||
const file = makeFile('pkg.zip', CHUNK_UPLOAD_PART_SIZE * 2)
|
||||
seedSession(file, RESUMED_ID)
|
||||
mocks.get.mockResolvedValue(axiosResponse(503, '<html>Bad Gateway</html>'))
|
||||
|
||||
await uploadFileInChunks(file, file.name)
|
||||
|
||||
expect(initCount()).toBe(0)
|
||||
expect(partPosts().every((part) => part.url.includes(RESUMED_ID))).toBe(true)
|
||||
})
|
||||
|
||||
it('探测超时(网络层错误):瞬态 ⇒ 同样保留原会话', async () => {
|
||||
const file = makeFile('pkg.zip', CHUNK_UPLOAD_PART_SIZE * 2)
|
||||
seedSession(file, RESUMED_ID)
|
||||
mocks.get.mockRejectedValue(new Error('timeout of 30000ms exceeded'))
|
||||
|
||||
await uploadFileInChunks(file, file.name)
|
||||
|
||||
expect(initCount()).toBe(0)
|
||||
expect(partPosts().every((part) => part.url.includes(RESUMED_ID))).toBe(true)
|
||||
})
|
||||
|
||||
it('HTTP 404:会话确实没了 ⇒ 清状态重开', async () => {
|
||||
const file = makeFile('pkg.zip', CHUNK_UPLOAD_PART_SIZE * 2)
|
||||
seedSession(file, RESUMED_ID)
|
||||
mocks.get.mockResolvedValue(axiosResponse(404, { success: false, message: 'Not Found', data: null }))
|
||||
|
||||
await uploadFileInChunks(file, file.name)
|
||||
|
||||
expect(initCount(), '会话已回收,不重建就永远卡在同一个死会话上').toBe(1)
|
||||
expect(partPosts().every((part) => part.url.includes(FRESH_ID))).toBe(true)
|
||||
})
|
||||
|
||||
it('后端 HTTP 200+「分片会话不存在或已过期」(现网形状)⇒ 同样重开', async () => {
|
||||
const file = makeFile('pkg.zip', CHUNK_UPLOAD_PART_SIZE * 2)
|
||||
seedSession(file, RESUMED_ID)
|
||||
mocks.get.mockResolvedValue(axiosResponse(
|
||||
200,
|
||||
{ success: false, message: '分片会话不存在或已过期', data: null },
|
||||
))
|
||||
|
||||
await uploadFileInChunks(file, file.name)
|
||||
|
||||
expect(initCount()).toBe(1)
|
||||
expect(partPosts().every((part) => part.url.includes(FRESH_ID))).toBe(true)
|
||||
})
|
||||
|
||||
it('拼装成功 ⇒ 本地会话清掉(同一文件再传要开新会话)', async () => {
|
||||
const file = makeFile('pkg.zip', CHUNK_UPLOAD_PART_SIZE * 2)
|
||||
seedSession(file, RESUMED_ID)
|
||||
mocks.get.mockResolvedValue(javaOk({ upload_id: RESUMED_ID, uploaded_parts: [] }))
|
||||
|
||||
await uploadFileInChunks(file, file.name)
|
||||
|
||||
expect(storedUploadId(file), '完成后会话已拼装落库,本地不该留残号').toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('P2-8 逐片超时按本片体积', () => {
|
||||
it('每片预算只看这一片有多大,不得按整包体积放大', async () => {
|
||||
const file = makeFile('big.zip', CHUNK_UPLOAD_PART_SIZE * 5)
|
||||
mocks.get.mockResolvedValue(javaOk({ upload_id: FRESH_ID, uploaded_parts: [] }))
|
||||
routePosts(FRESH_ID)
|
||||
|
||||
await uploadFileInChunks(file, file.name)
|
||||
|
||||
const parts = partPosts()
|
||||
expect(parts.length, '40MB=5 片').toBe(5)
|
||||
// 整包口径会给出 120s + 40×15s = 720s;按片口径 8MB 片=300s。判红要留出余量差。
|
||||
for (const part of parts) {
|
||||
expect(part.timeout, `片 ${part.url} 的超时没有按本片体积算`).toBeGreaterThan(0)
|
||||
expect(
|
||||
part.timeout,
|
||||
`片 ${part.url} 的超时 ${part.timeout}ms 是按整包体积算的(P2-8)`,
|
||||
).toBeLessThanOrEqual(partTimeoutOf(CHUNK_UPLOAD_PART_SIZE))
|
||||
}
|
||||
expect(partTimeoutOf(CHUNK_UPLOAD_PART_SIZE), '8MB 片的预算不该超过 10 分钟')
|
||||
.toBeLessThanOrEqual(600_000)
|
||||
expect(partTimeoutOf(1), '再小的片也要有保底,不能给 0').toBeGreaterThanOrEqual(60_000)
|
||||
})
|
||||
|
||||
it('init 与 complete 的预算不再随整包体积线性放大', async () => {
|
||||
const file = makeFile('big.zip', CHUNK_UPLOAD_PART_SIZE * 5)
|
||||
mocks.get.mockResolvedValue(javaOk({ upload_id: FRESH_ID, uploaded_parts: [] }))
|
||||
routePosts(FRESH_ID)
|
||||
|
||||
await uploadFileInChunks(file, file.name)
|
||||
|
||||
const initCall = mocks.post.mock.calls.find(([url]) => String(url).includes('/chunk/init'))
|
||||
const initTimeout = Number((initCall?.[2] as { timeout?: unknown } | undefined)?.timeout ?? -1)
|
||||
expect(initTimeout, 'init 只发一条登记请求,按整包体积给 720s 是把失败拖到天荒地老').toBeLessThan(300_000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('P3-5 阈值单点', () => {
|
||||
it('后管这一侧的 8MB 只有一个出口:阈值由片大小派生', () => {
|
||||
expect(CHUNK_UPLOAD_THRESHOLD, '阈值必须与片大小同源(P3-5 三处各写一遍的收口)')
|
||||
.toBe(CHUNK_UPLOAD_PART_SIZE)
|
||||
expect(CHUNK_UPLOAD_PART_SIZE).toBe(8 * 1024 * 1024)
|
||||
})
|
||||
})
|
||||
@@ -3,7 +3,7 @@
|
||||
// Pending Phase 4 激活。9MB 安装包(跨分片阈值)调 uploadSoftwareVersion,
|
||||
// 必须出现 POST /files/chunk/init;今天它走 presign → 一次 PUT 直传,
|
||||
// 512MB 断网只能从 0 重来。本文件不出网,mock 掉 http 与 axios 直传实例。
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { beforeEach, describe, it, expect, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
post: vi.fn(),
|
||||
@@ -34,9 +34,16 @@ vi.mock('@/api/http', () => ({
|
||||
}))
|
||||
|
||||
import { uploadSoftwareVersion } from '@/pages/records/version-api.ts'
|
||||
import { uploadTutorialPackage } from '@/pages/records/tutorial-api.ts'
|
||||
|
||||
|
||||
describe('AC-11 后管大档上传', () => {
|
||||
// 会话跨尝试复用后,两格之间必须清态:残留的 upload_id 会让第二格跳过本该发生的 init。
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
it('9MB 安装包必须走分片 init', async () => {
|
||||
// 预签名与分片两套响应揉成一个超集:哪条实现路径先走都能拿到自己要的字段。
|
||||
mocks.post.mockResolvedValue({
|
||||
@@ -68,5 +75,48 @@ describe('AC-11 后管大档上传', () => {
|
||||
urls.some((url) => url.includes('/files/chunk/init')),
|
||||
`AC-11:9MB 安装包仍走 presign 直传,实际出口:${urls.join(', ')}`,
|
||||
).toBe(true)
|
||||
// P2-6:删掉 uploadFileInChunks(…) 真调用后,这一格必须跟着红——所以还要核对分片片确实发出去了。
|
||||
expect(
|
||||
mocks.post.mock.calls.filter(([url]) => /\/files\/chunk\/[^/]+\/part\/\d+$/.test(String(url))).length,
|
||||
'AC-11:走分片就要真把片 POST 出去',
|
||||
).toBe(2)
|
||||
})
|
||||
|
||||
// P2-6:教程包那条道过去只有源码尺子覆盖(而尺子当时吃的是死常量),删掉真调用没人判红。
|
||||
it('9MB 教程包必须走分片 init', async () => {
|
||||
localStorage.clear()
|
||||
mocks.post.mockResolvedValue({
|
||||
data: {
|
||||
success: true,
|
||||
data: {
|
||||
upload_url: 'https://oss.example/put',
|
||||
file_url: 'https://oss.example/tutorial.zip',
|
||||
version: '9.9.9',
|
||||
object_key: 'client/tutorials/tutorial.zip',
|
||||
upload_id: 'b'.repeat(32),
|
||||
uploaded_parts: [],
|
||||
item: null,
|
||||
},
|
||||
},
|
||||
})
|
||||
mocks.get.mockResolvedValue({
|
||||
data: { success: true, data: { upload_id: 'b'.repeat(32), uploaded_parts: [] } },
|
||||
})
|
||||
mocks.directPut.mockResolvedValue({})
|
||||
|
||||
const file = new Blob([new Uint8Array(9 * 1024 * 1024)], {
|
||||
type: 'application/octet-stream',
|
||||
})
|
||||
await uploadTutorialPackage(file, 'tutorial.zip', '9.9.9')
|
||||
|
||||
const urls = mocks.post.mock.calls.map(([url]) => String(url))
|
||||
expect(
|
||||
urls.some((url) => url.includes('/files/chunk/init')),
|
||||
`AC-11:9MB 教程包仍走 presign 直传,实际出口:${urls.join(', ')}`,
|
||||
).toBe(true)
|
||||
expect(
|
||||
mocks.directPut.mock.calls.length,
|
||||
'AC-11:大档不该再走一次 PUT 直传',
|
||||
).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readSource } from './helpers.ts'
|
||||
|
||||
/** P1-9:任务证据读取面的后台入口必须存在,且只给超级管理员。 */
|
||||
|
||||
test('task evidence menu is super-admin only', () => {
|
||||
const routes = readSource('src/router/routes.ts')
|
||||
assert.match(routes, /path: 'records\/task-evidence'[\s\S]*?menuKey: 'admin_task_evidence'[\s\S]*?superAdminOnly: true/,
|
||||
'任务证据路由必须带 superAdminOnly')
|
||||
|
||||
const scope = readSource('src/config/company-scope.ts')
|
||||
assert.match(scope, /SUPER_ADMIN_ONLY_MENU_KEYS[^\n]*admin_task_evidence/,
|
||||
'菜单 key 必须在超级管理员可见清单里')
|
||||
|
||||
const guide = readSource('src/layout/operation-guides.ts')
|
||||
assert.match(guide, /admin_task_evidence:\s*\{/, '菜单必须配操作指引')
|
||||
})
|
||||
|
||||
test('task evidence page never renders object keys', () => {
|
||||
const page = readSource('src/pages/records/TaskEvidencePage.vue')
|
||||
assert.doesNotMatch(page, /objectKey|object_key|presign/i, '页面不得展示或持有对象直链')
|
||||
assert.match(page, /taskEvidenceDownloadUrl/, '下载必须走鉴权接口')
|
||||
assert.match(page, /deleteTaskEvidence/, '删除必须走鉴权接口')
|
||||
})
|
||||
|
||||
test('task evidence api is wired to admin endpoints', () => {
|
||||
const api = readSource('src/api/task-evidence.ts')
|
||||
assert.match(api, /\/admin\/task-evidence\/files/)
|
||||
assert.match(api, /\/admin\/task-evidence\/download\?fileId=/)
|
||||
assert.match(api, /\/admin\/task-evidence\/delete/)
|
||||
})
|
||||
Reference in New Issue
Block a user