Files
knowledge-governance/web/src/KnowledgeBaseBinding.test.tsx
T
姚章浩 ce2a155ebc feat(settings): 知识库绑定按环境一次保存连接与内外库
原「知识库映射 → WeKnora 连接」把地址、文件和绑定分散在多处,页面无法输入密钥,
也看不到候选实例真实可读的库。现在测试 090 / 生产 090 各自一个工作区:草稿填地址
与 API Key,服务器真实分页列库并区分空库/无权限/不可达,选内外库后一次保存连接与
绑定,回读真实生效值。

服务端以修订号 + 行锁 + 单事务写连接、绑定与待入库重排;旧部署无新行时继续使用文件
凭据/默认绑定。密钥只存 AES-256-GCM 密文,主密钥在独立文件;换地址必须重录,旧密钥
不转发、不跨环境取用。消费端(readiness/上传轮询/列库/探活/生产列库)统一从该存储
解析当前连接,避免只保存了页面数据。

验证:go test ./...;前端 606 项;隔离 PostgreSQL 集成用例覆盖保存/冲突/重排/拒错;
make verify 在本提交上执行(结果见交付说明)。
2026-11-19 14:51:47 +08:00

214 lines
7.6 KiB
TypeScript

// @vitest-environment jsdom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { AuthContext } from './auth'
import { KnowledgeBaseBinding } from './KnowledgeBaseBinding'
import type { KBEnvironmentBinding } from './knowledgeBaseBindings'
const binding = (environment: 'test' | 'production'): KBEnvironmentBinding => ({
environment,
revision: 1,
base_url: `https://${environment}.weknora.example`,
key_configured: true,
key_source: 'sealed',
internal_kb_id: `kb-${environment}-in-0001`,
internal_kb_name: `${environment} 内部资料`,
external_kb_id: `kb-${environment}-out-0001`,
external_kb_name: `${environment} 对外资料`,
verification: 'verified',
checked_at: null,
updated_by: 'admin',
updated_at: null,
source: 'web',
storage_ready: true,
replanned: 0,
retired_duplicates: 0,
})
const snapshot = {
data: { environments: [binding('test'), binding('production')], storage_ready: true },
}
const catalog = {
data: {
status: 'ok',
message: '已读取 2 个知识库',
page: 1,
page_size: 20,
total: 2,
options: [
{ id: 'kb-new-in-0001', name: '新内部库', knowledge_count: 3 },
{ id: 'kb-new-out-0001', name: '新对外库', knowledge_count: 4 },
],
},
}
const json = (value: unknown, status = 200) => ({
ok: status >= 200 && status < 300,
status,
json: async () => value,
})
const auth = (role: 'admin' | 'viewer') => ({
identity: { id: `${role}-1`, username: role, display_name: role, role, must_change_password: false },
ready: true,
login: async () => null,
logout: async () => {},
changePassword: async () => null,
signedOut: 0,
notifySignedOut: () => {},
})
let root: Root
let host: HTMLDivElement
const flush = async () => {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0))
})
}
const click = async (label: string) => {
const button = [...host.querySelectorAll('button')].find((item) => item.textContent?.trim() === label)
expect(button, label).toBeTruthy()
await act(async () => button!.click())
await flush()
}
const choose = async (label: string, value: string) => {
const select = [...host.querySelectorAll('label')]
.find((item) => item.textContent?.startsWith(label))
?.querySelector('select')
expect(select, label).toBeTruthy()
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'value')!.set!.call(select, value)
select!.dispatchEvent(new Event('change', { bubbles: true }))
})
}
const type = async (label: string, value: string) => {
const input = [...host.querySelectorAll('label')]
.find((item) => item.textContent?.startsWith(label))
?.querySelector('input')
expect(input, label).toBeTruthy()
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value)
input!.dispatchEvent(new Event('input', { bubbles: true }))
})
}
beforeEach(() => {
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
host = document.createElement('div')
document.body.append(host)
root = createRoot(host)
})
afterEach(async () => {
await act(async () => root.unmount())
host.remove()
vi.unstubAllGlobals()
})
const render = async (role: 'admin' | 'viewer' = 'admin') => {
await act(async () => {
root.render(
<AuthContext.Provider value={auth(role)}>
<KnowledgeBaseBinding />
</AuthContext.Provider>
)
})
await flush()
}
describe('KnowledgeBaseBinding', () => {
it('switches environments without letting a late catalog response cross over', async () => {
let resolveCatalog: ((value: unknown) => void) | null = null
vi.stubGlobal(
'fetch',
vi.fn((url: string) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
if (String(url).includes('/catalog')) {
return new Promise((resolve) => {
resolveCatalog = resolve
})
}
return Promise.resolve(json({ data: binding('test') }))
})
)
await render()
expect(host.textContent).toContain('当前生效 · 测试 090')
expect(host.textContent).toContain('test 内部资料(kb-test-…)')
await click('验证并读取知识库')
await click('生产 090')
expect(host.textContent).toContain('当前生效 · 生产 090')
expect(host.textContent).toContain('production 内部资料')
await act(async () => {
resolveCatalog?.(json(catalog))
})
await flush()
// 迟到的测试环境列库结果不得出现在生产工作区。
expect(host.textContent).not.toContain('新内部库')
expect(host.textContent).toContain('production 内部资料')
})
it('keeps the old binding visible when a save fails and never applies an unsaved draft', async () => {
const fetchMock = vi.fn((url: string, init?: { method?: string }) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
if (init?.method === 'PUT') return Promise.resolve(json({ error: '候选实例拒绝保存' }, 400))
return Promise.resolve(json({ data: binding('test') }))
})
vi.stubGlobal('fetch', fetchMock)
await render()
await click('验证并读取知识库')
await choose('对内知识库', 'kb-new-in-0001')
await choose('对外知识库', 'kb-new-out-0001')
expect(host.textContent).toContain('有未保存的修改')
await click('保存测试绑定')
expect(host.textContent).toContain('候选实例拒绝保存')
// 顶部当前生效仍是旧值;草稿只存在于下方。
expect(host.textContent).toContain('test 内部资料(kb-test-…)')
expect(host.textContent).not.toContain('当前生效 · 测试 090新内部库')
const put = fetchMock.mock.calls.find((call) => call[1]?.method === 'PUT')
expect(put).toBeTruthy()
const body = JSON.parse(String((put![1] as { body: string }).body))
expect(body).toMatchObject({
base_revision: 1,
base_url: 'https://test.weknora.example',
key_action: 'keep',
internal_kb_id: 'kb-new-in-0001',
external_kb_id: 'kb-new-out-0001',
})
expect(body.api_key).toBeUndefined()
})
it('gives viewers a read-only summary with no editing inputs', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot)))
await render('viewer')
expect(host.textContent).toContain('普通用户只读')
expect(host.textContent).toContain('当前生效 · 测试 090')
expect(host.querySelectorAll('input')).toHaveLength(0)
expect(
[...host.querySelectorAll('button')].every((button) =>
['测试 090', '生产 090'].includes(button.textContent?.trim() ?? '')
)
).toBe(true)
})
it('requires a new key after the address changes and clears the previous selection', async () => {
vi.stubGlobal(
'fetch',
vi.fn((url: string) => {
if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
return Promise.resolve(json(catalog))
})
)
await render()
await type('服务地址', 'https://new.weknora.example')
expect(host.textContent).toContain('已更换服务地址:必须为新地址重新录入 API Key')
const selects = [...host.querySelectorAll('select')]
expect(selects.every((select) => select.value === '')).toBe(true)
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
expect(save?.hasAttribute('disabled')).toBe(true)
})
})