2026-10-21 15:41:55 +08:00

172 lines
9.6 KiB
JavaScript
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.

const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const vm = require('node:vm');
const path = require('node:path');
const {EventEmitter} = require('node:events');
const source = fs.readFileSync(path.join(__dirname, '../task-manager.auto.js'), 'utf8');
// 仅模拟控件交互和文件接口;Android 实际布局、悬浮窗与权限仍需后续真机验证。
function load() {
let time = 1000;
class Clock extends Date {constructor(...args) {super(...(args.length ? args : [time]));} static now() {return time;}}
class View extends EventEmitter {
constructor() {super(); this.value = ''; this.checked = false; this.enabled = true; this.children = [];}
setText(value) {this.value = String(value);} text() {return this.value;}
setChecked(value) {this.checked = value;} isChecked() {return this.checked;}
setEnabled(value) {this.enabled = value;}
setSelection(value) {this.selection = value;} getSelectedItemPosition() {return this.selection;}
addView(view) {this.children.push(view);} removeAllViews() {this.children = [];}
}
const xmls = [];
const inflate = xml => {
xmls.push(xml);
const root = new View();
for (const match of xml.matchAll(/\bid="([^"]+)"/g)) root[match[1]] = new View();
return root;
};
const memory = {};
const paths = new Set(['/sdcard/脚本/番茄/fanqie-daily.auto.js', '/sdcard/脚本/红果/hongguo-daily.auto.js', '/sdcard/custom.js']);
const files = {path: p => p, join: path.posix.join, getName: path.posix.basename,
ensureDir() {}, exists: p => paths.has(p) || Object.hasOwn(memory, p), isDir: () => false,
read: p => memory[p], write: (p, s) => {memory[p] = s;}, append: (p, s) => {memory[p] = (memory[p] || '') + s;},
copy: (from, to) => {memory[to] = memory[from]; return true;}};
class File {
constructor(p) {this.path = p;} getCanonicalPath() {return path.posix.normalize(this.path);}
getParent() {return this.path === '/' ? null : path.posix.dirname(this.path);}
length() {return (memory[this.path] || '').length;}
renameTo(target) {memory[target.path] = memory[this.path]; delete memory[this.path]; return true;}
}
const me = {id: 99, getId: () => 99, getSource: () => '/manager/task-manager.auto.js'};
const engines = new EventEmitter();
engines.all = () => [me]; engines.myEngine = () => me;
const launches = [];
engines.execScriptFile = script => {
const engine = {id: 100 + launches.length, destroyed: false, stops: 0,
getId() {return this.id;}, isDestroyed() {return this.destroyed;},
getUncaughtException: () => null, forceStop() {this.stops++;}};
launches.push({path: script, engine});
return {getId: () => engine.id, getEngine: () => engine};
};
const ui = {emitter: new EventEmitter(), inflate, layout(xml) {Object.assign(this, inflate(xml));}};
let currentDialog;
const dialogs = {build(options) {
currentDialog = Object.assign(new EventEmitter(), {options, show() {}, dismiss() {this.dismissed = true;}});
return currentDialog;
}, confirm(_title, _text, callback) {callback(true);}};
const toasts = [], timers = [];
let backgrounds = 0;
const ctx = vm.createContext({Date: Clock, Math, JSON, Error, ui, files, engines, dialogs,
java: {io: {File}}, activity: {moveTaskToBack() {backgrounds++;}, finish() {}},
events: new EventEmitter(), floaty: {hasPermission: () => false, requestPermission() {}},
toast: s => toasts.push(s), toastLog: s => toasts.push(s), log() {}, exit() {throw Error('exit');},
setInterval: action => timers.push(action),
require: modulePath => require(path.join(__dirname, '..', modulePath.replace('/manager/', '')))});
vm.runInContext(source, ctx);
return {ctx, ui, engines, memory, xmls, launches, toasts, timers,
get dialog() {return currentDialog;}, get backgrounds() {return backgrounds;},
advance(delta) {time += delta; timers[0]();}};
}
test('任务启停状态修改多次并排序后,保存的是最新值而非旧闭包', () => {
const h = load();
h.ctx.rowControls[0][0].emit('check', false);
h.ctx.rowControls[0][0].emit('check', true);
h.ctx.rowControls[0][0].emit('check', false);
assert.equal(h.ctx.plan.tasks[0].enabled, false);
h.ctx.rowControls[0][2].emit('click');
assert.equal(h.ctx.plan.tasks[1].name, '番茄小说');
assert.equal(h.ctx.plan.tasks[1].enabled, false);
const saved = JSON.parse(h.memory['/manager/data/plan.json']);
assert.equal(saved.tasks[1].enabled, false);
assert.equal(saved.tasks[0].name, '红果免费短剧');
});
test('使用真实AutoJs6文件接口子集启动,并能从中文目录返回上级和根目录', () => {
const h = load();
assert.equal(h.ctx.files.dirname, undefined);
assert.equal(h.ctx.BASE, '/manager');
assert.equal(h.ctx.parentDirectory('/sdcard/脚本/任务管理器'), '/sdcard/脚本');
assert.equal(h.ctx.parentDirectory('/'), '/');
const visited = [];
h.ctx.files.isDir = () => true;
h.ctx.files.listDir = directory => {visited.push(directory); return [];};
let select;
h.ctx.dialogs.select = (_title, _items, callback) => {select = callback;};
h.ctx.browseScript('/sdcard/脚本', () => {});
select(0);
assert.deepEqual(visited, ['/sdcard/脚本', '/sdcard']);
});
test('添加任务表单实际保存路径、单次次数、超时、重试和失败策略', () => {
const h = load(); h.ui.addButton.emit('click');
const form = h.dialog.options.customView;
form.taskName.setText('测试任务'); form.taskPath.setText('/sdcard/custom.js');
form.timesInput.setText('3'); form.timeoutInput.setText('5'); form.retryInput.setText('2'); form.policyInput.setSelection(1);
h.dialog.emit('positive');
const saved = JSON.parse(h.memory['/manager/data/plan.json']);
assert.equal(saved.tasks.length, 3);
assert.deepEqual({...saved.tasks[2], id: 'id'}, {id: 'id', name: '测试任务', path: '/sdcard/custom.js', enabled: true,
times: 3, timeoutMinutes: 5, retries: 2, onFailure: 'stop', resultLog: ''});
assert.equal(h.dialog.dismissed, true);
});
test('开始整组会保存设置并退到后台;运行中锁定编辑,停止按钮等待旧引擎退出', () => {
const h = load(); h.ui.floatSwitch.setChecked(false); h.ui.loopsInput.setText('0');
h.ui.startButton.emit('click');
assert.equal(h.ctx.scheduler.phase, 'waiting'); assert.equal(h.backgrounds, 1);
assert.equal(h.ui.addButton.enabled, false); assert.equal(h.ui.stopButton.enabled, true);
assert.equal(JSON.parse(h.memory['/manager/data/plan.json']).loops, 0);
h.advance(500); assert.equal(h.launches.length, 1);
h.ui.stopButton.emit('click'); h.advance(500);
assert.equal(h.ctx.scheduler.phase, 'stopping'); assert.equal(h.launches[0].engine.stops, 1);
h.advance(500); assert.equal(h.launches.length, 1);
const e = h.launches[0].engine; e.destroyed = true; h.engines.emit('finish', e); h.advance(500);
assert.equal(h.ctx.scheduler.phase, 'stopped'); assert.equal(h.ui.startButton.enabled, true);
assert.equal(h.toasts.length, 0);
});
test('缺少悬浮权限时不启动任务,不将权限请求误算为正在执行', () => {
const h = load(); h.ui.startButton.emit('click'); h.advance(1000);
assert.equal(h.launches.length, 0); assert.equal(h.ctx.scheduler.phase, 'idle');
assert.match(h.toasts[0], /悬浮窗权限/);
});
test('主界面暂停继续按钮保留任务状态,暂停后可停止并恢复编辑', () => {
const h = load();
assert.equal(h.ui.pauseButton.enabled, false);
h.ui.floatSwitch.setChecked(false); h.ui.startButton.emit('click'); h.advance(500);
h.ui.pauseButton.emit('click');
assert.equal(h.ctx.scheduler.phase, 'pausing'); assert.equal(h.ui.pauseButton.value, '继续');
const e = h.launches[0].engine; e.destroyed = true; h.engines.emit('finish', e); h.advance(500);
assert.equal(h.ctx.scheduler.phase, 'paused'); assert.equal(h.ui.addButton.enabled, false);
h.advance(100000); assert.equal(h.launches.length, 1);
h.ui.pauseButton.emit('click'); h.advance(3000);
assert.equal(h.launches.length, 2); assert.equal(h.ui.pauseButton.value, '暂停');
h.ui.pauseButton.emit('click'); h.ui.stopButton.emit('click'); h.advance(500);
const next = h.launches[1].engine; next.destroyed = true; h.engines.emit('finish', next); h.advance(500);
assert.equal(h.ctx.scheduler.phase, 'stopped');
assert.equal(h.ui.pauseButton.enabled, false); assert.equal(h.ui.addButton.enabled, true);
});
test('任务删除只移除列表,不删除脚本文件;运行中返回键只退到后台', () => {
const h = load(); h.ctx.rowControls[1][4].emit('click');
assert.equal(h.ctx.plan.tasks.length, 1);
h.ui.floatSwitch.setChecked(false); h.ui.startButton.emit('click');
const event = {}; h.ui.emitter.emit('back_pressed', event);
assert.equal(event.consumed, true); assert.equal(h.backgrounds, 2);
});
test('表单保存遇到无效整组设置时不半提交任务,修正后重试不会重复添加', () => {
const h = load(); h.ui.addButton.emit('click');
const form = h.dialog.options.customView;
form.taskName.setText('测试任务'); form.taskPath.setText('/sdcard/custom.js');
h.ui.loopsInput.setText('-1'); h.dialog.emit('positive');
assert.equal(h.ctx.plan.tasks.length, 2);
assert.notEqual(h.dialog.dismissed, true);
h.ui.loopsInput.setText('1'); h.dialog.emit('positive');
assert.equal(h.ctx.plan.tasks.length, 3); assert.equal(h.dialog.dismissed, true);
});
module.exports = {load};