gongxiangp2/lib/__tests__/taobao-image-proxy-route.test.ts
chenpei 7326e273e1 fix: harden media upload and release safety
Protect upload cleanup and atomic completion paths, add durable media worker leases and brand asset validation, and introduce verified migration/bootstrap/deployment gates.
2026-08-12 18:04:08 +08:00

96 lines
2.6 KiB
TypeScript

/** @jest-environment node */
import { GET } from '@/app/api/taobao-detail-plus/image-proxy/route'
import { getServerSession } from 'next-auth'
import sharp from 'sharp'
jest.mock('next-auth', () => ({
getServerSession: jest.fn(),
}))
jest.mock('@/lib/auth', () => ({
authOptions: {},
}))
describe('taobao image proxy route', () => {
beforeEach(() => {
jest.clearAllMocks()
;(getServerSession as jest.Mock).mockResolvedValue({
user: { id: 'user-1', name: 'tester' },
})
global.fetch = jest.fn() as jest.Mock
})
function createRequest(url: string) {
return {
nextUrl: new URL(url),
} as any
}
test('未登录时应返回 401', async () => {
;(getServerSession as jest.Mock).mockResolvedValue(null)
const response = await GET(
createRequest(
'https://example.com/api/taobao-detail-plus/image-proxy?url=https%3A%2F%2Fimg.alicdn.com%2Fa.png',
),
)
const body = await response.json()
expect(response.status).toBe(401)
expect(body.error.code).toBe('UNAUTHORIZED')
})
test('图片来源域名不允许时应返回 400', async () => {
const response = await GET(
createRequest(
'https://example.com/api/taobao-detail-plus/image-proxy?url=https%3A%2F%2Fevil.example.com%2Fa.png',
),
)
const body = await response.json()
expect(response.status).toBe(400)
expect(body.error.code).toBe('IMAGE_HOST_NOT_ALLOWED')
})
test('允许的图片地址应返回 png 数据', async () => {
const upstreamBuffer = await sharp({
create: {
width: 1,
height: 1,
channels: 4,
background: { r: 255, g: 255, b: 255, alpha: 1 },
},
}).png().toBuffer()
;(global.fetch as jest.Mock).mockResolvedValue(
new Response(Uint8Array.from(upstreamBuffer), {
status: 200,
headers: {
'content-length': String(upstreamBuffer.length),
'content-type': 'image/png',
},
}),
)
const response = await GET(
createRequest(
'https://example.com/api/taobao-detail-plus/image-proxy?url=https%3A%2F%2Fimg.alicdn.com%2Fa.png',
),
)
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toBe('image/png')
expect(Number(response.headers.get('x-image-width'))).toBeGreaterThan(0)
expect(Number(response.headers.get('x-image-height'))).toBeGreaterThan(0)
const bodyBuffer = Buffer.from(await response.arrayBuffer())
expect(bodyBuffer.length).toBeGreaterThan(0)
expect(global.fetch).toHaveBeenCalledWith(
'https://img.alicdn.com/a.png',
expect.objectContaining({
method: 'GET',
}),
)
})
})