terminal.test.ts 27.9 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

M
Megan Rogge 已提交
6
import { window, Pseudoterminal, EventEmitter, TerminalDimensions, workspace, ConfigurationTarget, Disposable, UIKind, env, EnvironmentVariableMutatorType, EnvironmentVariableMutator, extensions, ExtensionContext, TerminalOptions, ExtensionTerminalOptions, Terminal } from 'vscode';
7
import { doesNotThrow, equal, deepEqual, throws, strictEqual } from 'assert';
J
Johannes Rieken 已提交
8
import { assertNoRpc } from '../utils';
9

D
Daniel Imms 已提交
10 11
// Disable terminal tests:
// - Web https://github.com/microsoft/vscode/issues/92826
D
Daniel Imms 已提交
12
(env.uiKind === UIKind.Web ? suite.skip : suite)('vscode API - terminal', () => {
13 14
	let extensionContext: ExtensionContext;

15
	suiteSetup(async () => {
16 17 18 19
		// Trigger extension activation and grab the context as some tests depend on it
		await extensions.getExtension('vscode.vscode-api-tests')?.activate();
		extensionContext = (global as any).testExtensionContext;

20
		const config = workspace.getConfiguration('terminal.integrated');
21
		// Disable conpty in integration tests because of https://github.com/microsoft/vscode/issues/76548
22 23 24
		await config.update('windowsEnableConpty', false, ConfigurationTarget.Global);
		// Disable exit alerts as tests may trigger then and we're not testing the notifications
		await config.update('showExitAlert', false, ConfigurationTarget.Global);
D
Daniel Imms 已提交
25
		// Canvas may cause problems when running in a container
M
meganrogge 已提交
26
		await config.update('gpuAcceleration', 'off', ConfigurationTarget.Global);
D
Daniel Imms 已提交
27 28
		// Disable env var relaunch for tests to prevent terminals relaunching themselves
		await config.update('environmentChangesRelaunch', false, ConfigurationTarget.Global);
29
	});
30

31
	suite('Terminal', () => {
32 33 34
		let disposables: Disposable[] = [];

		teardown(() => {
J
Johannes Rieken 已提交
35
			assertNoRpc();
36 37 38 39
			disposables.forEach(d => d.dispose());
			disposables.length = 0;
		});

D
Daniel Imms 已提交
40
		test('sendText immediately after createTerminal should not throw', async () => {
41
			const terminal = window.createTerminal();
M
Megan Rogge 已提交
42 43 44 45 46 47 48 49
			const result = await new Promise<Terminal>(r => {
				disposables.push(window.onDidOpenTerminal(t => {
					if (t === terminal) {
						r(t);
					}
				}));
			});
			equal(result, terminal);
50
			doesNotThrow(terminal.sendText.bind(terminal, 'echo "foo"'));
M
Megan Rogge 已提交
51 52 53 54 55 56 57 58
			await new Promise<void>(r => {
				disposables.push(window.onDidCloseTerminal(t => {
					if (t === terminal) {
						r();
					}
				}));
				terminal.dispose();
			});
59 60
		});

61
		test('echo works in the default shell', async () => {
62 63
			const terminal = await new Promise<Terminal>(r => {
				disposables.push(window.onDidOpenTerminal(t => {
D
Daniel Imms 已提交
64 65
					if (t === terminal) {
						r(terminal);
66
					}
67 68 69 70
				}));
				// Use a single character to avoid winpty/conpty issues with injected sequences
				const terminal = window.createTerminal({
					env: { TEST: '`' }
71
				});
72
				terminal.show();
73
			});
74 75 76 77

			let data = '';
			await new Promise<void>(r => {
				disposables.push(window.onDidWriteTerminalData(e => {
D
Daniel Imms 已提交
78 79 80 81 82
					if (e.terminal === terminal) {
						data += e.data;
						if (data.indexOf('`') !== 0) {
							r();
						}
83 84
					}
				}));
85 86 87 88 89 90 91
				// Print an environment variable value so the echo statement doesn't get matched
				if (process.platform === 'win32') {
					terminal.sendText(`$env:TEST`);
				} else {
					terminal.sendText(`echo $TEST`);
				}
			});
92

93
			await new Promise<void>(r => {
94
				terminal.dispose();
95 96 97 98 99
				disposables.push(window.onDidCloseTerminal(t => {
					strictEqual(terminal, t);
					r();
				}));
			});
100 101
		});

D
Daniel Imms 已提交
102
		test('onDidCloseTerminal event fires when terminal is disposed', async () => {
103
			const terminal = window.createTerminal();
M
Megan Rogge 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
			const result = await new Promise<Terminal>(r => {
				disposables.push(window.onDidOpenTerminal(t => {
					if (t === terminal) {
						r(t);
					}
				}));
			});
			equal(result, terminal);
			await new Promise<void>(r => {
				disposables.push(window.onDidCloseTerminal(t => {
					if (t === terminal) {
						r();
					}
				}));
				terminal.dispose();
			});
120 121
		});

D
Daniel Imms 已提交
122
		test('processId immediately after createTerminal should fetch the pid', async () => {
123
			const terminal = window.createTerminal();
M
Megan Rogge 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
			const result = await new Promise<Terminal>(r => {
				disposables.push(window.onDidOpenTerminal(t => {
					if (t === terminal) {
						r(t);
					}
				}));
			});
			equal(result, terminal);
			let pid = await result.processId;
			equal(true, pid && pid > 0);
			await new Promise<void>(r => {
				disposables.push(window.onDidCloseTerminal(t => {
					if (t === terminal) {
						r();
					}
				}));
140
				terminal.dispose();
M
Megan Rogge 已提交
141
			});
142 143
		});

D
Daniel Imms 已提交
144
		test('name in constructor should set terminal.name', async () => {
145
			const terminal = window.createTerminal('a');
M
Megan Rogge 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159
			const result = await new Promise<Terminal>(r => {
				disposables.push(window.onDidOpenTerminal(t => {
					if (t === terminal) {
						r(t);
					}
				}));
			});
			equal(result, terminal);
			await new Promise<void>(r => {
				disposables.push(window.onDidCloseTerminal(t => {
					if (t === terminal) {
						r();
					}
				}));
160
				terminal.dispose();
M
Megan Rogge 已提交
161
			});
162 163
		});

D
Daniel Imms 已提交
164
		test('creationOptions should be set and readonly for TerminalOptions terminals', async () => {
165 166 167 168 169
			const options = {
				name: 'foo',
				hideFromUser: true
			};
			const terminal = window.createTerminal(options);
M
Megan Rogge 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
			const terminalOptions = terminal.creationOptions as TerminalOptions;
			const result = await new Promise<Terminal>(r => {
				disposables.push(window.onDidOpenTerminal(t => {
					if (t === terminal) {
						r(t);
					}
				}));
			});
			equal(result, terminal);
			await new Promise<void>(r => {
				disposables.push(window.onDidCloseTerminal(t => {
					if (t === terminal) {
						r();
					}
				}));
				terminal.dispose();
			});
			throws(() => terminalOptions.name = 'bad', 'creationOptions should be readonly at runtime');
188 189
		});

D
Daniel Imms 已提交
190
		test('onDidOpenTerminal should fire when a terminal is created', async () => {
191
			const terminal = window.createTerminal('b');
M
Megan Rogge 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
			const result = await new Promise<Terminal>(r => {
				disposables.push(window.onDidOpenTerminal(t => {
					if (t === terminal) {
						r(t);
					}
				}));
			});
			equal(result, terminal);
			await new Promise<void>(r => {
				disposables.push(window.onDidCloseTerminal(t => {
					if (t === terminal) {
						r();
					}
				}));
				terminal.dispose();
			});
208
		});
209

D
Daniel Imms 已提交
210
		test('exitStatus.code should be set to undefined after a terminal is disposed', async () => {
M
Megan Rogge 已提交
211 212 213 214 215 216 217 218 219 220
			const terminal = window.createTerminal();
			const result = await new Promise<Terminal>(r => {
				disposables.push(window.onDidOpenTerminal(t => {
					if (t === terminal) {
						r(t);
					}
				}));
			});
			equal(result, terminal);
			await new Promise<void>(r => {
D
Daniel Imms 已提交
221
				disposables.push(window.onDidCloseTerminal(t => {
M
Megan Rogge 已提交
222
					if (t === terminal) {
D
Daniel Imms 已提交
223
						deepEqual(t.exitStatus, { code: undefined });
M
Megan Rogge 已提交
224
						r();
D
Daniel Imms 已提交
225 226 227
					}
				}));
				terminal.dispose();
M
Megan Rogge 已提交
228
			});
D
Daniel Imms 已提交
229 230
		});

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
		// test('onDidChangeActiveTerminal should fire when new terminals are created', (done) => {
		// 	const reg1 = window.onDidChangeActiveTerminal((active: Terminal | undefined) => {
		// 		equal(active, terminal);
		// 		equal(active, window.activeTerminal);
		// 		reg1.dispose();
		// 		const reg2 = window.onDidChangeActiveTerminal((active: Terminal | undefined) => {
		// 			equal(active, undefined);
		// 			equal(active, window.activeTerminal);
		// 			reg2.dispose();
		// 			done();
		// 		});
		// 		terminal.dispose();
		// 	});
		// 	const terminal = window.createTerminal();
		// 	terminal.show();
		// });
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
		// test('onDidChangeTerminalDimensions should fire when new terminals are created', (done) => {
		// 	const reg1 = window.onDidChangeTerminalDimensions(async (event: TerminalDimensionsChangeEvent) => {
		// 		equal(event.terminal, terminal1);
		// 		equal(typeof event.dimensions.columns, 'number');
		// 		equal(typeof event.dimensions.rows, 'number');
		// 		ok(event.dimensions.columns > 0);
		// 		ok(event.dimensions.rows > 0);
		// 		reg1.dispose();
		// 		let terminal2: Terminal;
		// 		const reg2 = window.onDidOpenTerminal((newTerminal) => {
		// 			// This is guarantees to fire before dimensions change event
		// 			if (newTerminal !== terminal1) {
		// 				terminal2 = newTerminal;
		// 				reg2.dispose();
		// 			}
		// 		});
		// 		let firstCalled = false;
		// 		let secondCalled = false;
		// 		const reg3 = window.onDidChangeTerminalDimensions((event: TerminalDimensionsChangeEvent) => {
		// 			if (event.terminal === terminal1) {
		// 				// The original terminal should fire dimension change after a split
		// 				firstCalled = true;
		// 			} else if (event.terminal !== terminal1) {
		// 				// The new split terminal should fire dimension change
		// 				secondCalled = true;
		// 			}
		// 			if (firstCalled && secondCalled) {
		// 				let firstDisposed = false;
		// 				let secondDisposed = false;
		// 				const reg4 = window.onDidCloseTerminal(term => {
		// 					if (term === terminal1) {
		// 						firstDisposed = true;
		// 					}
		// 					if (term === terminal2) {
		// 						secondDisposed = true;
		// 					}
		// 					if (firstDisposed && secondDisposed) {
		// 						reg4.dispose();
		// 						done();
		// 					}
		// 				});
		// 				terminal1.dispose();
		// 				terminal2.dispose();
		// 				reg3.dispose();
		// 			}
		// 		});
		// 		await timeout(500);
		// 		commands.executeCommand('workbench.action.terminal.split');
		// 	});
		// 	const terminal1 = window.createTerminal({ name: 'test' });
		// 	terminal1.show();
		// });
300

301
		suite('hideFromUser', () => {
M
Megan Rogge 已提交
302
			test('should be available to terminals API', async () => {
303
				const terminal = window.createTerminal({ name: 'bg', hideFromUser: true });
M
Megan Rogge 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317
				const result = await new Promise<Terminal>(r => {
					disposables.push(window.onDidOpenTerminal(t => {
						if (t === terminal) {
							r(t);
						}
					}));
				});
				equal(result, terminal);
				equal(true, window.terminals.indexOf(terminal) !== -1);
				await new Promise<void>(r => {
					disposables.push(window.onDidCloseTerminal(t => {
						if (t === terminal) {
							r();
						}
318
					}));
319
					terminal.dispose();
M
Megan Rogge 已提交
320
				});
321 322
			});
		});
323

324 325 326 327 328
		suite('window.onDidWriteTerminalData', () => {
			test('should listen to all future terminal data events', (done) => {
				const openEvents: string[] = [];
				const dataEvents: { name: string, data: string }[] = [];
				const closeEvents: string[] = [];
329
				disposables.push(window.onDidOpenTerminal(e => openEvents.push(e.name)));
330 331

				let resolveOnceDataWritten: (() => void) | undefined;
E
Eric Amodio 已提交
332
				let resolveOnceClosed: (() => void) | undefined;
333

334
				disposables.push(window.onDidWriteTerminalData(e => {
335 336 337
					dataEvents.push({ name: e.terminal.name, data: e.data });

					resolveOnceDataWritten!();
338
				}));
339

340
				disposables.push(window.onDidCloseTerminal(e => {
341
					closeEvents.push(e.name);
D
Daniel Imms 已提交
342 343 344 345 346 347 348 349 350 351
					try {
						if (closeEvents.length === 1) {
							deepEqual(openEvents, ['test1']);
							deepEqual(dataEvents, [{ name: 'test1', data: 'write1' }]);
							deepEqual(closeEvents, ['test1']);
						} else if (closeEvents.length === 2) {
							deepEqual(openEvents, ['test1', 'test2']);
							deepEqual(dataEvents, [{ name: 'test1', data: 'write1' }, { name: 'test2', data: 'write2' }]);
							deepEqual(closeEvents, ['test1', 'test2']);
						}
E
Eric Amodio 已提交
352
						resolveOnceClosed!();
D
Daniel Imms 已提交
353 354
					} catch (e) {
						done(e);
355
					}
356
				}));
357 358 359

				const term1Write = new EventEmitter<string>();
				const term1Close = new EventEmitter<void>();
E
Eric Amodio 已提交
360 361 362 363 364 365 366 367
				window.createTerminal({
					name: 'test1', pty: {
						onDidWrite: term1Write.event,
						onDidClose: term1Close.event,
						open: async () => {
							term1Write.fire('write1');

							// Wait until the data is written
368
							await new Promise<void>(resolve => { resolveOnceDataWritten = resolve; });
E
Eric Amodio 已提交
369 370 371 372 373

							term1Close.fire();

							// Wait until the terminal is closed
							await new Promise<void>(resolve => { resolveOnceClosed = resolve; });
D
Daniel Imms 已提交
374

E
Eric Amodio 已提交
375 376 377 378 379 380 381 382
							const term2Write = new EventEmitter<string>();
							const term2Close = new EventEmitter<void>();
							window.createTerminal({
								name: 'test2', pty: {
									onDidWrite: term2Write.event,
									onDidClose: term2Close.event,
									open: async () => {
										term2Write.fire('write2');
D
Daniel Imms 已提交
383

E
Eric Amodio 已提交
384 385
										// Wait until the data is written
										await new Promise<void>(resolve => { resolveOnceDataWritten = resolve; });
D
Daniel Imms 已提交
386

E
Eric Amodio 已提交
387
										term2Close.fire();
D
Daniel Imms 已提交
388

E
Eric Amodio 已提交
389 390 391 392 393 394 395 396 397 398 399 400
										// Wait until the terminal is closed
										await new Promise<void>(resolve => { resolveOnceClosed = resolve; });

										done();
									},
									close: () => { }
								}
							});
						},
						close: () => { }
					}
				});
401 402 403
			});
		});

D
Daniel Imms 已提交
404
		suite('Extension pty terminals', () => {
405
			test('should fire onDidOpenTerminal and onDidCloseTerminal', (done) => {
406
				disposables.push(window.onDidOpenTerminal(term => {
D
Daniel Imms 已提交
407 408 409 410
					try {
						equal(term.name, 'c');
					} catch (e) {
						done(e);
D
Daniel Imms 已提交
411
						return;
D
Daniel Imms 已提交
412
					}
413
					disposables.push(window.onDidCloseTerminal(() => done()));
414
					term.dispose();
415
				}));
416
				const pty: Pseudoterminal = {
D
Daniel Imms 已提交
417
					onDidWrite: new EventEmitter<string>().event,
418 419
					open: () => { },
					close: () => { }
420
				};
421
				window.createTerminal({ name: 'c', pty });
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
			// The below tests depend on global UI state and each other
			// test('should not provide dimensions on start as the terminal has not been shown yet', (done) => {
			// 	const reg1 = window.onDidOpenTerminal(term => {
			// 		equal(terminal, term);
			// 		reg1.dispose();
			// 	});
			// 	const pty: Pseudoterminal = {
			// 		onDidWrite: new EventEmitter<string>().event,
			// 		open: (dimensions) => {
			// 			equal(dimensions, undefined);
			// 			const reg3 = window.onDidCloseTerminal(() => {
			// 				reg3.dispose();
			// 				done();
			// 			});
			// 			// Show a terminal and wait a brief period before dispose, this will cause
			// 			// the panel to init it's dimenisons and be provided to following terminals.
			// 			// The following test depends on this.
			// 			terminal.show();
			// 			setTimeout(() => terminal.dispose(), 200);
			// 		},
			// 		close: () => {}
			// 	};
			// 	const terminal = window.createTerminal({ name: 'foo', pty });
			// });
			// test('should provide dimensions on start as the terminal has been shown', (done) => {
			// 	const reg1 = window.onDidOpenTerminal(term => {
			// 		equal(terminal, term);
			// 		reg1.dispose();
			// 	});
			// 	const pty: Pseudoterminal = {
			// 		onDidWrite: new EventEmitter<string>().event,
			// 		open: (dimensions) => {
			// 			// This test depends on Terminal.show being called some time before such
			// 			// that the panel dimensions are initialized and cached.
			// 			ok(dimensions!.columns > 0);
			// 			ok(dimensions!.rows > 0);
			// 			const reg3 = window.onDidCloseTerminal(() => {
			// 				reg3.dispose();
			// 				done();
			// 			});
			// 			terminal.dispose();
			// 		},
			// 		close: () => {}
			// 	};
			// 	const terminal = window.createTerminal({ name: 'foo', pty });
			// });
D
Daniel Imms 已提交
470

M
meganrogge 已提交
471
			test.skip('should respect dimension overrides', (done) => {
472
				disposables.push(window.onDidOpenTerminal(term => {
D
Daniel Imms 已提交
473 474 475 476
					try {
						equal(terminal, term);
					} catch (e) {
						done(e);
D
Daniel Imms 已提交
477
						return;
D
Daniel Imms 已提交
478
					}
D
Daniel Imms 已提交
479
					term.show();
480
					disposables.push(window.onDidChangeTerminalDimensions(e => {
D
Daniel Imms 已提交
481 482 483 484 485 486 487 488
						// The default pty dimensions have a chance to appear here since override
						// dimensions happens after the terminal is created. If so just ignore and
						// wait for the right dimensions
						if (e.dimensions.columns === 10 || e.dimensions.rows === 5) {
							try {
								equal(e.terminal, terminal);
							} catch (e) {
								done(e);
D
Daniel Imms 已提交
489
								return;
D
Daniel Imms 已提交
490 491 492
							}
							disposables.push(window.onDidCloseTerminal(() => done()));
							terminal.dispose();
D
Daniel Imms 已提交
493
						}
494 495
					}));
				}));
D
Daniel Imms 已提交
496 497
				const writeEmitter = new EventEmitter<string>();
				const overrideDimensionsEmitter = new EventEmitter<TerminalDimensions>();
498
				const pty: Pseudoterminal = {
499
					onDidWrite: writeEmitter.event,
D
Daniel Imms 已提交
500
					onDidOverrideDimensions: overrideDimensionsEmitter.event,
D
Daniel Imms 已提交
501 502 503 504 505 506
					open: () => overrideDimensionsEmitter.fire({ columns: 10, rows: 5 }),
					close: () => { }
				};
				const terminal = window.createTerminal({ name: 'foo', pty });
			});

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
			test('should change terminal name', (done) => {
				disposables.push(window.onDidOpenTerminal(term => {
					try {
						equal(terminal, term);
						equal(terminal.name, 'foo');
					} catch (e) {
						done(e);
						return;
					}
					disposables.push(window.onDidCloseTerminal(t => {
						try {
							equal(terminal, t);
							equal(terminal.name, 'bar');
						} catch (e) {
							done(e);
							return;
						}
						done();
					}));
				}));
				const changeNameEmitter = new EventEmitter<string>();
				const closeEmitter = new EventEmitter<number | undefined>();
				const pty: Pseudoterminal = {
					onDidWrite: new EventEmitter<string>().event,
					onDidChangeName: changeNameEmitter.event,
					onDidClose: closeEmitter.event,
					open: () => {
						changeNameEmitter.fire('bar');
						closeEmitter.fire(undefined);
					},
					close: () => { }
				};
				const terminal = window.createTerminal({ name: 'foo', pty });
			});

D
Daniel Imms 已提交
542 543 544 545 546 547 548
			test('exitStatus.code should be set to the exit code (undefined)', (done) => {
				disposables.push(window.onDidOpenTerminal(term => {
					try {
						equal(terminal, term);
						equal(terminal.exitStatus, undefined);
					} catch (e) {
						done(e);
D
Daniel Imms 已提交
549
						return;
D
Daniel Imms 已提交
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
					}
					disposables.push(window.onDidCloseTerminal(t => {
						try {
							equal(terminal, t);
							deepEqual(terminal.exitStatus, { code: undefined });
						} catch (e) {
							done(e);
							return;
						}
						done();
					}));
				}));
				const writeEmitter = new EventEmitter<string>();
				const closeEmitter = new EventEmitter<number | undefined>();
				const pty: Pseudoterminal = {
					onDidWrite: writeEmitter.event,
					onDidClose: closeEmitter.event,
567
					open: () => closeEmitter.fire(undefined),
D
Daniel Imms 已提交
568 569 570 571 572 573 574 575 576 577 578 579
					close: () => { }
				};
				const terminal = window.createTerminal({ name: 'foo', pty });
			});

			test('exitStatus.code should be set to the exit code (zero)', (done) => {
				disposables.push(window.onDidOpenTerminal(term => {
					try {
						equal(terminal, term);
						equal(terminal.exitStatus, undefined);
					} catch (e) {
						done(e);
D
Daniel Imms 已提交
580
						return;
D
Daniel Imms 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
					}
					disposables.push(window.onDidCloseTerminal(t => {
						try {
							equal(terminal, t);
							deepEqual(terminal.exitStatus, { code: 0 });
						} catch (e) {
							done(e);
							return;
						}
						done();
					}));
				}));
				const writeEmitter = new EventEmitter<string>();
				const closeEmitter = new EventEmitter<number | undefined>();
				const pty: Pseudoterminal = {
					onDidWrite: writeEmitter.event,
					onDidClose: closeEmitter.event,
					open: () => closeEmitter.fire(0),
					close: () => { }
				};
				const terminal = window.createTerminal({ name: 'foo', pty });
			});

			test('exitStatus.code should be set to the exit code (non-zero)', (done) => {
				disposables.push(window.onDidOpenTerminal(term => {
					try {
						equal(terminal, term);
						equal(terminal.exitStatus, undefined);
					} catch (e) {
						done(e);
D
Daniel Imms 已提交
611
						return;
D
Daniel Imms 已提交
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
					}
					disposables.push(window.onDidCloseTerminal(t => {
						try {
							equal(terminal, t);
							deepEqual(terminal.exitStatus, { code: 22 });
						} catch (e) {
							done(e);
							return;
						}
						done();
					}));
				}));
				const writeEmitter = new EventEmitter<string>();
				const closeEmitter = new EventEmitter<number | undefined>();
				const pty: Pseudoterminal = {
					onDidWrite: writeEmitter.event,
					onDidClose: closeEmitter.event,
629 630 631 632 633 634
					open: () => {
						// Wait 500ms as any exits that occur within 500ms of terminal launch are
						// are counted as "exiting during launch" which triggers a notification even
						// when showExitAlerts is true
						setTimeout(() => closeEmitter.fire(22), 500);
					},
635
					close: () => { }
D
Daniel Imms 已提交
636
				};
637
				const terminal = window.createTerminal({ name: 'foo', pty });
D
Daniel Imms 已提交
638
			});
639 640 641 642 643 644 645

			test('creationOptions should be set and readonly for ExtensionTerminalOptions terminals', (done) => {
				disposables.push(window.onDidOpenTerminal(term => {
					try {
						equal(terminal, term);
					} catch (e) {
						done(e);
D
Daniel Imms 已提交
646
						return;
647 648 649 650 651 652 653 654 655 656 657 658 659 660
					}
					terminal.dispose();
					disposables.push(window.onDidCloseTerminal(() => done()));
				}));
				const writeEmitter = new EventEmitter<string>();
				const pty: Pseudoterminal = {
					onDidWrite: writeEmitter.event,
					open: () => { },
					close: () => { }
				};
				const options = { name: 'foo', pty };
				const terminal = window.createTerminal(options);
				try {
					equal(terminal.name, 'foo');
661 662 663 664
					const terminalOptions = terminal.creationOptions as ExtensionTerminalOptions;
					equal(terminalOptions.name, 'foo');
					equal(terminalOptions.pty, pty);
					throws(() => terminalOptions.name = 'bad', 'creationOptions should be readonly at runtime');
665 666 667 668
				} catch (e) {
					done(e);
				}
			});
669
		});
670

D
Daniel Imms 已提交
671
		suite('environmentVariableCollection', () => {
672
			test('should have collection variables apply to terminals immediately after setting', (done) => {
673 674 675 676 677 678
				// Text to match on before passing the test
				const expectedText = [
					'~a2~',
					'b1~b2~',
					'~c2~c1'
				];
679
				let data = '';
680
				disposables.push(window.onDidWriteTerminalData(e => {
681
					if (terminal !== e.terminal) {
D
Daniel Imms 已提交
682
						return;
683
					}
684
					data += sanitizeData(e.data);
D
Daniel Imms 已提交
685 686
					console.log(`new data: "${e.data}"`);
					console.log(`all data: "${data}"`);
687
					// Multiple expected could show up in the same data event
688
					while (expectedText.length > 0 && data.indexOf(expectedText[0]) >= 0) {
D
Daniel Imms 已提交
689
						console.log(`found, shift expected: "${expectedText[0]}"`);
690 691 692 693 694 695 696 697
						expectedText.shift();
						// Check if all string are found, if so finish the test
						if (expectedText.length === 0) {
							disposables.push(window.onDidCloseTerminal(() => done()));
							terminal.dispose();
						}
					}
				}));
698 699
				const collection = extensionContext.environmentVariableCollection;
				disposables.push({ dispose: () => collection.clear() });
700 701 702 703 704 705 706 707 708 709
				collection.replace('A', '~a2~');
				collection.append('B', '~b2~');
				collection.prepend('C', '~c2~');
				const terminal = window.createTerminal({
					env: {
						A: 'a1',
						B: 'b1',
						C: 'c1'
					}
				});
710 711 712 713 714 715 716 717
				// Run both PowerShell and sh commands, errors don't matter we're just looking for
				// the correct output
				terminal.sendText('$env:A');
				terminal.sendText('echo $A');
				terminal.sendText('$env:B');
				terminal.sendText('echo $B');
				terminal.sendText('$env:C');
				terminal.sendText('echo $C');
718 719
			});

720
			test('should have collection variables apply to environment variables that don\'t exist', (done) => {
721 722 723 724 725 726
				// Text to match on before passing the test
				const expectedText = [
					'~a2~',
					'~b2~',
					'~c2~'
				];
727
				let data = '';
728
				disposables.push(window.onDidWriteTerminalData(e => {
729
					if (terminal !== e.terminal) {
D
Daniel Imms 已提交
730
						return;
731
					}
732
					data += sanitizeData(e.data);
733
					// Multiple expected could show up in the same data event
734
					while (expectedText.length > 0 && data.indexOf(expectedText[0]) >= 0) {
735 736 737 738 739 740 741 742
						expectedText.shift();
						// Check if all string are found, if so finish the test
						if (expectedText.length === 0) {
							disposables.push(window.onDidCloseTerminal(() => done()));
							terminal.dispose();
						}
					}
				}));
743 744
				const collection = extensionContext.environmentVariableCollection;
				disposables.push({ dispose: () => collection.clear() });
745 746 747 748 749 750 751 752 753 754
				collection.replace('A', '~a2~');
				collection.append('B', '~b2~');
				collection.prepend('C', '~c2~');
				const terminal = window.createTerminal({
					env: {
						A: null,
						B: null,
						C: null
					}
				});
755 756 757 758 759 760 761 762
				// Run both PowerShell and sh commands, errors don't matter we're just looking for
				// the correct output
				terminal.sendText('$env:A');
				terminal.sendText('echo $A');
				terminal.sendText('$env:B');
				terminal.sendText('echo $B');
				terminal.sendText('$env:C');
				terminal.sendText('echo $C');
763
			});
D
Daniel Imms 已提交
764

765
			test('should respect clearing entries', (done) => {
D
Daniel Imms 已提交
766 767 768 769 770
				// Text to match on before passing the test
				const expectedText = [
					'~a1~',
					'~b1~'
				];
771
				let data = '';
D
Daniel Imms 已提交
772
				disposables.push(window.onDidWriteTerminalData(e => {
773
					if (terminal !== e.terminal) {
D
Daniel Imms 已提交
774
						return;
D
Daniel Imms 已提交
775
					}
776
					data += sanitizeData(e.data);
D
Daniel Imms 已提交
777
					// Multiple expected could show up in the same data event
778
					while (expectedText.length > 0 && data.indexOf(expectedText[0]) >= 0) {
D
Daniel Imms 已提交
779 780 781 782 783 784 785 786
						expectedText.shift();
						// Check if all string are found, if so finish the test
						if (expectedText.length === 0) {
							disposables.push(window.onDidCloseTerminal(() => done()));
							terminal.dispose();
						}
					}
				}));
787 788
				const collection = extensionContext.environmentVariableCollection;
				disposables.push({ dispose: () => collection.clear() });
D
Daniel Imms 已提交
789 790 791 792 793 794 795 796 797
				collection.replace('A', '~a2~');
				collection.replace('B', '~a2~');
				collection.clear();
				const terminal = window.createTerminal({
					env: {
						A: '~a1~',
						B: '~b1~'
					}
				});
798 799 800 801 802 803
				// Run both PowerShell and sh commands, errors don't matter we're just looking for
				// the correct output
				terminal.sendText('$env:A');
				terminal.sendText('echo $A');
				terminal.sendText('$env:B');
				terminal.sendText('echo $B');
D
Daniel Imms 已提交
804 805
			});

806
			test('should respect deleting entries', (done) => {
D
Daniel Imms 已提交
807 808 809 810 811
				// Text to match on before passing the test
				const expectedText = [
					'~a1~',
					'~b2~'
				];
812
				let data = '';
D
Daniel Imms 已提交
813
				disposables.push(window.onDidWriteTerminalData(e => {
814
					if (terminal !== e.terminal) {
D
Daniel Imms 已提交
815
						return;
D
Daniel Imms 已提交
816
					}
817
					data += sanitizeData(e.data);
D
Daniel Imms 已提交
818
					// Multiple expected could show up in the same data event
819
					while (expectedText.length > 0 && data.indexOf(expectedText[0]) >= 0) {
D
Daniel Imms 已提交
820 821 822 823 824 825 826 827
						expectedText.shift();
						// Check if all string are found, if so finish the test
						if (expectedText.length === 0) {
							disposables.push(window.onDidCloseTerminal(() => done()));
							terminal.dispose();
						}
					}
				}));
828 829
				const collection = extensionContext.environmentVariableCollection;
				disposables.push({ dispose: () => collection.clear() });
D
Daniel Imms 已提交
830 831 832 833 834 835 836 837 838
				collection.replace('A', '~a2~');
				collection.replace('B', '~b2~');
				collection.delete('A');
				const terminal = window.createTerminal({
					env: {
						A: '~a1~',
						B: '~b2~'
					}
				});
839 840 841 842 843 844
				// Run both PowerShell and sh commands, errors don't matter we're just looking for
				// the correct output
				terminal.sendText('$env:A');
				terminal.sendText('echo $A');
				terminal.sendText('$env:B');
				terminal.sendText('echo $B');
D
Daniel Imms 已提交
845 846 847
			});

			test('get and forEach should work', () => {
848 849
				const collection = extensionContext.environmentVariableCollection;
				disposables.push({ dispose: () => collection.clear() });
D
Daniel Imms 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
				collection.replace('A', '~a2~');
				collection.append('B', '~b2~');
				collection.prepend('C', '~c2~');

				// Verify get
				deepEqual(collection.get('A'), { value: '~a2~', type: EnvironmentVariableMutatorType.Replace });
				deepEqual(collection.get('B'), { value: '~b2~', type: EnvironmentVariableMutatorType.Append });
				deepEqual(collection.get('C'), { value: '~c2~', type: EnvironmentVariableMutatorType.Prepend });

				// Verify forEach
				const entries: [string, EnvironmentVariableMutator][] = [];
				collection.forEach((v, m) => entries.push([v, m]));
				deepEqual(entries, [
					['A', { value: '~a2~', type: EnvironmentVariableMutatorType.Replace }],
					['B', { value: '~b2~', type: EnvironmentVariableMutatorType.Append }],
					['C', { value: '~c2~', type: EnvironmentVariableMutatorType.Prepend }]
				]);
			});
868
		});
869 870
	});
});
871 872 873 874 875 876 877 878 879 880 881 882

function sanitizeData(data: string): string {
	// Strip NL/CR so terminal dimensions don't impact tests
	data = data.replaceAll(/[\r\n]/g, '');

	// Strip escape sequences so winpty/conpty doesn't cause flakiness, do for all platforms for
	// consistency
	const terminalCodesRegex = /(?:\u001B|\u009B)[\[\]()#;?]*(?:(?:(?:[a-zA-Z0-9]*(?:;[a-zA-Z0-9]*)*)?\u0007)|(?:(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-PR-TZcf-ntqry=><~]))/g;
	data = data.replaceAll(terminalCodesRegex, '');

	return data;
}