Files
2026-10-26 14:37:21 +08:00

213 lines
8.0 KiB
TypeScript

import { afterEach, expect, it, vi } from 'vitest'
import { componentGateway } from '@/application/component-gateway'
import { componentForm, emptyPartInformation } from '@/domain/component-catalog'
import { activityGateway } from '@/application/activity-gateway'
import { userGateway } from '@/application/user-gateway'
import { api, assetUrl, proxyUrl } from '@/infrastructure/admin-api'
import { clearAuthSession, readAuthSession, writeAuthSession } from '@/application/auth'
import type { ComponentDetail } from '@/domain/component-catalog'
afterEach(() => vi.unstubAllGlobals())
it('downloads STEP, URDF and meshes directly from storage without API cookies', async () => {
const fetcher = vi.fn<typeof fetch>(async () => new Response('model-file'))
vi.stubGlobal('fetch', fetcher)
const prefix = 'cadworld_dev/components/CW-123/urdf/batch/'
const item = {
stepObjectKey: 'cadworld_dev/components/CW-123/step/安装板.step',
urdfPrefix: prefix,
urdfMainObjectKey: prefix + 'urdf/躯干.urdf',
urdfFiles: [{ relativePath: 'urdf/躯干.urdf' }, { relativePath: 'meshes/底 板.STL' }],
} as ComponentDetail
const step = await componentGateway.step(item)
const files = await componentGateway.urdf(item)
expect(step.name).toBe('安装板.step')
expect(files.map((file) => file.webkitRelativePath)).toEqual([
'urdf/urdf/躯干.urdf',
'urdf/meshes/底 板.STL',
])
expect(fetcher.mock.calls.map(([url]) => url)).toEqual([
assetUrl(item.stepObjectKey),
assetUrl(prefix + 'urdf/躯干.urdf'),
assetUrl(prefix + 'meshes/底 板.STL'),
])
for (const [url, options] of fetcher.mock.calls) {
expect(String(url)).toMatch(/^https:\/\/linkerbot\.oss-cn-beijing\.aliyuncs\.com\//)
expect(options?.credentials).toBe('omit')
expect(options?.headers).toBeUndefined()
}
})
const ok = (data: unknown) => Response.json({ code: 'OK', data, requestId: 'req-123' })
it('saves complete forms with version and without old IDs, payload blobs or upload routes', async () => {
const fetcher = vi.fn<typeof fetch>(async () => ok({ id: 123, version: 2 }))
vi.stubGlobal('fetch', fetcher)
const form = componentForm({
...emptyPartInformation(),
urdfInfo: {},
name: '安装板',
category: '自由分类',
})
await componentGateway.save(form, {}, { id: 123, version: 1 })
const [url, options] = fetcher.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('/admin-api/components/123')
expect(options.method).toBe('PUT')
expect(JSON.parse(options.body as string)).toEqual({ ...form, version: 1 })
})
it('sends only document-supported search and paging fields', async () => {
const fetcher = vi.fn<typeof fetch>(async () => ok({ items: [], page: 2, size: 10, total: 0 }))
vi.stubGlobal('fetch', fetcher)
await componentGateway.list({ page: 2, size: 10, keyword: 'CW-中文', category: '安装板' })
const url = new URL(fetcher.mock.calls[0][0] as unknown as string, 'http://local')
expect(Object.fromEntries(url.searchParams)).toEqual({
page: '2',
size: '10',
keyword: 'CW-中文',
category: '安装板',
})
})
it('updates a component status through the existing component editor endpoint', async () => {
const item = {
...componentForm({ ...emptyPartInformation(), name: '安装板', category: '自由分类' }),
id: 123,
componentCode: 'CW-123',
status: 'ENABLED',
stepUrl: '/admin-api/component-assets/step/part.step',
version: 1,
createdAt: '',
updatedAt: '',
}
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(ok(item))
.mockResolvedValueOnce(ok({ ...item, status: 'DISABLED', version: 2 }))
vi.stubGlobal('fetch', fetcher)
await componentGateway.setStatus(123, 'DISABLED')
expect(fetcher.mock.calls[0][0]).toBe('/admin-api/components/123')
const [url, options] = fetcher.mock.calls[1] as unknown as [string, RequestInit]
expect(url).toBe('/admin-api/components/123')
expect(options.method).toBe('PUT')
expect(JSON.parse(options.body as string)).toEqual({
...componentForm({ ...emptyPartInformation(), name: '安装板', category: '自由分类' }),
status: 'DISABLED',
version: 1,
})
})
it('preserves revision conflict codes and backend request IDs', async () => {
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>(async () =>
Response.json(
{ code: 'COMPONENT_REVISION_CONFLICT', message: '已修改', requestId: 'conflict-1' },
{ status: 409 },
),
),
)
await expect(api('/admin-api/components/123')).rejects.toMatchObject({
status: 409,
code: 'COMPONENT_REVISION_CONFLICT',
requestId: 'conflict-1',
})
})
it('sends admin Bearer tokens without cookies and clears expired sessions on 401', async () => {
const session = {
token: 'admin-token',
tokenType: 'Bearer',
expiresAt: Date.now() + 60000,
user: { userCode: 'A', nickname: '管理员', email: 'admin@example.com' },
}
writeAuthSession(session)
const fetcher = vi.fn<typeof fetch>(async () => ok({ items: [] }))
vi.stubGlobal('fetch', fetcher)
await api('/admin-api/components')
const options = fetcher.mock.calls[0][1] as RequestInit
expect(options.credentials).toBe('omit')
expect(new Headers(options.headers).get('Authorization')).toBe('Bearer admin-token')
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>(async () =>
Response.json({ code: 'UNAUTHORIZED', message: '登录失效' }, { status: 401 }),
),
)
await expect(api('/admin-api/components')).rejects.toMatchObject({ status: 401 })
expect(readAuthSession()).toBeNull()
clearAuthSession()
})
it('keeps API routing separate and encodes object keys for direct storage downloads', () => {
expect(proxyUrl('http://127.0.0.1:8992/admin-api/component-assets/a/b')).toBe(
'/admin-api/component-assets/a/b',
)
expect(assetUrl('cadworld_dev/CW/meshes/底 板.stl')).toBe(
'https://linkerbot.oss-cn-beijing.aliyuncs.com/cadworld_dev/CW/meshes/%E5%BA%95%20%E6%9D%BF.stl',
)
})
it('passes generic module and target filters without assuming component-only IDs', async () => {
const fetcher = vi.fn<typeof fetch>(async () => ok({ items: [] }))
vi.stubGlobal('fetch', fetcher)
await activityGateway.list({
page: 1,
size: 15,
module: 'FUTURE',
action: 'PUBLISH',
targetId: 'part-abc',
targetType: 'OTHER',
targetCode: 'CODE',
keyword: '名称',
success: false,
})
const url = new URL(fetcher.mock.calls[0][0] as unknown as string, 'http://local')
expect(url.searchParams.get('targetId')).toBe('part-abc')
expect(url.searchParams.get('success')).toBe('false')
expect(url.searchParams.get('module')).toBe('FUTURE')
})
it('maps user fields to nickname/email/type/status without unsupported local fields', async () => {
const fetcher = vi.fn<typeof fetch>(async () =>
ok({
id: 1,
nickname: '小王',
email: 'xiaowang@example.com',
userType: 'NORMAL',
status: 'ACTIVE',
createdAt: '',
updatedAt: '',
}),
)
vi.stubGlobal('fetch', fetcher)
await userGateway.createUser({
name: '小王',
email: ' Xiaowang@Example.com ',
role: 'viewer',
status: 'enabled',
})
const options = fetcher.mock.calls[0][1] as unknown as RequestInit
expect(JSON.parse(options.body as string)).toEqual({
nickname: '小王',
email: 'xiaowang@example.com',
userType: 'NORMAL',
status: 'ACTIVE',
})
})
it('loads and updates user email through the detail and edit endpoints', async () => {
const fetcher = vi.fn<typeof fetch>(async () =>
ok({
id: 42,
nickname: '小王',
email: 'xiaowang@example.com',
userType: 'NORMAL',
status: 'ACTIVE',
createdAt: '',
updatedAt: '',
}),
)
vi.stubGlobal('fetch', fetcher)
const user = await userGateway.detail('42')
expect(user.email).toBe('xiaowang@example.com')
await userGateway.updateUser(user.id, { ...user, email: 'new@example.com' })
const options = fetcher.mock.calls[1][1] as unknown as RequestInit
expect(options.method).toBe('PUT')
expect(JSON.parse(options.body as string)).toMatchObject({
email: 'new@example.com',
})
})