test.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. // electron/test.js - ESM 模块版本
  2. // Monkey Testing 和开发工具模块
  3. import { writeLog } from '../src/log/log-writer.js';
  4. import { BrowserWindow, ipcMain, Menu, globalShortcut } from 'electron';
  5. import { fileURLToPath } from 'url';
  6. import { dirname, join } from 'path';
  7. // 工具函数:安全的 JSON 序列化
  8. function safeStringify(obj) {
  9. const cache = new Set();
  10. return JSON.stringify(obj, (key, value) => {
  11. if (typeof value === 'object' && value !== null) {
  12. if (cache.has(value)) {
  13. return '[Circular]';
  14. }
  15. cache.add(value);
  16. }
  17. return value;
  18. });
  19. }
  20. // -------------- 命令行参数解析 --------------
  21. /**
  22. * 解析命令行参数
  23. * @returns {Object} 解析后的选项
  24. */
  25. export function parseCommandLineArgs() {
  26. const args = process.argv;
  27. return {
  28. enableMonkeyTesting: args.includes('--enable-monkey-testing'),
  29. enableDevMenu: args.includes('--enable-dev-menu'),
  30. enableDevTools: args.includes('--enable-dev-tools')
  31. };
  32. }
  33. // -------------- Monkey Testing 功能类 --------------
  34. /**
  35. * Monkey Testing 测试器
  36. * 用于模拟随机的用户操作,进行压力测试
  37. */
  38. export class MonkeyTester {
  39. /**
  40. * 创建 MonkeyTester 实例
  41. * @param {BrowserWindow} win - Electron 窗口实例
  42. * @param {boolean} isMac - 是否为macOS平台
  43. * @param {BrowserWindow} mainWindow - 主窗口实例
  44. */
  45. constructor(win, isMac = false, mainWindow = null) {
  46. this.win = win;
  47. this.isMac = isMac;
  48. this.mainWindow = mainWindow;
  49. this.active = false;
  50. this.interval = null;
  51. this.originalMenu = null; // 保存原始菜单
  52. }
  53. /**
  54. * 获取随机位置(在窗口内容区域内)
  55. * @returns {Object} {x, y} 坐标
  56. */
  57. getRandomPosition() {
  58. const bounds = this.win.getContentBounds();
  59. const margin = 5; // 安全边距,避免点击到窗口边缘
  60. return {
  61. x: Math.floor(Math.random() * (bounds.width - 2 * margin)) + margin,
  62. y: Math.floor(Math.random() * (bounds.height - 2 * margin)) + margin
  63. };
  64. }
  65. /**
  66. * 移动鼠标到指定位置
  67. */
  68. moveMouseTo(x, y) {
  69. if (this.win && !this.win.isDestroyed()) {
  70. this.win.webContents.sendInputEvent({
  71. type: 'mouseMove',
  72. x: x,
  73. y: y
  74. });
  75. }
  76. }
  77. /**
  78. * 模拟点击操作
  79. */
  80. performClick(x, y, button = 'left') {
  81. if (this.win && !this.win.isDestroyed()) {
  82. // 鼠标按下
  83. this.win.webContents.sendInputEvent({
  84. type: 'mouseDown',
  85. x: x,
  86. y: y,
  87. button: button
  88. });
  89. // 短暂延迟后释放
  90. setTimeout(() => {
  91. if (this.win && !this.win.isDestroyed()) {
  92. this.win.webContents.sendInputEvent({
  93. type: 'mouseUp',
  94. x: x,
  95. y: y,
  96. button: button
  97. });
  98. }
  99. }, 50);
  100. }
  101. }
  102. /**
  103. * 模拟键盘输入
  104. */
  105. simulateKeyPress(key) {
  106. if (this.win && !this.win.isDestroyed()) {
  107. this.win.webContents.sendInputEvent({
  108. type: 'keyDown',
  109. keyCode: key
  110. });
  111. setTimeout(() => {
  112. if (this.win && !this.win.isDestroyed()) {
  113. this.win.webContents.sendInputEvent({
  114. type: 'keyUp',
  115. keyCode: key
  116. });
  117. }
  118. }, 50);
  119. }
  120. }
  121. /**
  122. * 执行随机操作
  123. */
  124. performRandomOperation() {
  125. if (!this.win || this.win.isDestroyed()) return;
  126. const operations = ['move', 'click', 'doubleClick', 'rightClick', 'keyPress'];
  127. const operation = operations[Math.floor(Math.random() * operations.length)];
  128. const pos = this.getRandomPosition();
  129. switch (operation) {
  130. case 'move':
  131. this.moveMouseTo(pos.x, pos.y);
  132. break;
  133. case 'click':
  134. this.performClick(pos.x, pos.y);
  135. break;
  136. case 'doubleClick':
  137. this.performClick(pos.x, pos.y);
  138. this.performClick(pos.x, pos.y);
  139. break;
  140. case 'rightClick':
  141. this.performClick(pos.x, pos.y, 'right');
  142. break;
  143. case 'keyPress':
  144. const keys = ['a', 'b', 'c', 'Enter', 'Space', 'Tab'];
  145. const key = keys[Math.floor(Math.random() * keys.length)];
  146. this.simulateKeyPress(key);
  147. break;
  148. }
  149. }
  150. /**
  151. * 启动 Monkey Testing
  152. * @param {Object} options - 配置选项
  153. * @param {number} options.interval - 操作间隔(ms)
  154. * @param {number} options.duration - 持续时间(ms)
  155. * @param {number} options.maxOperations - 最大操作次数
  156. */
  157. start(options = {}) {
  158. if (this.active) return;
  159. const { interval = 100, duration = 2147483646, maxOperations = 600000 } = options;
  160. this.active = true;
  161. let operationCount = 0;
  162. writeLog('info', `启动monkey testing: 间隔${interval}ms, 持续${duration}ms, 最大操作${maxOperations}次`);
  163. // 保存原始菜单并隐藏菜单
  164. this.originalMenu = Menu.getApplicationMenu();
  165. Menu.setApplicationMenu(null);
  166. writeLog('info', '菜单已隐藏,测试期间不可见');
  167. // 注册全局快捷键 Ctrl+Alt+M 来显示菜单
  168. globalShortcut.register('CommandOrControl+Alt+M', () => {
  169. if (this.originalMenu) {
  170. Menu.setApplicationMenu(this.originalMenu);
  171. writeLog('info', '菜单已通过快捷键显示');
  172. // 5秒后自动隐藏菜单
  173. setTimeout(() => {
  174. if (this.active) {
  175. Menu.setApplicationMenu(null);
  176. writeLog('info', '菜单已自动隐藏');
  177. }
  178. }, 5000);
  179. }
  180. });
  181. writeLog('info', '全局快捷键 Ctrl+Alt+M 已注册,可用于临时显示菜单');
  182. this.interval = setInterval(() => {
  183. if (!this.active || operationCount >= maxOperations) {
  184. this.stop();
  185. return;
  186. }
  187. this.performRandomOperation();
  188. operationCount++;
  189. }, interval);
  190. // 超时自动停止
  191. setTimeout(() => {
  192. this.stop();
  193. }, duration);
  194. }
  195. /**
  196. * 停止 Monkey Testing
  197. */
  198. stop() {
  199. if (!this.active) return;
  200. this.active = false;
  201. if (this.interval) {
  202. clearInterval(this.interval);
  203. this.interval = null;
  204. }
  205. // 恢复菜单
  206. if (this.originalMenu) {
  207. Menu.setApplicationMenu(this.originalMenu);
  208. this.originalMenu = null;
  209. writeLog('info', '菜单已恢复显示');
  210. }
  211. // 注销全局快捷键
  212. globalShortcut.unregister('CommandOrControl+Alt+M');
  213. writeLog('info', '全局快捷键已注销');
  214. writeLog('info', '停止monkey testing');
  215. }
  216. /**
  217. * 检查是否正在运行
  218. */
  219. isActive() {
  220. return this.active;
  221. }
  222. }
  223. /**
  224. * 输出调试信息
  225. * @param {Object} options - 解析后的命令行选项
  226. */
  227. export function logDebugInfo(options) {
  228. writeLog('log', '=== Electron Debug Info ===');
  229. writeLog('log', `Command line args: ${safeStringify(process.argv)}`);
  230. writeLog('log', `Parsed options: ${safeStringify(options)}`);
  231. writeLog('log', '===========================');
  232. }
  233. /**
  234. * 显示Monkey Test参数输入对话框
  235. * @param {BrowserWindow} mainWindow - 主窗口实例
  236. */
  237. export function showMonkeyInputDialog(mainWindow) {
  238. const __filename = fileURLToPath(import.meta.url);
  239. const __dirname = dirname(__filename);
  240. const inputWindow = new BrowserWindow({
  241. width: 400,
  242. height: 300,
  243. parent: mainWindow,
  244. modal: true,
  245. show: false,
  246. webPreferences: {
  247. nodeIntegration: true, // 允许输入窗口使用 require
  248. contextIsolation: false
  249. },
  250. resizable: false,
  251. title: 'Monkey Test Parameters'
  252. });
  253. const htmlContent = `
  254. <!DOCTYPE html>
  255. <html>
  256. <head>
  257. <meta charset="UTF-8">
  258. <title>Monkey Test Parameters</title>
  259. <style>
  260. body {
  261. font-family: Arial, sans-serif;
  262. padding: 20px;
  263. background-color: #f5f5f5;
  264. }
  265. .form-group {
  266. margin-bottom: 15px;
  267. }
  268. label {
  269. display: block;
  270. margin-bottom: 5px;
  271. font-weight: bold;
  272. }
  273. input {
  274. width: 100%;
  275. padding: 8px;
  276. border: 1px solid #ccc;
  277. border-radius: 4px;
  278. box-sizing: border-box;
  279. }
  280. .buttons {
  281. text-align: right;
  282. margin-top: 20px;
  283. }
  284. button {
  285. padding: 8px 16px;
  286. margin-left: 10px;
  287. border: none;
  288. border-radius: 4px;
  289. cursor: pointer;
  290. }
  291. .start-btn {
  292. background-color: #007bff;
  293. color: white;
  294. }
  295. .cancel-btn {
  296. background-color: #6c757d;
  297. color: white;
  298. }
  299. </style>
  300. </head>
  301. <body>
  302. <h3>Monkey Test Parameters</h3>
  303. <form id="monkeyForm">
  304. <div class="form-group">
  305. <label for="interval">Interval (ms):</label>
  306. <input type="number" id="interval" value="100" min="10" required>
  307. </div>
  308. <div class="form-group">
  309. <label for="duration">Duration (ms):</label>
  310. <input type="number" id="duration" value="2147483646" min="1000" required>
  311. </div>
  312. <div class="form-group">
  313. <label for="maxOperations">Max Operations:</label>
  314. <input type="number" id="maxOperations" value="600000" min="1" required>
  315. </div>
  316. <div class="buttons">
  317. <button type="button" class="cancel-btn" onclick="window.close()">Cancel</button>
  318. <button type="submit" class="start-btn">Start Test</button>
  319. </div>
  320. </form>
  321. <script>
  322. const { ipcRenderer } = require('electron');
  323. document.getElementById('monkeyForm').addEventListener('submit', (e) => {
  324. e.preventDefault();
  325. const interval = parseInt(document.getElementById('interval').value);
  326. const duration = parseInt(document.getElementById('duration').value);
  327. const maxOperations = parseInt(document.getElementById('maxOperations').value);
  328. ipcRenderer.send('start-monkey-test', { interval, duration, maxOperations });
  329. window.close();
  330. });
  331. </script>
  332. </body>
  333. </html>
  334. `;
  335. inputWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`);
  336. inputWindow.once('ready-to-show', () => {
  337. inputWindow.show();
  338. });
  339. inputWindow.on('closed', () => {
  340. // 清理引用
  341. });
  342. }
  343. /**
  344. * 创建开发者菜单模板
  345. * @param {boolean} isMac - 是否为macOS平台
  346. * @param {BrowserWindow} mainWindow - 主窗口实例
  347. * @returns {Array} 菜单模板数组
  348. */
  349. export function createDevMenuTemplate(isMac, mainWindow) {
  350. return [
  351. ...(isMac ? [{
  352. label: 'Electron',
  353. submenu: [
  354. { role: 'about' },
  355. { type: 'separator' },
  356. { role: 'services' },
  357. { type: 'separator' },
  358. { role: 'hide' },
  359. { role: 'hideOthers' },
  360. { role: 'unhide' },
  361. { type: 'separator' },
  362. { role: 'quit' }
  363. ]
  364. }] : []),
  365. {
  366. label: 'File',
  367. submenu: [
  368. isMac ? { role: 'close' } : { role: 'quit' }
  369. ]
  370. },
  371. {
  372. label: 'Edit',
  373. submenu: [
  374. { role: 'undo' },
  375. { role: 'redo' },
  376. { type: 'separator' },
  377. { role: 'cut' },
  378. { role: 'copy' },
  379. { role: 'paste' },
  380. ...(isMac ? [
  381. { role: 'pasteAndMatchStyle' },
  382. { role: 'delete' },
  383. { role: 'selectAll' },
  384. { type: 'separator' },
  385. {
  386. label: 'Speech',
  387. submenu: [
  388. { role: 'startSpeaking' },
  389. { role: 'stopSpeaking' }
  390. ]
  391. }
  392. ] : [
  393. { role: 'delete' },
  394. { type: 'separator' },
  395. { role: 'selectAll' }
  396. ])
  397. ]
  398. },
  399. {
  400. label: 'View',
  401. submenu: [
  402. { role: 'reload' },
  403. { role: 'forceReload' },
  404. { role: 'toggleDevTools' },
  405. { type: 'separator' },
  406. { role: 'resetZoom' },
  407. { role: 'zoomIn' },
  408. { role: 'zoomOut' },
  409. { type: 'separator' },
  410. { role: 'togglefullscreen' },
  411. { type: 'separator' },
  412. { label: 'Start Monkey Test', click: () => showMonkeyInputDialog(mainWindow) }
  413. ]
  414. },
  415. {
  416. label: 'Window',
  417. submenu: [
  418. { role: 'minimize' },
  419. { role: 'close' },
  420. ...(isMac ? [
  421. { type: 'separator' },
  422. { role: 'front' },
  423. { type: 'separator' },
  424. { role: 'window' }
  425. ] : [
  426. { role: 'close' }
  427. ])
  428. ]
  429. },
  430. ...(isMac ? [{
  431. role: 'help',
  432. submenu: [
  433. {
  434. label: 'Learn More',
  435. click: async () => {
  436. const { shell } = require('electron');
  437. await shell.openExternal('https://electronjs.org');
  438. }
  439. }
  440. ]
  441. }] : [])
  442. ];
  443. }
  444. // 导出便捷函数:创建 MonkeyTester 实例
  445. export function createMonkeyTester(win) {
  446. return new MonkeyTester(win);
  447. }