forked from Unleash/unleash-client-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics_test.go
341 lines (287 loc) · 8.7 KB
/
metrics_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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package unleash
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Unleash/unleash-client-go/v4/api"
internalapi "github.com/Unleash/unleash-client-go/v4/internal/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"gopkg.in/h2non/gock.v1"
)
func TestMetrics_RegisterInstance(t *testing.T) {
assert := assert.New(t)
defer gock.OffAll()
gock.New(mockerServer).
Post("/client/register").
MatchHeader("UNLEASH-APPNAME", mockAppName).
MatchHeader("UNLEASH-INSTANCEID", mockInstanceId).
Reply(200)
gock.New(mockerServer).
Get("/client/features").
Reply(200).
JSON(api.FeatureResponse{})
mockListener := &MockedListener{}
mockListener.On("OnReady").Return()
mockListener.On("OnRegistered", mock.AnythingOfType("ClientData"))
client, err := NewClient(
WithUrl(mockerServer),
WithAppName(mockAppName),
WithInstanceId(mockInstanceId),
WithListener(mockListener),
)
time.Sleep(1 * time.Second)
client.Close()
assert.Nil(err, "client should not return an error")
assert.True(gock.IsDone(), "there should be no more mocks")
}
func TestMetrics_VariantsCountToggles(t *testing.T) {
assert := assert.New(t)
defer gock.OffAll()
gock.New(mockerServer).
Post("/client/register").
MatchHeader("UNLEASH-APPNAME", mockAppName).
MatchHeader("UNLEASH-INSTANCEID", mockInstanceId).
Reply(200)
gock.New(mockerServer).
Get("/client/features").
Reply(200).
JSON(api.FeatureResponse{})
mockListener := &MockedListener{}
mockListener.On("OnReady").Return()
mockListener.On("OnCount", "foo", false).Return()
mockListener.On("OnRegistered", mock.AnythingOfType("ClientData"))
client, err := NewClient(
WithUrl(mockerServer),
WithAppName(mockAppName),
WithInstanceId(mockInstanceId),
WithListener(mockListener),
)
client.WaitForReady()
client.GetVariant("foo")
assert.EqualValues(client.metrics.bucket.Toggles["foo"].No, 1)
client.Close()
assert.Nil(err, "client should not return an error")
assert.True(gock.IsDone(), "there should be no more mocks")
}
func TestMetrics_DoPost(t *testing.T) {
assert := assert.New(t)
defer gock.OffAll()
gock.New(mockerServer).
Post("/client/register").
Reply(200)
gock.New(mockerServer).
Get("/client/features").
Reply(200).
JSON(api.FeatureResponse{})
gock.New(mockerServer).
Post("").
MatchHeader("UNLEASH-APPNAME", mockAppName).
MatchHeader("UNLEASH-INSTANCEID", mockInstanceId).
Reply(200)
mockListener := &MockedListener{}
mockListener.On("OnReady").Return()
mockListener.On("OnRegistered", mock.AnythingOfType("ClientData"))
client, err := NewClient(
WithUrl(mockerServer),
WithAppName(mockAppName),
WithInstanceId(mockInstanceId),
WithListener(mockListener),
)
assert.Nil(err, "client should not return an error")
m := client.metrics
serverUrl, _ := url.Parse(mockerServer)
res, err := m.doPost(serverUrl, &struct{}{})
client.Close()
assert.Nil(err, "doPost should not return an error")
assert.Equal(200, res.StatusCode, "statusCode should be 200")
assert.True(gock.IsDone(), "there should be no more mocks")
}
func TestMetrics_DisabledMetrics(t *testing.T) {
assert := assert.New(t)
defer gock.OffAll()
gock.New(mockerServer).
Get("/client/features").
Reply(200).
JSON(api.FeatureResponse{})
mockListener := &MockedListener{}
mockListener.On("OnReady").Return()
client, err := NewClient(
WithUrl(mockerServer),
WithDisableMetrics(true),
WithMetricsInterval(100*time.Millisecond),
WithAppName(mockAppName),
WithInstanceId(mockInstanceId),
WithListener(mockListener),
)
assert.Nil(err, "client should not return an error")
client.WaitForReady()
client.IsEnabled("foo")
client.IsEnabled("bar")
client.IsEnabled("baz")
time.Sleep(300 * time.Millisecond)
client.Close()
assert.True(gock.IsDone(), "there should be no more mocks")
}
// TestMetrics_SendMetricsFail tests that no metrics are lost if /client/metrics
// fails temporarily.
func TestMetrics_SendMetricsFail(t *testing.T) {
assert := assert.New(t)
type metricsReq struct {
// toggles are the toggles sent to /client/metrics
toggles map[string]internalapi.ToggleCount
// status is the status code returned from /client/metrics
status int
}
metricsCalls := make(chan metricsReq, 10)
var prevToggles map[string]internalapi.ToggleCount
var sendStatus200 int32
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
switch req.Method + " " + req.URL.Path {
case "POST /client/register":
case "GET /client/features":
writeJSON(rw, api.FeatureResponse{})
case "POST /client/metrics":
body, err := ioutil.ReadAll(req.Body)
assert.Nil(err)
status200 := atomic.LoadInt32(&sendStatus200) == 1
status := 400
if status200 {
status = 200
}
var md MetricsData
err = json.Unmarshal(body, &md)
assert.Nil(err)
if status200 || !reflect.DeepEqual(md.Bucket.Toggles, prevToggles) {
prevToggles = md.Bucket.Toggles
metricsCalls <- metricsReq{md.Bucket.Toggles, status}
}
rw.WriteHeader(status)
default:
t.Fatalf("Unexpected request: %+v", req)
}
}))
defer srv.Close()
mockListener := &MockedListener{}
mockListener.On("OnReady").Return()
mockListener.On("OnRegistered", mock.AnythingOfType("ClientData"))
mockListener.On("OnCount", "foo", true).Return()
mockListener.On("OnCount", "foo", false).Return()
mockListener.On("OnWarning", mock.MatchedBy(func(e error) bool {
return strings.HasSuffix(e.Error(), "/client/metrics return 400")
})).Return()
mockListener.On("OnSent", mock.AnythingOfType("MetricsData")).Return()
client, err := NewClient(
WithUrl(srv.URL),
WithAppName(mockAppName),
WithInstanceId(mockInstanceId),
WithListener(mockListener),
WithMetricsInterval(time.Millisecond),
)
assert.Nil(err, "client should not return an error")
client.WaitForReady()
ck := func(status int, yes, no int32, r metricsReq) {
t.Helper()
assert.Equal(status, r.status)
assert.Equal(yes, r.toggles["foo"].Yes)
assert.Equal(no, r.toggles["foo"].No)
}
m := client.metrics
// /client/metrics returns 400, check that the counts aren't reset.
m.count("foo", true)
ck(400, 1, 0, <-metricsCalls)
m.count("foo", false)
ck(400, 1, 1, <-metricsCalls)
m.count("foo", true)
ck(400, 2, 1, <-metricsCalls)
mockListener.AssertNotCalled(t, "OnSent", mock.AnythingOfType("MetricsData"))
atomic.StoreInt32(&sendStatus200, 1)
ck(200, 2, 1, <-metricsCalls)
// As /client/metrics returned 200 and m.count hasn't been called again
// there are no more metrics to report and thus /client/metrics
// shouldn't be called again.
select {
case r := <-metricsCalls:
t.Fatalf("Didn't expect request to /client/metrics, got %+v", r)
case <-time.NewTimer(500 * time.Millisecond).C:
}
client.Close()
// Now OnSent should have been called as /client/metrics returned 200.
mockListener.AssertCalled(t, "OnSent", mock.AnythingOfType("MetricsData"))
}
func TestMetrics_ShouldNotCountMetricsForParentToggles(t *testing.T) {
assert := assert.New(t)
defer gock.OffAll()
gock.New(mockerServer).
Post("/client/register").
Reply(200)
gock.New(mockerServer).
Get("/client/features").
Reply(200).
JSON(api.FeatureResponse{
Features: []api.Feature{
{
Name: "parent",
Enabled: true,
Description: "parent toggle",
Strategies: []api.Strategy{
{
Id: 1,
Name: "flexibleRollout",
Constraints: []api.Constraint{},
Parameters: map[string]interface{}{
"rollout": 100,
"stickiness": "default",
},
},
},
},
{
Name: "child",
Enabled: true,
Description: "parent toggle",
Strategies: []api.Strategy{
{
Id: 1,
Name: "flexibleRollout",
Constraints: []api.Constraint{},
Parameters: map[string]interface{}{
"rollout": 100,
"stickiness": "default",
},
},
},
Dependencies: &[]api.Dependency{
{
Feature: "parent",
},
},
},
},
})
mockListener := &MockedListener{}
mockListener.On("OnReady").Return()
mockListener.On("OnError").Return()
mockListener.On("OnRegistered", mock.AnythingOfType("ClientData"))
mockListener.On("OnCount", "child", true).Return()
client, err := NewClient(
WithUrl(mockerServer),
WithAppName(mockAppName),
WithInstanceId(mockInstanceId),
WithListener(mockListener),
)
client.WaitForReady()
client.IsEnabled("child")
assert.EqualValues(client.metrics.bucket.Toggles["child"].Yes, 1)
assert.EqualValues(client.metrics.bucket.Toggles["parent"].Yes, 0)
client.Close()
assert.Nil(err, "client should not return an error")
assert.True(gock.IsDone(), "there should be no more mocks")
}