Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 43 additions & 3 deletions internal/strutil/random_hex_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package strutil

import (
"encoding/hex"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -12,7 +13,18 @@ func TestRandomHex(t *testing.T) {
name string
n int
wantLen int
wantErr bool
}{
{
name: "zero bytes produces empty string",
n: 0,
wantLen: 0,
},
{
name: "1 byte produces 2 hex chars",
n: 1,
wantLen: 2,
},
{
name: "16 bytes produces 32 hex chars",
n: 16,
Expand All @@ -24,21 +36,49 @@ func TestRandomHex(t *testing.T) {
wantLen: 64,
},
{
name: "1 byte produces 2 hex chars",
n: 1,
wantLen: 2,
name: "negative n returns error",
n: -1,
wantErr: true,
},
{
name: "large negative n returns error",
n: -100,
wantErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, err := RandomHex(tt.n)
if tt.wantErr {
require.Error(t, err)
assert.Empty(t, result, "result should be empty on error")
return
}
require.NoError(t, err)
assert.Len(t, result, tt.wantLen)
})
}
}

// TestRandomHex_ErrorMessageContainsSize verifies the error for negative n includes the invalid value.
func TestRandomHex_ErrorMessageContainsSize(t *testing.T) {
_, err := RandomHex(-5)
require.Error(t, err)
assert.Contains(t, err.Error(), "-5", "error message should include the invalid size")
}

// TestRandomHex_IsValidHex verifies the output is a valid lowercase hex-encoded string
// and that decoding it yields exactly n bytes.
func TestRandomHex_IsValidHex(t *testing.T) {
result, err := RandomHex(16)
require.NoError(t, err)

decoded, decodeErr := hex.DecodeString(result)
require.NoError(t, decodeErr, "result should be valid hex-encoded string")
assert.Len(t, decoded, 16, "decoded bytes should have length equal to input n")
}

func TestRandomHex_Uniqueness(t *testing.T) {
seen := make(map[string]bool)
for i := 0; i < 100; i++ {
Expand Down
Loading