OSDN Git Service

delete miner
[bytom/vapor.git] / vendor / github.com / go-kit / kit / sd / internal / instance / cache_test.go
1 package instance
2
3 import (
4         "reflect"
5         "testing"
6         "time"
7
8         "github.com/go-kit/kit/sd"
9 )
10
11 var _ sd.Instancer = (*Cache)(nil) // API check
12
13 // The test verifies the following:
14 //   registering causes initial notification of the current state
15 //   instances are sorted
16 //   different update causes new notification
17 //   identical notifications cause no updates
18 //   no updates after de-registering
19 func TestCache(t *testing.T) {
20         e1 := sd.Event{Instances: []string{"y", "x"}} // not sorted
21         e2 := sd.Event{Instances: []string{"c", "a", "b"}}
22
23         cache := NewCache()
24         if want, have := 0, len(cache.State().Instances); want != have {
25                 t.Fatalf("want %v instances, have %v", want, have)
26         }
27
28         cache.Update(e1) // sets initial state
29         if want, have := 2, len(cache.State().Instances); want != have {
30                 t.Fatalf("want %v instances, have %v", want, have)
31         }
32
33         r1 := make(chan sd.Event)
34         go cache.Register(r1)
35         expectUpdate(t, r1, []string{"x", "y"})
36
37         go cache.Update(e2) // different set
38         expectUpdate(t, r1, []string{"a", "b", "c"})
39
40         cache.Deregister(r1)
41         close(r1)
42 }
43
44 func expectUpdate(t *testing.T, r chan sd.Event, expect []string) {
45         select {
46         case e := <-r:
47                 if want, have := expect, e.Instances; !reflect.DeepEqual(want, have) {
48                         t.Fatalf("want: %v, have: %v", want, have)
49                 }
50         case <-time.After(time.Second):
51                 t.Fatalf("did not receive expected update %v", expect)
52         }
53 }
54
55 func TestRegistry(t *testing.T) {
56         reg := make(registry)
57         c1 := make(chan sd.Event, 1)
58         c2 := make(chan sd.Event, 1)
59         reg.register(c1)
60         reg.register(c2)
61
62         // validate that both channels receive the update
63         reg.broadcast(sd.Event{Instances: []string{"x", "y"}})
64         if want, have := []string{"x", "y"}, (<-c1).Instances; !reflect.DeepEqual(want, have) {
65                 t.Fatalf("want: %v, have: %v", want, have)
66         }
67         if want, have := []string{"x", "y"}, (<-c2).Instances; !reflect.DeepEqual(want, have) {
68                 t.Fatalf("want: %v, have: %v", want, have)
69         }
70
71         reg.deregister(c1)
72         reg.deregister(c2)
73         close(c1)
74         close(c2)
75         // if deregister didn't work, broadcast would panic on closed channels
76         reg.broadcast(sd.Event{Instances: []string{"x", "y"}})
77 }