Files
go_bt/tools/selftest_aistudio.js
2026-09-24 10:57:31 +08:00

73 lines
3.0 KiB
JavaScript
Raw Permalink 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.
/**
* @file tools/selftest_aistudio.js
* @brief AI Studio 一键组合功能的离线自测:
* 建表 + 写入/读取 aistudio_api_keys(明文)+ aistudio_flow_logs,
* 并确认 operation_logs 仍然存在、未受影响。不联网、不开浏览器。
*
* 用法(项目根目录):node tools/selftest_aistudio.js
*/
'use strict';
const db = require('../src/core/database');
function main() {
db.initDB();
const tables = db.getDb()
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name IN ('aistudio_api_keys','aistudio_flow_logs','operation_logs')")
.all()
.map(r => r.name);
console.log('[1] 关键表存在:', tables.join(', ') || '(无)');
const need = ['aistudio_api_keys', 'aistudio_flow_logs', 'operation_logs'];
const missing = need.filter(t => !tables.includes(t));
if (missing.length) throw new Error('缺少表: ' + missing.join(', '));
const email = 'selftest_aistudio@example.com';
// 流程日志:失败 + 成功各写一条
db.addAistudioFlowLog(email, 'failed', '改密码', '自测:模拟改密失败');
db.addAistudioFlowLog(email, 'success', '', '自测:全部步骤成功');
const logs = db.getAistudioFlowLogs(10).filter(r => r.email === email);
console.log('[2] 流程日志写入条数:', logs.length, '→', logs.map(l => `${l.status}/${l.failed_step || '-'}`).join(', '));
if (logs.length < 2) throw new Error('流程日志写入异常');
// API Key:明文写入并读回
db.upsertAistudioApiKey(email, {
apiKey: 'AQ.Ab8RN6L9PT1_3S8PJ9C4qnsF0nEBoo_IG1mAs7WUDyVTX4Ofbw',
keyName: 'Gemini API Key',
projectName: 'projects/833454763400',
projectNumber: '833454763400',
});
const row = db.getAistudioApiKey(email);
console.log('[3] API Key 明文读回:', row ? row.api_key : '(空)');
if (!row || !row.api_key || row.api_key.indexOf('AQ.') !== 0) throw new Error('API Key 明文存储校验失败');
console.log(' project_name:', row.project_name, '| project_number:', row.project_number, '| key_name:', row.key_name);
// upsert 覆盖同一邮箱(只保留最新一枚)
db.upsertAistudioApiKey(email, {
apiKey: 'AQ.newkey_0000000000000000',
keyName: 'Gemini API Key',
projectName: 'projects/999999999999',
projectNumber: '999999999999',
});
const all = db.getAllAistudioApiKeys().filter(r => r.email === email);
console.log('[4] 同邮箱记录数(应为1):', all.length, '| 最新key:', all[0] && all[0].api_key);
if (all.length !== 1) throw new Error('同邮箱应只保留一条记录');
// 清理自测数据
db.getDb().prepare('DELETE FROM aistudio_api_keys WHERE email = ?').run(email);
db.getDb().prepare('DELETE FROM aistudio_flow_logs WHERE email = ?').run(email);
console.log('[5] 已清理自测数据');
console.log('\n✅ 自测通过:两张新表建成、明文存储正确、同邮箱唯一、operation_logs 未受影响。');
}
try {
main();
process.exit(0);
} catch (e) {
console.error('\n❌ 自测失败:', e && e.message ? e.message : e);
process.exit(1);
}