github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zstring/snowflake_test.go (about)

     1  package zstring
     2  
     3  import (
     4  	"os"
     5  	"sync"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/sohaha/zlsgo"
    10  )
    11  
    12  func TestId(t *testing.T) {
    13  	var g sync.WaitGroup
    14  	var testSum = 10000
    15  	var ids = struct {
    16  		data map[int64]*interface{}
    17  		sync.RWMutex
    18  	}{
    19  		data: make(map[int64]*interface{}, testSum),
    20  	}
    21  
    22  	tt := zlsgo.NewTest(t)
    23  	w, err := NewIDWorker(0)
    24  	tt.EqualNil(err)
    25  
    26  	g.Add(testSum)
    27  	for i := 0; i < testSum; i++ {
    28  		go func(t *testing.T) {
    29  			id, err := w.ID()
    30  			tt.EqualNil(err)
    31  			ids.Lock()
    32  			if _, ok := ids.data[id]; ok {
    33  				t.Error("repeated")
    34  				os.Exit(1)
    35  			}
    36  			ids.data[id] = new(interface{})
    37  			ids.Unlock()
    38  			g.Done()
    39  		}(t)
    40  	}
    41  	g.Wait()
    42  
    43  	w, err = NewIDWorker(2)
    44  	tt.EqualNil(err)
    45  	id, _ := w.ID()
    46  	tim, ts, workerId, seq := ParseID(id)
    47  	tt.EqualNil(err)
    48  	t.Log(id, tim, ts, workerId, seq)
    49  }
    50  
    51  func TestIdWorker_timeReGen(t *testing.T) {
    52  	tt := zlsgo.NewTest(t)
    53  	w, err := NewIDWorker(0)
    54  	tt.EqualNil(err)
    55  
    56  	t.Log(w.ID())
    57  
    58  	g := w.timeGen()
    59  	now := time.Now()
    60  	reG := w.timeReGen(g + 1)
    61  	t.Log(g, reG)
    62  	v := time.Since(now).Nanoseconds()
    63  
    64  	g = w.timeGen()
    65  	now = time.Now()
    66  	reG = w.timeReGen(g)
    67  	t.Log(g, reG)
    68  
    69  	t.Log(v, time.Since(now).Nanoseconds())
    70  }