Files
gookit-goutil/strutil/convbase_test.go
T
dualfroz d6c91f3cdd fix(strutil): return zero digit instead of empty string in base conversion
BaseConvIntByTpl returned an empty string for the value zero because its
loop condition (dec > 0) was never entered. This affected BaseConv,
Base10Conv and BaseConvInt for bases above 62, and was inconsistent with
BaseConvInt for smaller bases which correctly returned "0" via strconv.

Emit the zero digit of the target base for a zero input and guard against
an empty template.
2026-09-04 09:00:39 +02:00

99 lines
2.5 KiB
Go

package strutil_test
import (
"testing"
"github.com/gookit/goutil/strutil"
"github.com/gookit/goutil/x/assert"
)
func TestBaseConv_zero(t *testing.T) {
// Zero must convert to the zero digit of the target base, not an empty
// string. This also keeps BaseConvInt consistent across all bases: the
// strconv-backed path already returns "0" for small bases.
assert.Eq(t, "0", strutil.BaseConv("0", 10, 16))
assert.Eq(t, "0", strutil.BaseConv("0", 16, 10))
assert.Eq(t, "0", strutil.Base10Conv("0", 62))
assert.Eq(t, "0", strutil.BaseConvInt(0, 16))
assert.Eq(t, "0", strutil.BaseConvInt(0, 62))
assert.Eq(t, "0", strutil.BaseConvInt(0, 64))
assert.Eq(t, "0", strutil.BaseConvIntByTpl(0, strutil.Base64Chars))
}
func TestBaseConv(t *testing.T) {
tests := []struct {
give string
from int
to int
want string
}{
// 10 -> 16
{"123", 10, 16, "7b"},
{"7b", 16, 10, "123"},
// 10 -> 32
{"123", 10, 32, "3r"},
{"3r", 32, 10, "123"},
// 10 -> 62
{"123", 10, 62, "1Z"},
{"1Z", 62, 10, "123"},
// 10 -> 64
{"123", 10, 64, "1X"},
{"1X", 64, 10, "123"},
}
for _, tt := range tests {
t.Run(tt.give, func(t *testing.T) {
got := strutil.BaseConv(tt.give, tt.from, tt.to)
if got != tt.want {
t.Errorf("BaseConv() got = %v, want %v; give=%s", got, tt.want, tt.give)
}
})
}
assert.Eq(t, "7b", strutil.BaseConvInt(123, 16))
assert.Eq(t, "2f", strutil.BaseConvInt(123, 54))
assert.Eq(t, "1X", strutil.BaseConvInt(123, 64))
}
func TestBase10Conv(t *testing.T) {
// fmt.Println(time.Now().Format("20060102150405"))
date := "20230829194900" // seconds
t.Run("date sec", func(t *testing.T) {
base16 := strutil.Base10Conv(date, 16)
assert.Eq(t, "12665b633e94", base16)
base32 := strutil.Base10Conv(date, 32)
assert.Eq(t, "icpdm6fkk", base32)
base62 := strutil.Base10Conv(date, 62)
assert.Eq(t, "5KaR3zRW", base62)
base64 := strutil.Base10Conv(date, 64)
assert.Eq(t, "4CproPWk", base64)
})
// fmt.Println(time.Now().Format("20060102150405.000"))
msDate := "20230829195105843"
t.Run("date ms", func(t *testing.T) {
base16 := strutil.Base10Conv(msDate, 16)
assert.Eq(t, "47dfd4fbaf9633", base16)
base32 := strutil.Base10Conv(msDate, 32)
assert.Eq(t, "huvqjtqv5hj", base32)
base62 := strutil.Base10Conv(msDate, 62)
assert.Eq(t, "1uEL5LJptx", base62)
base64 := strutil.Base10Conv(msDate, 64)
assert.Eq(t, "17TZjXHVoP", base64)
})
t.Run("panic", func(t *testing.T) {
assert.Panics(t, func() {
strutil.Base10Conv("invalid", 16)
})
})
}