Skip to content

Commit

Permalink
chore: use the new process API
Browse files Browse the repository at this point in the history
Signed-off-by: Vladyslav Zhukovskyi <[email protected]>
  • Loading branch information
vzhukovs authored and mairin committed Aug 29, 2023
1 parent 422a835 commit 72da010
Show file tree
Hide file tree
Showing 9 changed files with 244 additions and 261 deletions.
43 changes: 15 additions & 28 deletions extensions/podman/src/compatibility-mode.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,18 @@
/* eslint-disable @typescript-eslint/no-explicit-any */

import { afterEach, expect, test, vi } from 'vitest';
import { spawn } from 'node:child_process';
import { getSocketCompatibility, DarwinSocketCompatibility, LinuxSocketCompatibility } from './compatibility-mode';
import * as extensionApi from '@podman-desktop/api';
import type { Readable } from 'node:stream';

vi.mock('@podman-desktop/api', () => {
return {
window: {
showErrorMessage: vi.fn(),
showInformationMessage: vi.fn(),
},
process: {
exec: vi.fn(),
},
};
});

Expand Down Expand Up @@ -103,10 +104,12 @@ test('darwin: DarwinSocketCompatibility class, test promptRestart ran within run

const socketCompatClass = new DarwinSocketCompatibility();

// Mock execPromise was ran successfully
vi.mock('execPromise', () => {
return Promise.resolve();
});
vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({} as extensionApi.RunResult);
}),
);

// Mock that enable ran successfully
const spyEnable = vi.spyOn(socketCompatClass, 'runCommand');
Expand Down Expand Up @@ -175,28 +178,12 @@ test('linux: pass enabling when systemctl command exists', async () => {
value: 'linux',
});

// Mock that execSync runs successfully
vi.mock('child_process', () => {
return {
execSync: vi.fn(),
spawn: vi.fn(),
};
});

const on: any = vi.fn().mockImplementationOnce((event: string, cb: (arg0: string) => string) => {
if (event === 'data') {
cb('');
}
}) as unknown as Readable;
vi.mocked(spawn).mockReturnValue({
stdout: { on, setEncoding: vi.fn() },
stderr: { on, setEncoding: vi.fn() },
on: vi.fn().mockImplementation((event: string, cb: (arg0: number) => void) => {
if (event === 'close') {
cb(0);
}
}),
} as any);
vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({} as extensionApi.RunResult);
}),
);

const socketCompatClass = new LinuxSocketCompatibility();

Expand Down
10 changes: 5 additions & 5 deletions extensions/podman/src/compatibility-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import * as extensionApi from '@podman-desktop/api';
import * as sudo from 'sudo-prompt';
import * as fs from 'node:fs';
import * as os from 'node:os';
import { execPromise, getPodmanCli } from './podman-cli';
import { getPodmanCli } from './podman-cli';
import { findRunningMachine } from './extension';

const podmanSystemdSocket = 'podman.socket';
Expand Down Expand Up @@ -126,8 +126,8 @@ export class DarwinSocketCompatibility extends SocketCompatibility {
);
if (result === 'Yes') {
// Await since we must wait for the machine to stop before starting it again
await execPromise(getPodmanCli(), ['machine', 'stop', machine]);
await execPromise(getPodmanCli(), ['machine', 'start', machine]);
await extensionApi.process.exec(getPodmanCli(), ['machine', 'stop', machine]);
await extensionApi.process.exec(getPodmanCli(), ['machine', 'start', machine]);
}
}

