github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/twinj/uuid/saver_test.go (about) 1 package uuid 2 3 /**************** 4 * Date: 21/06/15 5 * Time: 6:46 PM 6 ***************/ 7 8 import ( 9 "sync" 10 "sync/atomic" 11 "testing" 12 "time" 13 ) 14 15 const ( 16 saveDuration time.Duration = 3 17 ) 18 19 var ( 20 config = StateSaverConfig{SaveReport: true, SaveSchedule: saveDuration * time.Second} 21 ) 22 23 func init() { 24 SetupFileSystemStateSaver(config) 25 } 26 27 // Tests that the schedule is run on the timeDuration 28 func TestUUID_State_saveSchedule(t *testing.T) { 29 30 if state.saver != nil { 31 count := 0 32 33 now := time.Now() 34 state.next = timestamp() + Timestamp(config.SaveSchedule/100) 35 36 for i := 0; i < 20000; i++ { 37 if timestamp() >= state.next { 38 count++ 39 } 40 NewV1() 41 time.Sleep(1 * time.Millisecond) 42 } 43 d := time.Since(now) 44 timesSaved := int(d.Seconds()) / int(saveDuration) 45 if count != timesSaved { 46 t.Errorf("Should be as many saves as %d second increments but got: %d instead of %d", saveDuration, count, timesSaved) 47 } 48 } 49 } 50 51 // Tests that the schedule saves properly when uuid are called in go routines 52 func TestUUID_State_saveScheduleGo(t *testing.T) { 53 54 if state.saver != nil { 55 56 size := 5000 57 ids := make([]UUID, size) 58 59 var wg sync.WaitGroup 60 wg.Add(size) 61 62 var count int32 63 mutex := &sync.Mutex{} 64 65 now := time.Now() 66 state.next = timestamp() + Timestamp(config.SaveSchedule/100) 67 68 for i := 0; i < size; i++ { 69 go func(index int) { 70 defer wg.Done() 71 if timestamp() >= state.next { 72 atomic.AddInt32(&count, 1) 73 } 74 u := NewV1() 75 mutex.Lock() 76 ids[index] = u 77 mutex.Unlock() 78 time.Sleep(100 * time.Nanosecond) 79 }(i) 80 } 81 wg.Wait() 82 duration := time.Since(now) 83 84 for j := size - 1; j >= 0; j-- { 85 for k := 0; k < size; k++ { 86 if k == j { 87 continue 88 } 89 if Equal(ids[j], ids[k]) { 90 t.Error("Should not create the same V1 UUID", ids[k], ids[j]) 91 } 92 } 93 } 94 95 timesSaved := int(duration.Seconds()) / int(saveDuration) 96 if int(count) != timesSaved { 97 t.Errorf("Should be as many saves as %d second increments but got: %d instead of %d", saveDuration, count, timesSaved) 98 } 99 } 100 }