-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathdeepnoteEnvironmentsView.unit.test.ts
More file actions
1128 lines (946 loc) · 51 KB
/
deepnoteEnvironmentsView.unit.test.ts
File metadata and controls
1128 lines (946 loc) · 51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
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 { assert } from 'chai';
import * as sinon from 'sinon';
import { anything, capture, instance, mock, when, verify, deepEqual, resetCalls } from 'ts-mockito';
import { CancellationToken, Disposable, NotebookDocument, ProgressOptions, Uri } from 'vscode';
import { DeepnoteEnvironmentsView } from './deepnoteEnvironmentsView.node';
import { IDeepnoteEnvironmentManager, IDeepnoteKernelAutoSelector, IDeepnoteNotebookEnvironmentMapper } from '../types';
import { IPythonApiProvider } from '../../../platform/api/types';
import { NoOpTelemetryService } from '../../../platform/analytics/noOpTelemetryService';
import { IDisposableRegistry, IOutputChannel } from '../../../platform/common/types';
import { IKernelProvider } from '../../../kernels/types';
import { DeepnoteEnvironment } from './deepnoteEnvironment';
import { PythonEnvironment } from '../../../platform/pythonEnvironments/info';
import { mockedVSCodeNamespaces, resetVSCodeMocks } from '../../../test/vscode-mock';
import { DeepnoteEnvironmentTreeDataProvider } from './deepnoteEnvironmentTreeDataProvider.node';
import { crateMockedPythonApi, whenKnownEnvironments } from '../../helpers.unit.test';
import type { PythonExtension } from '@vscode/python-extension';
import { createDeepnoteServerConfigHandle } from '../../../platform/deepnote/deepnoteServerUtils.node';
suite('DeepnoteEnvironmentsView', () => {
let view: DeepnoteEnvironmentsView;
let mockConfigManager: IDeepnoteEnvironmentManager;
let mockTreeDataProvider: DeepnoteEnvironmentTreeDataProvider;
let mockPythonApiProvider: IPythonApiProvider;
let mockDisposableRegistry: IDisposableRegistry;
let mockKernelAutoSelector: IDeepnoteKernelAutoSelector;
let mockNotebookEnvironmentMapper: IDeepnoteNotebookEnvironmentMapper;
let mockKernelProvider: IKernelProvider;
let mockOutputChannel: IOutputChannel;
let disposables: Disposable[] = [];
let pythonEnvironments: PythonExtension['environments'];
setup(() => {
resetVSCodeMocks();
disposables.push(new Disposable(() => resetVSCodeMocks()));
// Initialize Python API for helper functions
pythonEnvironments = crateMockedPythonApi(disposables).environments;
mockConfigManager = mock<IDeepnoteEnvironmentManager>();
mockTreeDataProvider = mock<DeepnoteEnvironmentTreeDataProvider>();
mockPythonApiProvider = mock<IPythonApiProvider>();
mockDisposableRegistry = mock<IDisposableRegistry>();
mockKernelAutoSelector = mock<IDeepnoteKernelAutoSelector>();
mockNotebookEnvironmentMapper = mock<IDeepnoteNotebookEnvironmentMapper>();
mockKernelProvider = mock<IKernelProvider>();
mockOutputChannel = mock<IOutputChannel>();
// Mock onDidChangeEnvironments to return a disposable event
when(mockConfigManager.onDidChangeEnvironments).thenReturn((_listener: () => void) => {
return {
dispose: () => {
/* noop */
}
};
});
view = new DeepnoteEnvironmentsView(
instance(mockConfigManager),
instance(mockTreeDataProvider),
instance(mockPythonApiProvider),
instance(mockDisposableRegistry),
instance(mockKernelAutoSelector),
instance(mockNotebookEnvironmentMapper),
instance(mockKernelProvider),
instance(mockOutputChannel),
new NoOpTelemetryService()
);
});
teardown(() => {
if (view) {
view.dispose();
}
disposables.forEach((d) => d.dispose());
disposables = [];
});
suite('constructor', () => {
test('should create tree view', () => {
// View should be created without errors
assert.ok(view);
});
test('should register with disposable registry', () => {
verify(mockDisposableRegistry.push(anything())).atLeast(1);
});
});
suite('dispose', () => {
test('should dispose all resources', () => {
view.dispose();
// Should not throw
});
test('should dispose tree view', () => {
view.dispose();
// Tree view should be disposed
// In a real test, we would verify the tree view's dispose was called
});
});
suite('editEnvironmentName', () => {
const testEnvironmentId = 'test-env-id';
const testInterpreter: PythonEnvironment = {
id: 'test-python-id',
uri: Uri.file('/usr/bin/python3'),
version: { major: 3, minor: 11, patch: 0, raw: '3.11.0' }
} as PythonEnvironment;
const testEnvironment: DeepnoteEnvironment = {
id: testEnvironmentId,
name: 'Original Name',
pythonInterpreter: testInterpreter,
venvPath: Uri.file('/path/to/venv'),
managedVenv: true,
createdAt: new Date(),
lastUsedAt: new Date()
};
const testEnvironmentExternal: DeepnoteEnvironment = {
id: testEnvironmentId,
name: 'Original Name',
pythonInterpreter: testInterpreter,
venvPath: Uri.file('/path/to/external/venv'),
managedVenv: false,
createdAt: new Date(),
lastUsedAt: new Date()
};
setup(() => {
// Reset mocks between tests
resetCalls(mockConfigManager);
resetCalls(mockedVSCodeNamespaces.window);
});
test('should return early if environment not found', async () => {
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(undefined);
await view.editEnvironmentName(testEnvironmentId);
// Should not call showInputBox or updateEnvironment
verify(mockedVSCodeNamespaces.window.showInputBox(anything())).never();
verify(mockConfigManager.updateEnvironment(anything(), anything())).never();
});
test('should return early if user cancels input', async () => {
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironment);
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenReturn(Promise.resolve(undefined));
await view.editEnvironmentName(testEnvironmentId);
verify(mockedVSCodeNamespaces.window.showInputBox(anything())).once();
verify(mockConfigManager.updateEnvironment(anything(), anything())).never();
});
test('should return early if user provides same name', async () => {
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironment);
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenReturn(Promise.resolve('Original Name'));
await view.editEnvironmentName(testEnvironmentId);
verify(mockedVSCodeNamespaces.window.showInputBox(anything())).once();
verify(mockConfigManager.updateEnvironment(anything(), anything())).never();
});
test('should validate that name cannot be empty', async () => {
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironment);
// Capture the validator function
let validatorFn: ((value: string) => string | undefined) | undefined;
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenCall((options) => {
validatorFn = options.validateInput;
return Promise.resolve(undefined);
});
await view.editEnvironmentName(testEnvironmentId);
assert.ok(validatorFn, 'Validator function should be provided');
assert.strictEqual(validatorFn!(''), 'Name cannot be empty');
assert.strictEqual(validatorFn!(' '), 'Name cannot be empty');
assert.strictEqual(validatorFn!('Valid Name'), undefined);
});
test('should successfully rename environment with trimmed name', async () => {
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironment);
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenReturn(Promise.resolve(' New Name '));
when(mockConfigManager.updateEnvironment(anything(), anything())).thenResolve();
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve();
await view.editEnvironmentName(testEnvironmentId);
verify(mockConfigManager.updateEnvironment(testEnvironmentId, deepEqual({ name: 'New Name' }))).once();
verify(mockedVSCodeNamespaces.window.showInformationMessage(anything())).once();
});
test('should show error message if update fails', async () => {
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironment);
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenReturn(Promise.resolve('New Name'));
when(mockConfigManager.updateEnvironment(anything(), anything())).thenReject(new Error('Update failed'));
when(mockedVSCodeNamespaces.window.showErrorMessage(anything())).thenResolve();
await view.editEnvironmentName(testEnvironmentId);
verify(mockConfigManager.updateEnvironment(anything(), anything())).once();
verify(mockedVSCodeNamespaces.window.showErrorMessage(anything())).once();
});
test('should call updateEnvironment with correct parameters', async () => {
const newName = 'Updated Environment Name';
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironment);
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenReturn(Promise.resolve(newName));
when(mockConfigManager.updateEnvironment(anything(), anything())).thenResolve();
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve();
await view.editEnvironmentName(testEnvironmentId);
verify(mockConfigManager.updateEnvironment(testEnvironmentId, deepEqual({ name: newName }))).once();
});
test('should preserve existing environment configuration except name', async () => {
const envWithPackages: DeepnoteEnvironment = {
...testEnvironment,
packages: ['numpy', 'pandas'],
description: 'Test description'
};
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(envWithPackages);
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenReturn(Promise.resolve('New Name'));
when(mockConfigManager.updateEnvironment(anything(), anything())).thenResolve();
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve();
await view.editEnvironmentName(testEnvironmentId);
// Should only update the name, not other properties
verify(mockConfigManager.updateEnvironment(testEnvironmentId, deepEqual({ name: 'New Name' }))).once();
});
test('should show input box with current name as default value', async () => {
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironment);
let capturedOptions: any;
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenCall((options) => {
capturedOptions = options;
return Promise.resolve(undefined);
});
await view.editEnvironmentName(testEnvironmentId);
assert.ok(capturedOptions, 'Options should be provided');
assert.strictEqual(capturedOptions.value, 'Original Name');
});
test('should successfully rename external environment (managedVenv: false)', async () => {
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironmentExternal);
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenReturn(
Promise.resolve('New External Name')
);
when(mockConfigManager.updateEnvironment(anything(), anything())).thenResolve();
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve();
await view.editEnvironmentName(testEnvironmentId);
verify(
mockConfigManager.updateEnvironment(testEnvironmentId, deepEqual({ name: 'New External Name' }))
).once();
verify(mockedVSCodeNamespaces.window.showInformationMessage(anything())).once();
});
});
suite('createEnvironmentCommand', () => {
const testInterpreter: PythonEnvironment = {
id: 'test-python-id',
uri: Uri.file('/usr/bin/python3.11'),
version: { major: 3, minor: 11, patch: 0, raw: '3.11.0' }
} as PythonEnvironment;
const createdEnvironment: DeepnoteEnvironment = {
id: 'new-env-id',
name: 'My Data Science Environment',
pythonInterpreter: testInterpreter,
venvPath: Uri.file('/path/to/new/venv'),
managedVenv: true,
packages: ['pandas', 'numpy', 'matplotlib'],
description: 'Environment for data science work',
createdAt: new Date(),
lastUsedAt: new Date()
};
setup(() => {
resetCalls(mockConfigManager);
resetCalls(mockPythonApiProvider);
resetCalls(mockedVSCodeNamespaces.window);
});
test('should successfully create environment with all inputs', async () => {
// Set up Python environments for helper functions to use
const mockResolvedEnvironment = {
id: testInterpreter.id,
path: testInterpreter.uri.fsPath,
version: {
major: 3,
minor: 11,
micro: 0
},
environment: {
name: 'test-env',
folderUri: testInterpreter.uri
},
tools: [],
executable: {
uri: testInterpreter.uri
}
};
// Configure the Python API that was initialized in setup()
whenKnownEnvironments(pythonEnvironments).thenReturn([mockResolvedEnvironment]);
// Mock the Python API provider to return the same environments
const mockPythonApi = {
environments: {
known: [mockResolvedEnvironment]
}
};
when(mockPythonApiProvider.getNewApi()).thenResolve(mockPythonApi as any);
// Mock interpreter selection - return the first item
when(mockedVSCodeNamespaces.window.showQuickPick(anything(), anything())).thenCall((items: any[]) => {
return Promise.resolve(items[0]);
});
// Mock input boxes for name, packages, and description
let inputBoxCallCount = 0;
when(mockedVSCodeNamespaces.window.showInputBox(anything())).thenCall(() => {
inputBoxCallCount++;
if (inputBoxCallCount === 1) {
// First call: environment name
return Promise.resolve('My Data Science Environment');
} else if (inputBoxCallCount === 2) {
// Second call: packages
return Promise.resolve('pandas, numpy, matplotlib');
} else {
// Third call: description
return Promise.resolve('Environment for data science work');
}
});
// Mock list environments to return empty (no duplicates)
when(mockConfigManager.listEnvironments()).thenReturn([]);
// Mock window.withProgress to execute the callback
when(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).thenCall(
(_options: ProgressOptions, callback: Function) => {
const mockProgress = {
report: (_value: { message?: string; increment?: number }) => {
// Mock progress reporting
}
};
const mockToken = {
isCancellationRequested: false,
onCancellationRequested: (_listener: any) => {
return {
dispose: () => {
// Mock disposable
}
};
}
};
return callback(mockProgress, mockToken);
}
);
// Mock environment creation
when(mockConfigManager.createEnvironment(anything(), anything())).thenResolve(createdEnvironment);
// Mock success message
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve(undefined);
// Execute the command
await view.createEnvironmentCommand();
// Verify API calls
verify(mockPythonApiProvider.getNewApi()).once();
verify(mockedVSCodeNamespaces.window.showQuickPick(anything(), anything())).once();
verify(mockedVSCodeNamespaces.window.showInputBox(anything())).times(3);
verify(mockConfigManager.listEnvironments()).once();
verify(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).once();
// Verify createEnvironment was called with correct options
verify(mockConfigManager.createEnvironment(anything(), anything())).once();
const [capturedOptions, capturedToken] = capture(mockConfigManager.createEnvironment).last();
assert.strictEqual(capturedOptions.name, 'My Data Science Environment');
assert.deepStrictEqual(capturedOptions.packages, ['pandas', 'numpy', 'matplotlib']);
assert.strictEqual(capturedOptions.description, 'Environment for data science work');
// Don't assert on pythonInterpreter.id as the helper functions transform it
assert.ok(capturedOptions.pythonInterpreter, 'Python interpreter should be provided');
assert.ok(capturedOptions.pythonInterpreter.uri, 'Python interpreter uri should be present');
assert.ok(capturedOptions.pythonInterpreter.id, 'Python interpreter id should be present');
assert.ok(capturedToken, 'Cancellation token should be provided');
// Verify success message was shown
verify(mockedVSCodeNamespaces.window.showInformationMessage(anything())).once();
});
});
suite('deleteEnvironmentCommand', () => {
const testEnvironmentId = 'test-env-id-to-delete';
const testExternalEnvironmentId = 'test-external-env-id-to-delete';
const testInterpreter: PythonEnvironment = {
id: 'test-python-id',
uri: Uri.file('/usr/bin/python3.11'),
version: { major: 3, minor: 11, patch: 0, raw: '3.11.0' }
} as PythonEnvironment;
const testEnvironment: DeepnoteEnvironment = {
id: testEnvironmentId,
name: 'Environment to Delete',
pythonInterpreter: testInterpreter,
venvPath: Uri.file('/path/to/venv'),
managedVenv: true,
createdAt: new Date(),
lastUsedAt: new Date()
};
const testExternalEnvironment: DeepnoteEnvironment = {
id: testExternalEnvironmentId,
name: 'External Environment to Delete',
pythonInterpreter: testInterpreter,
venvPath: Uri.file('/path/to/external/venv'),
managedVenv: false,
createdAt: new Date(),
lastUsedAt: new Date()
};
setup(() => {
resetCalls(mockConfigManager);
resetCalls(mockNotebookEnvironmentMapper);
resetCalls(mockedVSCodeNamespaces.window);
});
test('should successfully delete environment with notebooks using it', async () => {
// Mock environment exists
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironment);
// Mock user confirmation - user clicks "Delete" button
when(mockedVSCodeNamespaces.window.showWarningMessage(anything(), anything(), anything())).thenReturn(
Promise.resolve('Delete')
);
// Mock notebooks using this environment
const notebook1Uri = Uri.file('/workspace/notebook1.deepnote');
const notebook2Uri = Uri.file('/workspace/notebook2.deepnote');
when(mockNotebookEnvironmentMapper.getNotebooksUsingEnvironment(testEnvironmentId)).thenReturn([
notebook1Uri,
notebook2Uri
]);
// Mock removing environment mappings
when(mockNotebookEnvironmentMapper.removeEnvironmentForNotebook(anything())).thenResolve();
// Mock window.withProgress to execute the callback
when(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).thenCall(
(_options: ProgressOptions, callback: Function) => {
const mockProgress = {
report: (_value: { message?: string; increment?: number }) => {
// Mock progress reporting
}
};
const mockToken: CancellationToken = {
isCancellationRequested: false,
onCancellationRequested: (_listener: any) => {
return {
dispose: () => {
// Mock disposable
}
};
}
};
return callback(mockProgress, mockToken);
}
);
// Mock environment deletion
when(mockConfigManager.deleteEnvironment(testEnvironmentId, anything())).thenResolve();
// Mock success message
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve(undefined);
// Execute the command
await view.deleteEnvironmentCommand(testEnvironmentId);
// Verify API calls
verify(mockConfigManager.getEnvironment(testEnvironmentId)).once();
verify(mockedVSCodeNamespaces.window.showWarningMessage(anything(), anything(), anything())).once();
verify(mockNotebookEnvironmentMapper.getNotebooksUsingEnvironment(testEnvironmentId)).once();
// Verify environment mappings were removed for both notebooks
verify(mockNotebookEnvironmentMapper.removeEnvironmentForNotebook(notebook1Uri)).once();
verify(mockNotebookEnvironmentMapper.removeEnvironmentForNotebook(notebook2Uri)).once();
// Verify environment deletion
verify(mockConfigManager.deleteEnvironment(testEnvironmentId, anything())).once();
// Verify success message was shown
verify(mockedVSCodeNamespaces.window.showInformationMessage(anything())).once();
});
test('should dispose kernels from open notebooks using the deleted environment', async () => {
// Mock environment exists
when(mockConfigManager.getEnvironment(testEnvironmentId)).thenReturn(testEnvironment);
// Mock user confirmation
when(mockedVSCodeNamespaces.window.showWarningMessage(anything(), anything(), anything())).thenReturn(
Promise.resolve('Delete')
);
// Mock notebooks using this environment
when(mockNotebookEnvironmentMapper.getNotebooksUsingEnvironment(testEnvironmentId)).thenReturn([]);
when(mockNotebookEnvironmentMapper.removeEnvironmentForNotebook(anything())).thenResolve();
// Mock open notebooks with kernels
const openNotebook1 = {
uri: Uri.file('/workspace/open-notebook1.deepnote'),
notebookType: 'deepnote',
isClosed: false
} as any;
const openNotebook2 = {
uri: Uri.file('/workspace/open-notebook2.deepnote'),
notebookType: 'jupyter-notebook',
isClosed: false
} as any;
const openNotebook3 = {
uri: Uri.file('/workspace/open-notebook3.deepnote'),
notebookType: 'deepnote',
isClosed: false
} as any;
// Mock workspace.notebookDocuments
when(mockedVSCodeNamespaces.workspace.notebookDocuments).thenReturn([
openNotebook1,
openNotebook2,
openNotebook3
]);
// Mock kernels
const mockKernel1 = {
kernelConnectionMetadata: {
kind: 'startUsingDeepnoteKernel',
serverProviderHandle: {
handle: createDeepnoteServerConfigHandle(testEnvironmentId, openNotebook1.uri)
}
},
dispose: sinon.stub().resolves()
};
const mockKernel3 = {
kernelConnectionMetadata: {
kind: 'startUsingDeepnoteKernel',
serverProviderHandle: {
handle: createDeepnoteServerConfigHandle('different-env-id', openNotebook3.uri)
}
},
dispose: sinon.stub().resolves()
};
// Mock kernelProvider.get()
when(mockKernelProvider.get(openNotebook1)).thenReturn(mockKernel1 as any);
when(mockKernelProvider.get(openNotebook2)).thenReturn(undefined); // No kernel for jupyter notebook
when(mockKernelProvider.get(openNotebook3)).thenReturn(mockKernel3 as any);
// Mock window.withProgress
when(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).thenCall(
(_options: ProgressOptions, callback: Function) => {
const mockProgress = {
report: () => {
// Mock progress reporting
}
};
const mockToken: CancellationToken = {
isCancellationRequested: false,
onCancellationRequested: () => ({
dispose: () => {
// Mock disposable
}
})
};
return callback(mockProgress, mockToken);
}
);
// Mock environment deletion
when(mockConfigManager.deleteEnvironment(testEnvironmentId, anything())).thenResolve();
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve(undefined);
// Execute the command
await view.deleteEnvironmentCommand(testEnvironmentId);
// Verify that only kernel1 (using the deleted environment) was disposed
assert.strictEqual(mockKernel1.dispose.callCount, 1, 'Kernel using deleted environment should be disposed');
assert.strictEqual(
mockKernel3.dispose.callCount,
0,
'Kernel using different environment should not be disposed'
);
});
test('should successfully delete external environment (managedVenv: false) with same side effects', async () => {
// Mock environment exists - external environment
when(mockConfigManager.getEnvironment(testExternalEnvironmentId)).thenReturn(testExternalEnvironment);
// Mock user confirmation - user clicks "Delete" button
when(mockedVSCodeNamespaces.window.showWarningMessage(anything(), anything(), anything())).thenReturn(
Promise.resolve('Delete')
);
// Mock notebooks using this environment
const notebook1Uri = Uri.file('/workspace/notebook1.deepnote');
const notebook2Uri = Uri.file('/workspace/notebook2.deepnote');
when(mockNotebookEnvironmentMapper.getNotebooksUsingEnvironment(testExternalEnvironmentId)).thenReturn([
notebook1Uri,
notebook2Uri
]);
// Mock removing environment mappings
when(mockNotebookEnvironmentMapper.removeEnvironmentForNotebook(anything())).thenResolve();
// Mock open notebooks
when(mockedVSCodeNamespaces.workspace.notebookDocuments).thenReturn([]);
// Mock window.withProgress to execute the callback
when(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).thenCall(
(_options: ProgressOptions, callback: Function) => {
const mockProgress = {
report: (_value: { message?: string; increment?: number }) => {
// Mock progress reporting
}
};
const mockToken: CancellationToken = {
isCancellationRequested: false,
onCancellationRequested: (_listener: any) => {
return {
dispose: () => {
// Mock disposable
}
};
}
};
return callback(mockProgress, mockToken);
}
);
// Mock environment deletion - the manager handles managedVenv check internally
when(mockConfigManager.deleteEnvironment(testExternalEnvironmentId, anything())).thenResolve();
// Mock success message
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve(undefined);
// Execute the command
await view.deleteEnvironmentCommand(testExternalEnvironmentId);
// Verify API calls - same as for managed venv
verify(mockConfigManager.getEnvironment(testExternalEnvironmentId)).once();
verify(mockedVSCodeNamespaces.window.showWarningMessage(anything(), anything(), anything())).once();
verify(mockNotebookEnvironmentMapper.getNotebooksUsingEnvironment(testExternalEnvironmentId)).once();
// Verify environment mappings were removed for both notebooks
verify(mockNotebookEnvironmentMapper.removeEnvironmentForNotebook(notebook1Uri)).once();
verify(mockNotebookEnvironmentMapper.removeEnvironmentForNotebook(notebook2Uri)).once();
// Verify environment deletion - the manager is responsible for checking managedVenv
verify(mockConfigManager.deleteEnvironment(testExternalEnvironmentId, anything())).once();
// Verify success message was shown
verify(mockedVSCodeNamespaces.window.showInformationMessage(anything())).once();
});
test('should dispose kernels from open notebooks using deleted external environment (managedVenv: false)', async () => {
// Mock environment exists - external environment
when(mockConfigManager.getEnvironment(testExternalEnvironmentId)).thenReturn(testExternalEnvironment);
// Mock user confirmation
when(mockedVSCodeNamespaces.window.showWarningMessage(anything(), anything(), anything())).thenReturn(
Promise.resolve('Delete')
);
// Mock notebooks using this environment
when(mockNotebookEnvironmentMapper.getNotebooksUsingEnvironment(testExternalEnvironmentId)).thenReturn([]);
when(mockNotebookEnvironmentMapper.removeEnvironmentForNotebook(anything())).thenResolve();
// Mock open notebooks with kernels
const openNotebook1 = {
uri: Uri.file('/workspace/open-notebook1.deepnote'),
notebookType: 'deepnote',
isClosed: false
} as any;
when(mockedVSCodeNamespaces.workspace.notebookDocuments).thenReturn([openNotebook1]);
// Mock kernel using the external environment
const mockKernel1 = {
kernelConnectionMetadata: {
kind: 'startUsingDeepnoteKernel',
serverProviderHandle: {
handle: createDeepnoteServerConfigHandle(testExternalEnvironmentId, openNotebook1.uri)
}
},
dispose: sinon.stub().resolves()
};
when(mockKernelProvider.get(openNotebook1)).thenReturn(mockKernel1 as any);
// Mock window.withProgress
when(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).thenCall(
(_options: ProgressOptions, callback: Function) => {
const mockProgress = {
report: () => {
// Mock progress reporting
}
};
const mockToken: CancellationToken = {
isCancellationRequested: false,
onCancellationRequested: () => ({
dispose: () => {
// Mock disposable
}
})
};
return callback(mockProgress, mockToken);
}
);
// Mock environment deletion
when(mockConfigManager.deleteEnvironment(testExternalEnvironmentId, anything())).thenResolve();
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve(undefined);
// Execute the command
await view.deleteEnvironmentCommand(testExternalEnvironmentId);
// Verify that kernel was disposed even for external environment
assert.strictEqual(
mockKernel1.dispose.callCount,
1,
'Kernel using deleted external environment should be disposed'
);
});
});
suite('selectEnvironmentForNotebook', () => {
const testInterpreter1: PythonEnvironment = {
id: 'python-1',
uri: Uri.file('/usr/bin/python3.11'),
version: { major: 3, minor: 11, patch: 0, raw: '3.11.0' }
} as PythonEnvironment;
const testInterpreter2: PythonEnvironment = {
id: 'python-2',
uri: Uri.file('/usr/bin/python3.12'),
version: { major: 3, minor: 12, patch: 0, raw: '3.12.0' }
} as PythonEnvironment;
const currentEnvironment: DeepnoteEnvironment = {
id: 'current-env-id',
name: 'Current Environment',
pythonInterpreter: testInterpreter1,
venvPath: Uri.file('/path/to/current/venv'),
managedVenv: true,
createdAt: new Date(),
lastUsedAt: new Date()
};
const currentExternalEnvironment: DeepnoteEnvironment = {
id: 'current-external-env-id',
name: 'Current External Environment',
pythonInterpreter: testInterpreter1,
venvPath: Uri.file('/path/to/external/current/venv'),
managedVenv: false,
createdAt: new Date(),
lastUsedAt: new Date()
};
const newEnvironment: DeepnoteEnvironment = {
id: 'new-env-id',
name: 'New Environment',
pythonInterpreter: testInterpreter2,
venvPath: Uri.file('/path/to/new/venv'),
managedVenv: true,
packages: ['pandas', 'numpy'],
createdAt: new Date(),
lastUsedAt: new Date()
};
const newExternalEnvironment: DeepnoteEnvironment = {
id: 'new-external-env-id',
name: 'New External Environment',
pythonInterpreter: testInterpreter2,
venvPath: Uri.file('/path/to/external/new/venv'),
managedVenv: false,
packages: ['requests'],
createdAt: new Date(),
lastUsedAt: new Date()
};
setup(() => {
resetCalls(mockConfigManager);
resetCalls(mockNotebookEnvironmentMapper);
resetCalls(mockKernelAutoSelector);
resetCalls(mockKernelProvider);
resetCalls(mockedVSCodeNamespaces.window);
});
test('should successfully switch to a different environment', async () => {
// Mock active notebook
const notebookUri = Uri.file('/workspace/notebook.deepnote');
const mockNotebook = {
uri: notebookUri,
notebookType: 'deepnote',
cellCount: 5
};
const mockNotebookEditor = {
notebook: mockNotebook
};
when(mockedVSCodeNamespaces.window.activeNotebookEditor).thenReturn(mockNotebookEditor as any);
// Mock current environment mapping
const baseFileUri = notebookUri.with({ query: '', fragment: '' });
when(mockNotebookEnvironmentMapper.getEnvironmentForNotebook(baseFileUri)).thenReturn(
currentEnvironment.id
);
when(mockConfigManager.getEnvironment(currentEnvironment.id)).thenReturn(currentEnvironment);
// Mock available environments
when(mockConfigManager.listEnvironments()).thenReturn([currentEnvironment, newEnvironment]);
// Mock environment status
when(mockConfigManager.getEnvironment(currentEnvironment.id)).thenReturn(currentEnvironment);
when(mockConfigManager.getEnvironment(newEnvironment.id)).thenReturn(newEnvironment);
// Mock user selecting the new environment
when(mockedVSCodeNamespaces.window.showQuickPick(anything(), anything())).thenCall((items: any[]) => {
// Find the item for the new environment
const selectedItem = items.find((item) => item.environmentId === newEnvironment.id);
return Promise.resolve(selectedItem);
});
// Mock no executing cells
const mockKernel = { id: 'test-kernel' };
const mockKernelExecution = {
pendingCells: []
};
when(mockKernelProvider.get(mockNotebook as any)).thenReturn(mockKernel as any);
when(mockKernelProvider.getKernelExecution(mockKernel as any)).thenReturn(mockKernelExecution as any);
// Mock window.withProgress to execute the callback
when(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).thenCall(
(_options: ProgressOptions, callback: Function) => {
return callback();
}
);
// Mock environment mapping update
when(mockNotebookEnvironmentMapper.setEnvironmentForNotebook(baseFileUri, newEnvironment.id)).thenResolve();
// Mock controller rebuild
when(mockKernelAutoSelector.rebuildController(mockNotebook as any, anything(), anything())).thenResolve();
// Mock success message
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve(undefined);
// Execute the command
await view.selectEnvironmentForNotebook({ notebook: mockNotebook as NotebookDocument });
// Verify API calls
verify(mockNotebookEnvironmentMapper.getEnvironmentForNotebook(baseFileUri)).once();
verify(mockConfigManager.getEnvironment(currentEnvironment.id)).once();
verify(mockConfigManager.listEnvironments()).once();
verify(mockConfigManager.getEnvironment(currentEnvironment.id)).once();
verify(mockedVSCodeNamespaces.window.showQuickPick(anything(), anything())).once();
verify(mockKernelProvider.get(mockNotebook as any)).once();
verify(mockKernelProvider.getKernelExecution(mockKernel as any)).once();
// Verify environment switch
verify(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).once();
verify(mockNotebookEnvironmentMapper.setEnvironmentForNotebook(baseFileUri, newEnvironment.id)).once();
verify(mockKernelAutoSelector.rebuildController(mockNotebook as any, anything(), anything())).once();
// Verify success message was shown
verify(mockedVSCodeNamespaces.window.showInformationMessage(anything())).once();
});
test('should successfully switch from managed to external environment (managedVenv: false)', async () => {
// Mock active notebook
const notebookUri = Uri.file('/workspace/notebook.deepnote');
const mockNotebook = {
uri: notebookUri,
notebookType: 'deepnote',
cellCount: 5
};
const mockNotebookEditor = {
notebook: mockNotebook
};
when(mockedVSCodeNamespaces.window.activeNotebookEditor).thenReturn(mockNotebookEditor as any);
// Mock current environment mapping (managed)
const baseFileUri = notebookUri.with({ query: '', fragment: '' });
when(mockNotebookEnvironmentMapper.getEnvironmentForNotebook(baseFileUri)).thenReturn(
currentEnvironment.id
);
when(mockConfigManager.getEnvironment(currentEnvironment.id)).thenReturn(currentEnvironment);
// Mock available environments (mix of managed and external)
when(mockConfigManager.listEnvironments()).thenReturn([
currentEnvironment,
newEnvironment,
newExternalEnvironment
]);
// Mock environment status
when(mockConfigManager.getEnvironment(newExternalEnvironment.id)).thenReturn(newExternalEnvironment);
// Mock user selecting the new external environment
when(mockedVSCodeNamespaces.window.showQuickPick(anything(), anything())).thenCall((items: any[]) => {
// Find the item for the new external environment
const selectedItem = items.find((item) => item.environmentId === newExternalEnvironment.id);
return Promise.resolve(selectedItem);
});
// Mock no executing cells
const mockKernel = { id: 'test-kernel' };
const mockKernelExecution = {
pendingCells: []
};
when(mockKernelProvider.get(mockNotebook as any)).thenReturn(mockKernel as any);
when(mockKernelProvider.getKernelExecution(mockKernel as any)).thenReturn(mockKernelExecution as any);
// Mock window.withProgress to execute the callback
when(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).thenCall(
(_options: ProgressOptions, callback: Function) => {
return callback();
}
);
// Mock environment mapping update
when(
mockNotebookEnvironmentMapper.setEnvironmentForNotebook(baseFileUri, newExternalEnvironment.id)
).thenResolve();
// Mock controller rebuild
when(mockKernelAutoSelector.rebuildController(mockNotebook as any, anything(), anything())).thenResolve();
// Mock success message
when(mockedVSCodeNamespaces.window.showInformationMessage(anything())).thenResolve(undefined);
// Execute the command
await view.selectEnvironmentForNotebook({ notebook: mockNotebook as NotebookDocument });
// Verify environment switch to external environment
verify(mockedVSCodeNamespaces.window.withProgress(anything(), anything())).once();
verify(
mockNotebookEnvironmentMapper.setEnvironmentForNotebook(baseFileUri, newExternalEnvironment.id)
).once();
verify(mockKernelAutoSelector.rebuildController(mockNotebook as any, anything(), anything())).once();
// Verify success message was shown
verify(mockedVSCodeNamespaces.window.showInformationMessage(anything())).once();
});
test('should successfully switch from external to managed environment', async () => {
// Mock active notebook
const notebookUri = Uri.file('/workspace/notebook.deepnote');
const mockNotebook = {
uri: notebookUri,
notebookType: 'deepnote',
cellCount: 5
};
const mockNotebookEditor = {
notebook: mockNotebook
};
when(mockedVSCodeNamespaces.window.activeNotebookEditor).thenReturn(mockNotebookEditor as any);
// Mock current environment mapping (external)
const baseFileUri = notebookUri.with({ query: '', fragment: '' });
when(mockNotebookEnvironmentMapper.getEnvironmentForNotebook(baseFileUri)).thenReturn(
currentExternalEnvironment.id
);
when(mockConfigManager.getEnvironment(currentExternalEnvironment.id)).thenReturn(
currentExternalEnvironment
);
// Mock available environments
when(mockConfigManager.listEnvironments()).thenReturn([currentExternalEnvironment, newEnvironment]);
// Mock environment status
when(mockConfigManager.getEnvironment(newEnvironment.id)).thenReturn(newEnvironment);
// Mock user selecting the new managed environment
when(mockedVSCodeNamespaces.window.showQuickPick(anything(), anything())).thenCall((items: any[]) => {