github.com/benz9527/xboot@v0.0.0-20240504061247-c23f15593274/lib/id/snowflake_id_test.go (about) 1 package id 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/require" 8 9 "github.com/benz9527/xboot/lib/hrtime" 10 ) 11 12 // go test -run none -bench BenchmarkStandardSnowflake_IDGen -benchtime 3s -benchmem 13 func BenchmarkStandardSnowflake_IDGen(b *testing.B) { 14 hrtime.ClockInit() 15 idGen, err := StandardSnowFlakeID(1, 1, func() time.Time { 16 return hrtime.NowInDefaultTZ() 17 }) 18 require.NoError(b, err) 19 b.ResetTimer() 20 for i := 0; i < b.N; i++ { 21 _ = idGen() 22 } 23 b.ReportAllocs() 24 } 25 26 func TestStandardSnowflake_IDGen(t *testing.T) { 27 hrtime.ClockInit() 28 29 idGen, err := StandardSnowFlakeID(-1, 1, func() time.Time { 30 return hrtime.NowInDefaultTZ() 31 }) 32 require.Error(t, err) 33 34 idGen, err = StandardSnowFlakeID(1, -1, func() time.Time { 35 return hrtime.NowInDefaultTZ() 36 }) 37 require.Error(t, err) 38 39 idGen, err = StandardSnowFlakeID(1, 1, func() time.Time { 40 return hrtime.NowInDefaultTZ() 41 }) 42 require.NoError(t, err) 43 id1 := idGen() 44 id2 := idGen() 45 require.NotEqual(t, id1, id2) 46 } 47 48 func TestSnowFlakeID(t *testing.T) { 49 gen, err := SnowFlakeID(-1, 1, func() time.Time { 50 return time.Now() 51 }) 52 require.Error(t, err) 53 54 gen, err = SnowFlakeID(1, -1, func() time.Time { 55 return time.Now() 56 }) 57 require.Error(t, err) 58 59 gen, err = SnowFlakeID(1, 1, func() time.Time { 60 return time.Now() 61 }) 62 require.Nil(t, err) 63 for i := 0; i < 1000; i++ { 64 require.Less(t, gen.Number(), gen.Number()) 65 } 66 require.NotEqual(t, gen.Str(), gen.Str()) 67 }