This commit is contained in:
toom1996
2026-08-26 10:45:21 +08:00
parent 3cf1368e68
commit 30c9f21da4
48 changed files with 3442 additions and 0 deletions

View File

@ -0,0 +1,42 @@
package hashid
import "testing"
func TestRoundtrip(t *testing.T) {
// 覆盖边界与大量随机值,验证 Decode(Encode(n)) == n 严格成立
cases := []uint32{0, 1, 2, 3, 7, 15, 16, 255, 256, 4095, 4096, 65535, 65536, 1 << 31, (1 << 32) - 1}
for _, n := range cases {
got, err := Decode(Encode(n))
if err != nil {
t.Fatalf("Decode(Encode(%d)) 返回错误: %v", n, err)
}
if got != n {
t.Fatalf("往返不一致: 输入 %d, 得到 %d", n, got)
}
}
// 随机大批量
for n := uint32(1); n < 5000; n++ {
got, err := Decode(Encode(n))
if err != nil || got != n {
t.Fatalf("往返不一致: 输入 %d, 得到 %d (err=%v)", n, got, err)
}
}
}
func TestNonSequential(t *testing.T) {
Init("test-salt")
a, b, c := Encode(100), Encode(101), Encode(102)
if a == b || b == c || a == c {
t.Fatalf("相邻 id 编码结果出现了相等: %s %s %s", a, b, c)
}
}
func TestInvalid(t *testing.T) {
if _, err := Decode(""); err == nil {
t.Fatal("空串应返回错误")
}
if _, err := Decode("!!!"); err == nil {
t.Fatal("含非法字符应返回错误")
}
}