99 lines
5.1 KiB
TypeScript
99 lines
5.1 KiB
TypeScript
/** @jest-environment node */
|
|
|
|
import { createHash } from 'node:crypto'
|
|
import sharp from 'sharp'
|
|
import { GET, POST } from '@/app/api/desktop/[...path]/route'
|
|
import { prisma } from '@/lib/prisma'
|
|
import type { desktopTestProductPresets } from '@/lib/desktop-client/test-presets'
|
|
|
|
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
|
|
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
|
|
jest.mock('@/lib/prisma', () => ({ prisma: { $queryRawUnsafe: jest.fn(), user: { findUnique: jest.fn() } } }))
|
|
jest.mock('@/lib/detail-generator/repository', () => ({}))
|
|
jest.mock('@/lib/detail-generator/storage', () => ({}))
|
|
jest.mock('@/lib/desktop-client/project-lifecycle', () => ({}))
|
|
|
|
const querySession = jest.mocked(prisma.$queryRawUnsafe)
|
|
const findUser = prisma.user.findUnique as jest.Mock
|
|
const context = { params: { path: ['test-product-presets'] } }
|
|
const originalEnv = process.env
|
|
const account = { username: 'owner', isActive: true, status: 'active', archivedAt: null }
|
|
|
|
function request(method = 'GET', token = `Bearer dcs_${'a'.repeat(64)}`) {
|
|
return new Request('https://materials.test/api/desktop/test-product-presets', { method, headers: { authorization: token } })
|
|
}
|
|
|
|
beforeEach(() => {
|
|
process.env = { ...originalEnv, DETAIL_GENERATOR_ENABLED: 'true' }
|
|
querySession.mockReset().mockResolvedValue([{ id: 'device', ownerId: 'owner', expiresAt: new Date(Date.now() + 25 * 86400000) }])
|
|
findUser.mockReset()
|
|
})
|
|
|
|
afterEach(() => {
|
|
process.env = originalEnv
|
|
})
|
|
|
|
test('only a valid Bearer session reaches the role check', async () => {
|
|
expect((await GET(request('GET', ''), context)).status).toBe(401)
|
|
expect(querySession).not.toHaveBeenCalled()
|
|
querySession.mockResolvedValueOnce([])
|
|
const revoked = await GET(request(), context)
|
|
expect(revoked.status).toBe(401)
|
|
expect(await revoked.json()).toHaveProperty('code', 'session_expired')
|
|
expect(findUser).not.toHaveBeenCalled()
|
|
})
|
|
|
|
test.each(['USER', 'DEPT_ADMIN', 'ADMIN', 'SYSTEM_ADMIN'])('does not disclose presets to %s', async role => {
|
|
findUser.mockResolvedValue({ ...account, role, isSuperAdmin: false })
|
|
const response = await GET(request(), context)
|
|
expect(response.status).toBe(403)
|
|
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
|
expect(await response.json()).toEqual({ error: '无权读取测试商品资料', code: 'forbidden' })
|
|
expect(findUser).toHaveBeenLastCalledWith({ where: { id: 'owner' }, select: { isSuperAdmin: true } })
|
|
})
|
|
|
|
test('checks the current super-admin flag before reading presets', async () => {
|
|
findUser.mockResolvedValueOnce({ ...account, isSuperAdmin: true }).mockResolvedValueOnce({ isSuperAdmin: false })
|
|
expect((await GET(request(), context)).status).toBe(403)
|
|
})
|
|
|
|
test('does not serve presets for other methods or subpaths', async () => {
|
|
findUser.mockResolvedValue({ ...account, isSuperAdmin: true })
|
|
expect((await POST(request('POST'), context)).status).toBe(404)
|
|
expect((await GET(request(), { params: { path: ['test-product-presets', 'images'] } })).status).toBe(404)
|
|
})
|
|
|
|
test('super admins get three complete presets with four decodable, content-addressed product photos', async () => {
|
|
findUser.mockResolvedValue({ ...account, isSuperAdmin: true })
|
|
const response = await GET(request(), context)
|
|
expect(response.status).toBe(200)
|
|
expect(response.headers.get('cache-control')).toBe('private, no-store')
|
|
const { presets } = await response.json() as ReturnType<typeof desktopTestProductPresets>
|
|
expect(presets.map(preset => preset.productBrief.barcodeEntries.length)).toEqual([1, 2, 1])
|
|
expect(new Set(presets.map(preset => preset.id)).size).toBe(3)
|
|
const sources = new Set<string>()
|
|
for (const { label, productBrief: brief, imageAssets } of presets) {
|
|
expect(label).toBeTruthy()
|
|
expect(brief).toMatchObject({ name: expect.any(String), brandId: 'ekb:brand:小壹测试', brandName: '小壹测试',
|
|
categoryId: 'ekb:category:链路验收', identifierType: 'spu', identifier: expect.stringMatching(/^XYQA-/),
|
|
intake: { templateId: 'QA-FAST-001', productValues: {
|
|
productBrand: expect.stringContaining('演示'), sellingPoints: expect.any(String), specifications: expect.any(String),
|
|
} } })
|
|
expect(brief.images).toHaveLength(brief.barcodeEntries.length)
|
|
expect(imageAssets).toHaveLength(brief.images.length)
|
|
for (const image of imageAssets) {
|
|
const bytes = Buffer.from(image.base64, 'base64')
|
|
expect(image.contentType).toBe('image/jpeg')
|
|
expect(image.source).toBe(`local:${createHash('sha256').update(bytes).digest('hex')}`)
|
|
expect(brief.images).toContainEqual(expect.objectContaining({ source: image.source, name: image.name, purpose: 'product' }))
|
|
const { info } = await sharp(bytes).raw().toBuffer({ resolveWithObject: true })
|
|
expect(info.width).toBeGreaterThanOrEqual(640)
|
|
expect(info.height).toBeGreaterThanOrEqual(640)
|
|
sources.add(image.source)
|
|
}
|
|
}
|
|
expect(sources.size).toBe(4)
|
|
expect(presets[2].productBrief.intake.productValues.sellingPoints.length).toBeGreaterThan(180)
|
|
expect(presets[2].productBrief.intake.productValues.specifications.split('\n')).toHaveLength(12)
|
|
})
|