refactor: 重组目录结构,脚本收进 scripts/,配置独立成 config/

根目录原来平铺了构建脚本、运行器配置、两个 .cmd 启动器和一份中文名的
实跑报告,四类东西混在一起,新人分不清哪个是源码、哪个是产物。这次按
职责分层重排:

- 构建与检查脚本收进 scripts/:build.mjs、check.mjs
- 一键启动器收进 scripts/:start-headless.cmd、start-dev.cmd
- 运行器配置独立成 config/runner.config.mjs(日常调参不用重新 build)
- 真机测试收进 dev/tests/:real-cdp / real-test / real-e2e / real-run
- 运行报告改成 ASCII 名并移入 docs/reports/run-report-v203.md
- v2.0.x 时期的 7 份原始抓取片段归档到 docs/archive/v2.0-snapshots/,
  docs/evidence/ 只留当前版本的有效证据
- 测试每次重新生成的 3 张截图(e2e-01-after-login、e2e-02-playing、
  real-chrome-login)移出仓库并加入 .gitignore,改写到 .run-tmp/screenshots/;
  docs/screenshots/ 只保留手工挑选的 5 张展示图

路径修正:build.mjs 的 ROOT 上跳一级;dev/tests/ 四个脚本 ROOT 上跳两级、
对 runner/browser.mjs 的引用改 ../../;runner/config.mjs 默认配置文件路径改
config/runner.config.mjs;两个 .cmd 的 cd 改为仓库根、start-dev.cmd 指向
dev/serve.mjs;package.json 全部 npm scripts 同步;README、dev/README、证据
文件与源码注释里的路径一并更新。

顺带修掉测试里硬编码的 v2.7.0 断言:版本号改为从 package.json 读取。

