github.com/coyove/common@v0.0.0-20240403014525-f70e643f9de8/waitobject/wait_test.go (about) 1 package waitobject 2 3 import ( 4 "fmt" 5 "sync/atomic" 6 "testing" 7 "time" 8 ) 9 10 func I(i int) func(interface{}) interface{} { return func(interface{}) interface{} { return i } } 11 12 func TestObjectTimeout(t *testing.T) { 13 debug = true 14 o := New() 15 o.SetWaitDeadline(time.Now().Add(time.Second)) 16 _, ok := o.Wait() 17 if ok { 18 t.FailNow() 19 } 20 } 21 22 func TestObjectTimeout2(t *testing.T) { 23 debug = true 24 o := New() 25 start := time.Now() 26 27 go func() { 28 time.Sleep(time.Second) 29 o.SetWaitDeadline(time.Now()) 30 time.Sleep(time.Second) 31 o.Touch(I(1)) 32 }() 33 34 _, ok := o.Wait() 35 if ok { 36 t.FailNow() 37 } 38 39 if time.Since(start).Seconds() < 1 { 40 t.FailNow() 41 } 42 43 _, ok = o.Wait() 44 if ok { 45 t.FailNow() 46 } 47 48 o.SetWaitDeadline(time.Time{}) 49 v, _ := o.Wait() 50 if v.(int) != 1 { 51 t.FailNow() 52 } 53 } 54 55 func TestObjectTimeout3(t *testing.T) { 56 o := New() 57 go func() { 58 for i := 0; i < 5; i++ { 59 time.Sleep(time.Second * 2) 60 o.Touch(I(i)) 61 } 62 }() 63 o.SetWaitDeadline(time.Now().Add(time.Second * 5)) 64 for { 65 v, ok := o.Wait() 66 if !ok { 67 break 68 } 69 fmt.Println("a", v) 70 // 0, 1 71 } 72 if _, ok := o.Wait(); ok { 73 t.FailNow() 74 } 75 76 // wait more than 1 sec to omit '2' 77 time.Sleep(time.Second + 200*time.Millisecond) 78 o.SetWaitDeadline(time.Time{}) 79 for { 80 v, ok := o.Wait() 81 if !ok { 82 break 83 } 84 fmt.Println("b", v) 85 // 3, 4 86 if v.(int) == 4 { 87 o.SetWaitDeadline(time.Now()) 88 } 89 } 90 } 91 92 func TestObjectTimeoutThenRead(t *testing.T) { 93 debug = true 94 o := New() 95 go func() { 96 time.Sleep(1000 * time.Millisecond) 97 o.Touch(I(1)) 98 time.Sleep(3000 * time.Millisecond) 99 o.Touch(I(2)) 100 }() 101 o.SetWaitDeadline(time.Now().Add(time.Second * 2)) 102 v, _ := o.Wait() 103 if v.(int) != 1 { 104 t.FailNow() 105 } 106 time.Sleep(time.Second) 107 o.SetWaitDeadline(time.Time{}) 108 v, _ = o.Wait() 109 if v.(int) != 2 { 110 t.FailNow() 111 } 112 } 113 114 func TestObject(t *testing.T) { 115 o := New() 116 o.Touch(I(2)) 117 118 go func() { 119 time.Sleep(time.Second) 120 o.Touch(I(1)) 121 }() 122 123 var count uint64 124 for i := 0; i < 10; i++ { 125 go func() { 126 v, _ := o.Wait() 127 if v.(int) != 1 { 128 t.FailNow() 129 } 130 atomic.AddUint64(&count, 1) 131 }() 132 } 133 134 time.Sleep(1500 * time.Millisecond) 135 if count != 10 { 136 t.FailNow() 137 } 138 }