From 8d05ad46c91bf091b1c8bc86b6ae4988947d9bef Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 8 Dec 2023 08:34:04 +0100 Subject: [PATCH] do not truncate wlid if namespace is empty, use string builder Signed-off-by: Matthias Bertschy --- wlid/wlid.go | 27 +++++++++++++++----------- wlid/wlid_test.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 11 deletions(-) diff --git a/wlid/wlid.go b/wlid/wlid.go index ccfb63b..264fc49 100644 --- a/wlid/wlid.go +++ b/wlid/wlid.go @@ -81,24 +81,29 @@ func generateWLID(pLevel0, level0, pLevel1, level1, k, name string) string { kind := strings.ToLower(k) kind = strings.Replace(kind, "-", "", -1) - wlid := WlidPrefix - wlid += fmt.Sprintf("%s%s", pLevel0, level0) - if level1 == "" { - return wlid - } - wlid += fmt.Sprintf("/%s%s", pLevel1, level1) + var wlid strings.Builder + wlid.WriteString(WlidPrefix) + wlid.WriteString(pLevel0) + wlid.WriteString(level0) + + // don't exit if level1 is empty + wlid.WriteString("/") + wlid.WriteString(pLevel1) + wlid.WriteString(level1) if kind == "" { - return wlid + return wlid.String() } - wlid += fmt.Sprintf("/%s", kind) + wlid.WriteString("/") + wlid.WriteString(kind) if name == "" { - return wlid + return wlid.String() } - wlid += fmt.Sprintf("-%s", name) + wlid.WriteString("-") + wlid.WriteString(name) - return wlid + return wlid.String() } // GetWLID get the calculated wlid diff --git a/wlid/wlid_test.go b/wlid/wlid_test.go index e9f86ec..df36eb7 100644 --- a/wlid/wlid_test.go +++ b/wlid/wlid_test.go @@ -1,6 +1,7 @@ package wlid import ( + "github.com/stretchr/testify/assert" "testing" ) @@ -27,3 +28,51 @@ func TestSpiffeSIDInfoSuccess(t *testing.T) { t.Errorf("TestSpiffeSIDInfoSuccess failed to parse %v", SID) } } + +func Test_generateWLID(t *testing.T) { + type args struct { + pLevel0 string + level0 string + pLevel1 string + level1 string + k string + name string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "k8s wlid", + args: args{ + pLevel0: ClusterWlidPrefix, + level0: "HipsterShopCluster2", + pLevel1: NamespaceWlidPrefix, + level1: "prod", + k: "Deployment", + name: "cartservice", + }, + want: "wlid://cluster-HipsterShopCluster2/namespace-prod/deployment-cartservice", + }, + { + name: "k8s wlid no namespace", + args: args{ + pLevel0: ClusterWlidPrefix, + level0: "HipsterShopCluster2", + pLevel1: NamespaceWlidPrefix, + level1: "", + k: "ClusterRoleBinding", + name: "cartservice", + }, + want: "wlid://cluster-HipsterShopCluster2/namespace-/clusterrolebinding-cartservice", + // FIXME: do we want "wlid://cluster-HipsterShopCluster2/clusterrolebinding-cartservice" instead? + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := generateWLID(tt.args.pLevel0, tt.args.level0, tt.args.pLevel1, tt.args.level1, tt.args.k, tt.args.name) + assert.Equal(t, tt.want, got) + }) + } +}