github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/infra/logid/logid_test.go (about) 1 package logid 2 3 import ( 4 "runtime" 5 "sort" 6 "sync" 7 "sync/atomic" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 func TestDefault(t *testing.T) { 14 id1 := Gen() 15 assert.Len(t, id1, v1Length) 16 17 SetDefault(NewV2Gen(nil)) 18 defer SetDefault(NewV1Gen()) 19 id2 := Gen() 20 assert.Len(t, id2, v2IPv4Length) 21 } 22 23 func Test_encodeBase32(t *testing.T) { 24 for i := 0; i < 1000; i++ { 25 var buf = make([]byte, 10) 26 x := rand50bits() 27 encodeBase32(buf, x) 28 got, err := decodeBase32(string(buf)) 29 assert.Nil(t, err) 30 assert.Equal(t, x&mask50bits, got) 31 } 32 } 33 34 func TestUniqueness(t *testing.T) { 35 var count int32 = -1 36 var got = make([]string, 1000) 37 38 var wg sync.WaitGroup 39 var n = runtime.GOMAXPROCS(0) 40 for j := 0; j < n; j++ { 41 wg.Add(1) 42 go func() { 43 defer wg.Done() 44 for { 45 i := atomic.AddInt32(&count, 1) 46 if int(i) < len(got) { 47 got[i] = Gen() 48 continue 49 } 50 break 51 } 52 }() 53 } 54 wg.Wait() 55 56 sort.Strings(got) 57 dupCount := 0 58 for i := 0; i < len(got)-1; i++ { 59 if got[i] == got[i+1] { 60 dupCount++ 61 } 62 } 63 assert.True(t, dupCount < 2) 64 }