1package eureka
2
3import (
4	"testing"
5	"time"
6
7	"github.com/hudl/fargo"
8
9	"github.com/go-kit/kit/sd"
10)
11
12var _ sd.Instancer = (*Instancer)(nil) // API check
13
14func TestInstancer(t *testing.T) {
15	connection := &testConnection{
16		instances:      []*fargo.Instance{instanceTest1, instanceTest2},
17		errApplication: nil,
18	}
19
20	instancer := NewInstancer(connection, appNameTest, loggerTest)
21	defer instancer.Stop()
22
23	state := instancer.state()
24	if state.Err != nil {
25		t.Fatal(state.Err)
26	}
27
28	if want, have := 2, len(state.Instances); want != have {
29		t.Errorf("want %d, have %d", want, have)
30	}
31}
32
33func TestInstancerReceivesUpdates(t *testing.T) {
34	connection := &testConnection{
35		instances:      []*fargo.Instance{instanceTest1},
36		errApplication: nil,
37	}
38
39	instancer := NewInstancer(connection, appNameTest, loggerTest)
40	defer instancer.Stop()
41
42	verifyCount := func(want int) (have int, converged bool) {
43		const maxPollAttempts = 5
44		const delayPerAttempt = 200 * time.Millisecond
45		for i := 1; ; i++ {
46			state := instancer.state()
47			if have := len(state.Instances); want == have {
48				return have, true
49			} else if i == maxPollAttempts {
50				return have, false
51			}
52			time.Sleep(delayPerAttempt)
53		}
54	}
55
56	if have, converged := verifyCount(1); !converged {
57		t.Fatalf("initial: want %d, have %d", 1, have)
58	}
59
60	if err := connection.RegisterInstance(instanceTest2); err != nil {
61		t.Fatalf("failed to register an instance: %v", err)
62	}
63	if have, converged := verifyCount(2); !converged {
64		t.Fatalf("after registration: want %d, have %d", 2, have)
65	}
66
67	if err := connection.DeregisterInstance(instanceTest1); err != nil {
68		t.Fatalf("failed to unregister an instance: %v", err)
69	}
70	if have, converged := verifyCount(1); !converged {
71		t.Fatalf("after deregistration: want %d, have %d", 1, have)
72	}
73}
74
75func TestBadInstancerScheduleUpdates(t *testing.T) {
76	connection := &testConnection{
77		instances:      []*fargo.Instance{instanceTest1},
78		errApplication: errTest,
79	}
80
81	instancer := NewInstancer(connection, appNameTest, loggerTest)
82	defer instancer.Stop()
83
84	state := instancer.state()
85	if state.Err == nil {
86		t.Fatal("expecting error")
87	}
88
89	if want, have := 0, len(state.Instances); want != have {
90		t.Errorf("want %d, have %d", want, have)
91	}
92}
93