Files
crawler-plugin/frontend-vue/tests/mount/密钥面板青果检测.mount.test.ts
T
huangzd1997 a10aa6bda3 feat(用户端): 密钥设置面板 LLM 两卡加人民币余额行,与代理余量同形
现状纠偏(写死免得下次重研):桌面壳加载的是 frontend-vue 的 Vue SPA(app_client/blueprints/main.py:52 供产物、
config.py:96 WEB_HOME_URL 直载),所谓"客户端密钥设置"不在 Python 里;而密钥明文只在后端(前端手里只有掩码),
所以余额必须由后端查、前端不自打上游——本面只消费 GET /api/user-secrets/llm-balance。

- 新建 SecretBalanceRow.vue:根元素就是 <div class="secret-meta">,保住既有挂载测试按 .secret-meta 取数的断言不破;
  LLM 卡插一行、代理卡那 8 行 div 换成同一组件 ⇒ 两卡同形自动达成。面板 763→789 行,在 800 报警线内,
  可读棘轮基线不用动(该文件本就未点名)。
- 新建 shared/utils/llm-balance-text.ts(零依赖纯函数,node --test 直测)+ shared/composables/useLlmBalance.ts
  (按 moduleKey 存 items、三态文案、available=false 原样透出后端 message)。不引任何汇率乘算:绊线
  tests/llm-balance-text.test.ts 里钉住源码不得出现 7.2/per_usd 类字样——换算只在上游 credits.per_usd 里。
- loadLlmBalance() 移出 if (props.showProxy):原形状下 LLM 卡永远空白。刷新时机=挂载、保存该模块后、清空后、
  「检测已存值」后;⚠ 刻意不在「检测输入框未保存值」后刷——checkMyApiSecret(moduleKey,value) 探的是没落库的那把
  key,而余额读服务端已存密钥,刷出来是上一把 key 的钱挂在新渠道名下=串档形状(同一格绊线盯着这条)。
- 不动 ProxyBalanceAlert.vue / utils/proxy-balance-alert.ts:没要求告警,引阈值就是自造口径。
- 复用 jikip 那套 VO 的 surplus/scope/low 语义不 borrow 给 LLM(铁律 25):types/modules/user-secret.ts 里
  新类型与 :48-59 的 jikip VO 并置但互不相通。

测试:tests/llm-balance-text.test.ts 10 例(含源码绊线:面板行数<800、useLlmBalance 无汇率乘算、检测输入值路径
不触发 loadLlmBalance)+ tests/mount/密钥面板余额显示.mount.test.ts 11 例(两 LLM 卡各有 .secret-meta;龙抬头行
含 ¥+「龙抬头」、贞贞行含「不提供余额查询」且不含 ¥;两卡夹具给不同数字并交叉断言不互串;代理余量文案未变);
endpoints.test.ts 金样加一行;两支既有挂载夹具补 fetchLlmBalanceSafely 默认值。
catch-silence 棘轮:useLlmBalance.ts 那一枚 catch 的**首条语句是界面可见出口**(清空该 moduleKey 的展示),
console.warn 留在其后——按"首条即 log 才算静默"的口径它不该入账,实测入账了就把 blocks 311→312 如实登记并写明
理由,不删那个 catch(删了就是把失败读成"没有这一项")。vue-tsc rc=0、node --test 1018 例、vitest 66 例。
2026-11-05 12:03:14 +08:00

