Files
go_bt/tests/chatgpt_failure_session_preservation.test.js

78 lines
3.1 KiB
JavaScript

'use strict';
const assert = require('assert');
async function loadStepWithResult(result) {
const servicePath = require.resolve('../src/services/chatgpt_service');
const screenshotPath = require.resolve('../src/utils/screenshot');
const stepPath = require.resolve('../src/pipeline/steps/chatgpt_register');
const service = require(servicePath);
const screenshot = require(screenshotPath);
const originalLogin = service.loginOrRegisterChatGPT;
const originalScreenshot = screenshot.saveErrorScreenshot;
service.loginOrRegisterChatGPT = async () => result;
screenshot.saveErrorScreenshot = async () => null;
delete require.cache[stepPath];
const step = require(stepPath);
service.loginOrRegisterChatGPT = originalLogin;
screenshot.saveErrorScreenshot = originalScreenshot;
return step;
}
function makeContext(writes, existingSession) {
return {
account: { email: 'target@example.com' },
page: { url: () => 'https://chatgpt.com/' },
params: { age: 23, clearAuthState: false },
log: () => {},
results: {},
dbWrite: async (name, args) => {
writes.push({ name, args });
if (name === 'getAccount') return { chatgpt_session: existingSession };
return true;
},
updateStatus: async () => {},
updateMessage: async () => {},
};
}
(async () => {
const oldSession = JSON.stringify({ user: { email: 'target@example.com' } });
const timeoutWrites = [];
const timeoutStep = await loadStepWithResult({
ok: false,
code: 'CHATGPT_SESSION_TIMEOUT',
msg: 'Session读取超时',
});
await timeoutStep(makeContext(timeoutWrites, oldSession));
const timeoutUpdate = timeoutWrites.find(item => item.name === 'updateAccountChatgptResult');
assert(timeoutUpdate, '失败时应更新ChatGPT结果');
assert.strictEqual(timeoutUpdate.args[2], oldSession, '临时网络或Session读取失败应保留旧Session');
const wrongOldSession = JSON.stringify({ user: { email: 'other@example.com' } });
const wrongOldWrites = [];
await timeoutStep(makeContext(wrongOldWrites, wrongOldSession));
const wrongOldUpdate = wrongOldWrites.find(item => item.name === 'updateAccountChatgptResult');
assert.strictEqual(wrongOldUpdate.args[2], null, '旧Session属于其它邮箱时必须清空');
const malformedWrites = [];
await timeoutStep(makeContext(malformedWrites, '{invalid-json'));
const malformedUpdate = malformedWrites.find(item => item.name === 'updateAccountChatgptResult');
assert.strictEqual(malformedUpdate.args[2], null, '旧Session无法解析时必须清空');
const mismatchWrites = [];
const mismatchStep = await loadStepWithResult({
ok: false,
code: 'CHATGPT_ACCOUNT_MISMATCH',
msg: '当前会话属于其它账号',
});
await mismatchStep(makeContext(mismatchWrites, oldSession));
const mismatchUpdate = mismatchWrites.find(item => item.name === 'updateAccountChatgptResult');
assert.strictEqual(mismatchUpdate.args[2], null, '明确账号不匹配时必须清空旧Session');
console.log('chatgpt_failure_session_preservation.test.js: PASS');
})().catch(error => {
console.error(error);
process.exitCode = 1;
});