gongxiangp2/lib/__tests__/standard-model-white-background-upload-guard.test.ts

112 lines
2.9 KiB
TypeScript

/** @jest-environment node */
import sharp from 'sharp'
import {
assertWhiteBackgroundImageDimensions,
assertWhiteBackgroundUploadFiles,
STANDARD_MODEL_WHITE_BG_UPLOAD_LIMITS,
WhiteBackgroundUploadValidationError,
} from '@/lib/standard-model-white-background-upload-guard'
describe('standard model white-background upload guard', () => {
async function createPngFile(name = 'white-bg.png') {
const buffer = await sharp({
create: {
width: 4,
height: 4,
channels: 3,
background: '#ffffff',
},
}).png().toBuffer()
return new File(
[buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) as ArrayBuffer],
name,
{ type: 'image/png' },
)
}
test('接受单页且在大小和像素预算内的图片', async () => {
const file = await createPngFile()
await expect(
assertWhiteBackgroundUploadFiles({
fixedImages: { rightFront45: file },
otherImages: [],
}),
).resolves.toBeUndefined()
})
test('拒绝伪装成图片的不可解码内容', async () => {
const file = new File(
['not-an-image'],
'fake.png',
{ type: 'image/png' },
)
await expect(
assertWhiteBackgroundUploadFiles({
fixedImages: { rightFront45: file },
otherImages: [],
}),
).rejects.toThrow('无法读取或像素总量过大')
})
test('拒绝非白名单 MIME 类型', async () => {
const file = new File(
['image'],
'unsafe.svg',
{ type: 'image/svg+xml' },
)
await expect(
assertWhiteBackgroundUploadFiles({
fixedImages: { rightFront45: file },
otherImages: [],
}),
).rejects.toThrow('格式不支持')
})
test('拒绝超过其他图片数量上限的请求', async () => {
const files = Array.from(
{ length: STANDARD_MODEL_WHITE_BG_UPLOAD_LIMITS.maxOtherImages + 1 },
(_, index) => new File(
['x'],
`other-${index}.png`,
{ type: 'image/png' },
),
)
await expect(
assertWhiteBackgroundUploadFiles({
fixedImages: {},
otherImages: files,
}),
).rejects.toThrow('其他图片最多上传')
})
test('在解码前拒绝超过单文件体积上限的图片', async () => {
const file = new File(
[new Uint8Array(STANDARD_MODEL_WHITE_BG_UPLOAD_LIMITS.maxBytesPerImage + 1)],
'too-large.png',
{ type: 'image/png' },
)
await expect(
assertWhiteBackgroundUploadFiles({
fixedImages: { rightFront45: file },
otherImages: [],
}),
).rejects.toThrow('不能超过 20MB')
})
test('拒绝超过单图像素上限的尺寸', () => {
expect(() =>
assertWhiteBackgroundImageDimensions(
STANDARD_MODEL_WHITE_BG_UPLOAD_LIMITS.maxPixelsPerImage + 1,
1,
'测试图片',
),
).toThrow(WhiteBackgroundUploadValidationError)
})
})