// 离线模拟 Android PackageManager 和进程,不卸载真实应用。 const test = require('node:test'); const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const vm = require('node:vm'); const source = fs.readFileSync(path.join(__dirname, '..', 'uninstall_today_apps.js'), 'utf8'); function load(infos = []) { const logs = []; const calls = []; const pm = { getInstalledPackages: () => ({ size: () => infos.length, get: i => infos[i], }) }; const c = vm.createContext({ console: { log: message => logs.push(message) }, context: { getPackageName: () => 'org.autojs.autojs6', getPackageManager: () => pm, }, }); const entry = source.lastIndexOf('\ntry {\n main();'); assert.ok(entry > 0); vm.runInContext(source.slice(0, entry), c); const realRunCommand = c.runCommand; c.runCommand = command => { calls.push({ command, root: c.CONFIG.shellRoot }); return { code: 0, result: command === 'id' ? 'uid=0(root) gid=0(root)' : 'Success\n', error: '' }; }; return { c, logs, calls, pm, realRunCommand }; } function info(name, time, flags = 0) { return { packageName: name, firstInstallTime: time, applicationInfo: { flags } }; } test('本地自然日包含零点但不包含次日零点', () => { const { c } = load(); const now = new Date(2026, 6, 3, 15, 20); const range = c.getDayRange(now); assert.equal(range.start, new Date(2026, 6, 3).getTime()); assert.equal(range.end, new Date(2026, 6, 4).getTime()); assert.equal(c.isEligible(info('com.example.start', range.start), range, 'self'), true); assert.equal(c.isEligible(info('com.example.end', range.end), range, 'self'), false); assert.equal(c.isEligible(info('com.example.old', range.start - 1), range, 'self'), false); }); test('过滤系统应用、自身、保留项、无效时间及非法包名,去重排序', () => { const infos = [ info('com.example.z', 100), info('com.example.a', 100), info('com.example.z', 100), info('com.example.system', 100, 1), info('com.example.updatedsystem', 100, 128), info('org.autojs.autojs6', 100), info('com.example.keep', 100), info('com.example.bad;id', 100), info('com.example.nan', NaN), { packageName: 'com.example.noinfo', firstInstallTime: 100 }, ]; const { c, pm } = load(infos); c.CONFIG.keepPackages = ['com.example.keep']; assert.deepEqual(Array.from(c.collectPackages(pm, { start: 100, end: 200 }, 'org.autojs.autojs6')), ['com.example.a', 'com.example.z']); }); test('只看 firstInstallTime,不把今天更新的旧应用算进来', () => { const { c } = load(); const app = info('com.example.old', 10); app.lastUpdateTime = 150; assert.equal(c.isEligible(app, { start: 100, end: 200 }, 'self'), false); }); test('先打印完整列表,再逐个执行 root pm uninstall', () => { const now = Date.now(); const { c, logs, calls } = load([info('com.example.b', now), info('com.example.a', now)]); c.runCommand = command => { assert.ok(logs.some(line => line.includes('["com.example.a","com.example.b"]'))); calls.push({ command, root: c.CONFIG.shellRoot }); return { code: 0, result: command === 'id' ? 'uid=0(root)' : 'Success\n', error: '' }; }; c.main(); assert.deepEqual(calls, [ { command: 'id', root: true }, { command: 'pm uninstall com.example.a', root: true }, { command: 'pm uninstall com.example.b', root: true }, ]); assert.ok(logs.some(line => line.includes('成功 2 个,失败/状态未知 0 个'))); assert.ok(logs.some(line => line.includes('/system/xbin/mus -c id'))); }); test('仅查看模式及空列表均不执行 shell', () => { const { c, calls } = load([info('com.example.a', Date.now())]); c.CONFIG.dryRun = true; c.main(); assert.equal(calls.length, 0); const empty = load(); empty.c.main(); assert.equal(empty.calls.length, 0); }); test('pm 返回失败、异常或没有 Success 时继续下一包,并汇总失败', () => { const now = Date.now(); const { c, calls, logs } = load(['a', 'b', 'c', 'd'].map(n => info('com.example.' + n, now))); c.runCommand = command => { if (command === 'id') return { code: 0, result: 'uid=0(root)' }; calls.push(command); if (command.endsWith('.a')) return { code: 0, result: 'Failure [DELETE_FAILED_INTERNAL_ERROR]' }; if (command.endsWith('.b')) throw new Error('Root denied'); if (command.endsWith('.c')) return { code: 1, result: 'Success' }; return { code: 0, result: 'Success' }; }; c.main(); assert.equal(calls.length, 4); assert.ok(logs.some(line => line.includes('成功 1 个,失败/状态未知 3 个'))); assert.ok(logs.some(line => line.includes('失败/状态未知包名列表:["com.example.a","com.example.b","com.example.c"]'))); }); test('包名命令注入被拒绝;无法识别自身时不开始卸载', () => { const { c, calls } = load([info('com.example.a', Date.now())]); assert.throws(() => c.uninstallPackage('com.example.a; reboot'), /非法包名/); c.context.getPackageName = () => ''; assert.throws(() => c.main(), /自身包名/); assert.equal(calls.length, 0); }); function mockProcess(env, { finishAt = 0, code = 0, output = 'Success\n', startError = null } = {}) { const { c, realRunCommand } = env; let clock = 0; let destroyed = 0; let deleted = 0; c.runCommand = realRunCommand; c.monotonicMillis = () => clock; c.sleep = ms => { clock += ms; }; c.CONFIG.commandTimeoutMs = 1000; c.CONFIG.progressIntervalMs = 400; c.createOutputFile = () => ({ getAbsolutePath: () => '/cache/output.log', delete: () => { deleted++; }, }); c.files = { read: () => output }; c.startCommandProcess = () => { if (startError) throw startError; return { exitValue() { if (clock < finishAt) throw new Error('IllegalThreadStateException'); return code; }, destroy: () => { destroyed++; }, }; }; return { clock: () => clock, destroyed: () => destroyed, deleted: () => deleted }; } test('进程未结束时轮询,退出后从文件取结果并清理,不读取输出管道', () => { const env = load(); const state = mockProcess(env, { finishAt: 600 }); const result = env.c.runCommand('pm uninstall com.example.a'); assert.equal(result.code, 0); assert.equal(result.result, 'Success\n'); assert.equal(state.clock(), 600); assert.equal(state.destroyed(), 1); assert.equal(state.deleted(), 1); assert.ok(env.logs.some(line => line.includes('等待命令完成'))); }); test('进程永久不返回时在超时后销毁进程,携带超时标记及输出', () => { const env = load(); const state = mockProcess(env, { finishAt: Infinity, output: 'waiting for root' }); assert.throws(() => env.c.runCommand('id'), error => error.commandTimedOut === true && /命令超时/.test(error.message) && /waiting for root/.test(error.message)); assert.equal(state.clock(), 1000); assert.equal(state.destroyed(), 1); assert.equal(state.deleted(), 1); }); test('启动进程失败时也清理临时文件', () => { const env = load(); const state = mockProcess(env, { startError: new Error('cannot start') }); assert.throws(() => env.c.runCommand('id'), /cannot start/); assert.equal(state.destroyed(), 0); assert.equal(state.deleted(), 1); }); test('Root 检查未获授权或超时时,不执行任何卸载', () => { const env = load([info('com.example.a', Date.now())]); const commands = []; env.c.runCommand = command => { commands.push(command); return { code: 0, result: 'uid=10123(u0_a123)' }; }; assert.throws(() => env.c.main(), /未获得 Root/); assert.deepEqual(commands, ['id']); mockProcess(env, { finishAt: Infinity }); assert.throws(() => env.c.main(), error => error.commandTimedOut === true); }); test('卸载超时立即停止整批,输出尚未处理列表', () => { const env = load(['a', 'b'].map(n => info('com.example.' + n, Date.now()))); const commands = []; env.c.runCommand = command => { commands.push(command); if (command === 'id') return { code: 0, result: 'uid=0(root)' }; const error = new Error('命令超时'); error.commandTimedOut = true; throw error; }; env.c.main(); assert.deepEqual(commands, ['id', 'pm uninstall com.example.a']); assert.ok(env.logs.some(line => line.includes('尚未处理包名列表:["com.example.b"]'))); assert.ok(env.logs.some(line => line.includes('上一条卸载结果未知'))); }); test('默认通过 mus 执行单条命令,外层重定向覆盖提权输出,正确引用特殊路径', () => { const { c } = load(); let captured; c.java = { lang: { String, reflect: { Array: { newInstance: () => new Array(3) } }, ProcessBuilder: function(args) { captured = Array.from(args); this.start = () => ({ marker: 'process' }); }, } }; assert.equal(c.startCommandProcess('pm uninstall com.example.a', "/cache/a'b.log").marker, 'process'); assert.equal(captured[0], '/system/bin/sh'); assert.equal(captured[1], '-c'); assert.equal(captured[2], "exec /system/xbin/mus -c 'pm uninstall com.example.a' > '/cache/a'\\''b.log' 2>&1"); c.CONFIG.shellRoot = false; c.startCommandProcess('id', '/cache/test.log'); assert.equal(captured[2], "exec /system/bin/sh -c 'id' > '/cache/test.log' 2>&1"); });