github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/infra/logid/logid_v2_test.go (about) 1 package logid 2 3 import ( 4 "math" 5 "net" 6 "testing" 7 "time" 8 9 "github.com/stretchr/testify/assert" 10 ) 11 12 func TestV2Gen(t *testing.T) { 13 testIP := "10.1.2.3" 14 testV2Gen := NewV2Gen(net.ParseIP(testIP)) 15 16 now := time.Now().UnixMilli() 17 18 gotLogId := testV2Gen.Gen() 19 assert.Len(t, gotLogId, v2IPv4Length) 20 21 info := Decode(gotLogId) 22 assert.True(t, info.Valid()) 23 assert.Equal(t, byte(v2Version), info.Version()) 24 assert.True(t, math.Abs(float64(info.(V2Info).Time().UnixMilli()-now)) <= 1) 25 assert.Equal(t, testIP, info.(V2Info).IP().String()) 26 27 gotLogId2 := testV2Gen.Gen() 28 info2 := Decode(gotLogId2) 29 assert.True(t, info2.Valid()) 30 assert.NotEqual(t, info.(V2Info).Random(), info2.(V2Info).Random()) 31 32 info3 := Decode("2DAOLKWQALEKRALK") 33 assert.False(t, info3.Valid()) 34 assert.Equal(t, "0|invalid", info3.String()) 35 } 36 37 func BenchmarkV2Gen(b *testing.B) { 38 gen := NewV2Gen(nil) 39 id2 := gen.Gen() 40 41 b.Run("generate", func(b *testing.B) { 42 b.ReportAllocs() 43 for i := 0; i < b.N; i++ { 44 _ = gen.Gen() 45 } 46 }) 47 48 b.Run("decode", func(b *testing.B) { 49 b.ReportAllocs() 50 for i := 0; i < b.N; i++ { 51 _ = Decode(id2) 52 } 53 }) 54 }