Skip to content

Commit cf6c628

Browse files
committed
Fix bugs in programatic cluster config. Add unit test.
1 parent b9a90a5 commit cf6c628

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/config.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ export class KubeConfig {
5353
*/
5454
public 'currentContext': string;
5555

56+
constructor() {
57+
this.contexts = [];
58+
this.clusters = [];
59+
this.users = [];
60+
}
61+
5662
public getContexts() {
5763
return this.contexts;
5864
}
@@ -224,6 +230,9 @@ export class KubeConfig {
224230
}
225231

226232
public addCluster(cluster: Cluster) {
233+
if (!this.clusters) {
234+
this.clusters = [];
235+
}
227236
this.clusters.forEach((c: Cluster, ix: number) => {
228237
if (c.name === cluster.name) {
229238
throw new Error(`Duplicate cluster: ${c.name}`);
@@ -233,6 +242,9 @@ export class KubeConfig {
233242
}
234243

235244
public addUser(user: User) {
245+
if (!this.users) {
246+
this.users = [];
247+
}
236248
this.users.forEach((c: User, ix: number) => {
237249
if (c.name === user.name) {
238250
throw new Error(`Duplicate user: ${c.name}`);
@@ -242,6 +254,9 @@ export class KubeConfig {
242254
}
243255

244256
public addContext(ctx: Context) {
257+
if (!this.contexts) {
258+
this.contexts = [];
259+
}
245260
this.contexts.forEach((c: Context, ix: number) => {
246261
if (c.name === ctx.name) {
247262
throw new Error(`Duplicate context: ${c.name}`);

src/config_test.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1123,6 +1123,31 @@ describe('KubeConfig', () => {
11231123
});
11241124
});
11251125

1126+
describe('Programmatic', () => {
1127+
it('should be able to generate a valid config from code', () => {
1128+
const kc = new KubeConfig();
1129+
kc.addCluster({
1130+
name: 'testCluster',
1131+
server: `https://localhost:9889`,
1132+
skipTLSVerify: true,
1133+
});
1134+
kc.addUser({
1135+
token: 'token',
1136+
username: 'username',
1137+
name: 'testUser',
1138+
});
1139+
kc.addContext({
1140+
cluster: 'testCluster',
1141+
name: 'test',
1142+
user: 'testUser',
1143+
});
1144+
kc.setCurrentContext('test');
1145+
1146+
expect(kc.getCurrentCluster()!.name).to.equal('testCluster');
1147+
expect(kc.getCurrentUser()!.username).to.equal('username');
1148+
});
1149+
});
1150+
11261151
describe('BufferOrFile', () => {
11271152
it('should load from root if present', () => {
11281153
const data = 'some data for file';

0 commit comments

Comments
 (0)