Making apiBase injectable (#6022)

* Making apiBase injectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Convert all of Helm functions to be DI

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Make PortForward's use of apiBase fully injectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Convert all metric requests to be injectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Replace resource applier with injectables

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Switch KubeJsonApi.forCluster to be injectable but do not use

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Convert the rest of shell sessions to be DI-ed

- This is a prerequesit for using the new
  createKubeJsonApiForClusterInjectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Use new createKubeJsonApiForClusterInjectable for openNodeShellSession

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Make KubeconfigDialog injectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Remove jest-fetch-mock and make fetch injectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix tests with new global override

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Add new injectable for create KubeJsonApi and JsonApi instances

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix showing-details-for-helm-release behavioural tests

- Remove HelmChartStore in favour of all injectables

- Create a model for UpgradeChartDockTab

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix show details and updating helm releases tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix residual typing issues related to metrics

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix crash on load due to circular dependency

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix create resource tab not working

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Remove legacy apiBase global

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Introduce and use isDebuggingInjectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Introduce and use windowLocationInjectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Remove global legacy apiKube

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Improve injectable filenames compared to the injectables inside

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Remove modifying input in requestActivePortForwardInjectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Introduce and use get(Milli)SecondsFromUnixEpochInjectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Switch to non-reactive way of gettting possible helm release versions

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix typo

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix bug in KubeApi constructor

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Convert all KubeApi related tests to use asyncFn

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix unit tests after introducing new injectables that have side effects

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix bad rebase causing tests to fail

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Improve expects for multiple field values

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix crash will looking up api refs

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix breaking change on KubeApi.list

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Better fix for formatting urls

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Remove injectable for time since we should just use useMockTime

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Add happy path behavioural tests for upgrade chart tab

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Remove debug message

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Update snapshots

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* fix showing-details-for-helm-release tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix installing-helm-chart-from-new-tab tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix tests relating to hosted cluster id

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Update snapshots to recent changes in master

Co-authored-by: Janne Savolainen <janne.savolainen@live.fi>

Signed-off-by: Iku-turso <mikko.aspiala@gmail.com>

* Reupdated upgrade chart new tab test snapshots

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix flakiness in unit test when using <Animated>

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix flakiness and improve tests for DeleteClusterDialog

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix kubeconfig-sync tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix <Extensions> tests by removing mockFs and making everything injectable

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix build issues

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix getElectronAppPathInjectable override not returning absolute paths

- Also fixes the listing-active-helm-repos-in-prefs tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Replace all uses of getAbsolutePath with joinPaths as it is more correct and less confusing

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix opening application window tests by making override properly absolute

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Update snapshots relating no longer using getAbsolutePath

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix and add behavioural tests for RenderDelay

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix extension discovery tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix test flakiness because of path side effects, propagate uses to as many places

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix extension-discovery tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Add global override to fix some tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Rewrite and fix implementation of KubeconfigManager and its tests

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix tests by global override pathExists

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix unit tests failing on windows by using injectable verions of path functions

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Attempt to fix test timeout by using runInAction

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Update snapshots after rebase

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Update snapshots after rebase

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix tests after rebase

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Fix setupIpcMainHandlers usage

Signed-off-by: Sebastian Malton <sebastian@malton.name>

* Update snapshots

Signed-off-by: Sebastian Malton <sebastian@malton.name>

Signed-off-by: Sebastian Malton <sebastian@malton.name>
Signed-off-by: Iku-turso <mikko.aspiala@gmail.com>
Co-authored-by: Iku-turso <mikko.aspiala@gmail.com>
This commit is contained in:
authored and GitHub committed 2022-10-05 08:10:36 -04:00
1 parent ed073d6562
commit 76066c5ebf
367 files changed
+16701 -5302

No files matched your search

+231 -62
View File
@@ -4,12 +4,7 @@
*/
import { getDiForUnitTesting } from "../getDiForUnitTesting";
import { KubeconfigManager } from "../kubeconfig-manager/kubeconfig-manager";
import mockFs from "mock-fs";
import type { Cluster } from "../../common/cluster/cluster";
import fse from "fs-extra";
import { loadYaml } from "@kubernetes/client-node";
import { Console } from "console";
import * as path from "path";
import createKubeconfigManagerInjectable from "../kubeconfig-manager/create-kubeconfig-manager.injectable";
import { createClusterInjectionToken } from "../../common/cluster/create-cluster-injection-token";
import directoryForTempInjectable from "../../common/app-paths/directory-for-temp/directory-for-temp.injectable";
@@ -18,31 +13,53 @@ import type { DiContainer } from "@ogre-tools/injectable";
import { parse } from "url";
import loggerInjectable from "../../common/logger.injectable";
import type { Logger } from "../../common/logger";
import assert from "assert";
import directoryForUserDataInjectable from "../../common/app-paths/directory-for-user-data/directory-for-user-data.injectable";
import normalizedPlatformInjectable from "../../common/vars/normalized-platform.injectable";
import kubectlBinaryNameInjectable from "../kubectl/binary-name.injectable";
import kubectlDownloadingNormalizedArchInjectable from "../kubectl/normalized-arch.injectable";
console = new Console(process.stdout, process.stderr); // fix mockFS
import type { ReadFile } from "../../common/fs/read-file.injectable";
import readFileInjectable from "../../common/fs/read-file.injectable";
import type { AsyncFnMock } from "@async-fn/jest";
import asyncFn from "@async-fn/jest";
import type { WriteFile } from "../../common/fs/write-file.injectable";
import writeFileInjectable from "../../common/fs/write-file.injectable";
import type { PathExists } from "../../common/fs/path-exists.injectable";
import pathExistsInjectable from "../../common/fs/path-exists.injectable";
import type { DeleteFile } from "../../common/fs/delete-file.injectable";
import deleteFileInjectable from "../../common/fs/delete-file.injectable";
const clusterServerUrl = "https://192.168.64.3:8443";
describe("kubeconfig manager tests", () => {
let clusterFake: Cluster;
let createKubeconfigManager: (cluster: Cluster) => KubeconfigManager | undefined;
let createKubeconfigManager: (cluster: Cluster) => KubeconfigManager;
let di: DiContainer;
let loggerMock: jest.Mocked<Logger>;
let readFileMock: AsyncFnMock<ReadFile>;
let deleteFileMock: AsyncFnMock<DeleteFile>;
let writeFileMock: AsyncFnMock<WriteFile>;
let pathExistsMock: AsyncFnMock<PathExists>;
let kubeConfManager: KubeconfigManager;
let ensureServerMock: AsyncFnMock<() => Promise<void>>;
beforeEach(async () => {
di = getDiForUnitTesting({ doGeneralOverrides: true });
di.override(directoryForTempInjectable, () => "some-directory-for-temp");
di.override(directoryForUserDataInjectable, () => "some-directory-for-user-data");
di.override(directoryForTempInjectable, () => "/some-directory-for-temp");
di.override(directoryForUserDataInjectable, () => "/some-directory-for-user-data");
di.override(kubectlBinaryNameInjectable, () => "kubectl");
di.override(kubectlDownloadingNormalizedArchInjectable, () => "amd64");
di.override(normalizedPlatformInjectable, () => "darwin");
readFileMock = asyncFn();
di.override(readFileInjectable, () => readFileMock);
writeFileMock = asyncFn();
di.override(writeFileInjectable, () => writeFileMock);
pathExistsMock = asyncFn();
di.override(pathExistsInjectable, () => pathExistsMock);
deleteFileMock = asyncFn();
di.override(deleteFileInjectable, () => deleteFileMock);
loggerMock = {
warn: jest.fn(),
debug: jest.fn(),
@@ -53,29 +70,7 @@ describe("kubeconfig manager tests", () => {
di.override(loggerInjectable, () => loggerMock);
mockFs({
"minikube-config.yml": JSON.stringify({
apiVersion: "v1",
clusters: [{
name: "minikube",
cluster: {
server: clusterServerUrl,
},
}],
contexts: [{
context: {
cluster: "minikube",
user: "minikube",
},
name: "minikube",
}],
users: [{
name: "minikube",
}],
kind: "Config",
preferences: {},
}),
});
ensureServerMock = asyncFn();
di.override(createContextHandlerInjectable, () => (cluster) => ({
restartServer: jest.fn(),
@@ -86,7 +81,7 @@ describe("kubeconfig manager tests", () => {
resolveAuthProxyCa: jest.fn(),
resolveAuthProxyUrl: jest.fn(),
setupPrometheus: jest.fn(),
ensureServer: jest.fn(),
ensureServer: ensureServerMock,
}));
const createCluster = di.inject(createClusterInjectionToken);
@@ -96,48 +91,222 @@ describe("kubeconfig manager tests", () => {
clusterFake = createCluster({
id: "foo",
contextName: "minikube",
kubeConfigPath: "minikube-config.yml",
kubeConfigPath: "/minikube-config.yml",
}, {
clusterServerUrl,
});
jest.spyOn(KubeconfigManager.prototype, "resolveProxyUrl", "get").mockReturnValue("http://127.0.0.1:9191/foo");
kubeConfManager = createKubeconfigManager(clusterFake);
});
afterEach(() => {
mockFs.restore();
describe("when calling clear", () => {
it("should resolve immediately", async () => {
await kubeConfManager.clear();
});
it("being called several times shouldn't throw", async () => {
await kubeConfManager.clear();
await kubeConfManager.clear();
await kubeConfManager.clear();
});
});
it("should create 'temp' kube config with proxy", async () => {
const kubeConfManager = createKubeconfigManager(clusterFake);
describe("when getPath() is called initially", () => {
let getPathPromise: Promise<string>;
assert(kubeConfManager, "should actually create one");
beforeEach(async () => {
getPathPromise = kubeConfManager.getPath();
});
expect(loggerMock.error).not.toBeCalled();
expect(await kubeConfManager.getPath()).toBe(`some-directory-for-temp${path.sep}kubeconfig-foo`);
// this causes an intermittent "ENXIO: no such device or address, read" error
// const file = await fse.readFile(await kubeConfManager.getPath());
const file = fse.readFileSync(await kubeConfManager.getPath());
const yml = loadYaml<any>(file.toString());
it("should not call pathExists()", () => {
expect(pathExistsMock).not.toBeCalled();
});
expect(yml["current-context"]).toBe("minikube");
expect(yml["clusters"][0]["cluster"]["server"].endsWith("/foo")).toBe(true);
expect(yml["users"][0]["name"]).toBe("proxy");
});
it("should call ensureServer on the cluster context", () => {
expect(ensureServerMock).toBeCalledTimes(1);
});
it("should remove 'temp' kube config on unlink and remove reference from inside class", async () => {
const kubeConfManager = createKubeconfigManager(clusterFake);
describe("when ensureServer resolves", () => {
beforeEach(async () => {
await ensureServerMock.resolve();
assert(kubeConfManager, "should actually create one");
// clear state of calls
ensureServerMock.mock.calls.length = 0;
});
const configPath = await kubeConfManager.getPath();
describe("when reading cluster's kubeconfig resolves", () => {
beforeEach(async () => {
await readFileMock.resolveSpecific(
["/minikube-config.yml"],
JSON.stringify({
apiVersion: "v1",
clusters: [{
name: "minikube",
cluster: {
server: clusterServerUrl,
},
}],
contexts: [{
context: {
cluster: "minikube",
user: "minikube",
},
name: "minikube",
}],
users: [{
name: "minikube",
}],
kind: "Config",
preferences: {},
}),
);
});
expect(await fse.pathExists(configPath)).toBe(true);
await kubeConfManager.clear();
expect(await fse.pathExists(configPath)).toBe(false);
await kubeConfManager.clear(); // doesn't throw
expect(async () => {
await kubeConfManager.getPath();
}).rejects.toThrow("already unlinked");
describe("when writing out new proxy kubeconfig resolves", () => {
beforeEach(async () => {
await writeFileMock.resolveSpecific(
["/some-directory-for-temp/kubeconfig-foo", "apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: minikube\nclusters:\n - name: minikube\n cluster:\n server: http://127.0.0.1:9191/foo\ncontexts:\n - name: minikube\n context:\n cluster: minikube\n user: proxy\nusers:\n - name: proxy\n user: {}\n"],
);
});
it("should allow getPath to resolve with the path to the kubeconfig", async () => {
expect(await getPathPromise).toBe("/some-directory-for-temp/kubeconfig-foo");
});
describe("when calling clear", () => {
let clearPromise: Promise<void>;
beforeEach(() => {
clearPromise = kubeConfManager.clear();
});
it("should call deleteFile", () => {
expect(deleteFileMock).toBeCalledTimes(1);
});
describe("when deleteFile resolves", () => {
beforeEach(async () => {
await deleteFileMock.resolveSpecific(
["/some-directory-for-temp/kubeconfig-foo"],
);
});
it("should allow clear to resolve", async () => {
await clearPromise;
});
});
describe("when deleteFile rejects with ENOENT", () => {
beforeEach(async () => {
await deleteFileMock.resolveSpecific(
["/some-directory-for-temp/kubeconfig-foo"],
Promise.reject(Object.assign(new Error("file not found"), {
code: "ENOENT",
})),
);
});
it("should allow clear to resolve", async () => {
await clearPromise;
});
});
it("when deleteFile rejects with some other error; clear should also reject", async () => {
const expectPromise = expect(clearPromise).rejects.toBeDefined();
await deleteFileMock.reject(new Error("some other error"));
await expectPromise;
});
});
describe("when calling getPath a second time", () => {
let getPathPromise: Promise<string>;
beforeEach(async () => {
getPathPromise = kubeConfManager.getPath();
});
it("should call pathExists", () => {
expect(pathExistsMock).toBeCalledTimes(1);
});
describe("when pathExists resoves to true", () => {
beforeEach(async () => {
await pathExistsMock.resolveSpecific(
["/some-directory-for-temp/kubeconfig-foo"],
true,
);
});
it("always getPath to resolve with path", async () => {
expect(await getPathPromise).toBe("/some-directory-for-temp/kubeconfig-foo");
});
});
describe("when pathExists resoves to false", () => {
beforeEach(async () => {
await pathExistsMock.resolveSpecific(
["/some-directory-for-temp/kubeconfig-foo"],
false,
);
});
it("should call ensureServer on the cluster context", () => {
expect(ensureServerMock).toBeCalledTimes(1);
});
describe("when ensureServer resolves", () => {
beforeEach(async () => {
await ensureServerMock.resolve();
});
describe("when reading cluster's kubeconfig resolves", () => {
beforeEach(async () => {
await readFileMock.resolveSpecific(
["/minikube-config.yml"],
JSON.stringify({
apiVersion: "v1",
clusters: [{
name: "minikube",
cluster: {
server: clusterServerUrl,
},
}],
contexts: [{
context: {
cluster: "minikube",
user: "minikube",
},
name: "minikube",
}],
users: [{
name: "minikube",
}],
kind: "Config",
preferences: {},
}),
);
});
describe("when writing out new proxy kubeconfig resolves", () => {
beforeEach(async () => {
await writeFileMock.resolveSpecific(
["/some-directory-for-temp/kubeconfig-foo", "apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: minikube\nclusters:\n - name: minikube\n cluster:\n server: http://127.0.0.1:9191/foo\ncontexts:\n - name: minikube\n context:\n cluster: minikube\n user: proxy\nusers:\n - name: proxy\n user: {}\n"],
);
});
it("should allow getPath to resolve with the path to the kubeconfig", async () => {
expect(await getPathPromise).toBe("/some-directory-for-temp/kubeconfig-foo");
});
});
});
});
});
});
});
});
});
});
});