Skip to content

Commit

Permalink
fix: add unit tests
Browse files Browse the repository at this point in the history
Signed-off-by: Denis Golovin <[email protected]>
  • Loading branch information
dgolovin committed May 4, 2024
1 parent 7a9f2f5 commit f3379e8
Show file tree
Hide file tree
Showing 5 changed files with 264 additions and 1 deletion.
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@
"build": "vite build && node ./scripts/build.js",
"watch": "vite build -w",
"format:check": "prettier --check \"**/*.ts\" \"scripts/*.js\"",
"format:fix": "prettier --write \"**/*.ts\" \"scripts/*.js\""
"format:fix": "prettier --write \"**/*.ts\" \"scripts/*.js\"",
"test": "vitest run --coverage"
},
"dependencies": {
"@kubernetes/client-node": "^0.18.1",
Expand All @@ -73,12 +74,16 @@
"7zip-min": "^1.4.3",
"@types/fs-extra": "^11.0.1",
"@types/node": "^18.15.11",
"@vitest/coverage-v8": "^1.6.0",
"byline": "^5.0.0",
"copyfiles": "^2.4.1",
"jsdom": "^24.0.0",
"mkdirp": "^2.1.3",
"prettier": "^2.8.8",
"typescript": "^5.0.4",
"vite": "^4.5.3",
"vitest": "^1.6.0",
"vscode-uri": "^3.0.8",
"zip-local": "^0.3.5"
}
}
61 changes: 61 additions & 0 deletions src/extension.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**********************************************************************
* 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 { beforeEach, Mock, test, vi } from 'vitest';
import * as podmanDesktopApi from '@podman-desktop/api';
import * as extension from './extension';
import { URI } from 'vscode-uri';

vi.mock('@podman-desktop/api', async () => {
return {
provider: {
createProvider: vi.fn(),
onDidUpdateContainerConnection: vi.fn(),
setKubernetesProviderConnectionFactory: vi.fn(),
},

containerEngine: {
listContainers: vi.fn(),
},

kubernetes: {
getKubeconfig: vi.fn(),
},
};
});

const getKubeconfigMock = podmanDesktopApi.kubernetes.getKubeconfig as unknown as Mock<any, any>;
getKubeconfigMock.mockReturnValue(URI.parse('file:///usr/home/test'));

const context: podmanDesktopApi.ExtensionContext = {
subscriptions: [],
storagePath: '',
};

beforeEach(() => {
vi.clearAllMocks();
});

test('check we received notifications ', async () => {
const setKubernetesProviderConnectionFactoryMock = vi.fn();
(podmanDesktopApi.provider as any).setKubernetesProviderConnectionFactory =
setKubernetesProviderConnectionFactoryMock;
await extension.activate(context);
});
Empty file added src/kubeconfig.spec.ts
Empty file.
148 changes: 148 additions & 0 deletions src/sandbox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*-----------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*-----------------------------------------------------------------------------------------------*/

import fetch = require('make-fetch-happen');

// eslint-disable-next-line no-shadow
export enum SBAPIEndpoint {
SIGNUP = '/api/v1/signup',
VERIFICATION = '/api/v1/signup/verification',
}

export interface SBStatus {
ready: boolean;
reason: 'Provisioned' | 'PendingApproval';
verificationRequired: boolean;
}

export interface SBSignupResponse {
apiEndpoint: string;
cheDashboardURL: string;
clusterName: string;
company: string;
compliantUsername: string;
consoleURL: string;
familyName: string;
givenName: string;
status: SBStatus;
username: string;
}

export interface SBResponseData {
status: string;
code: number;
message: string;
details: string;
}

export interface VerificationCodeResponse {
ok: boolean;
json: SBResponseData;
}

export const OAUTH_SERVER_INFO_PATH = '.well-known/oauth-authorization-server';

