gongxiangp2/app/api/materials/upload/file-name.integration.test.ts

103 lines
4.1 KiB
TypeScript

/** @jest-environment node */
import { mkdtemp, readFile, rm } from 'fs/promises'
import os from 'os'
import path from 'path'
import { getServerSession } from 'next-auth'
import { NextRequest } from 'next/server'
import { POST as init } from './init/route'
import { POST as chunk } from './chunk/route'
import { POST as complete } from './complete/route'
import { cleanupConsumedUploadSession } from '@/lib/temp-cleanup'
import { getOwnedUploadSession, getUploadedFile, resolveOwnedMergedUpload } from '@/lib/upload-sessions'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
function jsonRequest(endpoint: string, body: object) {
return new NextRequest(`http://localhost/api/materials/upload/${endpoint}`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
})
}
describe('分片上传展示名与实际文件路径', () => {
const content = Buffer.from('source-content')
const owner = 'user-1'
let uploadRoot: string
const previousUploadDir = process.env.UPLOAD_DIR
beforeEach(async () => {
uploadRoot = await mkdtemp(path.join(os.tmpdir(), 'upload-file-name-'))
process.env.UPLOAD_DIR = uploadRoot
jest.mocked(getServerSession).mockResolvedValue({ user: { id: owner } })
})
afterEach(async () => {
if (previousUploadDir === undefined) delete process.env.UPLOAD_DIR
else process.env.UPLOAD_DIR = previousUploadDir
await rm(uploadRoot, { recursive: true, force: true })
})
async function upload(fileName: string) {
const response = await init(jsonRequest('init', {
fileName, fileSize: content.length, totalChunks: 1,
}))
const body = await response.json()
expect(body).toEqual({ uploadId: expect.any(String) })
expect(response.status).toBe(200)
const chunkResponse = await chunk(new NextRequest('http://localhost/api/materials/upload/chunk', {
method: 'POST',
headers: {
'content-type': 'application/octet-stream',
'content-length': String(content.length),
'x-upload-id': body.uploadId,
'x-chunk-index': '0',
'x-chunk-size': String(content.length),
'x-file-name': encodeURIComponent(fileName),
},
body: content,
}))
expect(chunkResponse.status).toBe(200)
return body.uploadId as string
}
test.each([
`ZH-GBSFY-${'SJ045004N1410V01-1-'.repeat(18)}组合款...psd`,
`${'文'.repeat(254)}ab.psb`,
'a..b.jpg',
])('init、分片、合并与重试完整保留名称 %s', async (fileName) => {
const uploadId = await upload(fileName)
const first = await complete(jsonRequest('complete', { uploadId }))
const firstBody = await first.json()
expect(firstBody).toMatchObject({ fileName, fileSize: content.length, uploadId })
expect(first.status).toBe(200)
const mergedPath = firstBody.existingFilePath
expect(Buffer.byteLength(path.basename(mergedPath))).toBeLessThanOrEqual(200)
expect(path.extname(mergedPath)).toBe(path.extname(fileName))
await expect(readFile(mergedPath)).resolves.toEqual(content)
const retry = await complete(jsonRequest('complete', { uploadId }))
expect(retry.status).toBe(200)
await expect(retry.json()).resolves.toEqual(firstBody)
await expect(resolveOwnedMergedUpload({ existingFilePath: mergedPath, userId: owner, uploadId }))
.resolves.toMatchObject({ session: { fileName } })
})
test('产品包组装后按会话名清理长中文文件', async () => {
const fileName = `${'组合源文件'.repeat(30)}...psd`
const uploadId = await upload(fileName)
await expect(getOwnedUploadSession(uploadId, owner)).resolves.toMatchObject({ fileName })
const assembledPath = await getUploadedFile(uploadId)
expect(assembledPath).toBe(path.join(uploadRoot, 'assembled', `${uploadId}.psd`))
await expect(readFile(assembledPath!)).resolves.toEqual(content)
await expect(getUploadedFile(uploadId)).resolves.toBe(assembledPath)
await cleanupConsumedUploadSession(uploadId)
await expect(readFile(assembledPath!)).rejects.toMatchObject({ code: 'ENOENT' })
})
})