-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_mon_test.go
75 lines (63 loc) · 1.53 KB
/
config_mon_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package cfg
import (
"math/rand"
"strconv"
"sync/atomic"
"testing"
"time"
)
func makeSrc(freq time.Duration) *SrcMap {
m := make(map[string]string)
m["prop0"] = "0"
m["prop1"] = "1"
m["prop2"] = "2"
m["prop3"] = "3"
m["prop4"] = "4"
mapSrc := NewSrcMapFromMap(m)
mapSrc.SetMonitorFreq(freq)
return mapSrc
}
type Notify struct {
count int32
}
func (n *Notify) ConfigChanged(cfg *Config, src SourceMonitored) {
atomic.AddInt32(&n.count, 1)
}
func TestConfig_Monitor(t *testing.T) {
config := &Config{}
defer config.Shutdown()
mapSrc := makeSrc(time.Millisecond * 20)
config.AppendSource(mapSrc)
notify := &Notify{}
config.AddChangedListener(notify)
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
done := time.After(2 * time.Second)
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
isDone := false
actual := int32(0)
for !isDone {
select {
case <-ticker.C:
mapSrc.Put("prop1", strconv.Itoa(rnd.Intn(30)))
actual++
case <-done:
isDone = true
}
}
count := atomic.LoadInt32(¬ify.count)
if count != actual {
t.Errorf("ChangedListener was called %d times; expected %d", count, actual)
}
// make sure listener not called after removal.
atomic.StoreInt32(¬ify.count, 0)
config.RemoveChangedListener(notify)
mapSrc.Put("prop1", "n/a")
time.Sleep(50 * time.Millisecond)
mapSrc.Put("prop2", "n/a")
time.Sleep(50 * time.Millisecond)
count = atomic.LoadInt32(¬ify.count)
if count != 0 {
t.Errorf("ChangedListener was called %d times after being removed.", count)
}
}