Skip to content

Commit

Permalink
fix: fix RandomName's dash when no prefix provided
Browse files Browse the repository at this point in the history
  • Loading branch information
pmalek committed Sep 29, 2023
1 parent 10a58fc commit 667b3ba
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
7 changes: 4 additions & 3 deletions pkg/envconf/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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]
}
20 changes: 20 additions & 0 deletions pkg/envconf/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ package envconf

import (
"flag"
"math/rand"
"os"
"strings"
"testing"
)

Expand Down Expand Up @@ -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)
}
})
}

0 comments on commit 667b3ba

Please sign in to comment.