-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathhelper.ts
1291 lines (1226 loc) · 50 KB
/
helper.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/* eslint-disable @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports, no-invalid-this, @typescript-eslint/no-explicit-any */
import type * as nbformat from '@jupyterlab/nbformat';
import { assert, expect } from 'chai';
import * as sinon from 'sinon';
import {
WorkspaceEdit,
commands,
Memento,
Uri,
window,
workspace,
NotebookCell,
NotebookDocument,
NotebookCellKind,
NotebookCellOutputItem,
NotebookRange,
NotebookCellExecutionState,
NotebookCellData,
notebooks,
Event,
env,
UIKind,
DebugSession,
languages,
Position,
Hover,
Diagnostic,
NotebookEdit,
CompletionContext,
CompletionTriggerKind,
CancellationTokenSource,
CompletionItem,
QuickPick,
QuickPickItem,
QuickInputButton,
QuickPickItemButtonEvent,
EventEmitter,
ConfigurationTarget,
NotebookEditor
} from 'vscode';
import { IApplicationShell, IVSCodeNotebook, IWorkspaceService } from '../../../platform/common/application/types';
import { JVSC_EXTENSION_ID, MARKDOWN_LANGUAGE, PYTHON_LANGUAGE } from '../../../platform/common/constants';
import { disposeAllDisposables } from '../../../platform/common/helpers';
import { traceInfo, traceInfoIfCI } from '../../../platform/logging';
import {
GLOBAL_MEMENTO,
IConfigurationService,
IDisposable,
IMemento,
IsWebExtension
} from '../../../platform/common/types';
import { createDeferred, sleep } from '../../../platform/common/utils/async';
import { IKernelProvider } from '../../../platform/../kernels/types';
import { noop } from '../../core';
import { closeActiveWindows, isInsiders } from '../../initialize';
import { DebugProtocol } from 'vscode-debugprotocol';
import { DataScience } from '../../../platform/common/utils/localize';
import { LastSavedNotebookCellLanguage } from '../../../notebooks/languages/cellLanguageService';
import { VSCodeNotebookController } from '../../../notebooks/controllers/vscodeNotebookController';
import { INotebookEditorProvider } from '../../../notebooks/types';
import {
IControllerLoader,
IControllerPreferredService,
IControllerRegistration,
IControllerSelection,
InteractiveControllerIdSuffix,
IVSCodeNotebookController
} from '../../../notebooks/controllers/types';
import { IS_SMOKE_TEST } from '../../constants';
import * as urlPath from '../../../platform/vscode-path/resources';
import * as uuid from 'uuid/v4';
import { IFileSystem, IPlatformService } from '../../../platform/common/platform/types';
import { initialize, waitForCondition } from '../../common';
import { VSCodeNotebook } from '../../../platform/common/application/notebook';
import { IDebuggingManager, IKernelDebugAdapter } from '../../../kernels/debugger/types';
import { PythonKernelCompletionProvider } from '../../../standalone/intellisense/pythonKernelCompletionProvider';
import { verifySelectedControllerIsRemoteForRemoteTests } from '../helpers';
import {
NotebookCellStateTracker,
hasErrorOutput,
CellOutputMimeTypes,
getTextOutputValue
} from '../../../kernels/execution/helpers';
import { chainWithPendingUpdates } from '../../../kernels/execution/notebookUpdater';
import { openAndShowNotebook } from '../../../platform/common/utils/notebooks';
import { IServerConnectionType } from '../../../kernels/jupyter/types';
// Running in Conda environments, things can be a little slower.
export const defaultNotebookTestTimeout = 60_000;
export async function getServices() {
const api = await initialize();
return {
vscodeNotebook: api.serviceContainer.get<IVSCodeNotebook>(IVSCodeNotebook) as IVSCodeNotebook,
editorProvider: api.serviceContainer.get<INotebookEditorProvider>(
INotebookEditorProvider
) as INotebookEditorProvider,
controllerRegistration: api.serviceContainer.get<IControllerRegistration>(
IControllerRegistration
) as IControllerRegistration,
controllerLoader: api.serviceContainer.get<IControllerLoader>(IControllerLoader),
controllerSelection: api.serviceContainer.get<IControllerSelection>(IControllerSelection),
controllerPreferred: api.serviceContainer.get<IControllerPreferredService>(IControllerPreferredService),
isWebExtension: api.serviceContainer.get<boolean>(IsWebExtension),
serviceContainer: api.serviceContainer
};
}
export async function selectCell(notebook: NotebookDocument, start: number, end: number) {
await window.showNotebookDocument(notebook, {
selections: [new NotebookRange(start, end)]
});
}
export async function insertMarkdownCell(source: string, options?: { index?: number }) {
const { vscodeNotebook } = await getServices();
const activeEditor = vscodeNotebook.activeNotebookEditor;
if (!activeEditor) {
throw new Error('No active editor');
}
const startNumber = options?.index ?? activeEditor.notebook.cellCount;
await chainWithPendingUpdates(activeEditor.notebook, (edit) => {
const cellData = new NotebookCellData(NotebookCellKind.Markup, source, MARKDOWN_LANGUAGE);
cellData.outputs = [];
cellData.metadata = {};
const nbEdit = NotebookEdit.insertCells(startNumber, [cellData]);
edit.set(activeEditor.notebook.uri, [nbEdit]);
});
return activeEditor.notebook.cellAt(startNumber)!;
}
export async function insertCodeCell(source: string, options?: { language?: string; index?: number }) {
const { vscodeNotebook } = await getServices();
const activeEditor = vscodeNotebook.activeNotebookEditor;
if (!activeEditor) {
throw new Error('No active editor');
}
const startNumber = options?.index ?? activeEditor.notebook.cellCount;
const edit = new WorkspaceEdit();
const cellData = new NotebookCellData(NotebookCellKind.Code, source, options?.language || PYTHON_LANGUAGE);
cellData.outputs = [];
cellData.metadata = {};
const nbEdit = NotebookEdit.insertCells(startNumber, [cellData]);
edit.set(activeEditor.notebook.uri, [nbEdit]);
await workspace.applyEdit(edit);
return activeEditor.notebook.cellAt(startNumber)!;
}
export async function deleteCell(index: number = 0) {
const { vscodeNotebook } = await getServices();
const activeEditor = vscodeNotebook.activeNotebookEditor;
if (!activeEditor || activeEditor.notebook.cellCount === 0) {
return;
}
if (!activeEditor) {
assert.fail('No active editor');
return;
}
await chainWithPendingUpdates(activeEditor.notebook, (edit) => {
const nbEdit = NotebookEdit.deleteCells(new NotebookRange(index, index + 1));
edit.set(activeEditor.notebook.uri, [nbEdit]);
});
}
export async function deleteAllCellsAndWait() {
const { vscodeNotebook } = await getServices();
const activeEditor = vscodeNotebook.activeNotebookEditor;
if (!activeEditor || activeEditor.notebook.cellCount === 0) {
return;
}
await chainWithPendingUpdates(activeEditor.notebook, (edit) => {
const nbEdit = NotebookEdit.deleteCells(new NotebookRange(0, activeEditor.notebook.cellCount));
edit.set(activeEditor.notebook.uri, [nbEdit]);
});
}
async function createTemporaryNotebookFromNotebook(
notebook: nbformat.INotebookContent,
disposables: IDisposable[],
rootFolder?: Uri,
prefix?: string
) {
const uri = await generateTemporaryFilePath('.ipynb', disposables, rootFolder, prefix);
await workspace.fs.writeFile(uri, Buffer.from(JSON.stringify(notebook)));
return uri;
}
export async function generateTemporaryFilePath(
extension: string,
disposables: IDisposable[],
rootFolder?: Uri,
prefix?: string
) {
const services = await getServices();
const platformService = services.serviceContainer.get<IPlatformService>(IPlatformService);
const workspaceService = services.serviceContainer.get<IWorkspaceService>(IWorkspaceService);
const rootUrl =
rootFolder ||
platformService.tempDir ||
workspaceService.rootFolder ||
Uri.file('./').with({ scheme: 'vscode-test-web' });
const uri = urlPath.joinPath(rootUrl, `${prefix || ''}${uuid()}.${extension}`);
disposables.push({
dispose: () => {
void workspace.fs.delete(uri).then(noop, noop);
}
});
return uri;
}
export async function createTemporaryNotebookFromFile(
file: Uri,
disposables: IDisposable[],
kernelName: string = 'Python 3'
) {
const services = await getServices();
const fileSystem = services.serviceContainer.get<IFileSystem>(IFileSystem);
const contents = await fileSystem.readFile(file);
const notebook = JSON.parse(contents);
if (notebook.kernel) {
notebook.kernel.display_name = kernelName;
}
return createTemporaryNotebookFromNotebook(notebook, disposables, undefined, urlPath.basename(file));
}
export async function createTemporaryNotebook(
cells: (nbformat.ICodeCell | nbformat.IMarkdownCell | nbformat.IRawCell | nbformat.IUnrecognizedCell)[],
disposables: IDisposable[],
kernelName: string = 'Python 3',
rootFolder?: Uri,
prefix?: string
): Promise<Uri> {
cells =
cells.length == 0
? [
{
cell_type: 'code',
outputs: [],
source: ['\n'],
execution_count: 0,
metadata: {}
}
]
: cells;
const data: nbformat.INotebookContent = {
cells,
metadata: {
orig_nbformat: 4
},
nbformat: 4,
nbformat_minor: 2,
kernel: {
display_name: kernelName
}
};
return createTemporaryNotebookFromNotebook(data, disposables, rootFolder, prefix);
}
/**
* Open an existing notebook with some metadata that tells extension to use Python kernel.
* Else creating a blank notebook could result in selection of non-python kernel, based on other tests.
* We have other tests where we test non-python kernels, this could mean we might end up with non-python kernels
* when creating a new notebook.
* This function ensures we always open a notebook for testing that is guaranteed to use a Python kernel.
*/
export async function createEmptyPythonNotebook(
disposables: IDisposable[] = [],
rootFolder?: Uri,
dontWaitForKernel?: boolean
) {
traceInfoIfCI('Creating an empty notebook');
const { serviceContainer } = await getServices();
const vscodeNotebook = serviceContainer.get<IVSCodeNotebook>(IVSCodeNotebook);
const serverConnectionType = serviceContainer.get<IServerConnectionType>(IServerConnectionType);
// Don't use same file (due to dirty handling, we might save in dirty.)
// Coz we won't save to file, hence extension will backup in dirty file and when u re-open it will open from dirty.
const nbFile = await createTemporaryNotebook([], disposables, 'Python 3', rootFolder, 'emptyPython');
// Open a python notebook and use this for all tests in this test suite.
await openAndShowNotebook(nbFile);
assert.isOk(vscodeNotebook.activeNotebookEditor, 'No active notebook');
if (!dontWaitForKernel) {
await waitForKernelToGetAutoSelected(undefined, undefined, !serverConnectionType.isLocalLaunch);
await verifySelectedControllerIsRemoteForRemoteTests();
}
await deleteAllCellsAndWait();
return vscodeNotebook.activeNotebookEditor!.notebook;
}
async function shutdownAllNotebooks() {
const api = await initialize();
const kernelProvider = api.serviceContainer.get<IKernelProvider>(IKernelProvider) as IKernelProvider;
await Promise.all(kernelProvider.kernels.map((k) => k.dispose().catch(noop)));
}
export async function ensureNewNotebooksHavePythonCells() {
const api = await initialize();
const globalMemento = api.serviceContainer.get<Memento>(IMemento, GLOBAL_MEMENTO);
const lastLanguage = (
globalMemento.get<string | undefined>(LastSavedNotebookCellLanguage) || PYTHON_LANGUAGE
).toLowerCase();
if (lastLanguage !== PYTHON_LANGUAGE.toLowerCase()) {
await globalMemento.update(LastSavedNotebookCellLanguage, PYTHON_LANGUAGE).then(noop, noop);
}
}
export async function closeNotebooksAndCleanUpAfterTests(disposables: IDisposable[] = []) {
if (!IS_SMOKE_TEST()) {
// When running smoke tests, we won't have access to these.
const configSettings = await import('../../../platform/common/configSettings');
// Dispose any cached python settings (used only in test env).
configSettings.JupyterSettings.dispose();
}
VSCodeNotebookController.kernelAssociatedWithDocument = undefined;
await closeNotebooks(disposables);
disposeAllDisposables(disposables);
await shutdownAllNotebooks();
await ensureNewNotebooksHavePythonCells();
try {
await commands.executeCommand('python.clearWorkspaceInterpreter');
} catch (ex) {
// Python extension may not be installed. Don't fail the test
}
sinon.restore();
}
export async function closeNotebooks(disposables: IDisposable[] = []) {
if (!isInsiders()) {
return false;
}
const api = await initialize();
VSCodeNotebookController.kernelAssociatedWithDocument = undefined;
const notebooks = api.serviceManager.get<IVSCodeNotebook>(IVSCodeNotebook) as VSCodeNotebook;
await notebooks.closeActiveNotebooks();
await closeActiveWindows();
disposeAllDisposables(disposables);
await shutdownAllNotebooks();
}
let waitForKernelPendingPromise: Promise<void> | undefined;
export async function waitForKernelToChange(
criteria:
| { labelOrId: string; isInteractiveController?: boolean }
| { interpreterPath: Uri; isInteractiveController?: boolean },
notebookEditor?: NotebookEditor,
timeout = defaultNotebookTestTimeout,
skipAutoSelection?: boolean
) {
// Wait for the previous kernel change to finish.
if (waitForKernelPendingPromise != undefined) {
await waitForKernelPendingPromise;
}
waitForKernelPendingPromise = waitForKernelToChangeImpl(criteria, notebookEditor, timeout, skipAutoSelection);
return waitForKernelPendingPromise;
}
async function waitForKernelToChangeImpl(
criteria:
| { labelOrId: string; isInteractiveController?: boolean }
| { interpreterPath: Uri; isInteractiveController?: boolean },
notebookEditor?: NotebookEditor,
timeout = defaultNotebookTestTimeout,
skipAutoSelection?: boolean
) {
const { vscodeNotebook, controllerLoader, controllerRegistration, controllerSelection } = await getServices();
// Wait for the active editor to come up
notebookEditor = await waitForActiveNotebookEditor(notebookEditor);
// Get the list of NotebookControllers for this document
await controllerLoader.loadControllers();
const notebookControllers = controllerRegistration.registered;
// Find the kernel id that matches the name we want
let controller: IVSCodeNotebookController | undefined;
let labelOrId = 'labelOrId' in criteria ? criteria.labelOrId : undefined;
if (labelOrId) {
controller = notebookControllers
?.filter((k) => (criteria.isInteractiveController ? k.id.includes(InteractiveControllerIdSuffix) : true))
?.find((k) => (labelOrId && k.label === labelOrId) || (k.id && k.id == labelOrId));
if (!controller) {
// Try includes instead
controller = notebookControllers?.find(
(k) => (labelOrId && k.label.includes(labelOrId)) || (k.id && k.id == labelOrId)
);
}
}
const interpreterPath = 'interpreterPath' in criteria ? criteria.interpreterPath : undefined;
if (interpreterPath && !controller) {
controller = notebookControllers
?.filter((k) => k.connection.interpreter)
?.filter((k) => (criteria.isInteractiveController ? k.id.includes(InteractiveControllerIdSuffix) : true))
.find((k) =>
// eslint-disable-next-line local-rules/dont-use-fspath
k.connection.interpreter!.uri.fsPath.toLowerCase().includes(interpreterPath.fsPath.toLowerCase())
);
}
traceInfo(`Switching to kernel id ${controller}`);
const isRightKernel = () => {
const doc = vscodeNotebook.activeNotebookEditor?.notebook;
if (!doc) {
return false;
}
const selectedController = controllerSelection.getSelected(doc);
if (!selectedController) {
return false;
}
if (selectedController.id === controller?.id) {
traceInfo(`Found selected kernel id:label ${selectedController.id}:${selectedController.label}`);
return true;
}
traceInfo(`Active kernel is id:label = ${selectedController.id}:${selectedController.label}`);
return false;
};
if (!isRightKernel()) {
let tryCount = 0;
await waitForCondition(
async () => {
// Double check not the right kernel (don't select again if already found to be correct)
if (!isRightKernel() && !skipAutoSelection) {
traceInfoIfCI(
`Notebook select.kernel command switching to kernel id ${controller?.connection.kind}${controller?.id}: Try ${tryCount}`
);
// Send a select kernel on the active notebook editor. Keep sending it if it fails.
await commands.executeCommand('notebook.selectKernel', {
id: controller?.id,
extension: JVSC_EXTENSION_ID
});
traceInfoIfCI(
`Notebook select.kernel command switched to kernel id ${controller?.connection.kind}:${controller}`
);
tryCount += 1;
}
// Check if it's the right one or not.
return isRightKernel();
},
timeout,
`Kernel with criteria ${JSON.stringify(criteria)} not selected`
);
// Make sure the kernel is actually in use before returning (switching is async)
await sleep(500);
}
}
async function waitForActiveNotebookEditor(notebookEditor?: NotebookEditor): Promise<NotebookEditor> {
const { vscodeNotebook } = await getServices();
// Wait for the active editor to come up
notebookEditor = notebookEditor || vscodeNotebook.activeNotebookEditor;
if (!notebookEditor) {
await waitForCondition(
async () => !!vscodeNotebook.activeNotebookEditor,
10_000,
'Active editor not a notebook'
);
notebookEditor = vscodeNotebook.activeNotebookEditor;
}
if (!notebookEditor) {
throw new Error('No notebook editor');
}
return notebookEditor;
}
export async function waitForKernelToGetAutoSelected(
notebookEditor?: NotebookEditor,
expectedLanguage?: string,
preferRemoteKernelSpec: boolean = false,
timeout = 100_000,
skipAutoSelection: boolean = false
) {
traceInfoIfCI('Wait for kernel to get auto selected');
const { controllerLoader, controllerRegistration, controllerSelection, controllerPreferred, isWebExtension } =
await getServices();
const useRemoteKernelSpec = preferRemoteKernelSpec || isWebExtension; // Web is only remote
// Wait for the active editor to come up
notebookEditor = await waitForActiveNotebookEditor(notebookEditor);
// Get the list of NotebookControllers for this document
await controllerLoader.loadControllers();
traceInfoIfCI(`Wait for kernel - got notebook controllers`);
const notebookControllers = controllerRegistration.registered;
// Make sure we don't already have a selection (this function gets run even after opening a document)
if (controllerSelection.getSelected(notebookEditor.notebook)) {
return;
}
// We don't have one, try to find the preferred one
let preferred: IVSCodeNotebookController | undefined;
// Wait for one of them to have affinity as the preferred (this may not happen)
try {
await waitForCondition(
async () => {
preferred = controllerPreferred.getPreferred(notebookEditor!.notebook);
return preferred != undefined;
},
30_000,
`Did not find a controller with document affinity`
);
} catch {
// Do nothing for now. Just log it
traceInfoIfCI(`No preferred controller found during waitForKernelToGetAutoSelected`);
}
traceInfoIfCI(
`Wait for kernel - got a preferred notebook controller: ${preferred?.connection.kind}:${preferred?.id}`
);
// Find one that matches the expected language or the preferred
const expectedLower = expectedLanguage?.toLowerCase();
const language = expectedLower || 'python';
const preferredKind = useRemoteKernelSpec ? 'startUsingRemoteKernelSpec' : preferred?.connection.kind;
let match: IVSCodeNotebookController | undefined;
if (preferred) {
if (
preferred.connection.kind !== 'connectToLiveRemoteKernel' &&
(!expectedLanguage || preferred.connection.kernelSpec?.language?.toLowerCase() === expectedLower) &&
preferredKind === preferred.connection.kind
) {
match = preferred;
} else if (preferred.connection.kind === 'connectToLiveRemoteKernel') {
match = preferred;
}
}
if (!match) {
match = notebookControllers.find(
(d) =>
d.connection.kind != 'connectToLiveRemoteKernel' &&
language === d.connection.kernelSpec?.language?.toLowerCase() &&
(!useRemoteKernelSpec || d.connection.kind.includes('Remote'))
);
}
if (!match) {
traceInfoIfCI(
`Houston, we have a problem, no match. Expected language ${expectedLanguage}. Expected kind ${preferredKind}.`
);
assert.fail(
`No notebook controller found for ${expectedLanguage} when useRemote is ${useRemoteKernelSpec} and preferred kind is ${preferredKind}. NotebookControllers : ${JSON.stringify(
notebookControllers.map((c) => c.connection)
)}`
);
}
const criteria = { labelOrId: match!.id };
traceInfo(
`Preferred kernel for selection is ${match.connection.kind}:${match?.id}, criteria = ${JSON.stringify(
criteria
)}`
);
assert.ok(match, 'No kernel to auto select');
return waitForKernelToChange(criteria, notebookEditor, timeout, skipAutoSelection);
}
const prewarmNotebooksDone = { done: false };
export async function prewarmNotebooks() {
if (prewarmNotebooksDone.done) {
return;
}
const { editorProvider, vscodeNotebook, serviceContainer } = await getServices();
await closeActiveWindows();
const disposables: IDisposable[] = [];
try {
// Ensure preferred language is always Python.
const memento = serviceContainer.get<Memento>(IMemento, GLOBAL_MEMENTO);
if (memento.get(LastSavedNotebookCellLanguage) !== PYTHON_LANGUAGE) {
await memento.update(LastSavedNotebookCellLanguage, PYTHON_LANGUAGE);
}
await editorProvider.createNew();
await insertCodeCell('print("Hello World1")', { index: 0 });
await waitForKernelToGetAutoSelected();
const cell = vscodeNotebook.activeNotebookEditor!.notebook.cellAt(0)!;
traceInfoIfCI(`Running all cells in prewarm notebooks`);
await Promise.all([waitForExecutionCompletedSuccessfully(cell, 60_000), runAllCellsInActiveNotebook()]);
await closeActiveWindows();
await shutdownAllNotebooks();
} finally {
disposables.forEach((d) => d.dispose());
prewarmNotebooksDone.done = true;
}
}
function assertHasExecutionCompletedSuccessfully(cell: NotebookCell) {
return (
(cell.executionSummary?.executionOrder ?? 0) > 0 &&
NotebookCellStateTracker.getCellState(cell) === NotebookCellExecutionState.Idle &&
!hasErrorOutput(cell.outputs)
);
}
/**
* Wait for VSC to perform some last minute clean up of cells.
* In tests we can end up deleting cells. However if extension is still dealing with the cells, we need to give it some time to finish.
*/
export async function waitForCellExecutionToComplete(cell: NotebookCell) {
// if (!CellExecution.cellsCompletedForTesting.has(cell)) {
// CellExecution.cellsCompletedForTesting.set(cell, createDeferred<void>());
// }
// // Yes hacky approach, however its difficult to synchronize everything as we update cells in a few places while executing.
// // 100ms should be plenty sufficient for other code to get executed when dealing with cells.
// // Again, we need to wait for rest of execution code to access the cells.
// // Else in tests we'd delete the cells & the extension code could fall over trying to access non-existent cells.
// // In fact code doesn't fall over, but VS Code just hangs in tests.
// // If this doesn't work on CI, we'll need to clean up and write more code to ensure we remove these race conditions as done with `CellExecution.cellsCompleted`.
// await CellExecution.cellsCompletedForTesting.get(cell)!.promise;
await waitForCondition(
async () => (cell.executionSummary?.executionOrder || 0) > 0,
defaultNotebookTestTimeout,
'Execution did not complete'
);
await sleep(100);
}
export async function waitForCellExecutionState(
cell: NotebookCell,
state: NotebookCellExecutionState,
disposables: IDisposable[],
timeout: number = defaultNotebookTestTimeout
) {
const deferred = createDeferred<boolean>();
const disposable = notebooks.onDidChangeNotebookCellExecutionState((e) => {
if (e.cell !== cell) {
return;
}
if (e.state === state) {
deferred.resolve(true);
}
});
disposables.push(disposable);
try {
await waitForCondition(async () => deferred.promise, timeout, `Execution state did not change to ${state}`);
} finally {
disposable.dispose();
}
}
export async function waitForOutputs(
cell: NotebookCell,
expectedNumberOfOutputs: number,
timeout: number = defaultNotebookTestTimeout
) {
await waitForCondition(
async () => cell.outputs.length === expectedNumberOfOutputs,
timeout,
() =>
`Cell ${cell.index + 1} did not complete successfully, State = ${NotebookCellStateTracker.getCellState(
cell
)}`
);
}
export async function waitForExecutionCompletedSuccessfully(
cell: NotebookCell,
timeout: number = defaultNotebookTestTimeout
) {
assert.ok(cell, 'No notebook cell to wait for');
await Promise.all([
waitForCondition(
async () => assertHasExecutionCompletedSuccessfully(cell),
timeout,
() =>
`Cell ${cell.index + 1} did not complete successfully, State = ${NotebookCellStateTracker.getCellState(
cell
)}`
),
waitForCellExecutionToComplete(cell)
]);
}
export async function waitForCompletions(
completionProvider: PythonKernelCompletionProvider,
cell: NotebookCell,
pos: Position,
triggerCharacter: string | undefined
) {
const token = new CancellationTokenSource().token;
let completions: CompletionItem[] = [];
await waitForCondition(
async () => {
await sleep(500); // Give it some time since last ask.
let context: CompletionContext = {
triggerKind: triggerCharacter ? CompletionTriggerKind.TriggerCharacter : CompletionTriggerKind.Invoke,
triggerCharacter
};
completions = await completionProvider.provideCompletionItems(cell.document, pos, token, context);
return completions.length > 0;
},
defaultNotebookTestTimeout,
`Unable to get completions for cell ${cell.document.uri}`
);
return completions;
}
export async function waitForCellHavingOutput(cell: NotebookCell) {
return waitForCondition(
async () => {
const cellOutputs = getCellOutputs(cell);
return cellOutputs.length > 0 && !cellOutputs.includes('No cell outputs');
},
defaultNotebookTestTimeout,
'No output'
);
}
/**
* When a cell is running (in progress), the start time will be > 0.
*/
export async function waitForExecutionInProgress(cell: NotebookCell, timeout: number = defaultNotebookTestTimeout) {
await waitForCondition(
async () => {
return (
NotebookCellStateTracker.getCellState(cell) === NotebookCellExecutionState.Executing &&
(cell.executionSummary?.executionOrder || 0) > 0 // If execution count > 0, then jupyter has started running this cell.
);
},
timeout,
`Cell ${cell.index + 1} did not start`
);
}
/**
* When a cell is queued for execution (in progress), the start time, last duration & status message will be `empty`.
*/
export async function waitForQueuedForExecution(cell: NotebookCell, timeout: number = defaultNotebookTestTimeout) {
await waitForCondition(
async () => {
return NotebookCellStateTracker.getCellState(cell) === NotebookCellExecutionState.Pending;
},
timeout,
() =>
`Cell ${cell.index + 1} not queued for execution, current state is ${NotebookCellStateTracker.getCellState(
cell
)}`
);
}
export async function waitForQueuedForExecutionOrExecuting(
cell: NotebookCell,
timeout: number = defaultNotebookTestTimeout
) {
await waitForCondition(
async () => {
return (
NotebookCellStateTracker.getCellState(cell) === NotebookCellExecutionState.Pending ||
NotebookCellStateTracker.getCellState(cell) === NotebookCellExecutionState.Executing
);
},
timeout,
() =>
`Cell ${
cell.index + 1
} not queued for execution nor already executing, current state is ${NotebookCellStateTracker.getCellState(
cell
)}`
);
}
export async function waitForExecutionCompletedWithoutChangesToExecutionCount(
cell: NotebookCell,
timeout: number = defaultNotebookTestTimeout
) {
await waitForCondition(
async () =>
(cell.executionSummary?.executionOrder ?? 0) === 0 &&
(NotebookCellStateTracker.getCellState(cell) ?? NotebookCellExecutionState.Idle) ===
NotebookCellExecutionState.Idle,
timeout,
() => `Cell ${cell.index + 1} did not complete, State = ${NotebookCellStateTracker.getCellState(cell)}`
);
}
export async function waitForExecutionCompletedWithErrors(
cell: NotebookCell,
timeout: number = defaultNotebookTestTimeout,
executionOderShouldChange: boolean = true
) {
await waitForCondition(
async () => assertHasExecutionCompletedWithErrors(cell, executionOderShouldChange),
timeout,
() => `Cell ${cell.index + 1} did not fail as expected, State = ${NotebookCellStateTracker.getCellState(cell)}`
);
if (executionOderShouldChange) {
await waitForCellExecutionToComplete(cell);
}
}
export async function waitForDiagnostics(
uri: Uri,
timeout: number = defaultNotebookTestTimeout
): Promise<Diagnostic[]> {
let diagnostics: Diagnostic[] = [];
await waitForCondition(
async () => {
diagnostics = languages.getDiagnostics(uri);
if (diagnostics && diagnostics.length) {
return true;
}
return false;
},
timeout,
`No diagnostics found for ${uri}`,
250
);
return diagnostics;
}
export async function waitForHover(
uri: Uri,
pos: Position,
timeout: number = defaultNotebookTestTimeout
): Promise<Hover[]> {
let hovers: Hover[] = [];
await waitForCondition(
async () => {
// Use a command to get back the list of hovers
hovers = (await commands.executeCommand('vscode.executeHoverProvider', uri, pos)) as Hover[];
if (hovers && hovers.length) {
return true;
}
return false;
},
timeout,
`No hovers found for ${uri}`,
250
);
return hovers;
}
function assertHasExecutionCompletedWithErrors(cell: NotebookCell, executionOderShouldChange = true) {
return (
(executionOderShouldChange ? (cell.executionSummary?.executionOrder ?? 0) > 0 : true) &&
(NotebookCellStateTracker.getCellState(cell) || NotebookCellExecutionState.Idle) ===
NotebookCellExecutionState.Idle &&
hasErrorOutput(cell.outputs)
);
}
export function getCellOutputs(cell: NotebookCell) {
return cell.outputs.length
? cell.outputs.map((output) => output.items.map(getOutputText).join('\n')).join('\n')
: '<No cell outputs>';
}
function getOutputText(output: NotebookCellOutputItem) {
if (
output.mime !== CellOutputMimeTypes.stdout &&
output.mime !== CellOutputMimeTypes.stderr &&
output.mime !== CellOutputMimeTypes.error &&
output.mime !== 'text/plain' &&
output.mime !== 'text/markdown'
) {
return '';
}
return Buffer.from(output.data).toString('utf8');
}
function hasTextOutputValue(output: NotebookCellOutputItem, value: string, isExactMatch = true) {
if (
output.mime !== CellOutputMimeTypes.stdout &&
output.mime !== CellOutputMimeTypes.stderr &&
output.mime !== CellOutputMimeTypes.error &&
output.mime !== 'text/plain' &&
output.mime !== 'text/markdown'
) {
return false;
}
try {
const haystack = Buffer.from(output.data).toString('utf8');
return isExactMatch
? haystack === value || haystack.trim() === value
: haystack.toLowerCase().includes(value.toLowerCase());
} catch (ex) {
traceInfoIfCI(`Looking for value ${value}, but failed with error`, ex);
return false;
}
}
export function assertHasTextOutputInVSCode(cell: NotebookCell, text: string, index: number = 0, isExactMatch = true) {
const cellOutputs = cell.outputs;
assert.ok(cellOutputs.length, 'No output');
const result = cell.outputs[index].items.some((item) => hasTextOutputValue(item, text, isExactMatch));
if (result) {
return result;
}
assert.isTrue(result, `${text} not found in outputs of cell ${cell.index} ${getCellOutputs(cell)}`);
return result;
}
export async function waitForTextOutput(
cell: NotebookCell,
text: string,
index: number = 0,
isExactMatch = true,
timeout = defaultNotebookTestTimeout
) {
await waitForCondition(
async () => assertHasTextOutputInVSCode(cell, text, index, isExactMatch),
timeout,
() =>
`After ${timeout}ms output, does not contain provided text '${text}' for Cell ${
cell.index + 1
} in output index ${index}, it is ${cell.outputs
.map(
(output, index) =>
`Output for Index "${index}" with total outputs ${output.items.length} is "${output.items
.map(getOutputText)
.join('\n')}"`
)
.join('\n')}`
);
}
export function assertNotHasTextOutputInVSCode(cell: NotebookCell, text: string, index: number, isExactMatch = true) {
const cellOutputs = cell.outputs;
assert.ok(cellOutputs, 'No output');
const outputText = getTextOutputValue(cellOutputs[index]).trim();
if (isExactMatch) {
assert.notEqual(outputText, text, 'Incorrect output');
} else {
expect(outputText).to.not.include(text, 'Output does not contain provided text');
}
return true;
}
export function assertVSCCellIsRunning(cell: NotebookCell) {
assert.equal(NotebookCellStateTracker.getCellState(cell), NotebookCellExecutionState.Executing);
// If execution count > 0, then jupyter has started running this cell.
assert.isAtLeast(cell.executionSummary?.executionOrder || 0, 1);
return true;
}
export function assertVSCCellIsNotRunning(cell: NotebookCell) {
assert.notEqual(NotebookCellStateTracker.getCellState(cell), NotebookCellExecutionState.Executing);
return true;
}
export function assertVSCCellStateIsUndefinedOrIdle(cell: NotebookCell) {
if (NotebookCellStateTracker.getCellState(cell) === undefined) {
return true;
}
assert.equal(NotebookCellStateTracker.getCellState(cell), NotebookCellExecutionState.Idle);
return true;
}
export function assertVSCCellHasErrorOutput(cell: NotebookCell) {
assert.isTrue(hasErrorOutput(cell.outputs), 'No error output in cell');
return true;
}
export async function saveActiveNotebook() {
await commands.executeCommand('workbench.action.files.saveAll');
}
export async function runCell(cell: NotebookCell, waitForExecutionToComplete = false) {
const api = await initialize();
const vscodeNotebook = api.serviceContainer.get<IVSCodeNotebook>(IVSCodeNotebook);
const notebookEditor = vscodeNotebook.notebookEditors.find((e) => e.notebook === cell.notebook);
await waitForKernelToGetAutoSelected(notebookEditor, undefined, false, 60_000);
if (!vscodeNotebook.activeNotebookEditor || !vscodeNotebook.activeNotebookEditor.notebook) {
throw new Error('No notebook or document');
}
const promise = commands.executeCommand(
'notebook.cell.execute',
{ start: cell.index, end: cell.index + 1 },
vscodeNotebook.activeNotebookEditor.notebook.uri
);
if (waitForExecutionToComplete) {
await promise.then(noop, noop);
}
}
export async function runAllCellsInActiveNotebook(
waitForExecutionToComplete = false,
activeEditor: NotebookEditor | undefined = undefined
) {
const api = await initialize();
const vscodeNotebook = api.serviceContainer.get<IVSCodeNotebook>(IVSCodeNotebook);
await waitForKernelToGetAutoSelected(activeEditor, undefined, false, 60_000);
if (!vscodeNotebook.activeNotebookEditor || !vscodeNotebook.activeNotebookEditor.notebook) {
throw new Error('No editor or document');
}
const promise = commands
.executeCommand('notebook.execute', vscodeNotebook.activeNotebookEditor.notebook.uri)
.then(noop, noop);
if (waitForExecutionToComplete) {
await promise.then(noop, noop);
}
}
export type WindowPromptStub = {
dispose: Function;
displayed: Promise<boolean>;
/**
* Gets the messages that were displayed. Access this once the promise `displayed` has resolved to get latest stuff.
*/
messages: string[];
clickButton(text?: string | undefined): void;
reset(): void;
getDisplayCount(): number;
};
export type WindowPromptStubButtonClickOptions = {
result?: string | Uri;
clickImmediately?: boolean;
dismissPrompt?: boolean;
};
/**
* Ability to stub prompts for VS Code tests.
* We can confirm prompt was displayed & invoke a button click.