-
Notifications
You must be signed in to change notification settings - Fork 268
/
extension.spec.ts
592 lines (520 loc) · 17.3 KB
/
extension.spec.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
/**********************************************************************
* Copyright (C) 2023 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/
/* eslint-disable @typescript-eslint/no-explicit-any */
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import * as extension from './extension';
import { getPodmanCli } from './podman-cli';
import type { Configuration } from '@podman-desktop/api';
import * as extensionApi from '@podman-desktop/api';
import * as fs from 'node:fs';
import { LoggerDelegator } from './util';
const config: Configuration = {
get: () => {
// not implemented
},
has: () => true,
update: () => Promise.resolve(),
};
const provider: extensionApi.Provider = {
setContainerProviderConnectionFactory: vi.fn(),
setKubernetesProviderConnectionFactory: vi.fn(),
registerContainerProviderConnection: vi.fn(),
registerKubernetesProviderConnection: vi.fn(),
registerLifecycle: vi.fn(),
registerInstallation: vi.fn(),
registerUpdate: vi.fn(),
registerAutostart: vi.fn(),
dispose: vi.fn(),
name: '',
id: '',
status: 'started',
updateStatus: vi.fn(),
onDidUpdateStatus: undefined,
version: '',
updateVersion: vi.fn(),
onDidUpdateVersion: undefined,
images: undefined,
links: [],
detectionChecks: [],
updateDetectionChecks: vi.fn(),
warnings: [],
updateWarnings: vi.fn(),
onDidUpdateDetectionChecks: undefined,
};
const machineInfo: extension.MachineInfo = {
cpus: 1,
diskSize: 1000000,
memory: 10000000,
name: 'name',
userModeNetworking: false,
};
const machineDefaultName = 'podman-machine-default';
const machine1Name = 'podman-machine-1';
// Create fake of MachineJSON
let fakeMachineJSON: extension.MachineJSON[];
let fakeMachineInfoJSON: any;
beforeEach(() => {
fakeMachineJSON = [
{
Name: machineDefaultName,
CPUs: 2,
Memory: '1048000000',
DiskSize: '250000000000',
Running: true,
Starting: false,
Default: false,
},
{
Name: machine1Name,
CPUs: 2,
Memory: '1048000000',
DiskSize: '250000000000',
Running: false,
Starting: false,
Default: true,
},
];
fakeMachineInfoJSON = {
Host: {
Arch: 'amd64',
CurrentMachine: '',
DefaultMachine: '',
EventsDir: 'dir1',
MachineConfigDir: 'dir2',
MachineImageDir: 'dir3',
MachineState: '',
NumberOfMachines: 5,
OS: 'windows',
VMType: 'wsl',
},
};
});
const originalConsoleError = console.error;
const consoleErrorMock = vi.fn();
vi.mock('@podman-desktop/api', async () => {
return {
configuration: {
getConfiguration: () => config,
},
proxy: {
isEnabled: () => false,
},
window: {
showInformationMessage: vi.fn(),
},
context: {
setValue: vi.fn(),
},
process: {
exec: vi.fn(),
},
};
});
beforeEach(() => {
vi.clearAllMocks();
vi.resetAllMocks();
console.error = consoleErrorMock;
});
afterEach(() => {
console.error = originalConsoleError;
});
test('verify create command called with correct values', async () => {
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec');
spyExecPromise.mockImplementation(() => {
return Promise.resolve({} as extensionApi.RunResult);
});
await extension.createMachine(
{
'podman.factory.machine.cpus': '2',
'podman.factory.machine.image-path': 'path',
'podman.factory.machine.memory': '1048000000', // 1048MB = 999.45MiB
'podman.factory.machine.diskSize': '250000000000', // 250GB = 232.83GiB
},
undefined,
);
expect(spyExecPromise).toBeCalledWith(
getPodmanCli(),
['machine', 'init', '--cpus', '2', '--memory', '999', '--disk-size', '232', '--image-path', 'path'],
{
env: {},
logger: undefined,
token: undefined,
},
);
});
test('verify create command called with correct values with user mode networking', async () => {
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec');
spyExecPromise.mockImplementation(() => {
return Promise.resolve({} as extensionApi.RunResult);
});
await extension.createMachine(
{
'podman.factory.machine.cpus': '2',
'podman.factory.machine.image-path': 'path',
'podman.factory.machine.memory': '1048000000',
'podman.factory.machine.diskSize': '250000000000',
'podman.factory.machine.user-mode-networking': true,
},
undefined,
undefined,
);
const parameters = [
'machine',
'init',
'--cpus',
'2',
'--memory',
'999',
'--disk-size',
'232',
'--image-path',
'path',
'--user-mode-networking',
];
expect(spyExecPromise).toBeCalledWith(getPodmanCli(), parameters, {
env: {},
logger: undefined,
});
expect(console.error).not.toBeCalled();
});
test('verify create command called with now flag if start machine after creation is enabled', async () => {
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec');
spyExecPromise.mockImplementation(() => {
return Promise.resolve({} as extensionApi.RunResult);
});
await extension.createMachine(
{
'podman.factory.machine.cpus': '2',
'podman.factory.machine.image-path': 'path',
'podman.factory.machine.memory': '1048000000',
'podman.factory.machine.diskSize': '250000000000',
'podman.factory.machine.now': true,
},
undefined,
undefined,
);
const parameters = [
'machine',
'init',
'--cpus',
'2',
'--memory',
'999',
'--disk-size',
'232',
'--image-path',
'path',
'--now',
];
expect(spyExecPromise).toBeCalledWith(getPodmanCli(), parameters, {
env: {},
logger: undefined,
});
expect(console.error).not.toBeCalled();
});
test('test checkDefaultMachine, if the machine running is not default, the function will prompt', async () => {
await extension.checkDefaultMachine(fakeMachineJSON);
expect(extensionApi.window.showInformationMessage).toBeCalledWith(
`Podman Machine '${machineDefaultName}' is running but not the default machine (default is '${machine1Name}'). This will cause podman CLI errors while trying to connect to '${machineDefaultName}'. Do you want to set it as default?`,
'Yes',
'Ignore',
'Cancel',
);
});
test('checkDefaultMachine: do not prompt if the running machine is already the default', async () => {
// Create fake of MachineJSON
const fakeJSON: extension.MachineJSON[] = [
{
Name: 'podman-machine-default',
CPUs: 2,
Memory: '1048000000',
DiskSize: '250000000000',
Running: true,
Starting: false,
Default: true,
},
{
Name: 'podman-machine-1',
CPUs: 2,
Memory: '1048000000',
DiskSize: '250000000000',
Running: false,
Starting: false,
Default: false,
},
];
await extension.checkDefaultMachine(fakeJSON);
expect(extensionApi.window.showInformationMessage).not.toHaveBeenCalled();
});
test('if a machine is successfully started it changes its state to started', async () => {
const spyUpdateStatus = vi.spyOn(provider, 'updateStatus');
spyUpdateStatus.mockImplementation(() => {
return;
});
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({} as extensionApi.RunResult);
}),
);
await extension.startMachine(provider, machineInfo);
expect(spyExecPromise).toBeCalledWith(getPodmanCli(), ['machine', 'start', 'name'], {
logger: new LoggerDelegator(),
});
expect(spyUpdateStatus).toBeCalledWith('started');
});
test('if a machine failed to start with a generic error, this is thrown', async () => {
vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>((resolve, reject) => {
// eslint-disable-next-line prefer-promise-reject-errors
reject(new Error('generic error') as extensionApi.RunError);
}),
);
await expect(extension.startMachine(provider, machineInfo)).rejects.toThrow('generic error');
expect(console.error).toBeCalled();
});
test('if a machine failed to start with a wsl distro not found error, the user is asked what to do', async () => {
vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>((resolve, reject) => {
// eslint-disable-next-line prefer-promise-reject-errors
reject(new Error('wsl bootstrap script failed: exit status 0xffffffff') as extensionApi.RunError);
}),
);
await expect(extension.startMachine(provider, machineInfo)).rejects.toThrow(
'wsl bootstrap script failed: exit status 0xffffffff',
);
expect(extensionApi.window.showInformationMessage).toBeCalledWith(
`Error while starting Podman Machine '${machineInfo.name}'. The WSL bootstrap script failed: exist status 0xffffffff. The machine is probably broken and should be deleted and reinitialized. Do you want to recreate it?`,
'Yes',
'Cancel',
);
expect(console.error).toBeCalled();
});
test('if a machine failed to start with a wsl distro not found error but the skipHandleError is false, the error is thrown', async () => {
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec');
spyExecPromise.mockImplementation(() => {
return Promise.reject(new Error('wsl bootstrap script failed: exit status 0xffffffff'));
});
await expect(extension.startMachine(provider, machineInfo, undefined, undefined, true)).rejects.toThrow(
'wsl bootstrap script failed: exit status 0xffffffff',
);
expect(extensionApi.window.showInformationMessage).not.toHaveBeenCalled();
expect(console.error).toBeCalled();
});
test('test checkDefaultMachine - if there is no machine marked as default, take the default system connection to retrieve it. Prompt as it is not running', async () => {
// Create fake of MachineJSON
const fakeJSON: extension.MachineJSON[] = fakeMachineJSON;
fakeJSON[1].Default = false;
const fakeConnectionJSON: extension.ConnectionJSON[] = [
{
Name: machineDefaultName,
URI: 'uri',
Identity: 'id',
IsMachine: true,
Default: false,
},
{
Name: `${machineDefaultName}-root`,
URI: 'uri',
Identity: 'id',
IsMachine: true,
Default: false,
},
{
Name: machine1Name,
URI: 'uri',
Identity: 'id',
IsMachine: true,
Default: false,
},
{
Name: `${machine1Name}-root`,
URI: 'uri',
Identity: 'id',
IsMachine: true,
Default: true,
},
];
vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({ stdout: JSON.stringify(fakeConnectionJSON) } as extensionApi.RunResult);
}),
);
await extension.checkDefaultMachine(fakeJSON);
expect(extensionApi.window.showInformationMessage).toBeCalledWith(
`Podman Machine '${machineDefaultName}' is running but not the default machine (default is '${machine1Name}'). This will cause podman CLI errors while trying to connect to '${machineDefaultName}'. Do you want to set it as default?`,
'Yes',
'Ignore',
'Cancel',
);
});
test('test checkDefaultMachine - if there is no machine marked as default, take the default system connection to retrieve it. Do not prompt as it is running', async () => {
// Create fake of MachineJSON
const fakeJSON: extension.MachineJSON[] = fakeMachineJSON;
fakeJSON[1].Default = false;
const fakeConnectionJSON: extension.ConnectionJSON[] = [
{
Name: machineDefaultName,
URI: 'uri',
Identity: 'id',
IsMachine: true,
Default: false,
},
{
Name: `${machineDefaultName}-root`,
URI: 'uri',
Identity: 'id',
IsMachine: true,
Default: true,
},
{
Name: machine1Name,
URI: 'uri',
Identity: 'id',
IsMachine: true,
Default: false,
},
{
Name: `${machine1Name}-root`,
URI: 'uri',
Identity: 'id',
IsMachine: true,
Default: false,
},
];
vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({ stdout: JSON.stringify(fakeConnectionJSON) } as extensionApi.RunResult);
}),
);
await extension.checkDefaultMachine(fakeJSON);
expect(extensionApi.window.showInformationMessage).not.toHaveBeenCalled();
});
test('test checkDefaultMachine - if user wants to change default machine, check if it is rootful and update connection', async () => {
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({ stdout: JSON.stringify(fakeMachineInfoJSON) } as extensionApi.RunResult);
}),
);
const spyPrompt = vi.spyOn(extensionApi.window, 'showInformationMessage');
spyPrompt.mockResolvedValue('Yes');
vi.mock('node:fs');
vi.spyOn(fs, 'existsSync').mockImplementation(() => {
return true;
});
const infoContentJSON = {
Rootful: true,
};
const spyReadFile = vi.spyOn(fs.promises, 'readFile');
spyReadFile.mockResolvedValue(JSON.stringify(infoContentJSON));
await extension.checkDefaultMachine(fakeMachineJSON);
expect(spyExecPromise).toHaveBeenNthCalledWith(1, getPodmanCli(), [
'system',
'connection',
'default',
machineDefaultName,
]);
expect(spyExecPromise).toHaveBeenNthCalledWith(2, getPodmanCli(), ['machine', 'info', '--format', 'json']);
expect(spyExecPromise).toHaveBeenNthCalledWith(3, getPodmanCli(), [
'system',
'connection',
'default',
`${machineDefaultName}-root`,
]);
});
test('test checkDefaultMachine - if user wants to change machine, check that it only change the connection once if it is rootless', async () => {
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({ stdout: JSON.stringify(fakeMachineInfoJSON) } as extensionApi.RunResult);
}),
);
const spyPrompt = vi.spyOn(extensionApi.window, 'showInformationMessage');
spyPrompt.mockResolvedValue('Yes');
vi.mock('node:fs');
vi.spyOn(fs, 'existsSync').mockImplementation(() => {
return true;
});
const infoContentJSON = {
Rootful: false,
};
const spyReadFile = vi.spyOn(fs.promises, 'readFile');
spyReadFile.mockResolvedValue(JSON.stringify(infoContentJSON));
await extension.checkDefaultMachine(fakeMachineJSON);
expect(spyExecPromise).toHaveBeenCalledTimes(2);
expect(spyExecPromise).toHaveBeenNthCalledWith(1, getPodmanCli(), [
'system',
'connection',
'default',
machineDefaultName,
]);
expect(spyExecPromise).toHaveBeenNthCalledWith(2, getPodmanCli(), ['machine', 'info', '--format', 'json']);
});
test('test checkDefaultMachine - if user wants to change machine, check that it only changes the connection once if it fails at checking rootful because file does not exist', async () => {
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({ stdout: JSON.stringify(fakeMachineInfoJSON) } as extensionApi.RunResult);
}),
);
const spyPrompt = vi.spyOn(extensionApi.window, 'showInformationMessage');
spyPrompt.mockResolvedValue('Yes');
vi.mock('node:fs');
vi.spyOn(fs, 'existsSync').mockImplementation(() => {
return false;
});
await extension.checkDefaultMachine(fakeMachineJSON);
expect(spyExecPromise).toHaveBeenCalledTimes(2);
expect(spyExecPromise).toHaveBeenNthCalledWith(1, getPodmanCli(), [
'system',
'connection',
'default',
machineDefaultName,
]);
expect(spyExecPromise).toHaveBeenNthCalledWith(2, getPodmanCli(), ['machine', 'info', '--format', 'json']);
});
test('if user wants to change machine, check that it only change the connection once if it fails at checking rootful because file is empty', async () => {
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({ stdout: JSON.stringify(fakeMachineInfoJSON) } as extensionApi.RunResult);
}),
);
const spyPrompt = vi.spyOn(extensionApi.window, 'showInformationMessage');
spyPrompt.mockResolvedValue('Yes');
vi.mock('node:fs');
vi.spyOn(fs, 'existsSync').mockImplementation(() => {
return true;
});
const spyReadFile = vi.spyOn(fs.promises, 'readFile');
spyReadFile.mockResolvedValue('');
await extension.checkDefaultMachine(fakeMachineJSON);
expect(spyExecPromise).toHaveBeenCalledTimes(2);
expect(spyExecPromise).toHaveBeenNthCalledWith(1, getPodmanCli(), [
'system',
'connection',
'default',
machineDefaultName,
]);
expect(spyExecPromise).toHaveBeenNthCalledWith(2, getPodmanCli(), ['machine', 'info', '--format', 'json']);
});