mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Technical requirements for behavioural unit tests (#5084)
* Implement a lot of technical requirements for behavioural unit tests Note: the crux of this was to make routing env-agnostic, and not based on URLs as magic strings, but instead something type-enforced. Note: extension-based routes comply to same exact interface by "late-registering" their routes when installed. Routes are just injectables. Note: another chunk of global shared state is no more. Note: a lot of explicit side effects have been cornered to injectables. Note: a lot of stuff has become reactive as part if this. Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com> Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Make a directory commonly available Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Require id for <Select /> to prevent non-deterministic renders This was caused by global state in a 3rd party lib: "react-select". Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Specify id for all <Select /> to satisfy previous commit Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Prevent explicit side effect in component by using existing dependency instead Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Extract instantiation of "conf" as injectables for causing side effects Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Introduce a legacy-helper to make gradual refactoring of inheritors of Singleton easier Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Make legacy unit tests for hotbar green and more simple by using the new legacy helper Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Temporarily kludge all unit tests green with a disclaimer about allowing side-effects Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Remove kludge in previous commit by explicitly permitting specific side effects where old unit tests require it Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Prevent old unit test with side effects from accessing file system Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Migrate to actual typing for di.permitSideEffects Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Prevent unit tests from failing because of non-standard method of HTML-element not present in js-dom Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Adapt integration tests to recent changes Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Fix code style Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Fix artifact from bad rebase Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Add a deprecation from a review comment Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Remove change that is not required Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Remove redundant comment Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Fix code style Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com> Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Remove redundant file Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Fix bad merge Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Improve variable name Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Tweak logger interface to be more descriptive Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Make injecting legacy singleton always provide new instance Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Remove conditional typing when not needed Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Improve naming of variable Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Remove unnecessary code style changes Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Remove flag for causing side effects from too broad scope Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com> Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Override side-effects in unit test using injectable instead of monkey patching Co-authored-by: Janne Savolainen <janne.savolainen@live.fi> Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Flag some side-effects and add general overrides Co-authored-by: Janne Savolainen <janne.savolainen@live.fi> Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Fix unit tests in CI by removing explicit side-effect Co-authored-by: Janne Savolainen <janne.savolainen@live.fi> Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Remove explicit side-effect from getting default shell Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Introduce abstraction for getting absolute paths Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com> Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Switch to using abstraction for getting absolute path to control explicit side effect Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com> Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Introduce abstraction for joining paths Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Switch to using abstraction for joining paths to control explicit side effect Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Fix fake implementation for join paths Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Fix test after removing explicit side effect Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Remove explicit side effects from kubeconfig-syncs Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Fix arguments after removing explicit side effect Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Make registrators not async for not being needed anymore Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Make generalCatalogEntities non-observable, as there is no requirement Co-authored-by: Janne Savolainen <janne.savolainen@live.fi> Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Remove redundant code Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com> Signed-off-by: Iku-turso <mikko.aspiala@gmail.com> * Simplify logic for registering general catalog entity sources Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Add TODO Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Replace function for getting application menu items with reactive solution Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Fix typo in interface name Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Remove global shared state usages of hot bar store Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> * Remove redundant enum Signed-off-by: Janne Savolainen <janne.savolainen@live.fi> Co-authored-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
1 parent
ab2cd27a27
commit
a277cfcf02
583 files changed
+13073
-6556
No files matched your search
+2
-2
@@ -8,7 +8,7 @@ import {
|
||||
getInjectable,
|
||||
Injectable,
|
||||
} from "@ogre-tools/injectable";
|
||||
import { setLegacyGlobalDiForExtensionApi } from "./legacy-global-di-for-extension-api";
|
||||
import { Environments, setLegacyGlobalDiForExtensionApi } from "./legacy-global-di-for-extension-api";
|
||||
import { asLegacyGlobalObjectForExtensionApiWithModifications } from "./as-legacy-global-object-for-extension-api-with-modifications";
|
||||
|
||||
describe("asLegacyGlobalObjectForExtensionApiWithModifications", () => {
|
||||
@@ -24,7 +24,7 @@ describe("asLegacyGlobalObjectForExtensionApiWithModifications", () => {
|
||||
|
||||
jest.spyOn(di, "inject");
|
||||
|
||||
setLegacyGlobalDiForExtensionApi(di);
|
||||
setLegacyGlobalDiForExtensionApi(di, Environments.renderer);
|
||||
|
||||
someInjectable = getInjectable({
|
||||
id: "some-injectable",
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { Injectable } from "@ogre-tools/injectable";
|
||||
import { asLegacyGlobalForExtensionApi } from "./as-legacy-global-object-for-extension-api";
|
||||
import { getLegacyGlobalDiForExtensionApi } from "./legacy-global-di-for-extension-api";
|
||||
import loggerInjectable from "../../common/logger.injectable";
|
||||
|
||||
export const asLegacyGlobalSingletonForExtensionApi = <
|
||||
Instance,
|
||||
InstantiationParameter = void,
|
||||
>(
|
||||
injectable: Injectable<Instance, unknown, InstantiationParameter>,
|
||||
instantiationParameter?: InstantiationParameter,
|
||||
) => {
|
||||
const instance = asLegacyGlobalForExtensionApi(
|
||||
injectable,
|
||||
instantiationParameter,
|
||||
);
|
||||
|
||||
return {
|
||||
createInstance: () => instance,
|
||||
|
||||
getInstance: () => instance,
|
||||
|
||||
resetInstance: () => {
|
||||
const di = getLegacyGlobalDiForExtensionApi();
|
||||
const logger = di.inject(loggerInjectable);
|
||||
|
||||
logger.warn(
|
||||
`resetInstance() for a legacy global singleton of "${injectable.id}" does nothing.`,
|
||||
);
|
||||
},
|
||||
};
|
||||
};
|
||||
+23
-4
@@ -4,10 +4,29 @@
|
||||
*/
|
||||
import type { DiContainer } from "@ogre-tools/injectable";
|
||||
|
||||
let legacyGlobalDi: DiContainer;
|
||||
const legacyGlobalDis = new Map<Environments, DiContainer>();
|
||||
|
||||
export const setLegacyGlobalDiForExtensionApi = (di: DiContainer) => {
|
||||
legacyGlobalDi = di;
|
||||
export enum Environments {
|
||||
renderer,
|
||||
main,
|
||||
}
|
||||
|
||||
export const setLegacyGlobalDiForExtensionApi = (
|
||||
di: DiContainer,
|
||||
environment: Environments,
|
||||
) => {
|
||||
legacyGlobalDis.set(environment, di);
|
||||
};
|
||||
|
||||
export const getLegacyGlobalDiForExtensionApi = () => legacyGlobalDi;
|
||||
export const getLegacyGlobalDiForExtensionApi = () => {
|
||||
const globalDis = [...legacyGlobalDis.values()];
|
||||
|
||||
if (globalDis.length > 1) {
|
||||
throw new Error("Tried to get DI container using legacy globals where there is multiple containers available.");
|
||||
}
|
||||
|
||||
return globalDis[0];
|
||||
};
|
||||
|
||||
export const getEnvironmentSpecificLegacyGlobalDiForExtensionApi = (environment: Environments) =>
|
||||
legacyGlobalDis.get(environment);
|
||||
+7
-3
@@ -3,14 +3,18 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import path from "path";
|
||||
import directoryForUserDataInjectable from "../../../../../common/app-paths/directory-for-user-data/directory-for-user-data.injectable";
|
||||
import getAbsolutePathInjectable from "../../../../../common/path/get-absolute-path.injectable";
|
||||
|
||||
const directoryForExtensionDataInjectable = getInjectable({
|
||||
id: "directory-for-extension-data",
|
||||
|
||||
instantiate: (di) =>
|
||||
path.join(di.inject(directoryForUserDataInjectable), "extension_data"),
|
||||
instantiate: (di) => {
|
||||
const getAbsolutePath = di.inject(getAbsolutePathInjectable);
|
||||
const directoryForUserData = di.inject(directoryForUserDataInjectable);
|
||||
|
||||
return getAbsolutePath(directoryForUserData, "extension_data");
|
||||
},
|
||||
});
|
||||
|
||||
export default directoryForExtensionDataInjectable;
|
||||
+2
@@ -15,6 +15,8 @@ const fileSystemProvisionerStoreInjectable = getInjectable({
|
||||
directoryForExtensionDataInjectable,
|
||||
),
|
||||
}),
|
||||
|
||||
causesSideEffects: true,
|
||||
});
|
||||
|
||||
export default fileSystemProvisionerStoreInjectable;
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
|
||||
const extensionInstallationCounterInjectable = getInjectable({
|
||||
id: "extension-installation-counter",
|
||||
instantiate: () => new Map<string, number>(),
|
||||
});
|
||||
|
||||
export default extensionInstallationCounterInjectable;
|
||||
@@ -5,8 +5,9 @@
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { ExtensionLoader } from "./extension-loader";
|
||||
import updateExtensionsStateInjectable from "./update-extensions-state/update-extensions-state.injectable";
|
||||
import createExtensionInstanceInjectable
|
||||
from "./create-extension-instance/create-extension-instance.injectable";
|
||||
import createExtensionInstanceInjectable from "./create-extension-instance/create-extension-instance.injectable";
|
||||
import { extensionRegistratorInjectionToken } from "./extension-registrator-injection-token";
|
||||
import extensionInstallationCounterInjectable from "./extension-installation-counter.injectable";
|
||||
|
||||
const extensionLoaderInjectable = getInjectable({
|
||||
id: "extension-loader",
|
||||
@@ -15,6 +16,8 @@ const extensionLoaderInjectable = getInjectable({
|
||||
new ExtensionLoader({
|
||||
updateExtensionsState: di.inject(updateExtensionsStateInjectable),
|
||||
createExtensionInstance: di.inject(createExtensionInstanceInjectable),
|
||||
extensionRegistrators: di.injectMany(extensionRegistratorInjectionToken),
|
||||
extensionInstallationCounter: di.inject(extensionInstallationCounterInjectable),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -25,6 +25,8 @@ const logModule = "[EXTENSIONS-LOADER]";
|
||||
interface Dependencies {
|
||||
updateExtensionsState: (extensionsState: Record<LensExtensionId, LensExtensionState>) => void;
|
||||
createExtensionInstance: (ExtensionClass: LensExtensionConstructor, extension: InstalledExtension) => LensExtension;
|
||||
extensionRegistrators: ((extension: LensExtension, extensionInstallationCount: number) => void)[];
|
||||
extensionInstallationCounter: Map<string, number>;
|
||||
}
|
||||
|
||||
export interface ExtensionLoading {
|
||||
@@ -247,7 +249,6 @@ export class ExtensionLoader {
|
||||
|
||||
return this.autoInitExtensions(async (extension: LensRendererExtension) => {
|
||||
const removeItems = [
|
||||
registries.GlobalPageRegistry.getInstance().add(extension.globalPages, extension),
|
||||
registries.EntitySettingRegistry.getInstance().add(extension.entitySettings),
|
||||
registries.CatalogEntityDetailRegistry.getInstance().add(extension.catalogEntityDetailItems),
|
||||
];
|
||||
@@ -274,8 +275,6 @@ export class ExtensionLoader {
|
||||
}
|
||||
|
||||
const removeItems = [
|
||||
registries.ClusterPageRegistry.getInstance().add(extension.clusterPages, extension),
|
||||
registries.ClusterPageMenuRegistry.getInstance().add(extension.clusterPageMenus, extension),
|
||||
registries.KubeObjectDetailRegistry.getInstance().add(extension.kubeObjectDetailItems),
|
||||
];
|
||||
|
||||
@@ -317,6 +316,14 @@ export class ExtensionLoader {
|
||||
extension,
|
||||
);
|
||||
|
||||
const installationCount = (this.dependencies.extensionInstallationCounter.get(instance.sanitizedExtensionId) | 0) + 1;
|
||||
|
||||
this.dependencies.extensionInstallationCounter.set(instance.sanitizedExtensionId, installationCount);
|
||||
|
||||
this.dependencies.extensionRegistrators.forEach((register) =>
|
||||
register(instance, installationCount),
|
||||
);
|
||||
|
||||
this.instances.set(extId, instance);
|
||||
|
||||
return {
|
||||
@@ -332,9 +339,7 @@ export class ExtensionLoader {
|
||||
}
|
||||
|
||||
return null;
|
||||
})
|
||||
// Remove null values
|
||||
.filter(extension => Boolean(extension));
|
||||
}).filter(extension => Boolean(extension));
|
||||
|
||||
// We first need to wait until each extension's `onActivate` is resolved or rejected,
|
||||
// as this might register new catalog categories. Afterwards we can safely .enable the extension.
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectionToken } from "@ogre-tools/injectable";
|
||||
import type { LensExtension } from "../lens-extension";
|
||||
|
||||
export const extensionRegistratorInjectionToken = getInjectionToken<
|
||||
(extension: LensExtension, extensionInstallationCount: number) => void
|
||||
>({
|
||||
id: "extension-registrator-token",
|
||||
});
|
||||
+1
-1
@@ -6,7 +6,7 @@ import { getInjectable } from "@ogre-tools/injectable";
|
||||
import extensionsStoreInjectable from "../../extensions-store/extensions-store.injectable";
|
||||
|
||||
const updateExtensionsStateInjectable = getInjectable({
|
||||
id: "upadte-extensions-state",
|
||||
id: "update-extensions-state",
|
||||
instantiate: (di) => di.inject(extensionsStoreInjectable).mergeState,
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,14 @@ import { ExtensionsStore } from "./extensions-store";
|
||||
|
||||
const extensionsStoreInjectable = getInjectable({
|
||||
id: "extensions-store",
|
||||
instantiate: () => ExtensionsStore.createInstance(),
|
||||
|
||||
instantiate: () => {
|
||||
ExtensionsStore.resetInstance();
|
||||
|
||||
return ExtensionsStore.createInstance();
|
||||
},
|
||||
|
||||
causesSideEffects: true,
|
||||
});
|
||||
|
||||
export default extensionsStoreInjectable;
|
||||
@@ -32,6 +32,10 @@ export class LensExtension {
|
||||
readonly manifestPath: string;
|
||||
readonly isBundled: boolean;
|
||||
|
||||
get sanitizedExtensionId() {
|
||||
return sanitizeExtensionName(this.name);
|
||||
}
|
||||
|
||||
protocolHandlers: ProtocolHandlerRegistration[] = [];
|
||||
|
||||
@observable private _isEnabled = false;
|
||||
@@ -90,6 +94,7 @@ export class LensExtension {
|
||||
|
||||
this[Disposers].push(...await register(this));
|
||||
logger.info(`[EXTENSION]: enabled ${this.name}@${this.version}`);
|
||||
|
||||
} catch (error) {
|
||||
logger.error(`[EXTENSION]: failed to activate ${this.name}@${this.version}: ${error}`);
|
||||
}
|
||||
@@ -129,6 +134,12 @@ export function sanitizeExtensionName(name: string) {
|
||||
return name.replace("@", "").replace("/", "--");
|
||||
}
|
||||
|
||||
export const getSanitizedPath = (...parts: string[]) => parts
|
||||
.filter(Boolean)
|
||||
.join("/")
|
||||
.replace(/\/+/g, "/")
|
||||
.replace(/\/$/, ""); // normalize multi-slashes (e.g. coming from page.id)
|
||||
|
||||
export function extensionDisplayName(name: string, version: string) {
|
||||
return `${name}@${version}`;
|
||||
}
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
import type * as registries from "./registries";
|
||||
import { Disposers, LensExtension } from "./lens-extension";
|
||||
import { getExtensionPageUrl } from "./registries/page-registry";
|
||||
import type { CatalogEntity } from "../common/catalog";
|
||||
import type { Disposer } from "../common/utils";
|
||||
import { catalogEntityRegistry, EntityFilter } from "../renderer/api/catalog-entity-registry";
|
||||
@@ -22,6 +21,13 @@ import type { StatusBarRegistration } from "../renderer/components/status-bar/st
|
||||
import type { KubeObjectMenuRegistration } from "../renderer/components/kube-object-menu/dependencies/kube-object-menu-items/kube-object-menu-registration";
|
||||
import type { WorkloadsOverviewDetailRegistration } from "../renderer/components/+workloads-overview/workloads-overview-detail-registration";
|
||||
import type { KubeObjectStatusRegistration } from "../renderer/components/kube-object-status-icon/kube-object-status-registration";
|
||||
import { Environments, getEnvironmentSpecificLegacyGlobalDiForExtensionApi } from "./as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
|
||||
import routesInjectable from "../renderer/routes/routes.injectable";
|
||||
import { fromPairs, map, matches, toPairs } from "lodash/fp";
|
||||
import extensionPageParametersInjectable from "../renderer/routes/extension-page-parameters.injectable";
|
||||
import { pipeline } from "@ogre-tools/fp";
|
||||
import { getExtensionRoutePath } from "../renderer/routes/get-extension-route-path";
|
||||
import { navigateToRouteInjectionToken } from "../common/front-end-routing/navigate-to-route-injection-token";
|
||||
|
||||
export class LensRendererExtension extends LensExtension {
|
||||
globalPages: registries.PageRegistration[] = [];
|
||||
@@ -43,14 +49,48 @@ export class LensRendererExtension extends LensExtension {
|
||||
customCategoryViews: CustomCategoryViewRegistration[] = [];
|
||||
|
||||
async navigate<P extends object>(pageId?: string, params?: P) {
|
||||
const { navigate } = await import("../renderer/navigation");
|
||||
const pageUrl = getExtensionPageUrl({
|
||||
extensionId: this.name,
|
||||
pageId,
|
||||
params: params ?? {}, // compile to url with params
|
||||
});
|
||||
const di = getEnvironmentSpecificLegacyGlobalDiForExtensionApi(
|
||||
Environments.renderer,
|
||||
);
|
||||
|
||||
navigate(pageUrl);
|
||||
const navigateToRoute = di.inject(navigateToRouteInjectionToken);
|
||||
const routes = di.inject(routesInjectable).get();
|
||||
|
||||
const targetRegistration = [...this.globalPages, ...this.clusterPages].find(
|
||||
registration => registration.id === (pageId || undefined),
|
||||
);
|
||||
|
||||
const targetRoutePath = getExtensionRoutePath(this, targetRegistration.id);
|
||||
|
||||
const targetRoute = routes.find(matches({ path: targetRoutePath }));
|
||||
|
||||
if (targetRoute) {
|
||||
const normalizedParams = di.inject(extensionPageParametersInjectable, {
|
||||
extension: this,
|
||||
registration: targetRegistration,
|
||||
});
|
||||
|
||||
const query = pipeline(
|
||||
params,
|
||||
|
||||
toPairs,
|
||||
|
||||
map(([key, value]) => {
|
||||
const normalizedParam = normalizedParams[key];
|
||||
|
||||
return [
|
||||
key,
|
||||
normalizedParam.stringify(value),
|
||||
];
|
||||
}),
|
||||
|
||||
fromPairs,
|
||||
);
|
||||
|
||||
navigateToRoute(targetRoute, {
|
||||
query,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { jest } from "@jest/globals";
|
||||
import { ClusterPageRegistry, getExtensionPageUrl, GlobalPageRegistry, PageParams } from "../page-registry";
|
||||
import { LensExtension } from "../../lens-extension";
|
||||
import React from "react";
|
||||
import fse from "fs-extra";
|
||||
import { Console } from "console";
|
||||
import { stderr, stdout } from "process";
|
||||
import { ThemeStore } from "../../../renderer/theme.store";
|
||||
import { UserStore } from "../../../common/user-store";
|
||||
import { getDisForUnitTesting } from "../../../test-utils/get-dis-for-unit-testing";
|
||||
import mockFs from "mock-fs";
|
||||
|
||||
jest.mock("electron", () => ({
|
||||
app: {
|
||||
getVersion: () => "99.99.99",
|
||||
getName: () => "lens",
|
||||
setName: jest.fn(),
|
||||
setPath: jest.fn(),
|
||||
getPath: () => "tmp",
|
||||
getLocale: () => "en",
|
||||
setLoginItemSettings: jest.fn(),
|
||||
},
|
||||
ipcMain: {
|
||||
on: jest.fn(),
|
||||
handle: jest.fn(),
|
||||
},
|
||||
ipcRenderer: {
|
||||
on: jest.fn(),
|
||||
invoke: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
console = new Console(stdout, stderr);
|
||||
|
||||
let ext: LensExtension = null;
|
||||
|
||||
describe("page registry tests", () => {
|
||||
beforeEach(async () => {
|
||||
const dis = getDisForUnitTesting({ doGeneralOverrides: true });
|
||||
|
||||
mockFs();
|
||||
|
||||
await dis.runSetups();
|
||||
|
||||
ext = new LensExtension({
|
||||
manifest: {
|
||||
name: "foo-bar",
|
||||
version: "0.1.1",
|
||||
},
|
||||
id: "/this/is/fake/package.json",
|
||||
absolutePath: "/absolute/fake/",
|
||||
manifestPath: "/this/is/fake/package.json",
|
||||
isBundled: false,
|
||||
isEnabled: true,
|
||||
isCompatible: true,
|
||||
});
|
||||
UserStore.createInstance();
|
||||
ThemeStore.createInstance();
|
||||
ClusterPageRegistry.createInstance();
|
||||
GlobalPageRegistry.createInstance().add({
|
||||
id: "page-with-params",
|
||||
components: {
|
||||
Page: () => React.createElement("Page with params"),
|
||||
},
|
||||
params: {
|
||||
test1: "test1-default",
|
||||
test2: "", // no default value, just declaration
|
||||
},
|
||||
}, ext);
|
||||
GlobalPageRegistry.createInstance().add([
|
||||
{
|
||||
id: "test-page",
|
||||
components: {
|
||||
Page: () => React.createElement("Text"),
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "another-page",
|
||||
components: {
|
||||
Page: () => React.createElement("Text"),
|
||||
},
|
||||
},
|
||||
{
|
||||
components: {
|
||||
Page: () => React.createElement("Default"),
|
||||
},
|
||||
},
|
||||
], ext);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
GlobalPageRegistry.resetInstance();
|
||||
ClusterPageRegistry.resetInstance();
|
||||
ThemeStore.resetInstance();
|
||||
UserStore.resetInstance();
|
||||
fse.remove("tmp");
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
describe("getPageUrl", () => {
|
||||
it("returns a page url for extension", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: ext.name })).toBe("/extension/foo-bar");
|
||||
});
|
||||
|
||||
it("allows to pass base url as parameter", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: ext.name, pageId: "/test" })).toBe("/extension/foo-bar/test");
|
||||
});
|
||||
|
||||
it("removes @ and replace `/` to `--`", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: "@foo/bar" })).toBe("/extension/foo--bar");
|
||||
});
|
||||
|
||||
it("adds / prefix", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: ext.name, pageId: "test" })).toBe("/extension/foo-bar/test");
|
||||
});
|
||||
|
||||
it("normalize possible multi-slashes in page.id", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: ext.name, pageId: "//test/" })).toBe("/extension/foo-bar/test");
|
||||
});
|
||||
|
||||
it("gets page url with custom params", () => {
|
||||
const params: PageParams = { test1: "one", test2: "2" };
|
||||
const searchParams = new URLSearchParams(params);
|
||||
const pageUrl = getExtensionPageUrl({
|
||||
extensionId: ext.name,
|
||||
pageId: "page-with-params",
|
||||
params,
|
||||
});
|
||||
|
||||
expect(pageUrl).toBe(`/extension/foo-bar/page-with-params?${searchParams}`);
|
||||
});
|
||||
|
||||
it("gets page url with default custom params", () => {
|
||||
const defaultPageUrl = getExtensionPageUrl({
|
||||
extensionId: ext.name,
|
||||
pageId: "page-with-params",
|
||||
});
|
||||
|
||||
expect(defaultPageUrl).toBe(`/extension/foo-bar/page-with-params?test1=test1-default`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("globalPageRegistry", () => {
|
||||
describe("getByPageTarget", () => {
|
||||
it("matching to first registered page without id", () => {
|
||||
const page = GlobalPageRegistry.getInstance().getByPageTarget({ extensionId: ext.name });
|
||||
|
||||
expect(page.id).toEqual(undefined);
|
||||
expect(page.extensionId).toEqual(ext.name);
|
||||
expect(page.url).toEqual(getExtensionPageUrl({ extensionId: ext.name }));
|
||||
});
|
||||
|
||||
it("returns matching page", () => {
|
||||
const page = GlobalPageRegistry.getInstance().getByPageTarget({
|
||||
pageId: "test-page",
|
||||
extensionId: ext.name,
|
||||
});
|
||||
|
||||
expect(page.id).toEqual("test-page");
|
||||
});
|
||||
|
||||
it("returns null if target not found", () => {
|
||||
const page = GlobalPageRegistry.getInstance().getByPageTarget({
|
||||
pageId: "wrong-page",
|
||||
extensionId: ext.name,
|
||||
});
|
||||
|
||||
expect(page).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -6,9 +6,7 @@
|
||||
// Extensions-api -> Register page menu items
|
||||
import type { IconProps } from "../../renderer/components/icon";
|
||||
import type React from "react";
|
||||
import type { PageTarget, RegisteredPage } from "./page-registry";
|
||||
import type { LensExtension } from "../lens-extension";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
import type { PageTarget } from "./page-registry";
|
||||
|
||||
export interface ClusterPageMenuRegistration {
|
||||
id?: string;
|
||||
@@ -21,36 +19,3 @@ export interface ClusterPageMenuRegistration {
|
||||
export interface ClusterPageMenuComponents {
|
||||
Icon: React.ComponentType<IconProps>;
|
||||
}
|
||||
|
||||
export class ClusterPageMenuRegistry extends BaseRegistry<ClusterPageMenuRegistration> {
|
||||
add(items: ClusterPageMenuRegistration[], ext: LensExtension) {
|
||||
const normalizedItems = items.map(menuItem => {
|
||||
menuItem.target = {
|
||||
extensionId: ext.name,
|
||||
...(menuItem.target || {}),
|
||||
};
|
||||
|
||||
return menuItem;
|
||||
});
|
||||
|
||||
return super.add(normalizedItems);
|
||||
}
|
||||
|
||||
getRootItems() {
|
||||
return this.getItems().filter((item) => !item.parentId);
|
||||
}
|
||||
|
||||
getSubItems(parent: ClusterPageMenuRegistration) {
|
||||
return this.getItems().filter((item) => (
|
||||
item.parentId === parent.id &&
|
||||
item.target.extensionId === parent.target.extensionId
|
||||
));
|
||||
}
|
||||
|
||||
getByPage({ id: pageId, extensionId }: RegisteredPage) {
|
||||
return this.getItems().find((item) => (
|
||||
item.target.pageId == pageId &&
|
||||
item.target.extensionId === extensionId
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,10 @@
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { PageParamInit, PageParam } from "../../renderer/navigation";
|
||||
|
||||
// Extensions-api -> Custom page registration
|
||||
|
||||
import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
import { LensExtension, LensExtensionId, sanitizeExtensionName } from "../lens-extension";
|
||||
import { createPageParam, PageParam, PageParamInit, searchParamsOptions } from "../../renderer/navigation";
|
||||
|
||||
export interface PageRegistration {
|
||||
/**
|
||||
* Page ID, part of extension's page url, must be unique within same extension
|
||||
@@ -48,95 +43,3 @@ export interface RegisteredPage {
|
||||
params: PageParams<PageParam>; // normalized params
|
||||
components: PageComponents; // normalized components
|
||||
}
|
||||
|
||||
export function getExtensionPageUrl(target: PageTarget): string {
|
||||
const { extensionId, pageId = "", params: targetParams = {}} = target;
|
||||
|
||||
const pagePath = ["/extension", sanitizeExtensionName(extensionId), pageId]
|
||||
.filter(Boolean)
|
||||
.join("/").replace(/\/+/g, "/").replace(/\/$/, ""); // normalize multi-slashes (e.g. coming from page.id)
|
||||
|
||||
const pageUrl = new URL(pagePath, `http://localhost`);
|
||||
|
||||
// stringify params to matched target page
|
||||
const registeredPage = GlobalPageRegistry.getInstance().getByPageTarget(target) || ClusterPageRegistry.getInstance().getByPageTarget(target);
|
||||
|
||||
if (registeredPage?.params) {
|
||||
Object.entries(registeredPage.params).forEach(([name, param]) => {
|
||||
pageUrl.searchParams.delete(name); // first off, clear existing value(s)
|
||||
|
||||
param.stringify(targetParams[name]).forEach(value => {
|
||||
if (searchParamsOptions.skipEmpty && !value) return;
|
||||
pageUrl.searchParams.append(name, value);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return pageUrl.href.replace(pageUrl.origin, "");
|
||||
}
|
||||
|
||||
class PageRegistry extends BaseRegistry<PageRegistration, RegisteredPage> {
|
||||
protected getRegisteredItem(page: PageRegistration, ext: LensExtension): RegisteredPage {
|
||||
const { id: pageId } = page;
|
||||
const extensionId = ext.name;
|
||||
const params = this.normalizeParams(extensionId, page.params);
|
||||
const components = this.normalizeComponents(page.components, params);
|
||||
const url = getExtensionPageUrl({ extensionId, pageId });
|
||||
|
||||
return {
|
||||
id: pageId, extensionId, params, components, url,
|
||||
};
|
||||
}
|
||||
|
||||
protected normalizeComponents(components: PageComponents, params?: PageParams<PageParam>): PageComponents {
|
||||
if (params) {
|
||||
const { Page } = components;
|
||||
|
||||
// inject extension's page component props.params
|
||||
components.Page = observer((props: object) => React.createElement(Page, { params, ...props }));
|
||||
}
|
||||
|
||||
return components;
|
||||
}
|
||||
|
||||
protected normalizeParams(extensionId: LensExtensionId, params?: PageParams<string | Partial<PageParamInit>>): PageParams<PageParam> {
|
||||
if (!params) return undefined;
|
||||
const normalizedParams: PageParams<PageParam> = {};
|
||||
|
||||
Object.entries(params).forEach(([paramName, paramValue]) => {
|
||||
const paramInit: PageParamInit = {
|
||||
name: paramName,
|
||||
prefix: `${extensionId}:`,
|
||||
defaultValue: paramValue,
|
||||
};
|
||||
|
||||
// handle non-string params
|
||||
if (typeof paramValue !== "string") {
|
||||
const { defaultValue: value, parse, stringify } = paramValue;
|
||||
|
||||
const notAStringValue = typeof value !== "string" || (
|
||||
Array.isArray(value) && !value.every(value => typeof value === "string")
|
||||
);
|
||||
|
||||
if (notAStringValue && !(parse || stringify)) {
|
||||
throw new Error(`PageRegistry: param's "${paramName}" initialization has failed: paramInit.parse() and paramInit.stringify() are required for non string | string[] "defaultValue"`);
|
||||
}
|
||||
|
||||
paramInit.defaultValue = value;
|
||||
paramInit.parse = parse;
|
||||
paramInit.stringify = stringify;
|
||||
}
|
||||
|
||||
normalizedParams[paramName] = createPageParam(paramInit);
|
||||
});
|
||||
|
||||
return normalizedParams;
|
||||
}
|
||||
|
||||
getByPageTarget(target: PageTarget): RegisteredPage | null {
|
||||
return this.getItems().find(page => page.extensionId === target.extensionId && page.id === target.pageId) || null;
|
||||
}
|
||||
}
|
||||
|
||||
export class ClusterPageRegistry extends PageRegistry {}
|
||||
export class GlobalPageRegistry extends PageRegistry {}
|
||||
@@ -4,15 +4,20 @@
|
||||
*/
|
||||
import type { KubeResource } from "../../common/rbac";
|
||||
import isAllowedResourceInjectable from "../../common/utils/is-allowed-resource.injectable";
|
||||
import { asLegacyGlobalFunctionForExtensionApi } from "../as-legacy-globals-for-extension-api/as-legacy-global-function-for-extension-api";
|
||||
import { castArray } from "lodash/fp";
|
||||
import { getLegacyGlobalDiForExtensionApi } from "../as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
|
||||
|
||||
export function isAllowedResource(resource: KubeResource | KubeResource[]) {
|
||||
const _isAllowedResource = asLegacyGlobalFunctionForExtensionApi(isAllowedResourceInjectable);
|
||||
|
||||
const resources = castArray(resource);
|
||||
|
||||
return resources.every(x => _isAllowedResource(x));
|
||||
const di = getLegacyGlobalDiForExtensionApi();
|
||||
|
||||
return resources.every((resourceName: any) => {
|
||||
const _isAllowedResource = di.inject(isAllowedResourceInjectable, resourceName);
|
||||
|
||||
// Note: Legacy isAllowedResource does not advertise reactivity
|
||||
return _isAllowedResource.get();
|
||||
});
|
||||
}
|
||||
|
||||
export { ResourceStack } from "../../common/k8s/resource-stack";
|
||||
|
||||
Reference in new issue
Block a user