验证:npm run build(104798 字节 / 102.3 KB)、npm run check(24/24)、
npm run test:real:headless(24/24 通过)。
This commit is contained in:
void committed 2026-10-25 23:21:59 +08:00
1 parent ae117222df
commit c1e883d67f
32 files changed
+148 -125

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
// 极简 CDP 客户端:Node 18+ 原生 WebSocket,无需 puppeteer / playwright。
// 只实现本项目真机测试用到的部分:send / waitEvent / 事件堆积。
// Linux 无图形化服务器 / 容器的浏览器探测与启动参数统一放在 runner/browser.mjs,
// 这里一并转发,避免 dev 测试脚本和 runner 两套逻辑跑偏。
import fs from 'node:fs';
import {
resolveBrowser as _resolveBrowser, safetyArgs as _safetyArgs, hasDisplay,
} from '../../runner/browser.mjs';
export { cleanStaleSingleton } from '../../runner/browser.mjs';
export async function connect(wsUrl) {
const ws = new WebSocket(wsUrl);
await new Promise((res, rej) => {
ws.addEventListener('open', res, { once: true });
ws.addEventListener('error', rej, { once: true });
});
let id = 0;
const pending = new Map();
const events = [];
const waiters = [];
const listeners = [];
ws.addEventListener('message', (ev) => {
const msg = JSON.parse(ev.data);
if (msg.id != null && pending.has(msg.id)) {
const { res, rej } = pending.get(msg.id);
pending.delete(msg.id);
if (msg.error) rej(new Error(msg.error.message));
else res(msg.result);
return;
}
events.push(msg);
for (const fn of listeners) {
try { fn(msg); } catch (e) { /* 忽略订阅者异常 */ }
}
for (let i = waiters.length - 1; i >= 0; i--) {
if (waiters[i].match(msg)) waiters.splice(i, 1)[0].res(msg);
}
});
const send = (method, params = {}) => new Promise((res, rej) => {
const mid = ++id;
pending.set(mid, { res, rej });
ws.send(JSON.stringify({ id: mid, method, params }));
});
const waitEvent = (name, timeoutMs = 30000) => new Promise((res, rej) => {
const timer = setTimeout(() => rej(new Error('等待事件超时: ' + name)), timeoutMs);
waiters.push({
match: (m) => m.method === name,
res: (m) => { clearTimeout(timer); res(m.params); },
});
});
const onEvent = (fn) => { listeners.push(fn); };
return { ws, send, waitEvent, onEvent, events, close: () => { try { ws.close(); } catch (e) {} } };
}
export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
export async function httpJson(url, method = 'GET') {
const r = await fetch(url, { method });
const t = await r.text();
try { return JSON.parse(t); } catch (e) { return t; }
}
// ---- Linux 无图形化服务器 / 容器适配 ----
// 无显示环境:Linux 上没有 DISPLAY / WAYLAND_DISPLAY 就只能无头
// (跑在 Xvfb 下时 Xvfb 会设置 DISPLAY,因此这里只判断变量)
export function forceHeadless() {
return !hasDisplay();
}
// 按环境变量 / 常见安装位置找到真实存在的浏览器;找不到时返回 null
export function findChrome(candidates) {
return _resolveBrowser() || candidates.filter(Boolean).find(function (p) {
try { return fs.statSync(p).isFile(); } catch (e) { return false; }
}) || null;
}
// 必须追加给浏览器的平台安全参数(容器 /dev/shm 小、root 无沙箱)
export function safetyArgs() {
return _safetyArgs();
}
+422
View File
@@ -0,0 +1,422 @@
#!/usr/bin/env node
/**
* 真机端到端测试:真实 Chrome + 真实云学堂账号,跑「登录 → 列表 → 进课 → 播放」全链路。
*
* 账号来源(环境变量,不写进代码、不打印明文):
* YUN_XUE_TANG_USR 员工邮箱 / 账号
* YUN_XUE_TANG_PWD 密码
*
* 用法:
* node dev/real-e2e.mjs 登录 + 列表断言(不动任何课程进度)
* node dev/real-e2e.mjs --play 额外进入最短的一门课,采样播放 N 秒后停止
* node dev/real-e2e.mjs --play --seconds 60
* node dev/real-e2e.mjs --headless 无头模式
* node dev/real-e2e.mjs --keep 跑完不关浏览器(便于人工复核)
* node dev/real-e2e.mjs --shotdir X 截图目录
*
* 安全约束(刻意保守):
* - 只有显式传 --play 才会进入课程页;默认全程只读,不改任何学习进度。
* - --play 默认只采样 25 秒,采完立刻 pause + 释放脚本,不会把整节课刷完。
* - 结束前会打印本轮进度变化(开课前 / 结束后 的 已完成 x/y),便于核对影响。
*/
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { connect, sleep, httpJson, findChrome, forceHeadless, safetyArgs } from './real-cdp.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
// 本文件在 dev/tests/ 下,仓库根目录是上两级
const ROOT = path.resolve(HERE, '..', '..');
const SCRIPT_SRC = fs.readFileSync(path.join(ROOT, 'yun-xue-tang-assistant.user.js'), 'utf8');
const argv = process.argv.slice(2);
const flag = (n) => argv.includes(n);
const opt = (n, d) => {
const i = argv.indexOf(n);
return i >= 0 && argv[i + 1] ? argv[i + 1] : d;
};
const USR = process.env.YUN_XUE_TANG_USR || '';
const PWD = process.env.YUN_XUE_TANG_PWD || '';
const PLAY = flag('--play');
const SAMPLE_SECONDS = Number(opt('--seconds', 25));
const HEADLESS = flag('--headless') || process.env.YUN_XUE_TANG_HEADLESS === '1';
const KEEP = flag('--keep');
const PORT = Number(process.env.YUN_XUE_TANG_CDP_PORT || 9334);
const SHOT_DIR = opt('--shotdir', path.join(ROOT, '.run-tmp', 'screenshots'));
const ORIGIN = 'https://kfmic.yunxuetang.cn';
const CANDIDATES = [
process.env.YUN_XUE_TANG_CHROME,
'C:/Program Files/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
].filter(Boolean);
const CHROME = findChrome(CANDIDATES);
const results = [];
const consoleLogs = [];
const log = (...a) => console.log(...a);
function check(name, ok, detail) {
results.push({ name, ok: !!ok, detail });
log((ok ? ' PASS ' : ' FAIL ') + name + (detail === undefined ? '' : ' → ' + JSON.stringify(detail)));
}
if (!CHROME) { console.error('找不到 Chrome/Edge,可用 YUN_XUE_TANG_CHROME=... 指定'); process.exit(2); }
if (!USR || !PWD) { console.error('缺少环境变量 YUN_XUE_TANG_USR / YUN_XUE_TANG_PWD'); process.exit(2); }
if (typeof WebSocket !== 'function' || typeof fetch !== 'function') {
console.error('需要 Node 22+,当前 ' + process.version);
process.exit(2);
}
log('[E2E] 账号:' + USR.slice(0, 3) + '***' + USR.slice(-2) + ' 密码:' + '*'.repeat(Math.min(PWD.length, 8)) + '(长度 ' + PWD.length + ')');
// Linux 无图形化服务器:没有 DISPLAY 时强制无头,并补容器/root 必需参数
const HEADLESS_ONLY = HEADLESS || forceHeadless();
log('[E2E] 浏览器:' + CHROME + (HEADLESS_ONLY ? '(headless)' : '(有界面)') + ' 进课采样:' + (PLAY ? SAMPLE_SECONDS + ' 秒' : '否(只读)'));
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yun-xue-tang-e2e-'));
const args = [
`--remote-debugging-port=${PORT}`,
`--user-data-dir=${userDataDir}`,
'--no-first-run', '--no-default-browser-check', '--disable-sync',
'--disable-background-timer-throttling', '--disable-renderer-backgrounding',
'--disable-backgrounding-occluded-windows',
'--autoplay-policy=no-user-gesture-required',
'--window-size=1360,940',
].concat(safetyArgs(), ['about:blank']);
if (HEADLESS_ONLY) args.unshift('--headless=new');
let chrome = null;
let cdp = null;
try {
chrome = spawn(CHROME, args, { stdio: 'ignore', windowsHide: true });
let version = null;
for (let i = 0; i < 100; i++) {
try { const v = await httpJson(`http://127.0.0.1:${PORT}/json/version`); if (v && v.webSocketDebuggerUrl) { version = v; break; } } catch (e) {}
await sleep(250);
}
if (!version) throw new Error('Chrome CDP 未就绪');
log('[E2E] ' + version.Browser);
const target = await httpJson(`http://127.0.0.1:${PORT}/json/new?${encodeURIComponent(ORIGIN + '/login.html')}`, 'PUT');
cdp = await connect(target.webSocketDebuggerUrl);
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Log.enable');
cdp.onEvent((m) => {
if (m.method === 'Runtime.consoleAPICalled') {
const text = (m.params.args || []).map((a) => (a.value !== undefined ? a.value : a.description || '')).join(' ');
consoleLogs.push({ type: m.params.type, text: String(text) });
} else if (m.method === 'Log.entryAdded') {
consoleLogs.push({ type: m.params.entry.level, text: m.params.entry.text });
}
});
const evalJS = async (expr) => {
const r = await cdp.send('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true });
if (r.exceptionDetails) {
const d = r.exceptionDetails;
throw new Error((d.exception && d.exception.description) || d.text);
}
return r.result.value;
};
const json = async (expr) => JSON.parse(await evalJS(expr));
const waitFor = async (exprFn, timeoutMs, label) => {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
try { if (await evalJS(exprFn)) return true; } catch (e) {}
await sleep(500);
}
return false;
};
const shot = async (name) => {
try {
fs.mkdirSync(SHOT_DIR, { recursive: true });
const s = await cdp.send('Page.captureScreenshot', { format: 'png' });
const f = path.join(SHOT_DIR, name);
fs.writeFileSync(f, Buffer.from(s.data, 'base64'));
return path.relative(ROOT, f);
} catch (e) { return '截图失败: ' + e.message; }
};
const loaded = cdp.waitEvent('Page.loadEventFired', 45000).catch(() => null);
await cdp.send('Page.navigate', { url: ORIGIN + '/login.html' });
await loaded;
await sleep(2000);
// ---------- 1. 登录页 + 注入 ----------
await evalJS(SCRIPT_SRC);
await sleep(1000);
const loginInfo = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
return {
url: location.href,
title: document.title,
isLoginPage: a.isLoginPage(),
panel: !!document.getElementById('yun-xue-tang-panel'),
fields: (() => { const f = a.loginFields(); return { user: !!f.user, pwd: !!f.pwd, ph: f.user ? f.user.placeholder : null }; })(),
};
})())`);
check('登录页加载 + 脚本注入', loginInfo.isLoginPage === true && loginInfo.panel === true, loginInfo.url);
check('识别到账号/密码输入框', loginInfo.fields.user && loginInfo.fields.pwd, loginInfo.fields);
// ---------- 2. 填账号密码(走真实的 setNativeValue + Vue 双向绑定) ----------
const filled = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const u = ${JSON.stringify(USR)};
const p = ${JSON.stringify(PWD)};
document.getElementById('yun-xue-tang-login-user').value = u;
document.getElementById('yun-xue-tang-login-pass').value = p;
const okForm = a.fillLoginForm(u, p);
const f = a.loginFields();
return {
okForm,
userValueLen: f.user ? f.user.value.length : -1,
pwdValueLen: f.pwd ? f.pwd.value.length : -1,
userMatched: f.user ? f.user.value === u : false,
pwdMatched: f.pwd ? f.pwd.value === p : false,
panelUser: document.getElementById('yun-xue-tang-login-user').value.length,
};
})())`);
check('账号密码写入真实输入框', filled.okForm === true && filled.userMatched === true && filled.pwdMatched === true,
{ 长度: [filled.userValueLen, filled.pwdValueLen], 一致: [filled.userMatched, filled.pwdMatched] });
const agree = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const before = [...document.querySelectorAll('label')].filter(x => /已阅读并同意|隐私政策/.test(x.innerText||''))
.map(x => { const c = x.querySelector('input[type=checkbox]'); return c ? c.checked : null; });
const ok = a.checkLoginAgreement ? a.checkLoginAgreement() : 'no-api';
const after = [...document.querySelectorAll('label')].filter(x => /已阅读并同意|隐私政策/.test(x.innerText||''))
.map(x => { const c = x.querySelector('input[type=checkbox]'); return c ? c.checked : null; });
return { before, after, ok };
})())`);
check('隐私政策勾选处理正常', agree.ok === true || agree.ok === 'no-api', agree);
// ---------- 3. 点「一键登录并刷课」,等真实登录成功 ----------
// 注意:这个按钮会写 LS_PENDING,登录后自动开启列表刷课(脚本设计行为)。
// 默认(不加 --play)测完登录马上刹住,避免动到真实学习进度。
await evalJS(`(document.getElementById('yun-xue-tang-oneclick').click(), true)`);
const loginOk = await waitFor(`(() => {
if (/\\/login/.test(location.pathname)) return false;
if (!document.body) return false;
if (document.querySelector('input[type=password]')) return false;
return true;
})()`, 45000);
await sleep(2000);
const afterLogin = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const status = (document.getElementById('yun-xue-tang-status') || {}).textContent || '';
const bodyText = document.body ? (document.body.innerText || '').replace(/\\s+/g, ' ').slice(0, 400) : '';
return {
url: location.href, title: document.title, status,
alive: typeof window.__yunXueTangAuto,
isLoginPage: a ? a.isLoginPage() : null,
captcha: /验证码|滑块|安全验证/.test(bodyText),
errText: (bodyText.match(/(用户名密码错误|账号或密码错误|密码错误|账号不存在|登录失败)[^ ]{0,40}/) || [''])[0],
panel: !!document.getElementById('yun-xue-tang-panel'),
};
})())`);
check('真实登录成功(离开登录页)', loginOk === true, afterLogin);
const scriptErrs = () => consoleLogs.filter((l) => l.type === 'error' && /云学堂助手/.test(l.text));
check('登录流程无脚本 error', scriptErrs().length === 0, scriptErrs().map((e) => e.text.slice(0, 140)));
log(' 截图:' + await shot('e2e-01-after-login.png'));
// 登录是整页跳转(新 document),真实 Tampermonkey 会按 @match 重新注入;
// 这里模拟同样的行为。
if ((await evalJS('typeof window.__yunXueTangAuto')) === 'undefined') {
log('[E2E] 登录后是新 document(' + afterLogin.url + '),重新注入脚本');
await evalJS(SCRIPT_SRC);
await sleep(1200);
}
check('登录后新 document 上脚本已注入', (await evalJS('typeof window.__yunXueTangAuto')) === 'object', await evalJS('document.title || location.pathname'));
if (!PLAY) {
// 立即刹住列表刷课:清 pending 标记 + 关闭 running,防止在真实账号上推进课程
const halted = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
if (a) { a.S.batchRunning = false; a.S.batchFinished = false; a.S.activeCourse = null; a.S.coursePhase = 'idle'; a.save(); }
return { running: a ? a.S.batchRunning : null, current: a ? a.S.activeCourse : null };
})())`);
check('默认只读:登录后立即停用列表刷课', halted.running === false && halted.current === null, halted);
}
// ---------- 4. 列表页断言 ----------
const listNavStarted = Date.now();
await evalJS(`(location.href = 'https://kfmic.yunxuetang.cn/kng/#/list', true)`);
await cdp.waitEvent('Page.loadEventFired', 30000).catch(() => null);
await sleep(2500);
// 换页后可能又是新 document,重新注入
if ((await evalJS('typeof window.__yunXueTangAuto')) === 'undefined') {
log('[E2E] 列表页是新 document,重新注入脚本');
await evalJS(SCRIPT_SRC);
await sleep(1000);
}
if (!PLAY) {
// 新 document 里 S 从 sessionStorage 恢复了 batchRunning=true,再次刹住
await evalJS(`(() => {
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
const a = window.__yunXueTangAuto;
if (a) { a.S.batchRunning = false; a.S.activeCourse = null; a.S.coursePhase = 'idle'; a.save(); }
return true;
})()`);
await sleep(400);
}
const listReady = await waitFor(`!!window.__yunXueTangAuto && document.querySelectorAll('li.kng-list-new__item').length > 0`, 45000);
await sleep(1500);
const listInfo = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto; const cards = a.scanCards();
const vm = (() => {
const ul = document.querySelector('ul.kng-list-new');
let v = ul && ul.__vue__;
while (v && !(v.kngListData && v.kngListData.length)) v = v.$parent;
return v || null;
})();
const data = (vm && vm.kngListData) || [];
return {
url: location.href,
route: a.route(),
cards: cards.length,
page: a.currentPage(),
maxPage: a.maxPageNumber(),
first3: cards.slice(0, 3).map((c) => ({ title: c.title.slice(0, 30), status: c.status })),
vmCount: data.length,
vmFirst: data.slice(0, 3).map((d) => ({ title: String(d.title || d.name || '').slice(0, 26), studyHours: d.studyHours, id: String(d.id || d.kngId || '').slice(0, 12) })),
pending: cards.filter((c) => c.title && !/已学完|已完成|已学习/.test(c.status)).length,
};
})())`);
check('列表页卡片渲染', listReady === true && listInfo.cards > 0, { 卡片数: listInfo.cards, 页码: listInfo.page + '/' + listInfo.maxPage });
check('scanCards 解析标题与状态', listInfo.first3.every((c) => c.title.length > 0), listInfo.first3);
check('列表 Vue 组件可读(时长来源)', listInfo.vmCount > 0, { 条数: listInfo.vmCount, 样例: listInfo.vmFirst });
const dur = listInfo.vmFirst.filter((d) => Number.isFinite(d.studyHours) && d.studyHours > 0);
check('studyHours 时长可用(短课程优先的数据源)', dur.length > 0, dur);
// ---------- 5. 可选:真实进课 + 采样播放 ----------
let beforeProgress = null;
let playInfo = null;
if (PLAY) {
// 选一门「最短」的未学完课程,尽量减小对真实进度的影响
const pick = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const cards = a.scanCards();
const ul = document.querySelector('ul.kng-list-new');
let v = ul && ul.__vue__;
while (v && !(v.kngListData && v.kngListData.length)) v = v.$parent;
const data = (v && v.kngListData) || [];
const byTitle = new Map();
for (const d of data) byTitle.set(String(d.title || d.name || '').trim(), d);
const cand = cards
.filter((c) => c.title && !/已学完|已完成|已学习/.test(c.status))
.map((c) => ({ c, d: byTitle.get(c.title) }))
.filter((x) => x.d && Number(x.d.studyHours) > 0)
.sort((x, y) => Number(x.d.studyHours) - Number(y.d.studyHours));
if (!cand.length) {
const any = cards.find((c) => c.title && !/已学完|已完成|已学习/.test(c.status));
return any ? { title: any.title, studyHours: null, idx: any.i, fallback: true } : null;
}
return { title: cand[0].c.title, studyHours: Number(cand[0].d.studyHours), idx: cand[0].c.i };
})())`);
check('找到可学的最短课程', !!pick, pick);
if (pick) {
log('[E2E] 选课:' + pick.title + '(' + (pick.studyHours ? Math.round(pick.studyHours / 60) + ' 分钟' : '时长未知') + ')');
// 用脚本自己的 startCourse 走真实进课流程(会写 S.activeCourse 并点卡片)
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
const card = a.scanCards().find((c) => c.i === ${pick.idx});
if (!card) return 'no-card';
a.startCourse(card);
return 'started';
})()`);
const entered = await waitFor(`window.__yunXueTangAuto && window.__yunXueTangAuto.route() === 'course' && /\\/play/.test(location.hash)`, 40000);
await sleep(2500);
const before = await json(`JSON.stringify((() => ({
url: location.hash,
summary: window.__yunXueTangAuto.readSummary(),
countdown: window.__yunXueTangAuto.readCountdown(),
lessons: window.__yunXueTangAuto.lessonItems().length,
active: window.__yunXueTangAuto.lessonItems().length ? (document.querySelector('.yxtulcdsdk-catalog .liactive') || {}).innerText || '' : '',
}))())`);
beforeProgress = before.summary && before.summary.text;
check('进入真实课程播放页', entered === true, before.url);
check('读取到课程汇总/目录', !!before.summary || before.lessons > 0, { 汇总: before.summary && before.summary.text, 目录: before.lessons });
// 触发「开始学习」并观察播放器
const play = await waitFor(`(() => {
const v = document.querySelector('video, audio');
return !!v && v.duration > 0;
})()`, 25000);
const t0 = Date.now();
// 让主循环自己动起来(模拟用户手动打开课程时的自动连播开关)
await evalJS(`(() => { window.__yunXueTangAuto.tick(); return true; })()`);
await sleep(SAMPLE_SECONDS * 1000);
playInfo = await json(`JSON.stringify((() => {
const v = document.querySelector('video, audio');
const a = window.__yunXueTangAuto;
return {
found: !!v,
muted: v ? v.muted : null,
paused: v ? v.paused : null,
rate: v ? v.playbackRate : null,
currentTime: v ? Math.round(v.currentTime) : null,
duration: v ? Math.round(v.duration) : null,
summary: a.readSummary(),
countdown: a.readCountdown(),
status: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
elapsedSec: Math.round((Date.now() - ${t0}) / 1000),
};
})())`);
check('播放器被找到并接管(静音 1x)', playInfo.found === true && playInfo.muted === true && playInfo.rate === 1, playInfo);
check('视频真实在播放(时间在走)', playInfo.paused === false && playInfo.currentTime > 0, { 已播到: playInfo.currentTime + 's / ' + playInfo.duration + 's' });
check('采样期间无脚本 error', scriptErrs().length === 0, scriptErrs().map((e) => e.text.slice(0, 140)));
log(' 截图:' + await shot('e2e-02-playing.png'));
// 立刻停手:暂停媒体 + 关闭批量 + dispose
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
a.S.batchRunning = false;
a.save();
a.pauseAllMedia ? a.pauseAllMedia() : document.querySelectorAll('video, audio').forEach((x) => x.pause());
return true;
})()`);
await sleep(1200);
const stopped = await json(`JSON.stringify((() => {
const v = document.querySelector('video, audio');
return { paused: v ? v.paused : null, running: window.__yunXueTangAuto ? window.__yunXueTangAuto.S.batchRunning : null,
summary: window.__yunXueTangAuto ? window.__yunXueTangAuto.readSummary() : null };
})())`);
check('停止后媒体已暂停', stopped.paused === true && stopped.running === false, stopped);
}
}
// ---------- 6. 释放脚本,确认无残留 ----------
if (PLAY) {
const disposed = await json(`JSON.stringify((() => {
window.__yunXueTangDispose();
return { panel: !!document.getElementById('yun-xue-tang-panel'), api: typeof window.__yunXueTangAuto };
})())`);
check('dispose 后面板与 API 清理干净', disposed.panel === false && disposed.api === 'undefined', disposed);
}
log('\n[E2E] 脚本日志(' + consoleLogs.filter((l) => /云学堂助手/.test(l.text)).length + ' 条脚本相关):');
for (const l of consoleLogs.filter((x) => /云学堂助手/.test(x.text)).slice(-25)) log(' [' + l.type + '] ' + l.text.slice(0, 170));
if (beforeProgress) log('[E2E] 进度快照:进入前「' + beforeProgress + '」→ 采样后「' + (playInfo && playInfo.summary && playInfo.summary.text) + '」');
} catch (e) {
check('E2E 流程执行完毕', false, e && e.stack ? e.stack.split('\n').slice(0, 5).join(' | ') : String(e));
} finally {
if (cdp && !KEEP) cdp.close();
if (chrome && !KEEP) { try { chrome.kill(); } catch (e) {} }
if (!KEEP) { await sleep(700); try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch (e) {} }
else log('[E2E] --keep:浏览器保持打开 ' + userDataDir);
}
const failed = results.filter((r) => !r.ok);
log('\n===== E2E 结果:' + (results.length - failed.length) + '/' + results.length + ' 通过,失败 ' + failed.length + ' =====');
for (const f of failed) log(' FAIL ' + f.name + ' → ' + JSON.stringify(f.detail));
process.exit(failed.length ? 1 : 0);
+468
View File
@@ -0,0 +1,468 @@
#!/usr/bin/env node
/**
* 真机持续运行测试:跨章节 + 跨课程。
*
* 真实 Chrome + 真实账号,让脚本自己跑列表刷课,观察它能否
* 1) 在一门多课时课程里自动从第 N 节切到第 N+1 节(跨章节)
* 2) 一门课完成后回到列表、进下一门课(跨课程)
* 3) 每次整页跳转(新 document)后重新注入并接续运行
* 4) 全程视频持续推进、无脚本 error、没学完的课程按退避重试而不是被跳过
*
* 用法:
* node dev/real-run.mjs --scan 只登录 + 列表,打印所有卡片(只读)
* node dev/real-run.mjs --probe 8 读前 8 门课最短的「未学完」课的目录(不进播放,不动进度)
* node dev/real-run.mjs --max 2 --budget 15 跑批量,最多完成 2 门 / 最多 15 分钟
* node dev/real-run.mjs --title 坚持 --max 2 先把匹配标题的课程跑完,再自动跑下一门
* node dev/real-run.mjs --headless --keep 无头 / 跑完不关浏览器
* node dev/real-run.mjs --out run.json 时间线写到指定文件(默认临时目录)
*
* 注意:这个测试会**真实推进学习进度**(这就是它的目的)。
* 只读的登录/列表测试请看 dev/real-e2e.mjs。
*/
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { connect, sleep, httpJson, findChrome, forceHeadless, safetyArgs } from './real-cdp.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
// 本文件在 dev/tests/ 下,仓库根目录是上两级
const ROOT = path.resolve(HERE, '..', '..');
const SCRIPT_SRC = fs.readFileSync(path.join(ROOT, 'yun-xue-tang-assistant.user.js'), 'utf8');
const argv = process.argv.slice(2);
const flag = (n) => argv.includes(n);
const opt = (n, d) => {
const i = argv.indexOf(n);
return i >= 0 && argv[i + 1] ? argv[i + 1] : d;
};
const USR = process.env.YUN_XUE_TANG_USR || '';
const PWD = process.env.YUN_XUE_TANG_PWD || '';
const SCAN = flag('--scan');
const PROBE = flag('--probe') ? Number(opt('--probe', 8)) : 0;
const HEADLESS = flag('--headless') || process.env.YUN_XUE_TANG_HEADLESS === '1';
const KEEP = flag('--keep');
const MAX_COURSES = Number(opt('--max', 2));
const BUDGET_MIN = Number(opt('--budget', 15));
const PIN_TITLE = opt('--title', '');
const PORT = Number(process.env.YUN_XUE_TANG_CDP_PORT || 9335);
const ORIGIN = 'https://kfmic.yunxuetang.cn';
const OUT = opt('--out', path.join(os.tmpdir(), 'yun-xue-tang-run-' + Date.now() + '.json'));
const CANDIDATES = [
process.env.YUN_XUE_TANG_CHROME,
'C:/Program Files/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
].filter(Boolean);
const CHROME = findChrome(CANDIDATES);
const results = [];
const consoleLogs = [];
const timeline = [];
const log = (...a) => console.log(...a);
const clock = () => new Date().toISOString().slice(11, 19);
function check(name, ok, detail) {
results.push({ name, ok: !!ok, detail });
log((ok ? ' PASS ' : ' FAIL ') + name + (detail === undefined ? '' : ' → ' + JSON.stringify(detail)));
}
if (!CHROME) { console.error('找不到 Chrome/Edge,可用 YUN_XUE_TANG_CHROME=... 指定'); process.exit(2); }
if (!USR || !PWD) { console.error('缺少环境变量 YUN_XUE_TANG_USR / YUN_XUE_TANG_PWD'); process.exit(2); }
if (typeof WebSocket !== 'function' || typeof fetch !== 'function') {
console.error('需要 Node 22+,当前 ' + process.version);
process.exit(2);
}
log('[RUN] 账号:' + USR.slice(0, 3) + '***' + USR.slice(-2));
log('[RUN] 模式:' + (SCAN ? '只读扫描列表' : (PROBE ? '只读探测前 ' + PROBE + ' 门课的目录' : '批量持续运行(最多 ' + MAX_COURSES + ' 门 / ' + BUDGET_MIN + ' 分钟)')) +
(PIN_TITLE ? ' 指定课程:' + PIN_TITLE : ''));
// Linux 无图形化服务器:没有 DISPLAY 时强制无头,并补容器/root 必需参数
const HEADLESS_ONLY = HEADLESS || forceHeadless();
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yun-xue-tang-run-'));
const args = [
`--remote-debugging-port=${PORT}`,
`--user-data-dir=${userDataDir}`,
'--no-first-run', '--no-default-browser-check', '--disable-sync',
// 后台标签页/最小化时不要把定时器和视频节流,否则「持续运行」测不准
'--disable-background-timer-throttling', '--disable-renderer-backgrounding',
'--disable-backgrounding-occluded-windows',
'--autoplay-policy=no-user-gesture-required',
'--window-size=1360,940',
].concat(safetyArgs(), ['about:blank']);
if (HEADLESS_ONLY) args.unshift('--headless=new');
let chrome = null;
let cdp = null;
log('[RUN] 浏览器:' + CHROME + (HEADLESS_ONLY ? '(headless)' : '(有界面)'));
try {
chrome = spawn(CHROME, args, { stdio: 'ignore', windowsHide: true });
let version = null;
for (let i = 0; i < 100; i++) {
try { const v = await httpJson(`http://127.0.0.1:${PORT}/json/version`); if (v && v.webSocketDebuggerUrl) { version = v; break; } } catch (e) {}
await sleep(250);
}
if (!version) throw new Error('Chrome CDP 未就绪');
log('[RUN] ' + version.Browser);
const target = await httpJson(`http://127.0.0.1:${PORT}/json/new?${encodeURIComponent(ORIGIN + '/login.html')}`, 'PUT');
cdp = await connect(target.webSocketDebuggerUrl);
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Log.enable');
cdp.onEvent((m) => {
if (m.method === 'Runtime.consoleAPICalled') {
const text = (m.params.args || []).map((a) => (a.value !== undefined ? a.value : a.description || '')).join(' ');
consoleLogs.push({ t: Date.now(), type: m.params.type, text: String(text) });
} else if (m.method === 'Log.entryAdded') {
consoleLogs.push({ t: Date.now(), type: m.params.entry.level, text: m.params.entry.text });
}
});
const evalJS = async (expr) => {
const r = await cdp.send('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true });
if (r.exceptionDetails) {
const d = r.exceptionDetails;
throw new Error((d.exception && d.exception.description) || d.text);
}
return r.result.value;
};
const json = async (expr) => JSON.parse(await evalJS(expr));
const waitFor = async (exprFn, timeoutMs) => {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
try { if (await evalJS(exprFn)) return true; } catch (e) {}
await sleep(500);
}
return false;
};
// ---------- 整页跳转后自动重新注入(等价 Tampermonkey 按 @match 重注入) ----------
let injections = 0;
let reinjectTimer = null;
const injectIfMissing = async () => {
let t;
try { t = await evalJS('typeof window.__yunXueTangAuto'); } catch (e) { return false; }
if (t === 'object') return false;
try {
await evalJS(SCRIPT_SRC);
injections++;
return true;
} catch (e) { return false; }
};
// 每 1.5 秒兜底检查一次:任何原因导致脚本不在,就补注入(真实环境里由 @match 保证)
const startWatchdog = () => {
if (reinjectTimer) clearInterval(reinjectTimer);
reinjectTimer = setInterval(() => {
injectIfMissing().then((did) => {
if (did) console.log('[RUN] ' + clock() + ' 新 document 已重新注入(第 ' + injections + ' 次)');
}).catch(() => {});
}, 1500);
};
const loaded = cdp.waitEvent('Page.loadEventFired', 45000).catch(() => null);
await cdp.send('Page.navigate', { url: ORIGIN + '/login.html' });
await loaded;
await sleep(2000);
// ---------- 登录 ----------
await evalJS(SCRIPT_SRC);
injections++;
await sleep(1200);
const loginPage = await evalJS(`!!(window.__yunXueTangAuto && window.__yunXueTangAuto.isLoginPage())`);
check('登录页脚本就绪', loginPage === true, await evalJS('location.pathname'));
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
a.fillLoginForm(${JSON.stringify(USR)}, ${JSON.stringify(PWD)});
try { a.checkLoginAgreement(); } catch (e) {}
return true;
})()`);
await evalJS(`(document.getElementById('yun-xue-tang-oneclick').click(), true)`);
const loginOk = await waitFor(`(() => {
if (/\\/login/.test(location.pathname)) return false;
if (!document.body) return false;
return !document.querySelector('input[type=password]');
})()`, 45000);
check('真实登录成功', loginOk === true, await evalJS('location.pathname'));
// 进列表(新 document)
const loaded2 = cdp.waitEvent('Page.loadEventFired', 30000).catch(() => null);
await evalJS(`(location.href = '${ORIGIN}/kng/#/list', true)`);
await loaded2;
await sleep(2500);
await injectIfMissing();
if (injections === 1) injections++; // 上面那次是列表页注入
await waitFor(`!!window.__yunXueTangAuto && window.__yunXueTangAuto.scanCards().length > 0`, 45000);
await sleep(1500);
// 优先短课程(缩短验证耗时;真机上这是默认勾选行为)
await evalJS(`(() => { try { localStorage.setItem('yun-xue-tang-prefer-short', '1'); } catch (e) {} const a = window.__yunXueTangAuto; if (a) a.state.preferShortCourses = true; return true; })()`);
// ---------- --probe:只读探测目录(关掉自动播放,避免动进度) ----------
if (PROBE) {
// 当前课程自动连播开关关掉:进课后脚本不会自动起播、也不会自动切节
await evalJS(`(() => { localStorage.setItem('yun-xue-tang-auto-play-enabled', '0'); const a = window.__yunXueTangAuto; if (a) a.state.autoPlayEnabled = false; return true; })()`);
const picks = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const ul = document.querySelector('ul.kng-list-new');
let v = ul && ul.__vue__;
while (v && !(v.kngListData && v.kngListData.length)) v = v.$parent;
const data = (v && v.kngListData) || [];
const byTitle = new Map();
for (const d of data) byTitle.set(String(d.title || d.name || '').trim(), d);
return a.scanCards()
.filter((c) => c.title && !/已学完|已完成|已学习/.test(c.status))
.map((c) => {
const d = byTitle.get(c.title) || {};
return { i: c.i, title: c.title, studyHours: Number(d.studyHours) || 0, id: String(d.id || '') };
})
.filter((c) => c.studyHours > 0)
.sort((x, y) => x.studyHours - y.studyHours)
.slice(0, ${PROBE});
})())`);
log('\n[RUN] 探测 ' + picks.length + ' 门课(按总时长正序):');
const report = [];
for (const p of picks) {
await evalJS(`(() => {
try { localStorage.setItem('yun-xue-tang-auto-play-enabled', '0'); } catch (e) {}
const a = window.__yunXueTangAuto;
a.state.autoPlayEnabled = false;
const card = a.scanCards().find((c) => c.i === ${p.i});
if (card) a.startCourse(card);
return true;
})()`).catch(() => {});
const ok = await waitFor(`(() => {
const a = window.__yunXueTangAuto;
return !!a && a.route() === 'course' && a.lessonItems().length > 0;
})()`, 25000);
let info = null;
if (ok) {
await sleep(1200);
info = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const items = a.lessonItems();
return {
lessons: items.length,
completed: items.filter((li) => a.isLessonCompleted(li)).length,
quiz: /考试|测验|问卷|答题/.test((document.querySelector('.yxtulcdsdk-catalog') || {}).innerText || ''),
names: items.map((li) => ((li.innerText || '').replace(/\\s+/g, ' ').trim()).slice(0, 22)),
summary: a.readSummary(),
};
})())`);
}
const remaining = info ? info.lessons - info.completed : 0;
log(' ' + (info ? (info.lessons + ' 节/剩 ' + remaining + (info.quiz ? ' [含考试]' : '')) : '进课失败').padEnd(18) +
' ' + String(Math.round(p.studyHours / 60)).padStart(4) + ' 分 ' + p.title.slice(0, 40));
report.push({ ...p, ...(info || {}), remaining });
// 回列表
await evalJS(`(location.href = '${ORIGIN}/kng/#/list', true)`).catch(() => {});
await sleep(2500);
await injectIfMissing();
await waitFor(`!!window.__yunXueTangAuto && window.__yunXueTangAuto.scanCards().length > 0`, 40000);
await sleep(1200);
}
const multi = report.filter((r) => r.remaining >= 2 && !r.quiz);
log('\n[RUN] 适合测「跨章节」的候选(≥2 节未学完且不含考试):');
for (const m of multi) log(' ' + m.remaining + ' 节待学 ' + m.title.slice(0, 40) + ' → ' + m.names.join(' / '));
check('找到可跨章节验证的课程(≥2 节未学完)', multi.length > 0, multi.slice(0, 5).map((m) => ({ title: m.title.slice(0, 30), remaining: m.remaining })));
fs.writeFileSync(path.join(os.tmpdir(), 'yun-xue-tang-probe.json'), JSON.stringify(report, null, 2));
} else if (SCAN) {
const cards = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
const ul = document.querySelector('ul.kng-list-new');
let v = ul && ul.__vue__;
while (v && !(v.kngListData && v.kngListData.length)) v = v.$parent;
const data = (v && v.kngListData) || [];
const byTitle = new Map();
for (const d of data) byTitle.set(String(d.title || d.name || '').trim(), d);
return a.scanCards().map((c) => {
const d = byTitle.get(c.title) || {};
return { title: c.title, status: c.status, studyHours: d.studyHours, id: String(d.id || '') };
});
})())`);
log('\n[RUN] 列表卡片(' + cards.length + ' 张):');
for (const c of cards) {
log(' ' + (c.status || '-').padEnd(4) + ' ' +
(c.studyHours ? String(Math.round(c.studyHours / 60)).padStart(5) + ' 分' : ' ? 分') +
' ' + c.title.slice(0, 46));
}
check('列表可读', cards.length > 0, { 卡片数: cards.length });
} else {
// ---------- 启动批量 ----------
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
a.S.completedThisRun = 0;
a.S.batchFinished = false;
a.startBatch();
return true;
})()`);
await sleep(1500);
// 指定课程:进入列表后抢先开始它(S.batchRunning 先关掉,避免 listTick 抢选别的课)
if (PIN_TITLE) {
const armed = await waitFor(`window.__yunXueTangAuto && window.__yunXueTangAuto.route() === 'list' && window.__yunXueTangAuto.scanCards().length > 0`, 60000);
if (armed) {
const pinned = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
a.S.batchRunning = false; a.save();
const card = a.scanCards().find((c) => c.title.indexOf(${JSON.stringify(PIN_TITLE)}) >= 0);
if (!card) { a.S.batchRunning = true; a.save(); return { ok: false }; }
a.startCourse(card);
a.S.batchRunning = true; a.save();
return { ok: true, title: card.title };
})())`);
check('已指定首门课程并开始', pinned.ok === true, pinned);
} else {
check('已指定首门课程并开始', false, '列表未就绪');
}
}
// ---------- 持续监控 ----------
const startedAt = Date.now();
const deadline = startedAt + BUDGET_MIN * 60 * 1000;
let lastSig = '';
let lastSample = null;
let lastAdvanceAt = Date.now();
let lastCt = 0;
let maxStallMs = 0;
const perCourse = new Map(); // title -> lesson keys seen
const transitions = []; // { t, from, to, course }
let playEvidence = 0; // currentTime 增长次数
const sample = async () => {
try {
return await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
if (!a) return { gone: true, href: location.href };
const v = document.querySelector('video, audio');
const items = a.lessonItems();
return {
href: location.href,
route: a.route(),
phase: a.S.coursePhase,
running: a.S.batchRunning,
runFinished: a.S.batchFinished,
completed: a.S.completedThisRun,
pendingRetries: Object.keys(a.S.courseRetries || {}).length,
cur: a.S.activeCourse ? a.S.activeCourse.title : null,
curId: a.S.activeCourse ? a.S.activeCourse.id : null,
lesson: a.readActiveLessonKey ? a.readActiveLessonKey() : '',
lessonCount: items.length,
summary: a.readSummary(),
countdown: a.readCountdown(),
status: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
video: v ? { ct: Math.round(v.currentTime), dur: Math.round(v.duration), paused: v.paused, muted: v.muted, rate: v.playbackRate } : null,
done: Object.keys(a.S.completedTitles || {}).length,
retryTitles: Object.keys(a.S.courseRetries || {}).length,
};
})())`);
} catch (e) {
return null; // 跳转中 DOM 不可用
}
};
log('\n[RUN] 开始持续监控(Ctrl+C 或到点自动结束)…\n');
while (Date.now() < deadline) {
const s = await sample();
if (s && !s.gone) {
lastSample = s;
// 视频推进证据
if (s.video && !s.video.paused && s.video.ct > lastCt) {
playEvidence++;
lastAdvanceAt = Date.now();
lastCt = s.video.ct;
} else if (s.video && s.video.paused && s.video.ct !== lastCt) {
lastCt = s.video.ct;
}
if (Date.now() - lastAdvanceAt > maxStallMs) maxStallMs = Date.now() - lastAdvanceAt;
// 每门课出现过的课时
if (s.cur) {
if (!perCourse.has(s.cur)) perCourse.set(s.cur, []);
const keys = perCourse.get(s.cur);
if (s.lesson && keys[keys.length - 1] !== s.lesson) keys.push(s.lesson);
}
const sig = [s.cur, s.lesson, s.completed, s.phase, s.runFinished].join('|');
if (sig !== lastSig) {
const prev = lastSample && lastSig ? lastSig.split('|') : null;
log('[RUN] ' + clock() + ' ' + (s.cur ? s.cur.slice(0, 26) : '(列表)') +
' ' + (s.phase || '-') + (s.runFinished ? ' [已停止]' : '') +
' 完成 ' + s.completed + ' 待重试 ' + s.pendingRetries +
(s.lesson ? ' 课时:' + s.lesson.slice(0, 30) : '') +
(s.summary ? ' 汇总:' + s.summary.text : '') +
(s.countdown != null ? ' 倒计时 ' + s.countdown + 's' : ''));
if (prev && prev[0] && s.cur && prev[0] === s.cur && prev[1] && s.lesson && prev[1] !== s.lesson) {
transitions.push({ t: Date.now() - startedAt, course: s.cur, from: prev[1], to: s.lesson });
}
timeline.push({ at: Date.now() - startedAt, ...s });
lastSig = sig;
}
if (s.completed >= MAX_COURSES) { log('\n[RUN] 已完成 ' + s.completed + ' 门,达到上限,收尾'); break; }
if (s.runFinished) { log('\n[RUN] 脚本自己停止了:' + s.status); break; }
if (s.runFinished && /重试 .* 次仍未完成/.test(s.status || '')) { log('[RUN] 重试用尽,脚本已停止,收尾'); break; }
}
await sleep(2000);
}
const elapsed = Math.round((Date.now() - startedAt) / 1000);
const errors = consoleLogs.filter((l) => l.type === 'error' && /云学堂助手/.test(l.text));
const final = (await sample()) || lastSample || {};
check('持续运行未因脚本 exception 中断', errors.length === 0, errors.map((e) => e.text.slice(0, 140)));
check('批处理仍在运行或已按上限结束', final.runFinished !== undefined, { running: final.running, runFinished: final.runFinished });
check('至少完成 2 门课程(跨课程)', (final.completed || 0) >= 2, { 完成: final.completed, 用时秒: elapsed });
check('观察到课时自动切换(跨章节)', transitions.length >= 1, { 切换次数: transitions.length, 明细: transitions.map((x) => x.from.slice(0, 14) + ' → ' + x.to.slice(0, 14)) });
check('视频持续推进(无长时间卡死)', playEvidence >= 3 && maxStallMs < 120000, { 推进采样: playEvidence, 最长停滞秒: Math.round(maxStallMs / 1000) });
check('整页跳转后自动恢复(重新注入)', injections >= 2, { 注入次数: injections });
check('没有课程被永久跳过(重试计数可控)', (final.retryTitles || 0) < 5, { 待重试标题: final.retryTitles });
log('\n[RUN] 每门课观察到的课时:');
for (const [title, keys] of perCourse) {
log(' ' + title.slice(0, 34) + ' → ' + keys.length + ' 节:' + keys.map((k) => k.slice(0, 18)).join(' / '));
}
log('[RUN] 完成后本地已记录 done:' + (final.done || 0) + ' 门;用时 ' + Math.round(elapsed / 60) + ' 分 ' + (elapsed % 60) + ' 秒');
// 收尾:停批量 + 暂停媒体
await evalJS(`(() => {
const a = window.__yunXueTangAuto;
if (a) { a.S.batchRunning = false; a.save(); if (a.pauseAllMedia) a.pauseAllMedia(); }
return true;
})()`).catch(() => {});
await sleep(1000);
const disposed = await json(`JSON.stringify((() => {
try { window.__yunXueTangDispose(); } catch (e) {}
return { panel: !!document.getElementById('yun-xue-tang-panel'), api: typeof window.__yunXueTangAuto };
})())`).catch(() => ({ panel: null, api: 'n/a' }));
check('dispose 后面板与 API 清理干净', disposed.panel === false && disposed.api === 'undefined', disposed);
}
log('\n[RUN] 脚本日志(' + consoleLogs.filter((l) => /云学堂助手/.test(l.text)).length + ' 条):');
for (const l of consoleLogs.filter((x) => /云学堂助手/.test(x.text)).slice(-40)) log(' [' + l.type + '] ' + l.text.slice(0, 170));
} catch (e) {
check('持续运行流程执行完毕', false, e && e.stack ? e.stack.split('\n').slice(0, 5).join(' | ') : String(e));
} finally {
if (cdp && !KEEP) cdp.close();
if (chrome && !KEEP) { try { chrome.kill(); } catch (e) {} }
if (!KEEP) { await sleep(700); try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch (e) {} }
else log('[RUN] --keep:浏览器保持打开 ' + userDataDir);
try {
fs.writeFileSync(OUT, JSON.stringify({ timeline, results, logs: consoleLogs.slice(-400) }, null, 2));
log('[RUN] 时间线已写入 ' + OUT);
} catch (e) { /* ignore */ }
}
const failed = results.filter((r) => !r.ok);
log('\n===== RUN 结果:' + (results.length - failed.length) + '/' + results.length + ' 通过,失败 ' + failed.length + ' =====');
for (const f of failed) log(' FAIL ' + f.name + ' → ' + JSON.stringify(f.detail));
process.exit(failed.length ? 1 : 0);
+329
View File
@@ -0,0 +1,329 @@
#!/usr/bin/env node
/**
* 真机测试:真实 Chrome + 真实 https://kfmic.yunxuetang.cn 页面。
*
* 做法:启动一个独立用户目录的 Chrome(不碰你日常配置),通过 CDP 把打包产物
* yun-xue-tang-assistant.user.js 注入页面主世界——这与 Tampermonkey 在
* @grant none 下的执行环境一致,所以断言的是脚本在真实浏览器 / 真实站点
* DOM 上的行为,而不是 Node 里的 DOM 桩。
*
* 用法:
* node dev/real-test.mjs 有界面浏览器(默认,最接近真机)
* node dev/real-test.mjs --headless 无头模式(CI 用)
* node dev/real-test.mjs --keep 跑完不关浏览器(便于人工肉眼复核)
*
* 环境变量:
* YUN_XUE_TANG_CHROME Chrome/Edge 可执行文件路径
* YUN_XUE_TANG_CDP_PORT 调试端口,默认 9333
* YUN_XUE_TANG_URL 起始页面,默认 https://kfmic.yunxuetang.cn/login.html
* YUN_XUE_TANG_SHOT_DIR 截图目录,默认 .run-tmp/screenshots(不入库)
*
* 需要 Node 22+(用到全局 WebSocket 与 fetch);只做只读探测:
* 不填写账号密码、不点登录、不修改线上数据。
*/
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { connect, sleep, httpJson, findChrome, forceHeadless, safetyArgs } from './real-cdp.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
// 本文件在 dev/tests/ 下,仓库根目录是上两级
const ROOT = path.resolve(HERE, '..', '..');
const SCRIPT_FILE = path.join(ROOT, 'yun-xue-tang-assistant.user.js');
const SCRIPT_SRC = fs.readFileSync(SCRIPT_FILE, 'utf8');
// 版本号只有 package.json 一个来源(与 build.mjs 注入产物的一致),避免断言写死后每次升版都要改测试
const VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
const EXPECT_VERSION = 'v' + VERSION;
const CANDIDATES = [
process.env.YUN_XUE_TANG_CHROME,
'C:/Program Files/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
'C:/Program Files/Microsoft/Edge/Application/msedge.exe',
'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
].filter(Boolean);
const CHROME = findChrome(CANDIDATES);
const PORT = Number(process.env.YUN_XUE_TANG_CDP_PORT || 9333);
const START_URL = process.env.YUN_XUE_TANG_URL || 'https://kfmic.yunxuetang.cn/login.html';
const HEADLESS = process.env.YUN_XUE_TANG_HEADLESS === '1' || process.argv.includes('--headless');
const KEEP = process.env.YUN_XUE_TANG_KEEP === '1' || process.argv.includes('--keep');
const SHOT_DIR = process.env.YUN_XUE_TANG_SHOT_DIR || path.join(ROOT, '.run-tmp', 'screenshots');
const results = [];
const consoleLogs = [];
const log = (...a) => console.log(...a);
function check(name, ok, detail) {
results.push({ name, ok: !!ok, detail });
log((ok ? ' PASS ' : ' FAIL ') + name + (detail === undefined ? '' : ' → ' + JSON.stringify(detail)));
}
if (typeof WebSocket !== 'function' || typeof fetch !== 'function') {
console.error('需要 Node 22 及以上(依赖全局 WebSocket / fetch),当前 ' + process.version);
process.exit(2);
}
if (!CHROME) {
console.error('找不到 Chrome/Edge,可用 YUN_XUE_TANG_CHROME=/path/to/chrome 指定');
process.exit(2);
}
if (!fs.existsSync(SCRIPT_FILE)) {
console.error('缺少构建产物,先运行 npm run build');
process.exit(2);
}
// Linux 无图形化服务器:没有 DISPLAY 时强制无头,并补容器/root 必需参数
const HEADLESS_ONLY = HEADLESS || forceHeadless();
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yun-xue-tang-chrome-'));
const args = [
`--remote-debugging-port=${PORT}`,
`--user-data-dir=${userDataDir}`,
'--no-first-run', '--no-default-browser-check', '--disable-sync',
'--disable-background-timer-throttling', '--disable-renderer-backgrounding',
'--disable-backgrounding-occluded-windows',
'--window-size=1280,900',
].concat(safetyArgs(), ['about:blank']);
if (HEADLESS_ONLY) args.unshift('--headless=new');
let chrome = null;
let cdp = null;
try {
log('[真机] 浏览器:' + CHROME + (HEADLESS_ONLY ? '(headless=new)' : '(有界面)'));
chrome = spawn(CHROME, args, { stdio: 'ignore', windowsHide: true });
// ---- 1. 等 CDP 就绪 ----
let version = null;
for (let i = 0; i < 100; i++) {
try {
const v = await httpJson(`http://127.0.0.1:${PORT}/json/version`);
if (v && v.webSocketDebuggerUrl) { version = v; break; }
} catch (e) { /* 还没起来 */ }
await sleep(250);
}
if (!version) throw new Error('Chrome CDP 端口未就绪(' + PORT + ')');
check('真实浏览器进程启动', /^(Chrome|HeadlessChrome|Edg)\//.test(version.Browser || ''), version.Browser);
// ---- 2. 打开真实页面 ----
const target = await httpJson(`http://127.0.0.1:${PORT}/json/new?${encodeURIComponent(START_URL)}`, 'PUT');
cdp = await connect(target.webSocketDebuggerUrl);
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Log.enable');
await cdp.send('Network.enable');
cdp.onEvent((m) => {
if (m.method === 'Runtime.consoleAPICalled') {
const text = (m.params.args || []).map((a) => (a.value !== undefined ? a.value : a.description || '')).join(' ');
consoleLogs.push({ type: m.params.type, text: String(text) });
} else if (m.method === 'Log.entryAdded') {
consoleLogs.push({ type: m.params.entry.level, text: m.params.entry.text });
}
});
const evalJS = async (expr) => {
const r = await cdp.send('Runtime.evaluate', {
expression: expr, returnByValue: true, awaitPromise: true, userGesture: true,
});
if (r.exceptionDetails) {
const d = r.exceptionDetails;
throw new Error((d.exception && d.exception.description) || d.text);
}
return r.result.value;
};
const json = async (expr) => JSON.parse(await evalJS(expr));
const loaded = cdp.waitEvent('Page.loadEventFired', 45000).catch(() => null);
await cdp.send('Page.navigate', { url: START_URL });
await loaded;
await sleep(1800);
const page = await json(`JSON.stringify({ url: location.href, title: document.title, host: location.host, ua: navigator.userAgent })`);
log('[真机] 页面:' + page.url);
log('[真机] 标题:' + page.title);
check('落在真实云学堂页面', /(^|\.)yunxuetang\.cn$/.test(page.host), page.host);
check('真实浏览器内核', /Chrome\//.test(page.ua), page.ua.slice(0, 96) + '…');
// ---- 3. 注入(等价 Tampermonkey @grant none 主世界执行)----
check('注入前页面无残留实例', (await evalJS('typeof window.__yunXueTangAuto')) === 'undefined', await evalJS('typeof window.__yunXueTangAuto'));
await evalJS(SCRIPT_SRC);
await sleep(1200);
const loadedLog = consoleLogs.find((l) => /云学堂助手 v[\d.]+ 已加载/.test(l.text));
check('控制台打印加载日志', !!loadedLog, loadedLog && loadedLog.text);
// ---- 4. 面板在真实 DOM 里的渲染 ----
const panel = await json(`JSON.stringify((() => {
const el = document.getElementById('yun-xue-tang-panel');
if (!el) return null;
const r = el.getBoundingClientRect();
const cs = getComputedStyle(el);
return {
version: (document.getElementById('yun-xue-tang-version') || {}).textContent || '',
w: Math.round(r.width), h: Math.round(r.height),
right: Math.round(innerWidth - r.right), bottom: Math.round(innerHeight - r.bottom),
visible: cs.display !== 'none' && cs.visibility !== 'hidden' && Number(cs.opacity) > 0,
position: cs.position, zIndex: cs.zIndex,
buttons: [...el.querySelectorAll('button')].map((b) => b.textContent.trim()),
inputTypes: [...el.querySelectorAll('input')].map((i) => i.type),
text: el.innerText.replace(/\\s+/g, ' ').trim().slice(0, 220),
};
})())`);
check('面板渲染进真实 DOM 且可见', panel && panel.visible && panel.w > 0 && panel.h > 0,
panel && { 宽: panel.w, 高: panel.h, position: panel.position, zIndex: panel.zIndex });
check('面板版本号 ' + EXPECT_VERSION, panel && panel.version === EXPECT_VERSION, panel && panel.version);
check('固定在右下角', panel && panel.right >= 0 && panel.right < 40 && panel.bottom >= 0 && panel.bottom < 40,
panel && { 距右: panel.right, 距下: panel.bottom });
check('面板含按钮与密码框', panel && panel.buttons.length >= 2 && panel.inputTypes.includes('password'),
panel && { 按钮: panel.buttons, 输入框: panel.inputTypes });
// ---- 5. 真实页面上调试入口 / 页面识别 ----
const api = await json(`JSON.stringify((() => {
const a = window.__yunXueTangAuto;
if (!a) return null;
return {
keys: Object.keys(a).length,
route: a.route(),
isLoginPage: a.isLoginPage(),
hasDispose: typeof window.__yunXueTangDispose === 'function',
courseId: a.courseIdFromUrl(),
summary: a.readSummary(),
countdown: a.readCountdown(),
};
})())`);
check('window.__yunXueTangAuto 调试入口存在', !!api && api.keys > 20, api && { 导出项: api.keys });
check('真实登录页被正确识别', api && api.isLoginPage === true, api && { route: api.route, isLoginPage: api.isLoginPage });
check('__yunXueTangDispose 可用(热替换前提)', api && api.hasDispose === true, api && api.hasDispose);
check('登录页上 readSummary/readCountdown 安全返回 null',
api && api.summary === null && api.countdown === null, api && { summary: api.summary, countdown: api.countdown });
// ---- 6. 真实点击面板按钮(不填账号,只验证不崩)----
const click = await json(`JSON.stringify((() => {
const panel = document.getElementById('yun-xue-tang-panel');
const btn = document.getElementById('yun-xue-tang-oneclick');
if (!btn) return { error: 'no #yun-xue-tang-oneclick' };
btn.click();
return {
label: btn.textContent.trim(),
panelVisibleAfter: getComputedStyle(panel).display !== 'none',
statusLine: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
panelText: panel.innerText.replace(/\\s+/g, ' ').slice(0, 200),
};
})())`);
await sleep(800);
const afterClick = await json(`JSON.stringify(({
url: location.href,
alive: typeof window.__yunXueTangAuto,
panel: !!document.getElementById('yun-xue-tang-panel'),
}))`);
check('点击「一键登录并刷课」不崩溃', afterClick.alive === 'object' && afterClick.panel === true, { 点击前标签: click.label, ...afterClick });
const scriptErrors = () => consoleLogs.filter((l) => l.type === 'error' && /云学堂助手/.test(l.text));
check('无脚本自身 error 日志', scriptErrors().length === 0, scriptErrors().map((e) => e.text.slice(0, 140)));
// ---- 7. 真实 localStorage 读写 ----
const ls = await json(`JSON.stringify((() => {
const before = localStorage.getItem('yun-xue-tang-auto-play-enabled');
localStorage.setItem('yun-xue-tang-auto-play-enabled', '0');
const read = localStorage.getItem('yun-xue-tang-auto-play-enabled');
if (before === null) localStorage.removeItem('yun-xue-tang-auto-play-enabled'); else localStorage.setItem('yun-xue-tang-auto-play-enabled', before);
return { read, keys: Object.keys(localStorage).filter((k) => k.indexOf('yun-xue-tang-') === 0) };
})())`);
check('真实 localStorage 可读写', ls.read === '0', ls);
// ---- 8. 真实热替换:dispose → 重新注入 ----
const hot = await json(`JSON.stringify((() => {
window.__yunXueTangDispose();
return { panel: !!document.getElementById('yun-xue-tang-panel'), api: typeof window.__yunXueTangAuto, dispose: typeof window.__yunXueTangDispose };
})())`);
await evalJS(SCRIPT_SRC);
await sleep(900);
const hot2 = await json(`JSON.stringify({
count: document.querySelectorAll('#yun-xue-tang-panel').length,
api: typeof window.__yunXueTangAuto,
version: (document.getElementById('yun-xue-tang-version') || {}).textContent,
timers: 'n/a',
})`);
check('dispose 后真实 DOM 面板被移除', hot.panel === false && hot.api === 'undefined',
hot);
check('重新注入后面板唯一且版本正确', hot2.count === 1 && hot2.api === 'object' && hot2.version === EXPECT_VERSION, hot2);
// ---- 9. 截图存证 ----
try {
fs.mkdirSync(SHOT_DIR, { recursive: true });
const shot = await cdp.send('Page.captureScreenshot', { format: 'png' });
const file = path.join(SHOT_DIR, 'real-chrome-login.png');
fs.writeFileSync(file, Buffer.from(shot.data, 'base64'));
const size = fs.statSync(file).size;
check('真机截图已保存', size > 5000, path.relative(ROOT, file) + ' (' + size + ' 字节)');
} catch (e) {
check('真机截图已保存', false, e.message);
}
// ---- 10. SPA 内 hash 路由(不换 document):脚本靠 hashchange 自更新,不需要重新注入 ----
const hashNav = await json(`JSON.stringify((() => {
location.hash = '#/list';
return { hash: location.hash, route: window.__yunXueTangAuto.route(), panel: !!document.getElementById('yun-xue-tang-panel') };
})())`);
await sleep(600);
const hashAfter = await json(`JSON.stringify({ hash: location.hash, route: window.__yunXueTangAuto.route(), alive: typeof window.__yunXueTangAuto })`);
check('SPA 内 hash 切换后脚本自动跟随路由', hashAfter.route === 'list' && hashAfter.alive === 'object', { 切前: hashNav, 切后: hashAfter });
// ---- 11. 未登录访问 #/list:站点整页重定向到登录页(新 document)----
// 真实 Tampermonkey 会在新 document 上按 @match 重新注入,这里同样重新注入后再断言。
// 先订阅 load 事件再触发跳转,避免竞态。
const redirected = cdp.waitEvent('Page.loadEventFired', 30000).catch(() => null);
await evalJS(`(() => { window.__yunXueTangDocMarker = 'before-nav'; location.href = 'https://kfmic.yunxuetang.cn/kng/#/list'; return true; })()`);
await redirected;
await sleep(2500);
const afterNav = await json(`JSON.stringify({
url: location.href,
host: location.host,
title: document.title,
newDocument: window.__yunXueTangDocMarker === undefined,
alive: typeof window.__yunXueTangAuto,
})`);
check('未登录访问 #/list 被站点重定向(document 已换新)',
/(^|\.)yunxuetang\.cn$/.test(afterNav.host) && afterNav.newDocument === true, afterNav);
check('新 document 上脚本未残留(重定向后必须重新注入)', afterNav.alive === 'undefined', afterNav.alive);
// 模拟 Tampermonkey 在新 document 上按 @match 自动注入
await evalJS(SCRIPT_SRC);
await sleep(1200);
const reinjected = await json(`JSON.stringify({
url: location.href,
route: window.__yunXueTangAuto ? window.__yunXueTangAuto.route() : 'no-api',
isLoginPage: window.__yunXueTangAuto ? window.__yunXueTangAuto.isLoginPage() : null,
panel: document.querySelectorAll('#yun-xue-tang-panel').length,
version: (document.getElementById('yun-xue-tang-version') || {}).textContent,
bodyScrollable: document.body.scrollHeight > 0,
})`);
check('重定向后重新注入:面板唯一且脚本正常',
reinjected.panel === 1 && reinjected.version === EXPECT_VERSION && reinjected.route !== 'no-api', reinjected);
check('列表页导航无脚本报错', scriptErrors().length === 0, scriptErrors().map((e) => e.text.slice(0, 140)));
// ---- 汇总控制台 ----
log('\n[真机] 控制台共 ' + consoleLogs.length + ' 条,最后 15 条:');
for (const l of consoleLogs.slice(-15)) log(' [' + l.type + '] ' + l.text.slice(0, 170));
} catch (e) {
check('真机流程执行完毕', false, e && e.stack ? e.stack.split('\n').slice(0, 4).join(' | ') : String(e));
} finally {
if (cdp && !KEEP) cdp.close();
if (chrome && !KEEP) { try { chrome.kill(); } catch (e) {} }
if (!KEEP) {
await sleep(600);
try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch (e) {}
} else {
log('[真机] YUN_XUE_TANG_KEEP=1,浏览器保持打开:' + userDataDir);
}
}
const failed = results.filter((r) => !r.ok);
log('\n===== 真机结果:' + (results.length - failed.length) + '/' + results.length + ' 通过,失败 ' + failed.length + ' =====');
for (const f of failed) log(' FAIL ' + f.name + ' → ' + JSON.stringify(f.detail));
process.exit(failed.length ? 1 : 0);