Files
knowledge-governance/web/src/sourceConnections.test.ts
T
zheromiku f6cb90cd70 feat(web): login gate, session identity UI and member management
- main.tsx 挂 AuthProvider 门控:未登录→登录页;must_change_password→强制改密页
- 登录页/改密页/顶栏身份(头像+姓名+角色徽章+退出)按 A·Data-console token 样式
- 全局 fetch 拦截器:任意业务请求 401 自动回登录页(会话过期/被撤销不留死表单)
- 系统设置新增「成员与角色」分区(仅 admin 可见):名单、角色调整、启停、重置临时密码、新增成员
- 消灭全部手填操作人:审核/封批/确认计划集/范围规则/来源调度/UI 设置/开始处理/批量重试/
  目录差异确认共 9 处输入框删除,请求体不再携带 actor 字段(服务端从会话注入)
- 测试断言方向翻转:显式验证请求体不含 operator_ref/created_by 等字段
- 附带修复:登录失败计数 SQL 参数类型无法推断导致 500(pgx 扩展协议),显式 cast 解决

前端门禁:tsc 0 错、125 用例全绿、build 通过
2026-09-30 10:54:07 +08:00

182 lines
9.7 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from 'vitest'
import {
activateSourceSettingsRevision,
createSourceSettingsRevision,
fetchSourceConnectionList,
fetchSourceConnections,
fetchSourceScanDetail,
fetchSourceSettingsRevisions,
fetchSourceScans,
parseSourceConnectionsResponse,
parseSourceScanDetailResponse,
parseSourceScansResponse,
triggerSourceScan,
} from './sourceConnections'
afterEach(() => vi.unstubAllGlobals())
describe('parseSourceConnectionsResponse', () => {
it('normalizes only the safe source connection projection', () => {
const result = parseSourceConnectionsResponse({
data: [{
id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
schedule_configured: true, health_status: 'healthy', item_count: 42,
updated_at: '2026-09-06T01:00:00Z', base_url: 'https://secret-origin.example', secret_ref: 'secret-name',
last_scan: {
id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
completed_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip', previous_revision: 'must-strip',
},
}],
summary: { total: 1, enabled: 1, disabled: 0, healthy: 1, degraded: 0, unhealthy: 0, unknown: 0 },
})
expect(result.items).toEqual([{
id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
schedule_configured: true, health_status: 'healthy', item_count: 42,
updated_at: '2026-09-06T01:00:00Z',
last_scan: {
id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
completed_at: '2026-09-06T01:00:00Z',
},
}])
expect(result.summary.total).toBe(1)
expect(result.items[0]).not.toHaveProperty('base_url')
expect(result.items[0]).not.toHaveProperty('secret_ref')
expect(result.items[0].last_scan).not.toHaveProperty('snapshot_sha256')
})
})
describe('fetchSourceConnections', () => {
it('uses the fixed read-only source connection endpoint', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
data: [],
summary: { total: 0, enabled: 0, disabled: 0, healthy: 0, degraded: 0, unhealthy: 0, unknown: 0 },
}),
})
vi.stubGlobal('fetch', fetchMock)
await fetchSourceConnections()
expect(fetchMock).toHaveBeenCalledWith(
'/api/v1/source-connections',
expect.objectContaining({ headers: { Accept: 'application/json' } }),
)
})
})
describe('triggerSourceScan', () => {
it('posts to the encoded connection scan endpoint and normalizes the response', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending',
created_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip',
}),
})
vi.stubGlobal('fetch', fetchMock)
const scan = await triggerSourceScan('conn/a')
expect(fetchMock).toHaveBeenCalledWith('/api/v1/source-connections/conn%2Fa/scan', expect.objectContaining({ method: 'POST' }))
expect(scan).toEqual({
id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending', created_at: '2026-09-06T01:00:00Z',
})
})
})
describe('source scan history and details', () => {
const scan = {
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
snapshot_sha256: 'must-be-dropped', stable_external_id: 'must-be-dropped',
}
it('strictly parses safe history and detail projections', () => {
expect(parseSourceScansResponse({ data: [scan], total: 1, limit: 20, offset: 0 })).toEqual({
items: [{
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
}], total: 1, limit: 20, offset: 0,
})
expect(parseSourceScanDetailResponse({ data: {
...scan,
changes: [{
id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42,
created_at: '2026-09-06T06:01:00Z', previous_revision: 'must-be-dropped', observed_revision: 'must-be-dropped',
}],
}})).toEqual({
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
changes: [{ id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42, created_at: '2026-09-06T06:01:00Z' }],
})
})
it('requests connection-scoped history and details', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [scan], total: 1, limit: 20, offset: 0 }), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...scan, changes: [] } }), { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
await fetchSourceScans('conn / pp')
await fetchSourceScanDetail('conn / pp', 'scan / one')
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/source-connections/conn%20%2F%20pp/scans?limit=20&offset=0')
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/source-connections/conn%20%2F%20pp/scans/scan%20%2F%20one')
})
})
describe('V1 source settings client', () => {
it('projects the connection list without sensitive fields', async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
data: [{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z',
base_url: 'https://strip.me', secret_ref: 'strip-too' }],
}), { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
const items = await fetchSourceConnectionList()
expect(items).toEqual([{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z' }])
expect(JSON.stringify(items)).not.toContain('strip')
})
it('rejects malformed connection items', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
data: [{ id: 'x' }],
}), { status: 200 })))
await expect(fetchSourceConnectionList()).rejects.toThrow('invalid source connection item')
})
it('creates and activates revisions with intent + idempotency headers and surfaces operation', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { id: 'scr-2' }, operation: 'created' }), { status: 201 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { connection_id: 'c', revision_id: 'scr-2' }, operation: 'replayed' }), { status: 200 }))
vi.stubGlobal('fetch', fetchMock)
expect(await createSourceSettingsRevision('conn/1', { source_type: 'alist', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).toEqual({ operation: 'created', id: 'scr-2' })
expect(await activateSourceSettingsRevision('conn/1', 'scr/2')).toEqual({ operation: 'replayed', id: null })
const [createCall, activateCall] = fetchMock.mock.calls
expect(createCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions')
expect((createCall[1] as RequestInit).headers).toMatchObject({ 'X-Governance-Action': 'source-settings' })
expect(((createCall[1] as RequestInit).headers as Record<string, string>)['Idempotency-Key']).toMatch(/[0-9a-f-]{36}/)
expect(activateCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions/scr%2F2/activate')
expect(createCall[1]).not.toBe(activateCall[1])
})
it('surfaces server error details on failure', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'manual sources cannot be scheduled' }), { status: 400 })))
await expect(createSourceSettingsRevision('c', { source_type: 'manual', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled')
})
it('parses revision history strictly', async () => {
const revision = { id: 'scr-1', revision_number: 1, state: 'active', name: 'A', endpoint: 'http://x', credential_ref: 'ref', enabled: true, refresh_interval_seconds: '3600', created_by: 'z', created_at: '2026-09-12T01:00:00Z', validated_at: null, activated_at: '2026-09-12T01:00:00Z', retired_at: null }
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [revision] }), { status: 200 })))
const history = await fetchSourceSettingsRevisions('c')
expect(history[0].state).toBe('active')
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ ...revision, state: 'weird' }] }), { status: 200 })))
await expect(fetchSourceSettingsRevisions('c')).rejects.toThrow('invalid source settings revision')
})
})