-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
uiMode.ts
288 lines (255 loc) · 10.2 KB
/
uiMode.ts
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
/**
* Copyright Microsoft Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { showTraceViewer } from 'playwright-core/lib/server';
import { isUnderTest, ManualPromise } from 'playwright-core/lib/utils';
import type { FullResult } from '../../reporter';
import { clearCompilationCache, collectAffectedTestFiles, dependenciesForTestFile } from '../transform/compilationCache';
import type { FullConfigInternal } from '../common/config';
import { InternalReporter } from '../reporters/internalReporter';
import { TeleReporterEmitter } from '../reporters/teleEmitter';
import { createReporters } from './reporters';
import { TestRun, createTaskRunnerForList, createTaskRunnerForWatch, createTaskRunnerForWatchSetup } from './tasks';
import { chokidar } from '../utilsBundle';
import type { FSWatcher } from 'chokidar';
import { open } from 'playwright-core/lib/utilsBundle';
import ListReporter from '../reporters/list';
import type { Transport } from 'playwright-core/lib/server/trace/viewer/traceViewer';
class UIMode {
private _config: FullConfigInternal;
private _transport!: Transport;
private _testRun: { run: Promise<FullResult['status']>, stop: ManualPromise<void> } | undefined;
globalCleanup: (() => Promise<FullResult['status']>) | undefined;
private _globalWatcher: Watcher;
private _testWatcher: Watcher;
private _originalStdoutWrite: NodeJS.WriteStream['write'];
private _originalStderrWrite: NodeJS.WriteStream['write'];
constructor(config: FullConfigInternal) {
this._config = config;
process.env.PW_LIVE_TRACE_STACKS = '1';
config.cliListOnly = false;
config.cliPassWithNoTests = true;
for (const project of config.projects) {
project.deps = [];
project.teardown = undefined;
}
for (const p of config.projects) {
p.project.retries = 0;
p.project.repeatEach = 1;
}
config.configCLIOverrides.use = config.configCLIOverrides.use || {};
config.configCLIOverrides.use.trace = { mode: 'on', sources: false };
this._originalStdoutWrite = process.stdout.write;
this._originalStderrWrite = process.stderr.write;
this._globalWatcher = new Watcher('deep', () => this._dispatchEvent('listChanged', {}));
this._testWatcher = new Watcher('flat', events => {
const collector = new Set<string>();
events.forEach(f => collectAffectedTestFiles(f.file, collector));
this._dispatchEvent('testFilesChanged', { testFileNames: [...collector] });
});
}
async runGlobalSetup(): Promise<FullResult['status']> {
const reporter = new InternalReporter([new ListReporter()]);
const taskRunner = createTaskRunnerForWatchSetup(this._config, reporter);
reporter.onConfigure(this._config);
const testRun = new TestRun(this._config, reporter);
const { status, cleanup: globalCleanup } = await taskRunner.runDeferCleanup(testRun, 0);
await reporter.onExit({ status });
if (status !== 'passed') {
await globalCleanup();
return status;
}
this.globalCleanup = globalCleanup;
return status;
}
async showUI(options: { host?: string, port?: number }) {
const exitPromise = new ManualPromise();
let queue = Promise.resolve();
this._transport = {
dispatch: async (method, params) => {
if (method === 'ping')
return;
if (method === 'exit') {
exitPromise.resolve();
return;
}
if (method === 'watch') {
this._watchFiles(params.fileNames);
return;
}
if (method === 'open' && params.location) {
open('vscode://file/' + params.location).catch(e => this._originalStderrWrite.call(process.stderr, String(e)));
return;
}
if (method === 'resizeTerminal') {
process.stdout.columns = params.cols;
process.stdout.rows = params.rows;
process.stderr.columns = params.cols;
process.stderr.columns = params.rows;
return;
}
if (method === 'stop') {
void this._stopTests();
return;
}
queue = queue.then(() => this._queueListOrRun(method, params));
await queue;
},
onclose: () => exitPromise.resolve(),
};
await showTraceViewer([], 'chromium', {
app: 'uiMode.html',
headless: isUnderTest() && process.env.PWTEST_HEADED_FOR_TEST !== '1',
transport: this._transport,
host: options.host,
port: options.port,
openInBrowser: options.host !== undefined || options.port !== undefined,
});
if (!process.env.PWTEST_DEBUG) {
process.stdout.write = (chunk: string | Buffer) => {
this._dispatchEvent('stdio', chunkToPayload('stdout', chunk));
return true;
};
process.stderr.write = (chunk: string | Buffer) => {
this._dispatchEvent('stdio', chunkToPayload('stderr', chunk));
return true;
};
}
await exitPromise;
if (!process.env.PWTEST_DEBUG) {
process.stdout.write = this._originalStdoutWrite;
process.stderr.write = this._originalStderrWrite;
}
}
private async _queueListOrRun(method: string, params: any) {
if (method === 'list')
await this._listTests();
if (method === 'run')
await this._runTests(params.testIds);
}
private _dispatchEvent(method: string, params?: any) {
this._transport.sendEvent?.(method, params);
}
private async _listTests() {
const listReporter = new TeleReporterEmitter(e => this._dispatchEvent(e.method, e.params));
const reporter = new InternalReporter([listReporter]);
this._config.cliListOnly = true;
this._config.testIdMatcher = undefined;
const taskRunner = createTaskRunnerForList(this._config, reporter, 'out-of-process', { failOnLoadErrors: false });
const testRun = new TestRun(this._config, reporter);
clearCompilationCache();
reporter.onConfigure(this._config);
const status = await taskRunner.run(testRun, 0);
await reporter.onExit({ status });
const projectDirs = new Set<string>();
for (const p of this._config.projects)
projectDirs.add(p.project.testDir);
this._globalWatcher.update([...projectDirs], false);
}
private async _runTests(testIds: string[]) {
await this._stopTests();
const testIdSet = testIds ? new Set<string>(testIds) : null;
this._config.cliListOnly = false;
this._config.testIdMatcher = id => !testIdSet || testIdSet.has(id);
const reporters = await createReporters(this._config, 'ui');
reporters.push(new TeleReporterEmitter(e => this._dispatchEvent(e.method, e.params)));
const reporter = new InternalReporter(reporters);
const taskRunner = createTaskRunnerForWatch(this._config, reporter);
const testRun = new TestRun(this._config, reporter);
clearCompilationCache();
reporter.onConfigure(this._config);
const stop = new ManualPromise();
const run = taskRunner.run(testRun, 0, stop).then(async status => {
await reporter.onExit({ status });
this._testRun = undefined;
this._config.testIdMatcher = undefined;
return status;
});
this._testRun = { run, stop };
await run;
}
private _watchFiles(fileNames: string[]) {
const files = new Set<string>();
for (const fileName of fileNames) {
files.add(fileName);
dependenciesForTestFile(fileName).forEach(file => files.add(file));
}
this._testWatcher.update([...files], true);
}
private async _stopTests() {
this._testRun?.stop?.resolve();
await this._testRun?.run;
}
}
export async function runUIMode(config: FullConfigInternal, options: { host?: string, port?: number }): Promise<FullResult['status']> {
const uiMode = new UIMode(config);
const status = await uiMode.runGlobalSetup();
if (status !== 'passed')
return status;
await uiMode.showUI(options);
return await uiMode.globalCleanup?.() || 'passed';
}
type StdioPayload = {
type: 'stdout' | 'stderr';
text?: string;
buffer?: string;
};
function chunkToPayload(type: 'stdout' | 'stderr', chunk: Buffer | string): StdioPayload {
if (chunk instanceof Buffer)
return { type, buffer: chunk.toString('base64') };
return { type, text: chunk };
}
type FSEvent = { event: 'add' | 'addDir' | 'change' | 'unlink' | 'unlinkDir', file: string };
class Watcher {
private _onChange: (events: FSEvent[]) => void;
private _watchedFiles: string[] = [];
private _collector: FSEvent[] = [];
private _fsWatcher: FSWatcher | undefined;
private _throttleTimer: NodeJS.Timeout | undefined;
private _mode: 'flat' | 'deep';
constructor(mode: 'flat' | 'deep', onChange: (events: FSEvent[]) => void) {
this._mode = mode;
this._onChange = onChange;
}
update(watchedFiles: string[], reportPending: boolean) {
if (JSON.stringify(this._watchedFiles) === JSON.stringify(watchedFiles))
return;
if (reportPending)
this._reportEventsIfAny();
this._watchedFiles = watchedFiles;
void this._fsWatcher?.close();
this._fsWatcher = undefined;
this._collector.length = 0;
clearTimeout(this._throttleTimer);
this._throttleTimer = undefined;
if (!this._watchedFiles.length)
return;
this._fsWatcher = chokidar.watch(watchedFiles, { ignoreInitial: true }).on('all', async (event, file) => {
if (this._throttleTimer)
clearTimeout(this._throttleTimer);
if (this._mode === 'flat' && event !== 'add' && event !== 'change')
return;
if (this._mode === 'deep' && event !== 'add' && event !== 'change' && event !== 'unlink' && event !== 'addDir' && event !== 'unlinkDir')
return;
this._collector.push({ event, file });
this._throttleTimer = setTimeout(() => this._reportEventsIfAny(), 250);
});
}
private _reportEventsIfAny() {
if (this._collector.length)
this._onChange(this._collector.slice());
this._collector.length = 0;
}
}