From 667b3bab8c1bc5da9d605032c6f5800f76b79064 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patryk=20Ma=C5=82ek?= Date: Fri, 29 Sep 2023 20:49:51 +0200 Subject: [PATCH] fix: fix RandomName's dash when no prefix provided --- pkg/envconf/config.go | 7 ++++--- pkg/envconf/config_test.go | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/pkg/envconf/config.go b/pkg/envconf/config.go index 1534c564..5a4cb7bf 100644 --- a/pkg/envconf/config.go +++ b/pkg/envconf/config.go @@ -17,11 +17,10 @@ limitations under the License. package envconf import ( + "crypto/rand" "encoding/hex" "fmt" - "math/rand" "regexp" - "time" log "k8s.io/klog/v2" @@ -300,8 +299,10 @@ func RandomName(prefix string, n int) string { if len(prefix) >= n { return prefix } - rand.Seed(time.Now().UnixNano()) p := make([]byte, n) rand.Read(p) + if len(prefix) == 0 { + return hex.EncodeToString(p)[:n] + } return fmt.Sprintf("%s-%s", prefix, hex.EncodeToString(p))[:n] } diff --git a/pkg/envconf/config_test.go b/pkg/envconf/config_test.go index 5da18c64..9d579b97 100644 --- a/pkg/envconf/config_test.go +++ b/pkg/envconf/config_test.go @@ -18,7 +18,9 @@ package envconf import ( "flag" + "math/rand" "os" + "strings" "testing" ) @@ -85,3 +87,21 @@ func TestConfig_New_WithIgnorePanicRecovery(t *testing.T) { t.Error("expected ignore-panic-recovery mode to be enabled when -disable-graceful-teardown argument is passed") } } + +func TestRandomName(t *testing.T) { + const maxLen = 64 + + t.Run("no prefix yields random name without dash", func(t *testing.T) { + out := RandomName("", int(rand.Int31n(maxLen))) + if strings.Contains(out, "-") { + t.Errorf("random name %q shouldn't contain a dash when no prefix provided", out) + } + }) + + t.Run("non empty prefix yields random name with dash", func(t *testing.T) { + out := RandomName("abc", int(rand.Int31n(maxLen))) + if !strings.Contains(out, "-") { + t.Errorf("random name %q should contain a dash when prefix provided", out) + } + }) +}