-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathtestProcessHandling.js
More file actions
512 lines (416 loc) · 18.9 KB
/
testProcessHandling.js
File metadata and controls
512 lines (416 loc) · 18.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/*
* Windows Kill Process Unit Tests
*
* Copyright 2015 Raising the Floor - International
*
* Licensed under the New BSD license. You may not use this file except in
* compliance with this License.
*
* The research leading to these results has received funding from the European Union's
* Seventh Framework Programme (FP7/2007-2013)
* under grant agreement no. 289016.
*
* You may obtain a copy of the License at
* https://github.com/GPII/universal/blob/master/LICENSE.txt
*/
"use strict";
var fluid = require("gpii-universal");
var jqUnit = fluid.require("node-jqunit");
var gpii = fluid.registerNamespace("gpii");
var shelljs = require("shelljs"),
path = require("path"),
os = require("os"),
fs = require("fs"),
child_process = require("child_process");
require("../processHandling.js");
fluid.registerNamespace("gpii.tests.windows.processHandling");
var waitExe = "gpii-process-handling-test.exe";
var waitExePath = null;
var teardowns = [];
jqUnit.module("gpii.tests.windows.processHandling", {
setup: function () {
// Take a copy of the built-in "waitfor" command, to ensure a unique process name.
// This command is a glorified "sleep" that is also able to be terminated "nicely".
waitExePath = path.join(process.env.TEMP, waitExe);
shelljs.cp(path.join(process.env.SystemRoot, "/System32/waitfor.exe"), waitExePath);
},
teardown: function () {
while (teardowns.length) {
teardowns.pop()();
}
if (waitExePath !== null) {
gpii.windows.killProcessByName(waitExe);
shelljs.rm(waitExePath);
}
}
});
jqUnit.test("Testing isProcessRunning", function () {
// Check a PID that isn't running.
var running = gpii.windows.isProcessRunning(-1);
jqUnit.assertFalse("Process should not have been found running", running);
// Check a PID that is running.
running = gpii.windows.isProcessRunning(process.pid);
jqUnit.assertTrue("Process should have been found running", running);
// Check an exe file that isn't running.
running = gpii.windows.isProcessRunning("a non-matching process.exe");
jqUnit.assertFalse("Process should not have been found running", running);
// Check an exe file that is running.
running = gpii.windows.isProcessRunning("node.exe");
jqUnit.assertTrue("Process should have been found running", running);
// Check multiple processes. There's always more than one svchost.exe running on Windows.
running = gpii.windows.isProcessRunning("svchost.exe", true);
jqUnit.assertTrue("Process should have been found running (multiple processes)", running);
});
jqUnit.asyncTest("Testing timeout waiting for processes start", function () {
jqUnit.expect(1);
var exe = "a non-matching process.exe";
gpii.windows.waitForProcessStart(exe, { timeout: 100 })
.then(function () {
jqUnit.fail("The process '" + exe + "' should not be running");
}, function () {
jqUnit.assert("Should have timed out");
jqUnit.start();
});
});
jqUnit.asyncTest("Testing timeout waiting for processes termination", function () {
jqUnit.expect(1);
var exe = "node.exe";
gpii.windows.waitForProcessTermination(exe, { timeout: 100 })
.then(function () {
jqUnit.fail("The process '" + exe + "' should not have terminated");
}, function () {
jqUnit.assert("Should have timed out");
jqUnit.start();
});
});
jqUnit.asyncTest("Testing waiting for processes start and end", function () {
jqUnit.expect(3);
var running = gpii.processReporter.find(waitExe);
jqUnit.assertFalse("The process should not already be running.", running);
// Timeout waiting for the process start/end after 20 seconds.
var options = { timeout: 20000 };
// Wait for it to start.
gpii.windows.waitForProcessStart(waitExe, options)
.then(function () {
jqUnit.assert("We just started the new process.");
// Wait for it to die
gpii.windows.waitForProcessTermination(waitExe, options)
.then(function () {
jqUnit.assert("Child process terminated.");
jqUnit.start();
}, function () {
jqUnit.fail("Failed to detect process termination.");
});
// Tell the process to stop now.
child_process.execSync("waitfor /SI waitForProcessTerminationTest");
}, function () {
jqUnit.fail("Failed to detect process start.");
});
// Create the process, with a 5 second timeout
child_process.exec(waitExePath + " waitForProcessTerminationTest /T 5 > nul", function (err, stdout, stderr) {
if (err) {
fluid.log(stdout, stderr);
fluid.fail(err);
}
});
});
// Check if getExplorerProcess returns an explorer.exe pid.
jqUnit.test("Testing getExplorerProcess", function () {
var explorerPid = gpii.windows.getExplorerProcess();
jqUnit.assertFalse("explorer PID must be a number", isNaN(explorerPid));
var isRunning = gpii.windows.isProcessRunning(explorerPid);
jqUnit.assertTrue("explorer pid must be a running process", isRunning);
var processes = gpii.processes.windows.getProcessList(explorerPid);
jqUnit.assertEquals("getProcessList should return 1 process", 1, processes.length);
jqUnit.assertEquals("process name should be explorer.exe", "explorer.exe", processes[0].command.toLowerCase());
});
jqUnit.test("Testing getProcessWindows", function () {
// Get the process which owns the taskbar, then check the taskbar window is in the list of windows owned by that
// process.
var pid = gpii.windows.getExplorerProcess();
var explorerWindows = gpii.windows.getProcessWindows(pid);
jqUnit.assertTrue("getProcessWindows(explorer pid) should return an array", Array.isArray(explorerWindows));
var trayWindow = gpii.windows.getTasktrayWindow();
jqUnit.assertTrue("The tasktray window should be one of Explorer's windows", explorerWindows.includes(trayWindow));
// Ensure passing pids as an array works.
var explorerWindows2 = gpii.windows.getProcessWindows([0, pid]);
jqUnit.assertDeepEq("getProcessWindows with array should return the same result as before",
explorerWindows, explorerWindows2);
// Try a process with no windows
var systemProcessWindows = gpii.windows.getProcessWindows(4);
jqUnit.assertTrue("getProcessWindows(system pid) should return an array", Array.isArray(explorerWindows));
jqUnit.assertEquals("The SYSTEM process should return 0 windows", 0, systemProcessWindows.length);
// A process that isn't running ('1' will never be running because pids are multiples of 4)
var notRunningWindows = gpii.windows.getProcessWindows(1);
jqUnit.assertDeepEq("getProcessWindows(1) should return an empty array", [], notRunningWindows);
// nothing
var noArgWindows = gpii.windows.getProcessWindows();
jqUnit.assertDeepEq("getProcessWindows(undefined) should return an empty array", [], noArgWindows);
});
jqUnit.asyncTest("Testing Killing Processes", function () {
jqUnit.expect(3);
var running = gpii.processReporter.find(waitExe);
jqUnit.assertFalse("The process should not already be running.", running);
// On the call below, async is true because if it is false shelljs will
// wait around until it is manually killed before continuing with the
// rest of the tests.
var command = waitExePath + " killProcessByNameTest /T 30";
fluid.log("Executing " + command);
child_process.exec(command, function (error, stdout, stderr) {
fluid.log("Exit code:", error.code);
jqUnit.assertEquals("Process should have terminated with code SIGKILL", 9, error.code);
fluid.log("Program output:", stdout);
fluid.log("Program stderr:", stderr);
jqUnit.start();
});
// Kill the process when it starts
gpii.windows.waitForProcessStart(waitExe)
.then(function () {
jqUnit.assert("The process has started");
gpii.windows.killProcessByName(waitExe);
});
});
jqUnit.asyncTest("Testing closeProcessByName", function () {
jqUnit.expect(3);
var exitCode = 5;
// Start a process that creates a window.
var exeName = "test-window.exe";
var exePath = path.join(__dirname, exeName);
var command = exePath + " -window";
fluid.log("Executing " + command);
var child = child_process.exec(command, function (error) {
fluid.log("Exit code:", error.code);
jqUnit.assertEquals("Exit code", exitCode, error.code);
// If our exitCode is not as expected, we are unlikely to get to the next set of checks and might as well start the clock for failure.
if (exitCode !== error.code) { jqUnit.start(); }
});
child.stdout.on("data", function (data) {
// Wait for the window to be created
if (data.match("Window created")) {
jqUnit.assert("Window is created");
gpii.windows.closeProcessByName(exeName, {cleanOnly: true, timeout: 1000, exitCode: exitCode})
.then(function (clean) {
jqUnit.assertTrue("Should have closed cleanly", clean);
jqUnit.start();
}, function (e) {
fluid.log(e.message);
jqUnit.fail("Process should have closed.");
gpii.windows.killProcessByName(exeName);
});
}
});
});
jqUnit.asyncTest("Testing closeProcessByName (window-less process)", function () {
jqUnit.expect(3);
// Start a process that does not have a window.
gpii.windows.waitForProcessStart(waitExe)
.then(function () {
jqUnit.assert("Process started");
// The process doesn't have any windows, so this should fail to terminate it.
gpii.windows.closeProcessByName(waitExe, {cleanOnly: true})
.then(function () {
jqUnit.fail("Process should not have closed.");
}, function (e) {
jqUnit.assert("Process not closed");
fluid.log(e.message);
// Retry with force
gpii.windows.closeProcessByName(waitExe, {cleanOnly: false})
.then(function () {
jqUnit.assert("Process terminated");
jqUnit.start();
});
});
});
var command = waitExePath + " closeProcessByNameTest /T 30";
fluid.log("Executing " + command);
child_process.exec(command);
});
jqUnit.test("Testing getServiceState", function () {
// Local Session Manager will always be running.
var state = gpii.windows.getServiceState("LSM");
jqUnit.assertEquals("LSM service should be running", "running", state);
// Low chances that the Phone Service is Running
state = gpii.windows.getServiceState("PhoneSvc");
jqUnit.assertEquals("Fax service should be stopped", "stopped", state);
state = gpii.windows.getServiceState("gpii-unknown");
jqUnit.assertEquals("gpii-unknown service should be unknown", "unknown", state);
});
jqUnit.asyncTest("Testing stopExplorer", function () {
jqUnit.expect(5);
// Instead of killing the real explorer, start the test window which will accept the same message that the tasktray
// window does.
// The test window will record the message, but will remain so the more forceful termination can also be tested.
// Start a process that creates a window.
var exeName = "test-window.exe";
var exePath = path.join(__dirname, exeName);
var command = exePath + " -window";
var stopExplorerPromise = fluid.promise();
var tasktrayClosePromise = fluid.promise();
fluid.log("Executing " + command);
var child = child_process.exec(command, function (error) {
fluid.log("Exit code:", error.code);
jqUnit.assertEquals("Exit code", 5, error.code);
if (error.code !== 5) {
jqUnit.fail();
} else {
// This test shouldn't have stopped the real explorer.
jqUnit.assertTrue("Explorer should still be running.", gpii.windows.getExplorerProcess());
fluid.promise.sequence([stopExplorerPromise, tasktrayClosePromise]).then(jqUnit.start);
}
});
child.stdout.on("data", function (data) {
fluid.log(data);
// Wait for the window to be created
var match = data.match(/Window created.*hwnd=([0-9]+)/);
if (match) {
// Window was created - get the handle.
var testWindow = match[1];
var p = gpii.windows.stopExplorer({
trayWindow: testWindow,
timeout: 1000,
ignoreFolders: true,
explorerExe: exeName
});
jqUnit.assertTrue("stopExplorer should return a promise", fluid.isPromise(p));
p.then(function () {
jqUnit.assert("stopExplorer resolved");
stopExplorerPromise.resolve();
}, fluid.fail);
} else if (data.indexOf("tasktray close") >= 0) {
// The "tasktray close" message was received.
jqUnit.assert("stopExplorer attempted clean shutdown");
tasktrayClosePromise.resolve();
}
});
});
jqUnit.asyncTest("Testing restartExplorer", function () {
jqUnit.expect(4);
var explorerPid = gpii.windows.getExplorerProcess();
jqUnit.assertTrue("Explorer should be running", explorerPid);
var exeName = "test-window.exe";
var exePath = path.join(__dirname, exeName);
jqUnit.assertFalse("There shouldn't be a test-window process running.", gpii.windows.isProcessRunning(exeName));
teardowns.push(function () {
gpii.windows.killProcessByName(exeName);
});
// Setting trayWindow to INVALID_HANDLE_VALUE will prevent restartExplorer from hiding the real taskbar.
var INVALID_HANDLE_VALUE = 0xffffffff;
var restartPromise = gpii.windows.restartExplorer({
trayWindow: INVALID_HANDLE_VALUE,
explorer: exePath,
args: [ "-window" ],
ignoreFolders: true
});
jqUnit.assertTrue("restartExplorer should return a promise", fluid.isPromise(restartPromise));
restartPromise.then(null, jqUnit.fail);
// restartExplorer could resolve either before or after the test process is started, because it detects real
// explorer (which is already running).
fluid.promise.sequence([
restartPromise,
gpii.windows.waitForProcessStart(exeName)
]).then(function () {
// This test shouldn't have touched explorer.
jqUnit.assertEquals("Explorer should still be running.", explorerPid, gpii.windows.getExplorerProcess());
jqUnit.start();
});
});
jqUnit.test("Testing getProcessPath", function () {
var pid = gpii.windows.getExplorerProcess();
var path = gpii.windows.getProcessPath(pid);
jqUnit.assertEquals("Path for explorer be correct", "c:\\windows\\explorer.exe", path.toLowerCase());
// Try the "System" process.
var path2 = gpii.windows.getProcessPath(4);
jqUnit.assertEquals("Path for explorer be correct", "system", path2.toLowerCase());
});
// Test startProcess starts the process with the correct window state.
jqUnit.asyncTest("Testing startProcess", function () {
var exeName = "test-window.exe";
var exePath = path.join(__dirname, exeName);
var tests = [
{
windowState: undefined,
expect: "none"
}, {
windowState: "hide",
expect: gpii.windows.API_constants.SW_HIDE
}, {
windowState: "normal",
expect: gpii.windows.API_constants.SW_SHOWNORMAL
}, {
windowState: "minimized",
expect: gpii.windows.API_constants.SW_SHOWMINIMIZED
}, {
windowState: "maximized",
expect: gpii.windows.API_constants.SW_SHOWMAXIMIZED
}, {
windowState: "noactivate",
expect: gpii.windows.API_constants.SW_SHOWNOACTIVATE
}, {
windowState: "normal",
activateRunning: true,
expect: gpii.windows.API_constants.SW_SHOWNORMAL
}, {
activateRunning: true,
expect: "none"
}, {
testingSecondInstance: true,
activateRunning: true,
expect: "not started"
}
];
jqUnit.expect(tests.length * 3);
var tempFiles = [];
teardowns.push(function () {
shelljs.rm(tempFiles);
});
var runTest = function (testIndex) {
var test = tests[testIndex];
if (!test) {
jqUnit.start();
return;
}
var tempFile = path.join(os.tmpdir(), "gpii-startprocess" + Math.random());
tempFiles.push(tempFile);
var otherInstance, otherInstancePromise;
if (test.testingSecondInstance) {
// Start the first instance
otherInstance = gpii.windows.startProcess(exePath, ["-window"], {windowState: test.windowState});
// Wait for the window to show
otherInstancePromise = gpii.windows.waitForCondition(function () {
return gpii.windows.getProcessWindows(otherInstance).length > 0;
}, {timeout:10000});
} else {
otherInstancePromise = fluid.promise().resolve();
}
otherInstancePromise.then(function () {
// Start a process which spits out the initial window state to a file and terminates.
var p = gpii.windows.startProcess(exePath, ["-windowState", tempFile], {
windowState: test.windowState, activateRunning: test.activateRunning
});
jqUnit.assertEquals("startProcess should return a number", "number", typeof (p));
var processPromise;
if (test.testingSecondInstance) {
jqUnit.assertEquals("startProcess (second instance test) should return a zero PID", 0, p);
processPromise = fluid.promise().resolve();
try {
process.kill(otherInstance);
} catch (e) {
fluid.log("process.kill:", e);
}
} else {
jqUnit.assertTrue("startProcess should return a process ID", p > 0);
processPromise = gpii.windows.waitForProcessTermination(p, 15000);
}
processPromise.then(function (result) {
if (result === "timeout") {
jqUnit.fail("Timeout waiting for test-window.exe to finish");
}
var actualWindowState = fs.existsSync(tempFile) ? fs.readFileSync(tempFile, "utf8") : "not started";
jqUnit.assertEquals("wShowWindow in the child window must be the expected value",
test.expect.toString(), actualWindowState);
runTest(testIndex + 1);
}, jqUnit.fail);
}, fluid.fail);
};
runTest(0);
});