Expand Down Expand Up @@ -188,7 +188,7 @@ export class LinuxSocketCompatibility extends SocketCompatibility {

try {
// Have to run via sudo
await execPromise('systemctl', fullCommand);
await extensionApi.process.exec('systemctl', fullCommand);
} catch (error) {
console.error(`Error running systemctl command: ${error}`);
await extensionApi.window.showErrorMessage(`Error running systemctl command: ${error}`, 'OK');
Expand All @@ -207,7 +207,7 @@ export class LinuxSocketCompatibility extends SocketCompatibility {
// If the user clicked Yes, run the ln command
if (result === 'Yes') {
try {
await execPromise('pkexec', ['ln', '-s', '/run/podman/podman.sock', '/var/run/docker.sock']);
await extensionApi.process.exec('pkexec', ['ln', '-s', '/run/podman/podman.sock', '/var/run/docker.sock']);
await extensionApi.window.showInformationMessage(
'Symlink created successfully. The Podman socket is now available at /var/run/docker.sock.',
);
Expand Down
126 changes: 72 additions & 54 deletions extensions/podman/src/extension.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,11 @@

import { afterEach, beforeEach, expect, test, vi } from 'vitest';
import * as extension from './extension';
import * as podmanCli from './podman-cli';
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: () => {
Expand Down Expand Up @@ -127,6 +127,10 @@ vi.mock('@podman-desktop/api', async () => {
window: {
showInformationMessage: vi.fn(),
},

process: {
exec: vi.fn(),
},
};
});

Expand All @@ -141,9 +145,9 @@ afterEach(() => {
});

test('verify create command called with correct values', async () => {
const spyExecPromise = vi.spyOn(podmanCli, 'execPromise');
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec');
spyExecPromise.mockImplementation(() => {
return Promise.resolve('');
return Promise.resolve({} as extensionApi.RunResult);
});
await extension.createMachine(
{
Expand All @@ -160,16 +164,15 @@ test('verify create command called with correct values', async () => {
{
env: {},
logger: undefined,
token: undefined,
},
undefined,
);
expect(console.error).not.toBeCalled();
});

test('verify create command called with correct values with user mode networking', async () => {
const spyExecPromise = vi.spyOn(podmanCli, 'execPromise');
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec');
spyExecPromise.mockImplementation(() => {
return Promise.resolve('');
return Promise.resolve({} as extensionApi.RunResult);
});
await extension.createMachine(
{
Expand All @@ -195,15 +198,10 @@ test('verify create command called with correct values with user mode networking
'path',
'--user-mode-networking',
];
expect(spyExecPromise).toBeCalledWith(
getPodmanCli(),
parameters,
{
env: {},
logger: undefined,
},
undefined,
);
expect(spyExecPromise).toBeCalledWith(getPodmanCli(), parameters, {
env: {},
logger: undefined,
});
expect(console.error).not.toBeCalled();
});

Expand Down Expand Up @@ -251,34 +249,42 @@ test('if a machine is successfully started it changes its state to started', asy
return;
});

const spyExecPromise = vi.spyOn(podmanCli, 'execPromise');
spyExecPromise.mockImplementation(() => {
return Promise.resolve('');
});
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: undefined,
logger: new LoggerDelegator(),
});

expect(spyUpdateStatus).toBeCalledWith('started');
});

test('if a machine failed to start with a generic error, this is thrown', async () => {
const spyExecPromise = vi.spyOn(podmanCli, 'execPromise');
spyExecPromise.mockImplementation(() => {
return Promise.reject(new Error('generic error'));
});
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 () => {
const spyExecPromise = vi.spyOn(podmanCli, 'execPromise');
spyExecPromise.mockImplementation(() => {
return Promise.reject(new Error('wsl bootstrap script failed: exit status 0xffffffff'));
});
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',
Expand All @@ -292,7 +298,7 @@ test('if a machine failed to start with a wsl distro not found error, the user i
});

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(podmanCli, 'execPromise');
const spyExecPromise = vi.spyOn(extensionApi.process, 'exec');
spyExecPromise.mockImplementation(() => {
return Promise.reject(new Error('wsl bootstrap script failed: exit status 0xffffffff'));
});
Expand Down Expand Up @@ -339,10 +345,12 @@ test('test checkDefaultMachine - if there is no machine marked as default, take
},
];

const spyExecPromise = vi.spyOn(podmanCli, 'execPromise');
spyExecPromise.mockImplementation(() => {
return Promise.resolve(JSON.stringify(fakeConnectionJSON));
});
vi.spyOn(extensionApi.process, 'exec').mockImplementation(
() =>
new Promise<extensionApi.RunResult>(resolve => {
resolve({ stdout: JSON.stringify(fakeConnectionJSON) } as extensionApi.RunResult);
}),
);

await extension.checkDefaultMachine(fakeJSON);

Expand Down Expand Up @@ -390,20 +398,24 @@ test('test checkDefaultMachine - if there is no machine marked as default, take
},
];

const spyExecPromise = vi.spyOn(podmanCli, 'execPromise');
spyExecPromise.mockImplementation(() => {
return Promise.resolve(JSON.stringify(fakeConnectionJSON));
});
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(podmanCli, 'execPromise');
spyExecPromise.mockImplementation(() => {
return Promise.resolve(JSON.stringify(fakeMachineInfoJSON));
});
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');
Expand Down Expand Up @@ -440,10 +452,12 @@ test('test checkDefaultMachine - if user wants to change default machine, check
});

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(podmanCli, 'execPromise');
spyExecPromise.mockImplementation(() => {
return Promise.resolve(JSON.stringify(fakeMachineInfoJSON));
});
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');
Expand Down Expand Up @@ -475,10 +489,12 @@ test('test checkDefaultMachine - if user wants to change machine, check that it
});

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(podmanCli, 'execPromise');
spyExecPromise.mockImplementation(() => {
return Promise.resolve(JSON.stringify(fakeMachineInfoJSON));
});
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');
Expand All @@ -504,10 +520,12 @@ test('test checkDefaultMachine - if user wants to change machine, check that it
});

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(podmanCli, 'execPromise');
spyExecPromise.mockImplementation(() => {
return Promise.resolve(JSON.stringify(fakeMachineInfoJSON));
});
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');
Expand Down
Loading

0 comments on commit 72da010

Please sign in to comment.