-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathcompass.ts
1230 lines (1089 loc) · 36.5 KB
/
compass.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
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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { inspect } from 'util';
import { ObjectId, EJSON } from 'bson';
import { promises as fs, rmdirSync } from 'fs';
import type Mocha from 'mocha';
import path from 'path';
import os from 'os';
import { execFile } from 'child_process';
import type { ExecFileOptions, ExecFileException } from 'child_process';
import { promisify } from 'util';
import zlib from 'zlib';
import { remote } from 'webdriverio';
import { rebuild } from '@electron/rebuild';
import type { RebuildOptions } from '@electron/rebuild';
import { run as packageCompass } from 'hadron-build/commands/release';
import { redactConnectionString } from 'mongodb-connection-string-url';
import { getConnectionTitle } from '@mongodb-js/connection-info';
export * as Selectors from './selectors';
export * as Commands from './commands';
import * as Commands from './commands';
import type { CompassBrowser } from './compass-browser';
import type { LogEntry } from './telemetry';
import Debug from 'debug';
import semver from 'semver';
import { CHROME_STARTUP_FLAGS } from './chrome-startup-flags';
import {
DEFAULT_CONNECTION_STRINGS,
DEFAULT_CONNECTION_NAMES,
DEFAULT_CONNECTIONS_SERVER_INFO,
isTestingWeb,
isTestingDesktop,
context,
assertTestingWeb,
isTestingAtlasCloudExternal,
} from './test-runner-context';
import {
ELECTRON_CHROMIUM_VERSION,
LOG_PATH,
LOG_COVERAGE_PATH,
COMPASS_DESKTOP_PATH,
LOG_OUTPUT_PATH,
LOG_SCREENSHOTS_PATH,
ELECTRON_PATH,
} from './test-runner-paths';
import treeKill from 'tree-kill';
const killAsync = async (pid: number, signal?: string) => {
return new Promise<void>((resolve, reject) => {
treeKill(pid, signal ?? 'SIGTERM', (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
const debug = Debug('compass-e2e-tests');
const { gunzip } = zlib;
const { Z_SYNC_FLUSH } = zlib.constants;
const packageCompassAsync = promisify(packageCompass);
// should we test compass-web (true) or compass electron (false)?
export const TEST_COMPASS_WEB = isTestingWeb();
// Extending the WebdriverIO's types to allow a verbose option to the chromedriver
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace WebdriverIO {
interface ChromedriverOptions {
verbose?: boolean;
}
}
}
/*
A helper so we can easily find all the tests we're skipping in compass-web.
Reason is there so you can fill it in and have it show up in search results
in a scannable manner. It is not being output at present because the tests will
be logged as pending anyway.
*/
export function skipForWeb(
test: Mocha.Runnable | Mocha.Context,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
reason: string
) {
if (TEST_COMPASS_WEB) {
test.skip();
}
}
export const DEFAULT_CONNECTION_STRING_1 = DEFAULT_CONNECTION_STRINGS[0];
// NOTE: in browser.setupDefaultConnections() we don't give the first connection an
// explicit name, so it gets a calculated one based off the connection string
export const DEFAULT_CONNECTION_NAME_1 = DEFAULT_CONNECTION_NAMES[0];
// for testing multiple connections
export const DEFAULT_CONNECTION_STRING_2 = DEFAULT_CONNECTION_STRINGS[1];
// NOTE: in browser.setupDefaultConnections() the second connection gets given an explicit name
export const DEFAULT_CONNECTION_NAME_2 = DEFAULT_CONNECTION_NAMES[1];
export const serverSatisfies = (
semverCondition: string,
enterpriseExact?: boolean
) => {
const { version, enterprise } = DEFAULT_CONNECTIONS_SERVER_INFO[0];
return (
semver.satisfies(version, semverCondition, {
includePrerelease: true,
}) &&
(typeof enterpriseExact === 'boolean'
? (enterpriseExact && enterprise) || (!enterpriseExact && !enterprise)
: true)
);
};
// For the user data dirs and logs
let runCounter = 0;
interface Coverage {
main?: string;
renderer?: string;
}
interface RenderLogEntry {
timestamp: string;
type: string;
text: string;
args: unknown;
}
interface CompassOptions {
mode: 'electron' | 'web';
writeCoverage?: boolean;
needsCloseWelcomeModal?: boolean;
}
export class Compass {
name: string;
browser: CompassBrowser;
mode: 'electron' | 'web';
writeCoverage: boolean;
needsCloseWelcomeModal: boolean;
renderLogs: RenderLogEntry[];
logs: LogEntry[];
logPath?: string;
userDataPath?: string;
appName?: string;
mainProcessPid?: number;
constructor(
name: string,
browser: CompassBrowser,
{
mode,
writeCoverage = false,
needsCloseWelcomeModal = false,
}: CompassOptions
) {
this.name = name;
this.browser = browser;
this.mode = mode;
this.writeCoverage = writeCoverage;
this.needsCloseWelcomeModal = needsCloseWelcomeModal;
this.logs = [];
this.renderLogs = [];
for (const [k, v] of Object.entries(Commands)) {
this.browser.addCommand(k, (...args) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return v(browser, ...args);
});
}
this.addDebugger();
}
async recordElectronLogs(): Promise<void> {
debug('Setting up renderer log listeners ...');
const puppeteerBrowser = await this.browser.getPuppeteer();
const pages = await puppeteerBrowser.pages();
const page = pages[0];
page.on('console', (message) => {
const run = async () => {
// human and machine readable, always UTC
const timestamp = new Date().toISOString();
// startGroup, endGroup, log, table, warning, etc.
const type = message.type();
const text = message.text();
// first arg is usually == text, but not always
const args = [];
for (const arg of message.args()) {
let value;
try {
value = await arg.jsonValue();
} catch (err) {
// there are still some edge cases we can't easily convert into text
console.error('could not convert', arg);
value = '¯\\_(ツ)_/¯';
}
args.push(value);
}
// uncomment to see browser logs
//console.log({ timestamp, type, text, args });
this.renderLogs.push({ timestamp, type, text, args });
};
void run();
});
// get the app logPath out of electron early in case the app crashes before we
// close it and load the logs
[this.logPath, this.userDataPath, this.appName, this.mainProcessPid] =
await this.browser.execute(() => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { ipcRenderer } = require('electron');
return Promise.all([
ipcRenderer.invoke('compass:logPath'),
ipcRenderer.invoke('compass:userDataPath'),
ipcRenderer.invoke('compass:appName'),
ipcRenderer.invoke('compass:mainProcessPid'),
] as const);
});
}
addDebugger(): void {
const browser = this.browser;
const debugClient = debug.extend('webdriver:client');
const browserProto = Object.getPrototypeOf(browser);
// We can pull the own property names straight from browser, but brings up a
// lot of things we're not interested. So this is just a list of the public
// interface methods.
const props = Object.getOwnPropertyNames(browserProto).concat(
'$$',
'$',
'addCommand',
'call',
'custom$$',
'custom$',
'debug',
'deleteCookies',
'execute',
'executeAsync',
'getCookies',
'getPuppeteer',
'getWindowSize',
'keys',
'mock',
'mockClearAll',
'mockRestoreAll',
'newWindow',
'overwriteCommand',
'pause',
'react$$',
'react$',
'reloadSession',
'savePDF',
'saveRecordingScreen',
'saveScreenshot',
'setCookies',
'setTimeout',
'setWindowSize',
'switchWindow',
'throttle',
'touchAction',
'uploadFile',
'url',
'waitUntil'
);
for (const prop of props) {
// disable emit logging for now because it is very noisy
if (prop.includes('.') || prop === 'emit') {
continue;
}
const protoDescriptor = Object.getOwnPropertyDescriptor(
browserProto,
prop
);
const browserDescriptor = Object.getOwnPropertyDescriptor(browser, prop);
const descriptor = protoDescriptor || browserDescriptor;
if (!descriptor || typeof descriptor.value !== 'function') {
continue;
}
const origFn = descriptor.value;
descriptor.value = function (...args: any[]) {
debugClient(
`${prop}(${args
.map((arg) => redact(inspect(arg, { breakLength: Infinity })))
.join(', ')})`
);
const stack = new Error(prop).stack ?? '';
let result;
try {
// eslint-disable-next-line prefer-const
result = origFn.call(this, ...args);
} catch (error) {
// In this case the method threw synchronously
augmentError(error as Error, stack);
throw error;
}
// Many of the webdriverio browser methods are chainable, so rather just
// return their objects as is. They are also promises, but resolving
// them will mess with the chainability.
if (protoDescriptor && result && result.then) {
// If the result looks like a promise, resolve it and look for errors
return result.catch((error: Error) => {
augmentError(error, stack);
throw error;
});
}
// return the synchronous result for our browser commands or possibly
// chainable thing as is for builtin browser commands
return result;
};
Object.defineProperty(
protoDescriptor ? browserProto : browser,
prop,
descriptor
);
}
}
async stopElectron(): Promise<void> {
const renderLogPath = path.join(
LOG_PATH,
`electron-render.${this.name}.json`
);
debug(`Writing application render process log to ${renderLogPath}`);
await fs.writeFile(renderLogPath, JSON.stringify(this.renderLogs, null, 2));
if (this.writeCoverage) {
// coverage
debug('Writing coverage');
const coverage: Coverage = await this.browser.executeAsync((done) => {
void (async () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const mainCoverage = await require('electron').ipcRenderer.invoke(
'coverage'
);
done({
main: JSON.stringify(mainCoverage, null, 4),
renderer: JSON.stringify((window as any).__coverage__, null, 4),
});
})();
});
if (coverage.main) {
await fs.writeFile(
path.join(LOG_COVERAGE_PATH, `main.${this.name}.log`),
coverage.main
);
}
if (coverage.renderer) {
await fs.writeFile(
path.join(LOG_COVERAGE_PATH, `renderer.${this.name}.log`),
coverage.renderer
);
}
}
const copyCompassLog = async () => {
const compassLog = await getCompassLog(this.logPath ?? '');
const compassLogPath = path.join(
LOG_PATH,
`compass-log.${this.name}.log`
);
debug(`Writing Compass application log to ${compassLogPath}`);
await fs.writeFile(compassLogPath, compassLog.raw);
return compassLog;
};
// Copy log files before stopping in case that stopping itself fails and needs to be debugged
await copyCompassLog();
debug(`Stopping Compass application [${this.name}]`);
await this.browser.deleteSession({ shutdownDriver: true });
this.logs = (await copyCompassLog()).structured;
}
async stopBrowser(): Promise<void> {
const logging: any[] = await this.browser.execute(function () {
// eslint-disable-next-line no-restricted-globals
return 'logging' in window && (window.logging as any);
});
const lines = logging.map((log) => JSON.stringify(log));
const text = lines.join('\n');
const compassLogPath = path.join(LOG_PATH, `compass-log.${this.name}.log`);
debug(`Writing Compass application log to ${compassLogPath}`);
await fs.writeFile(compassLogPath, text);
debug(`Stopping Compass application [${this.name}]`);
await this.browser.deleteSession({ shutdownDriver: true });
}
async stop(): Promise<void> {
if (TEST_COMPASS_WEB) {
await this.stopBrowser();
} else {
await this.stopElectron();
}
}
}
interface StartCompassOptions {
firstRun?: boolean;
extraSpawnArgs?: string[];
wrapBinary?: (binary: string) => Promise<string> | string;
}
let defaultUserDataDir: string | undefined;
export function removeUserDataDir(): void {
if (!defaultUserDataDir) {
return;
}
debug('Removing user data');
try {
// this is sync so we can use it in cleanup() in index.ts
rmdirSync(defaultUserDataDir, { recursive: true });
} catch (e) {
debug(
`Failed to remove temporary user data directory at ${defaultUserDataDir}:`
);
debug(e);
}
}
async function getCompassExecutionParameters(): Promise<{
testPackagedApp: boolean;
binary: string;
}> {
const testPackagedApp = isTestingDesktop(context) && context.testPackagedApp;
const binary = testPackagedApp
? getCompassBinPath(await getCompassBuildMetadata())
: ELECTRON_PATH;
return { testPackagedApp, binary };
}
function execFileIgnoreError(
path: string,
args: readonly string[],
opts: ExecFileOptions
): Promise<{
error: ExecFileException | null;
stdout: string;
stderr: string;
}> {
return new Promise((resolve) => {
execFile(path, args, opts, function (error, stdout, stderr) {
resolve({
error,
stdout,
stderr,
});
});
});
}
export async function runCompassOnce(args: string[], timeout = 30_000) {
const { binary } = await getCompassExecutionParameters();
debug('spawning compass...', {
binary,
COMPASS_DESKTOP_PATH,
defaultUserDataDir,
args,
timeout,
});
// For whatever reason, running the compass CLI frequently completes what it
// was set to do and then exits the process with error code 1 and no other
// output. So while figuring out what's going on, don't ever throw but do log
// the error. Assertions that follow runCompassOnce() can then check if it did
// what it was supposed to do and fail if it didn't.
const { error, stdout, stderr } = await execFileIgnoreError(
binary,
[
COMPASS_DESKTOP_PATH,
// When running binary without webdriver, we need to pass the same flags
// as we pass when running with webdriverio to have similar behaviour.
...CHROME_STARTUP_FLAGS,
`--user-data-dir=${String(defaultUserDataDir)}`,
...args,
],
{
timeout,
env: {
...process.env,
// prevent xdg-settings: unknown desktop environment error logs
DE: 'generic',
},
}
);
debug('Ran compass with args', { args, error, stdout, stderr });
return { stdout, stderr };
}
async function processCommonOpts({
// true unless otherwise specified
firstRun = true,
}: StartCompassOptions = {}) {
const nowFormatted = formattedDate();
let needsCloseWelcomeModal: boolean;
// If this is not the first run, but we want it to be, delete the user data
// dir so it will be recreated below.
if (defaultUserDataDir && firstRun) {
removeUserDataDir();
// windows seems to be weird about us deleting and recreating this dir, so
// just make a new one for next time
defaultUserDataDir = undefined;
needsCloseWelcomeModal = true;
} else {
// Need to close the welcome modal if firstRun is undefined or true, because
// in those cases we do not pass --showed-network-opt-in=true, but only
// if Compass hasn't been run before (i.e. defaultUserDataDir is defined)
needsCloseWelcomeModal = !defaultUserDataDir && firstRun;
}
// Calculate the userDataDir once so it will be the same between runs. That
// way we can test first run vs second run experience.
if (!defaultUserDataDir) {
defaultUserDataDir = path.join(
os.tmpdir(),
`user-data-dir-${Date.now().toString(32)}-${runCounter}`
);
}
const chromedriverLogPath = path.join(
LOG_PATH,
`chromedriver.${nowFormatted}.log`
);
const webdriverLogPath = path.join(LOG_PATH, 'webdriver');
// Ensure that the user data dir exists
await fs.mkdir(defaultUserDataDir, { recursive: true });
// Chromedriver will fail if log path doesn't exist, webdriver doesn't care,
// for consistency let's mkdir for both of them just in case
await fs.mkdir(path.dirname(chromedriverLogPath), { recursive: true });
await fs.mkdir(webdriverLogPath, { recursive: true });
await fs.mkdir(LOG_OUTPUT_PATH, { recursive: true });
await fs.mkdir(LOG_SCREENSHOTS_PATH, { recursive: true });
await fs.mkdir(LOG_COVERAGE_PATH, { recursive: true });
// https://webdriver.io/docs/options/#webdriver-options
const webdriverOptions = {
logLevel: 'trace' as const,
outputDir: webdriverLogPath,
};
// https://webdriver.io/docs/options/#webdriverio
const wdioOptions = {
waitforTimeout: context.webdriverWaitforTimeout,
waitforInterval: context.webdriverWaitforInterval,
};
process.env.DEBUG = `${process.env.DEBUG ?? ''},mongodb-compass:main:logging`;
process.env.MONGODB_COMPASS_TEST_LOG_DIR = path.join(LOG_PATH, 'app');
process.env.CHROME_LOG_FILE = chromedriverLogPath;
// https://peter.sh/experiments/chromium-command-line-switches/
// https://www.electronjs.org/docs/latest/api/command-line-switches
const chromeArgs: string[] = [
...CHROME_STARTUP_FLAGS,
`--user-data-dir=${defaultUserDataDir}`,
];
return {
needsCloseWelcomeModal,
webdriverOptions,
wdioOptions,
chromeArgs,
};
}
async function startCompassElectron(
name: string,
opts: StartCompassOptions = {}
): Promise<Compass> {
runCounter++;
const { testPackagedApp, binary } = await getCompassExecutionParameters();
const { needsCloseWelcomeModal, webdriverOptions, wdioOptions, chromeArgs } =
await processCommonOpts(opts);
if (!testPackagedApp) {
// https://www.electronjs.org/docs/latest/tutorial/automated-testing#with-webdriverio
chromeArgs.push(`--app=${COMPASS_DESKTOP_PATH}`);
}
if (opts.firstRun === false) {
chromeArgs.push('--showed-network-opt-in=true');
}
// Logging output from Electron, even before the app loads any JavaScript
const electronLogFile = path.join(LOG_PATH, `electron-${runCounter}.log`);
chromeArgs.push(
// See https://www.electronjs.org/docs/latest/api/command-line-switches#--enable-loggingfile
'--enable-logging=file',
// See https://www.electronjs.org/docs/latest/api/command-line-switches#--log-filepath
`--log-file=${electronLogFile}`,
// See https://chromium.googlesource.com/chromium/src/+/master/docs/chrome_os_logging.md
'--log-level=0'
);
if (opts.extraSpawnArgs) {
chromeArgs.push(...opts.extraSpawnArgs);
}
// Electron on Windows interprets its arguments in a weird way where
// the second positional argument inserted by webdriverio (about:blank)
// throws it off and won't let it start because it then interprets the first
// positional argument as an app path.
if (
process.platform === 'win32' &&
chromeArgs.some((arg) => !arg.startsWith('--'))
) {
chromeArgs.push('--');
}
const maybeWrappedBinary = (await opts.wrapBinary?.(binary)) ?? binary;
process.env.APP_ENV = 'webdriverio';
// For webdriverio env we are changing appName so that keychain records do not
// overlap with anything else
process.env.HADRON_PRODUCT_NAME_OVERRIDE = 'MongoDB Compass WebdriverIO';
// Guide cues might affect too many tests in a way where the auto showing of the cue prevents
// clicks from working on elements. Dealing with this case-by-case is way too much work, so
// we disable the cues completely for the e2e tests
process.env.DISABLE_GUIDE_CUES = 'true';
const options = {
automationProtocol: 'webdriver' as const,
capabilities: {
browserName: 'chromium',
browserVersion: ELECTRON_CHROMIUM_VERSION,
// https://chromedriver.chromium.org/capabilities#h.p_ID_106
'goog:chromeOptions': {
binary: maybeWrappedBinary,
args: chromeArgs,
},
// from https://github.com/webdriverio-community/wdio-electron-service/blob/32457f60382cb4970c37c7f0a19f2907aaa32443/packages/wdio-electron-service/src/launcher.ts#L102
'wdio:enforceWebDriverClassic': true,
'wdio:chromedriverOptions': {
// enable logging so we don't have to debug things blindly
// This goes in .log/webdriver/wdio-chromedriver-*.log. It is the
// chromedriver log and since this is verbose it also contains the
// stdout of the electron main process.
verbose: true,
},
},
...webdriverOptions,
...wdioOptions,
};
debug('Starting compass via webdriverio with the following configuration:');
debug(JSON.stringify(options, null, 2));
let browser: CompassBrowser;
try {
browser = (await remote(options)) as CompassBrowser;
} catch (err) {
debug('Failed to start remote webdriver session', {
error: (err as Error).stack,
});
// Sometimes when webdriver fails to start the remote session, we end up
// with a running app that hangs the test runner in CI causing the run to
// fail with idle timeout. We will try to clean up a potentially hanging app
// before rethrowing an error
// ps-list is ESM-only in recent versions.
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const { default: psList }: typeof import('ps-list') = await eval(
`import('ps-list')`
);
const processList = await psList();
const filteredProcesses = processList.filter((p) => {
return (
p.ppid === process.pid &&
(p.cmd?.startsWith(binary) ||
/(MongoDB Compass|Electron|electron|chromedriver)/.test(p.name))
);
});
debug(
filteredProcesses.length === 0
? `Found no application running that need to be closed (following processes were spawned by this: ${processList
.filter((p) => {
return p.ppid === process.pid;
})
.map((p) => {
return p.name;
})
.join(', ')})`
: `Found following applications running: ${filteredProcesses
.map((p) => {
return p.name;
})
.join(', ')}`
);
for (const p of filteredProcesses) {
await killAsync(p.pid);
}
throw err;
}
const compass = new Compass(name, browser, {
mode: 'electron',
writeCoverage: !testPackagedApp,
needsCloseWelcomeModal,
});
await compass.recordElectronLogs();
return compass;
}
export type StoredAtlasCloudCookies = {
name: string;
value: string;
domain: string;
path: string;
secure: boolean;
httpOnly: boolean;
expirationDate: number;
}[];
export async function startBrowser(
name: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
opts: StartCompassOptions = {}
) {
assertTestingWeb(context);
runCounter++;
const { webdriverOptions, wdioOptions } = await processCommonOpts();
// webdriverio removed RemoteOptions. It is now
// Capabilities.WebdriverIOConfig, but Capabilities is not exported
const options = {
capabilities: {
browserName: context.browserName,
...(context.browserVersion && {
browserVersion: context.browserVersion,
}),
// from https://github.com/webdriverio-community/wdio-electron-service/blob/32457f60382cb4970c37c7f0a19f2907aaa32443/packages/wdio-electron-service/src/launcher.ts#L102
'wdio:enforceWebDriverClassic': true,
},
...webdriverOptions,
...wdioOptions,
};
debug('Starting browser via webdriverio with the following configuration:');
debug(JSON.stringify(options, null, 2));
const browser: CompassBrowser = (await remote(options)) as CompassBrowser;
if (isTestingAtlasCloudExternal(context)) {
const {
atlasCloudExternalCookiesFile,
atlasCloudExternalUrl,
atlasCloudExternalProjectId,
} = context;
// To be able to use `setCookies` method, we need to first open any page on
// the same domain as the cookies we are going to set
// https://webdriver.io/docs/api/browser/setCookies/
await browser.navigateTo(`${atlasCloudExternalUrl}/404`);
type StoredAtlasCloudCookies = {
name: string;
value: string;
domain: string;
path: string;
secure: boolean;
httpOnly: boolean;
expirationDate: number;
}[];
const cookies: StoredAtlasCloudCookies = JSON.parse(
await fs.readFile(atlasCloudExternalCookiesFile, 'utf8')
);
await browser.setCookies(
cookies
.filter((cookie) => {
// These are the relevant cookies for auth:
// https://github.com/10gen/mms/blob/6d27992a6ab9ab31471c8bcdaa4e347aa39f4013/server/src/features/com/xgen/svc/cukes/helpers/Client.java#L122-L130
return (
cookie.name.includes('mmsa-') ||
cookie.name.includes('mdb-sat') ||
cookie.name.includes('mdb-srt')
);
})
.map((cookie) => ({
name: cookie.name,
value: cookie.value,
domain: cookie.domain,
path: cookie.path,
secure: cookie.secure,
httpOnly: cookie.httpOnly,
}))
);
await browser.navigateTo(
`${atlasCloudExternalUrl}/v2/${atlasCloudExternalProjectId}#/explorer`
);
} else {
await browser.navigateTo(context.sandboxUrl);
}
const compass = new Compass(name, browser, {
mode: 'web',
writeCoverage: false,
needsCloseWelcomeModal: false,
});
return compass;
}
/**
* @param {string} logPath The compass application log path
* @returns {Promise<CompassLog>}
*/
async function getCompassLog(
logPath: string
): Promise<{ raw: Buffer; structured: any[] }> {
const names = await fs.readdir(logPath);
const logNames = names.filter((name) => name.endsWith('_log.gz'));
if (!logNames.length) {
debug('no log output indicator found!');
return { raw: Buffer.from(''), structured: [] };
}
// find the latest log file
let latest = 0;
let lastName = logNames[0];
for (const name of logNames.slice(1)) {
const id = name.slice(0, name.indexOf('_'));
const time = new ObjectId(id).getTimestamp().valueOf();
if (time > latest) {
latest = time;
lastName = name;
}
}
const filename = path.join(logPath, lastName);
debug('reading Compass application logs from', filename);
const contents = await promisify(gunzip)(await fs.readFile(filename), {
finishFlush: Z_SYNC_FLUSH,
});
return {
raw: contents,
structured: contents
.toString()
.split('\n')
.filter((line) => line.trim())
.map((line) => {
try {
return EJSON.parse(line);
} catch {
return { unparsabableLine: line };
}
}),
};
}
function formattedDate(): string {
// Mimicking webdriver path with this for consistency
return new Date().toISOString().replace(/:/g, '-').replace(/Z$/, '');
}
export async function rebuildNativeModules(
compassPath = COMPASS_DESKTOP_PATH
): Promise<void> {
const fullCompassPath = require.resolve(
path.join(compassPath, 'package.json')
);
const {
config: {
hadron: { rebuild: rebuildConfig },
},
} = JSON.parse(await fs.readFile(fullCompassPath, 'utf8'));
const fullElectronPath = require.resolve('electron/package.json');
const electronVersion = JSON.parse(
await fs.readFile(fullElectronPath, 'utf8')
).version;
const rebuildOptions: RebuildOptions = {
...rebuildConfig,
electronVersion,
buildPath: compassPath,
// monorepo root, so that the root packages are also inspected
projectRootPath: path.resolve(compassPath, '..', '..'),
};
await rebuild(rebuildOptions);
}
export async function compileCompassAssets(
compassPath = COMPASS_DESKTOP_PATH
): Promise<void> {
await promisify(execFile)('npm', ['run', 'compile'], { cwd: compassPath });
}
async function getCompassBuildMetadata(): Promise<BinPathOptions> {
try {
let metadata;
if (process.env.COMPASS_APP_PATH && process.env.COMPASS_APP_NAME) {
metadata = {
appPath: process.env.COMPASS_APP_PATH,
packagerOptions: { name: process.env.COMPASS_APP_NAME },
};
} else {
metadata = require('mongodb-compass/dist/target.json');
}
// Double-checking that Compass app path exists, not only the metadata
await fs.stat(metadata.appPath as string);
debug('Existing Compass found', metadata);
return metadata;
} catch (e: unknown) {
debug('Existing Compass build not found', e);
throw new Error(
`Compass package metadata doesn't exist. Make sure you built Compass before running e2e tests: ${
(e as Error).message
}`
);
}
}
export async function buildCompass(
force = false,
compassPath = COMPASS_DESKTOP_PATH
): Promise<void> {
if (!force) {
try {
await getCompassBuildMetadata();
return;
} catch (e) {
// No compass build found, let's build it
}
}
await packageCompassAsync({
dir: compassPath,
skip_installer: true,
});
}
type BinPathOptions = {
appPath: string;
packagerOptions: {
name: string;
};
};
export function getCompassBinPath({
appPath,
packagerOptions,
}: BinPathOptions): string {
const { name } = packagerOptions;
switch (process.platform) {
case 'win32':
return path.join(appPath, `${name}.exe`);
case 'linux':
return path.join(appPath, name);
case 'darwin':
return path.join(appPath, 'Contents', 'MacOS', name);
default:
throw new Error(
`Unsupported platform: don't know where the app binary is for ${process.platform}`
);
}
}
function augmentError(error: Error, stack: string) {
const lines = stack.split('\n');
const strippedLines = lines.filter((line, index) => {
// try to only contain lines that originated in this workspace