github.com/clly/consul@v1.4.5/agent/consul/session_timers_test.go (about) 1 package consul 2 3 import ( 4 "testing" 5 "time" 6 ) 7 8 func TestSessionTimers(t *testing.T) { 9 m := NewSessionTimers() 10 ch := make(chan int) 11 newTm := func(d time.Duration) *time.Timer { 12 return time.AfterFunc(d, func() { ch <- 1 }) 13 } 14 15 waitForTimer := func() { 16 select { 17 case <-ch: 18 return 19 case <-time.After(100 * time.Millisecond): 20 t.Fatal("timer did not fire") 21 } 22 } 23 24 // check that non-existent id returns nil 25 if got, want := m.Get("foo"), (*time.Timer)(nil); got != want { 26 t.Fatalf("got %v want %v", got, want) 27 } 28 29 // add a timer and look it up and delete via Set(id, nil) 30 tm := newTm(time.Millisecond) 31 m.Set("foo", tm) 32 if got, want := m.Len(), 1; got != want { 33 t.Fatalf("got len %d want %d", got, want) 34 } 35 if got, want := m.Get("foo"), tm; got != want { 36 t.Fatalf("got %v want %v", got, want) 37 } 38 m.Set("foo", nil) 39 if got, want := m.Get("foo"), (*time.Timer)(nil); got != want { 40 t.Fatalf("got %v want %v", got, want) 41 } 42 waitForTimer() 43 44 // same thing via Del(id) 45 tm = newTm(time.Millisecond) 46 m.Set("foo", tm) 47 if got, want := m.Get("foo"), tm; got != want { 48 t.Fatalf("got %v want %v", got, want) 49 } 50 m.Del("foo") 51 if got, want := m.Len(), 0; got != want { 52 t.Fatalf("got len %d want %d", got, want) 53 } 54 waitForTimer() 55 56 // create timer via ResetOrCreate 57 m.ResetOrCreate("foo", time.Millisecond, func() { ch <- 1 }) 58 if got, want := m.Len(), 1; got != want { 59 t.Fatalf("got len %d want %d", got, want) 60 } 61 waitForTimer() 62 63 // timer is still there 64 if got, want := m.Len(), 1; got != want { 65 t.Fatalf("got len %d want %d", got, want) 66 } 67 68 // reset the timer and check that it fires again 69 m.ResetOrCreate("foo", time.Millisecond, nil) 70 waitForTimer() 71 72 // reset the timer with a long ttl and then stop it 73 m.ResetOrCreate("foo", 20*time.Millisecond, func() { ch <- 1 }) 74 m.Stop("foo") 75 select { 76 case <-ch: 77 t.Fatal("timer fired although it shouldn't") 78 case <-time.After(100 * time.Millisecond): 79 // want 80 } 81 82 // stopping a stopped timer should not break 83 m.Stop("foo") 84 85 // stop should also remove the timer 86 if got, want := m.Len(), 0; got != want { 87 t.Fatalf("got len %d want %d", got, want) 88 } 89 90 // create two timers and stop and then stop all 91 m.ResetOrCreate("foo1", 20*time.Millisecond, func() { ch <- 1 }) 92 m.ResetOrCreate("foo2", 30*time.Millisecond, func() { ch <- 2 }) 93 m.StopAll() 94 select { 95 case x := <-ch: 96 t.Fatalf("timer %d fired although it shouldn't", x) 97 case <-time.After(100 * time.Millisecond): 98 // want 99 } 100 101 // stopall should remove all timers 102 if got, want := m.Len(), 0; got != want { 103 t.Fatalf("got len %d want %d", got, want) 104 } 105 }