bindbox-game/internal/pkg/utils/truncate_test.go
邹方成 a7a0f639e1 feat: 新增取消发货功能并优化任务中心
fix: 修复微信通知字段截断导致的编码错误
feat: 添加有效邀请相关字段和任务中心常量
refactor: 重构一番赏奖品格位逻辑
perf: 优化道具卡列表聚合显示
docs: 更新项目说明文档和API文档
test: 添加字符串截断工具测试
2025-12-23 22:26:07 +08:00

59 lines
1.7 KiB
Go

package utils
import (
"testing"
)
func TestTruncateRunes(t *testing.T) {
tests := []struct {
name string
input string
limit int
want string
}{
{"Short English", "hello", 10, "hello"},
{"Long English", "hello world", 5, "hello"},
{"Short Chinese", "你好世界", 10, "你好世界"},
{"Long Chinese", "你好世界", 2, "你好"},
{"Mixed", "hi你好", 3, "hi你"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := TruncateRunes(tt.input, tt.limit); got != tt.want {
t.Errorf("TruncateRunes() = %v, want %v", got, tt.want)
}
})
}
}
func TestTruncateBytes(t *testing.T) {
tests := []struct {
name string
input string
limit int
want string
}{
{"Short English", "hello", 10, "hello"},
{"Long English", "hello world", 5, "hello"},
{"Chinese Exact", "你好", 6, "你好"}, // 3+3=6
{"Chinese Cut", "你好", 5, "你"}, // 3+3=6 > 5, cut to 3
{"Chinese Cut 2", "你好", 4, "你"}, // 3+3=6 > 4, cut to 3
{"Chinese Cut 3", "你好", 2, ""}, // 3 > 2, cut to 0
{"Mixed", "hi你好", 4, "hi"}, // 1+1+3=5 > 4, cut to 2
{"Mixed 2", "hi你好", 5, "hi你"}, // 1+1+3=5 <= 5
{"Log Case", "名创优品 O20251223131406 盲盒赏品: MINISO名创优品U型枕飞机云朵护颈枕记忆棉", 40, "名创优品 O20251223131406 盲盒赏"}, // Correctly truncates before "品"
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := TruncateBytes(tt.input, tt.limit)
if got != tt.want {
t.Errorf("TruncateBytes(%q, %d) = %q, want %q", tt.input, tt.limit, got, tt.want)
}
// Verify valid utf8
if len(got) > tt.limit {
t.Errorf("Length %d > limit %d", len(got), tt.limit)
}
})
}
}