Files
crawler-plugin/frontend-vue/tests/mount/密钥面板authpwd显隐.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

275 lines
10 KiB
TypeScript

/**
* 密钥设置面板「青果 Authpwd 眼睛」的挂载用例(2026-11-02 用户看图点名:Authkey 是明文可见的,
* Authpwd 却是 •••••••• 且没有任何查看手段,填错了只能靠猜)。
*
* 五组靶子:
* ① 默认掩码,点眼睛变明文,再点回掩码(`useSecretVisibility` 的两态开关在界面上真的成立);
* ② 切换眼睛**不动绑定值**、**不产生改动标记**、**不发保存/送检请求**(点一下眼睛就冒出
* 「检测输入账密(未保存)」=把可见性误判成用户改了代理);
* ③ 眼睛只管 Authpwd 这一格:Authkey 照旧明文、各模块密钥照旧掩码,不做全站唯一的特例化扩散;
* ④ 保存成功即回到掩码(沿用该面板「保存成功即清空输入」的口径),且输入值不丢;
* ⑤ 卸载后重新挂载(重开弹窗/换号后重读配置)不得留一个还显示着明文的重载路径。
*
* ⚠ 用例里的账密一律是假值(fakekey/fakepwd),真实凭据不得进任何跟踪件。
*
* 跑法:`npx vitest run tests/mount/密钥面板authpwd显隐.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'
const UID = '1301'
const FAKE_KEY = 'fakekey'
const FAKE_PWD = 'fakepwd'
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,
}
}
let wrapper: VueWrapper | null = null
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]
}
/** 青果账密那一行:[0]=Authkey、[1]=Authpwd。 */
function accountInput(panel: VueWrapper) {
return proxyCard(panel).findAll('input')[0]
}
function passwordInput(panel: VueWrapper) {
return proxyCard(panel).findAll('input')[1]
}
function eyeButton(panel: VueWrapper) {
return proxyCard(panel).find('.password-toggle')
}
/** 读输入框当前值:VTU 的 DOMWrapper 上没有取值的语法糖,别拿 text() 冒充。 */
function valueOf(node: { element: Element }) {
return (node.element as HTMLInputElement).value
}
function proxyCheckButton(panel: VueWrapper) {
return proxyCard(panel).findAll('.check-btn')[0]
}
async function saveAll(panel: VueWrapper, options: { requireAll?: boolean } = {}) {
const exposed = panel.vm as unknown as { saveAll: (o?: { requireAll?: boolean }) => Promise<boolean> }
const saved = await exposed.saveAll(options)
await flushPromises()
await flushPromises()
return saved
}
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.putMyApiSecret.mockResolvedValue({})
secretApi.fetchProxyPlan.mockResolvedValue({ planId: null, jikipUserId: null, configured: false })
bridge.readConfig.mockResolvedValue(qingguoConfig())
bridge.saveConfig.mockResolvedValue(undefined)
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
})
describe('Authpwd 眼睛:两态切换', () => {
it('默认掩码,点一次变明文,再点一次回掩码', async () => {
const panel = await mountPanel()
const pwd = passwordInput(panel)
expect(pwd.attributes('type')).toBe('password')
expect(eyeButton(panel).attributes('aria-pressed')).toBe('false')
await eyeButton(panel).trigger('click')
expect(pwd.attributes('type'), '点眼睛就是把这一格的 type 换掉').toBe('text')
expect(eyeButton(panel).attributes('aria-pressed')).toBe('true')
expect(eyeButton(panel).attributes('aria-label')).toBe('隐藏密码')
await eyeButton(panel).trigger('click')
expect(pwd.attributes('type')).toBe('password')
expect(eyeButton(panel).attributes('aria-pressed')).toBe('false')
})
it('切换眼睛不动绑定值、不记成改动、也不发保存或送检请求', async () => {
const panel = await mountPanel()
const pwd = passwordInput(panel)
const storageKeys = Object.keys(localStorage)
await eyeButton(panel).trigger('click')
await eyeButton(panel).trigger('click')
await flushPromises()
expect(valueOf(pwd), '可见性切换不该吃掉一个字符').toBe(FAKE_PWD)
expect(valueOf(accountInput(panel))).toBe(FAKE_KEY)
expect(proxyCheckButton(panel).text(), '点眼睛不等于「改了代理」:按钮不许开始自称检的是未保存输入值')
.toContain('检测配置代理')
expect(store.checkApiSecret).not.toHaveBeenCalled()
expect(bridge.saveConfig).not.toHaveBeenCalled()
expect(secretApi.putMyApiSecret).not.toHaveBeenCalled()
expect(Object.keys(localStorage), '「用户点了显示密码」不配拥有一个持久化键').toEqual(storageKeys)
})
it('只切 Authpwd 这一格:Authkey 照旧明文、模块密钥照旧掩码', async () => {
const panel = await mountPanel()
await eyeButton(panel).trigger('click')
expect(passwordInput(panel).attributes('type')).toBe('text')
expect(accountInput(panel).attributes('type')).toBe('text')
for (const card of panel.findAll('.secret-card').slice(0, -1)) {
expect(card.find('input').attributes('type'), '别的密钥不跟着这次改动放开').toBe('password')
}
})
})
describe('Authpwd 眼睛:复位口径', () => {
it('保存成功后回到掩码,且账密输入值不丢', async () => {
const panel = await mountPanel()
const pwd = passwordInput(panel)
await eyeButton(panel).trigger('click')
expect(pwd.attributes('type')).toBe('text')
await pwd.setValue(`${FAKE_PWD}Z`)
expect(await saveAll(panel)).toBe(true)
expect(bridge.saveConfig).toHaveBeenCalledTimes(1)
expect(pwd.attributes('type'), '保存成功=配置已落地,界面没理由还亮着明文').toBe('password')
expect(valueOf(pwd)).toBe(`${FAKE_PWD}Z`)
})
it('卸载后重新挂载(重开弹窗/换号重读配置)不带出明文', async () => {
const first = await mountPanel()
await eyeButton(first).trigger('click')
expect(passwordInput(first).attributes('type')).toBe('text')
first.unmount()
const again = await mountPanel()
expect(passwordInput(again).attributes('type')).toBe('password')
expect(eyeButton(again).attributes('aria-pressed')).toBe('false')
expect(valueOf(passwordInput(again)), '重读到的还是那把假密码,只是重新盖上').toBe(FAKE_PWD)
})
it('后台锁定代理时眼睛跟着输入框一起禁用', async () => {
store.getServerProxySnapshot.mockReturnValue({
...emptySnapshot(), exists: true, locked: true, channel: 'qingguo', full: '',
})
const panel = await mountPanel()
expect(passwordInput(panel).attributes('disabled')).toBeDefined()
expect(eyeButton(panel).attributes('disabled'), '只读态不该还能把明文翻出来').toBeDefined()
})
})