export interface OauthServerInfo {
issuer: string;
authorization_endpoint: string;
token_endpoint: string;
scopes_supported: string[];
response_types_supported: string[];
grant_types_supported: string[];
code_challenge_methods_supported: string[];
}

export function getSandboxAPIUrl(): string {
return '';
}

export function getSandboxAPITimeout(): number {
return 5000;
}

export interface SandboxAPI {
getSignUpStatus(token: string): Promise<SBSignupResponse | undefined>;
signUp(token: string): Promise<boolean>;
requestVerificationCode(token: string, areaCode: string, phoneNumber: string): Promise<VerificationCodeResponse>;
validateVerificationCode(token: string, code: string): Promise<boolean>;
getOauthServerInfo(apiEndpointUrl: string): Promise<OauthServerInfo>;
}

export async function getSignUpStatus(token: string): Promise<SBSignupResponse | undefined> {
const signupResponse = await fetch(`${getSandboxAPIUrl()}${SBAPIEndpoint.SIGNUP}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
},
cache: 'no-cache',
timeout: getSandboxAPITimeout(),
});
return signupResponse.ok ? (signupResponse.json() as Promise<SBSignupResponse>) : undefined;
}

export async function signUp(token: string): Promise<boolean> {
const signupResponse = await fetch(`${getSandboxAPIUrl()}${SBAPIEndpoint.SIGNUP}`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
},
timeout: getSandboxAPITimeout(),
});
return signupResponse.ok;
}

export async function requestVerificationCode(
token: string,
countryCode: string,
phoneNumber: string,
): Promise<VerificationCodeResponse> {
const verificationCodeRequestResponse = await fetch(`${getSandboxAPIUrl()}${SBAPIEndpoint.VERIFICATION}`, {
method: 'PUT',
headers: {
Authorization: `Bearer ${token}`,
},
timeout: getSandboxAPITimeout(),
body: JSON.stringify({
country_code: countryCode,
phone_number: phoneNumber,
}),
});
const responseText = await verificationCodeRequestResponse.text();
return {
ok: verificationCodeRequestResponse.ok,
json: (responseText ? JSON.parse(responseText) : {}) as SBResponseData,
};
}

export async function validateVerificationCode(token: string, code: string): Promise<boolean> {
const validationRequestResponse = await fetch(`${getSandboxAPIUrl()}${SBAPIEndpoint.VERIFICATION}/${code}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
},
timeout: getSandboxAPITimeout(),
});

return validationRequestResponse.ok;
}

export async function getOauthServerInfo(apiEndpointUrl: string): Promise<OauthServerInfo> {
const oauthServerInfoResponse = await fetch(`${apiEndpointUrl}/${OAUTH_SERVER_INFO_PATH}`, {
method: 'GET',
timeout: getSandboxAPITimeout(),
});
const oauthInfoText = await oauthServerInfoResponse.text();
return (oauthInfoText ? JSON.parse(oauthInfoText) : {}) as OauthServerInfo;
}

export function createSandboxAPI(): SandboxAPI {
return {
getSignUpStatus,
signUp,
requestVerificationCode,
validateVerificationCode,
getOauthServerInfo,
};
}
49 changes: 49 additions & 0 deletions vitest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**********************************************************************
* 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
***********************************************************************/

import path from 'node:path';

/**
* Config for global end-to-end tests
* placed in project root tests folder
* @type {import('vite').UserConfig}
* @see https://vitest.dev/config/
*/
const config = {
test: {
globals: true,
environment: 'jsdom',
/**
* By default, vitest search test files in all packages.
* For e2e tests have sense search only is project root tests folder
*/
include: ['**/src/**/*.spec.ts'],
/**
* A default timeout of 5000ms is sometimes not enough for playwright.
*/
testTimeout: 60_000,
hookTimeout: 60_000,
},
resolve: {
alias: {
'@podman-desktop/api': path.resolve(__dirname, '__mocks__/@podman-desktop/api.js'),
},
},
};

export default config;

0 comments on commit f3379e8

Please sign in to comment.