293 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 密钥设置面板「代理」那一张卡的挂载用例(2026-11-02 三件事:放开青果检测、结果文案以接口为准、
* 卡片货源标签按供应商)。判的是运行时行为,不是读源码形状。
*
* 四组靶子:
* ① 青果不再被 `proxyProvider === 'qingguo'` 排除在「检测」之外:按钮可点、文案不许说「无需检测」;
* ② 未保存状态下点检测,送出去的是 composeQingguoLink(账密) 现拼的那条(与保存路径同一个出处),
* 没改动时送 undefined 让服务端检库里那条——后端列表读路已套 maskProxy,前端拿不到链接原文;
* ③ 结果文案一律用接口返回的 checkMessage 原文:channel_busy(后端落 error 档)必须是「可重试」语气
* (黄,不是红),也不许被吞成「无法判定」(用户报的就是这个现象);
* ④ 余量按供应商显示;查不到时说人话(不是「不支持」、也不是笼统「暂不可用」)。
*
* ⚠ 用例里的账密一律是假值(fakekey/fakepwd),真实凭据不得进任何跟踪件。
*
* 跑法:`npx vitest run tests/mount/密钥面板青果检测.mount.test.ts`
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ApiSecretSettingsPanel from '@/shared/components/ApiSecretSettingsPanel.vue'
import { composeQingguoLink } from '@/shared/utils/qingguo-link'
const UID = '1301'
const FAKE_KEY = 'fakekey'
const FAKE_PWD = 'fakepwd'
/** 后端为「通道被占」发的独立码与文案(措辞权威在后端 UserApiSecretCheckService)。 */
const CHANNEL_BUSY_MESSAGE = '青果通道正被你自己的采集占着,等约 3 分钟释放后再点检测'
const message = vi.hoisted(() => ({
error: vi.fn(),
warning: vi.fn(),
success: vi.fn(),
info: vi.fn(),
}))
const store = vi.hoisted(() => ({
checkApiSecret: vi.fn(),
clearApiSecret: vi.fn(),
getServerProxySnapshot: vi.fn(),
getStoredApiSecretSnapshot: vi.fn(),
listApiSecretModules: vi.fn(),
loadApiSecrets: vi.fn(),
saveApiSecret: vi.fn(),
subscribeApiSecrets: vi.fn(),
fetchProxyBalanceSafely: vi.fn(),
fetchLlmBalanceSafely: vi.fn(),
}))
const secretApi = vi.hoisted(() => ({
putMyApiSecret: vi.fn(),
deleteMyApiSecret: vi.fn(),
fetchProxyPlan: vi.fn(),
saveProxyPlan: vi.fn(),
clearProxyPlan: vi.fn(),
}))
const bridge = vi.hoisted(() => ({
readConfig: vi.fn(),
saveConfig: vi.fn(),
}))
vi.mock('element-plus', () => ({ ElMessage: message }))
vi.mock('@/shared/utils/api-secret-store', () => ({
checkApiSecret: store.checkApiSecret,
clearApiSecret: store.clearApiSecret,
getServerProxySnapshot: store.getServerProxySnapshot,
getStoredApiSecretSnapshot: store.getStoredApiSecretSnapshot,
listApiSecretModules: store.listApiSecretModules,
loadApiSecrets: store.loadApiSecrets,
saveApiSecret: store.saveApiSecret,
subscribeApiSecrets: store.subscribeApiSecrets,
fetchProxyBalanceSafely: store.fetchProxyBalanceSafely,
fetchLlmBalanceSafely: store.fetchLlmBalanceSafely,
}))
vi.mock('@/shared/api/types/modules/user-secret', () => ({
putMyApiSecret: secretApi.putMyApiSecret,
deleteMyApiSecret: secretApi.deleteMyApiSecret,
fetchProxyPlan: secretApi.fetchProxyPlan,
saveProxyPlan: secretApi.saveProxyPlan,
clearProxyPlan: secretApi.clearProxyPlan,
}))
vi.mock('@/shared/bridges/pywebview', () => ({
getPywebviewApi: () => ({ read_config: bridge.readConfig, save_config: bridge.saveConfig }),
}))
function emptySnapshot() {
return {
value: '', masked: '', channel: '', exists: false, locked: false,
checkStatus: 'unknown', checkCode: '', checkMessage: '',
checkLatencyMs: null, checkedAt: null, updatedAt: null,
}
}
/** 本机已存过青果账密(proxy_users[uid]):桌面桥读得到的就是这份。 */
function qingguoConfig() {
return {
proxy_users: {
[UID]: {
proxy_url: '', proxy_mode: 2, proxy_provider: 'qingguo',
proxy_account: FAKE_KEY, proxy_password: FAKE_PWD,
},
},
}
}
function checkResult(over: Record<string, unknown> = {}) {
return {
moduleKey: 'proxy',
checkStatus: 'passed',
checkCode: 'ok',
checkMessage: '连通正常',
checkLatencyMs: 120,
checkedAt: null,
viaProxy: false,
...over,
}
}
async function mountPanel() {
wrapper = mount(ApiSecretSettingsPanel)
await flushPromises()
await flushPromises()
return wrapper!
}
/** 代理是最后一张卡:它的动作区与余量行都落在这一张里。 */
function proxyCard(panel: VueWrapper) {
const cards = panel.findAll('.secret-card')
return cards[cards.length - 1]
}
function proxyCheckButton(panel: VueWrapper) {
return proxyCard(panel).findAll('.check-btn')[0]
}
function proxyResultText(panel: VueWrapper) {
return proxyCard(panel).find('.check-result')
}
beforeEach(() => {
localStorage.clear()
localStorage.setItem('uid', UID)
vi.clearAllMocks()
store.listApiSecretModules.mockReturnValue([
{ moduleKey: 'appearance-patent', moduleLabel: '外观专利密钥' },
{ moduleKey: 'similar-asin', moduleLabel: '货源查询密钥' },
])
store.getStoredApiSecretSnapshot.mockReturnValue(emptySnapshot())
store.getServerProxySnapshot.mockReturnValue(null)
store.subscribeApiSecrets.mockReturnValue(() => undefined)
store.loadApiSecrets.mockResolvedValue('complete')
store.checkApiSecret.mockResolvedValue(checkResult())
store.fetchProxyBalanceSafely.mockResolvedValue({
available: true, surplus: '12', balance: '34', message: null, scope: 'user', low: false, lowReason: null,
})
// 本文件的靶子是代理那一张卡;LLM 余额回空数组即可(面板按「没查到」显示,不参与这里的任何断言)
store.fetchLlmBalanceSafely.mockResolvedValue([])
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
bridge.readConfig.mockResolvedValue(qingguoConfig())
bridge.saveConfig.mockResolvedValue(undefined)
})
let wrapper: VueWrapper | null = null
afterEach(() => {
wrapper?.unmount()
wrapper = null
})
describe('青果放开检测:按钮、送检链接与结果文案', () => {
it('青果选中时「检测」可点,且不再自称「无需检测」', async () => {
const panel = await mountPanel()
const button = proxyCheckButton(panel)
expect(button.attributes('disabled')).toBeUndefined()
expect(button.text()).not.toContain('无需检测')
expect(button.text()).toContain('检测配置代理')
expect(panel.html()).not.toContain('青果账密直连,无需检测')
})
it('没改动时送 undefined:服务端用它库里存的那条(链接原文已不下发前端)', async () => {
const panel = await mountPanel()
await proxyCheckButton(panel).trigger('click')
await flushPromises()
expect(store.checkApiSecret).toHaveBeenCalledWith('proxy', undefined, 'qingguo')
})
it('改了账密没保存就送现拼链接(与保存路径同一个 composeQingguoLink 出处)', async () => {
const panel = await mountPanel()
const accountInput = proxyCard(panel).findAll('input')[0]
await accountInput.setValue(`${FAKE_KEY}X`)
expect(proxyCheckButton(panel).text()).toContain('检测输入账密(未保存)')
await proxyCheckButton(panel).trigger('click')
await flushPromises()
const sent = store.checkApiSecret.mock.calls[0]?.[1] as string
expect(sent, '送检值必须逐字节等于拼装出处的输出').toBe(
composeQingguoLink(`${FAKE_KEY}X`, FAKE_PWD),
)
expect(sent).toContain('overseas.proxy.qg.net')
expect(message.success).toHaveBeenCalledWith('输入值连通正常(未保存)')
})
it('账密被清空时拦住这一次必然失败的检测(空串≠"用库里的值")', async () => {
const panel = await mountPanel()
const accountInput = proxyCard(panel).findAll('input')[0]
await accountInput.setValue('')
await proxyCheckButton(panel).trigger('click')
await flushPromises()
expect(store.checkApiSecret, '拼不出链接就不该发检测,否则服务端检的是库里那条旧链接').not.toHaveBeenCalled()
expect(message.warning).toHaveBeenCalled()
})
it('channel_busy:文案用接口原文,语气是可重试(黄),不是红色密钥错误也不是「无法判定」', async () => {
store.checkApiSecret.mockResolvedValue(checkResult({
checkStatus: 'error',
checkCode: 'channel_busy',
checkMessage: CHANNEL_BUSY_MESSAGE,
checkLatencyMs: null,
}))
const panel = await mountPanel()
await proxyCheckButton(panel).trigger('click')
await flushPromises()
const result = proxyResultText(panel)
expect(result.text()).toContain(CHANNEL_BUSY_MESSAGE)
expect(result.text()).not.toContain('无法判定')
expect(result.classes()).toContain('check-result--warn')
expect(result.classes()).not.toContain('check-result--fail')
})
it('failed 才标红,且仍原样显示接口给的文案', async () => {
store.checkApiSecret.mockResolvedValue(checkResult({
checkStatus: 'failed',
checkCode: 'invalid_key',
checkMessage: '青果密钥不可用或已失效(INVALID_KEY),请核对提取链接里的 key',
}))
const panel = await mountPanel()
await proxyCheckButton(panel).trigger('click')
await flushPromises()
const result = proxyResultText(panel)
expect(result.text()).toContain('青果密钥不可用或已失效(INVALID_KEY)')
expect(result.classes()).toContain('check-result--fail')
})
it('接口没给文案时才兜底:error 档兜「稍后再点一次」,不再回落到「无法判定」', async () => {
store.checkApiSecret.mockResolvedValue(checkResult({
checkStatus: 'error', checkCode: 'timeout', checkMessage: '',
}))
const panel = await mountPanel()
await proxyCheckButton(panel).trigger('click')
await flushPromises()
const text = proxyResultText(panel).text()
expect(text).toContain('稍后可以再点一次检测')
expect(text).not.toContain('无法判定')
})
})
describe('货源标签与代理余量:按供应商,不套 LLM 渠道字典', () => {
it('代理卡标题下的货源是供应商名(青果),不是 LLM 渠道名', async () => {
const panel = await mountPanel()
expect(proxyCard(panel).find('.source-tag').text()).toBe('青果')
expect(proxyCard(panel).text(), '代理卡里不许出现 LLM 渠道选项').not.toContain('贞贞')
})
it('余量行按当前供应商显示,并按 scope 说明是谁的池子', async () => {
const panel = await mountPanel()
expect(proxyCard(panel).find('.secret-meta').text()).toContain('青果余量(你的套餐)')
expect(proxyCard(panel).find('.secret-meta').text()).toContain('套餐IP 12')
})
it('available=false:把后端给的原因原样摆出来,不说成「该供应商不支持」', async () => {
store.fetchProxyBalanceSafely.mockResolvedValue({
available: false, surplus: null, balance: null, message: '尚未配置套餐,按平台套餐也读不到', scope: null,
})
const panel = await mountPanel()
const meta = proxyCard(panel).find('.secret-meta').text()
expect(meta).toContain('尚未配置套餐,按平台套餐也读不到')
expect(meta).not.toContain('暂不可用')
})
})