768ad53fe2
build / build (push) Successful in 1m49s
- clear 不再把 internal_kb_name / external_kb_name 写成空串:改取事务内锁定行的 旧值,且只在库 ID 未变时沿用(同时改指向又清密钥不会把旧库名贴到新库上); 生产侧一并保留已冻结的实例地址与租户,执行器的实例一致性检查不会把「只是没 密钥」误判成换了实例 - 存量集成用例对齐「留空 = 取消绑定」新语义:只填一端保存成功、该侧为空、回退 来源字段写明回退到哪、revision 递增,后续修订期望随之前移 - 新增真实库用例:clear 后 key_configured=false、verification=not_configured、 名称/库 ID/租户不变、Resolve() 返回 ErrNotConfigured、历史表只记布尔无密钥 - 前端清密钥用例补充断言:请求带当前库 ID,页面仍显示名称而不回落短 ID
276 lines
10 KiB
TypeScript
276 lines
10 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,
|
|
key_tail: '9f2c',
|
|
internal_fallback: '',
|
|
external_fallback: '',
|
|
frozen: 0,
|
|
retargetable: 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('allows clearing one direction and says where the empty side falls back', async () => {
|
|
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 Promise.resolve(json(catalog))
|
|
return Promise.resolve(json({ data: binding('test') }))
|
|
})
|
|
)
|
|
await render()
|
|
await click('验证并读取知识库')
|
|
await choose('对内知识库', 'kb-new-in-0001')
|
|
await choose('对外知识库', '')
|
|
const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
|
|
// 留空 = 取消绑定:允许保存,但必须说清回退到哪里。
|
|
expect(save?.hasAttribute('disabled')).toBe(false)
|
|
expect(host.textContent).toContain('留空 = 取消该方向绑定')
|
|
await choose('对外知识库', 'kb-new-in-0001')
|
|
// 两边同一个库仍然不允许保存。
|
|
expect(save?.hasAttribute('disabled')).toBe(true)
|
|
})
|
|
|
|
it('clears the key through the dedicated action, not by saving a blank draft', async () => {
|
|
const put = vi
|
|
.fn()
|
|
.mockResolvedValue(
|
|
json({ data: { ...binding('test'), key_configured: false, key_tail: '', verification: 'not_configured' } })
|
|
)
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn((url: string, init?: RequestInit) => {
|
|
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 put(url, init)
|
|
return Promise.resolve(json({ data: binding('test') }))
|
|
})
|
|
)
|
|
vi.stubGlobal('confirm', () => true)
|
|
await render()
|
|
const clear = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('清除密钥'))
|
|
expect(clear).toBeTruthy()
|
|
await act(async () => {
|
|
clear!.dispatchEvent(new MouseEvent('click', { bubbles: true }))
|
|
})
|
|
expect(put).toHaveBeenCalled()
|
|
const body = JSON.parse(String((put.mock.calls[0][1] as { body: string }).body))
|
|
expect(body.key_action).toBe('clear')
|
|
expect(body.api_key).toBeUndefined()
|
|
// 清密钥只清凭据:请求带上当前的库 ID,页面随后仍显示名称而不是回落短 ID。
|
|
expect(body.internal_kb_id).toBe('kb-test-in-0001')
|
|
expect(body.external_kb_id).toBe('kb-test-out-0001')
|
|
expect(host.textContent).toContain('test 内部资料')
|
|
expect(host.textContent).toContain('test 对外资料')
|
|
expect(host.textContent).toContain('test 内部资料(kb-test-…)')
|
|
expect(host.textContent).toContain('test 对外资料(kb-test-…)')
|
|
})
|
|
|
|
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)
|
|
})
|
|
})
|