From cf6c6283a513fff096fc08b849f0f8f85f814697 Mon Sep 17 00:00:00 2001 From: Brendan Burns Date: Thu, 14 Nov 2019 21:34:46 -0800 Subject: [PATCH] Fix bugs in programatic cluster config. Add unit test. --- src/config.ts | 15 +++++++++++++++ src/config_test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/config.ts b/src/config.ts index 5e13ccc354..db7633a03a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -53,6 +53,12 @@ export class KubeConfig { */ public 'currentContext': string; + constructor() { + this.contexts = []; + this.clusters = []; + this.users = []; + } + public getContexts() { return this.contexts; } @@ -224,6 +230,9 @@ export class KubeConfig { } public addCluster(cluster: Cluster) { + if (!this.clusters) { + this.clusters = []; + } this.clusters.forEach((c: Cluster, ix: number) => { if (c.name === cluster.name) { throw new Error(`Duplicate cluster: ${c.name}`); @@ -233,6 +242,9 @@ export class KubeConfig { } public addUser(user: User) { + if (!this.users) { + this.users = []; + } this.users.forEach((c: User, ix: number) => { if (c.name === user.name) { throw new Error(`Duplicate user: ${c.name}`); @@ -242,6 +254,9 @@ export class KubeConfig { } public addContext(ctx: Context) { + if (!this.contexts) { + this.contexts = []; + } this.contexts.forEach((c: Context, ix: number) => { if (c.name === ctx.name) { throw new Error(`Duplicate context: ${c.name}`); diff --git a/src/config_test.ts b/src/config_test.ts index bffe24eabd..71b1141a2a 100644 --- a/src/config_test.ts +++ b/src/config_test.ts @@ -1123,6 +1123,31 @@ describe('KubeConfig', () => { }); }); + describe('Programmatic', () => { + it('should be able to generate a valid config from code', () => { + const kc = new KubeConfig(); + kc.addCluster({ + name: 'testCluster', + server: `https://localhost:9889`, + skipTLSVerify: true, + }); + kc.addUser({ + token: 'token', + username: 'username', + name: 'testUser', + }); + kc.addContext({ + cluster: 'testCluster', + name: 'test', + user: 'testUser', + }); + kc.setCurrentContext('test'); + + expect(kc.getCurrentCluster()!.name).to.equal('testCluster'); + expect(kc.getCurrentUser()!.username).to.equal('username'); + }); + }); + describe('BufferOrFile', () => { it('should load from root if present', () => { const data = 'some data for file';