forked from statsig-io/go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_adapter_test.go
288 lines (274 loc) · 10.1 KB
/
data_adapter_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
package statsig
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
)
func TestBootstrapWithAdapter(t *testing.T) {
events := []Event{}
dcs_bytes, _ := os.ReadFile("download_config_specs.json")
idlists_bytes, _ := os.ReadFile("test_data/get_id_lists.json")
idlist_bytes, _ := os.ReadFile("test_data/list_1.txt")
testServer := getTestServer(testServerOptions{
dcsOnline: true,
onLogEvent: func(newEvents []map[string]interface{}) {
for _, newEvent := range newEvents {
eventTyped := convertToExposureEvent(newEvent)
events = append(events, eventTyped)
}
},
})
dataAdapter := dataAdapterExample{store: make(map[string]string)}
dataAdapter.Initialize()
defer dataAdapter.Shutdown()
dataAdapter.Set(CONFIG_SPECS_KEY, string(dcs_bytes))
dataAdapter.Set(ID_LISTS_KEY, string(idlists_bytes))
dataAdapter.Set(fmt.Sprintf("%s::%s", ID_LISTS_KEY, "list_1"), string(idlist_bytes))
options := &Options{
DataAdapter: &dataAdapter,
API: testServer.URL,
Environment: Environment{Tier: "test"},
OutputLoggerOptions: getOutputLoggerOptionsForTest(t),
StatsigLoggerOptions: getStatsigLoggerOptionsForTest(t),
}
t.Run("able to fetch config spec data from adapter and populate store without network", func(t *testing.T) {
InitializeWithOptions("secret-key", options)
user := User{UserID: "statsig_user", Email: "[email protected]"}
value := CheckGate(user, "always_on_gate")
if !value {
t.Errorf("Expected gate to return true")
}
config := GetConfig(user, "test_config")
if config.GetString("string", "") != "statsig" {
t.Errorf("Expected config to return statsig")
}
layer := GetLayer(user, "a_layer")
if layer.GetString("experiment_param", "") != "control" {
t.Errorf("Expected layer param to return control")
}
ShutdownAndDangerouslyClearInstance() // shutdown here to flush event queue
if len(events) != 3 {
t.Errorf("Should receive exactly 3 log_event. Got %d", len(events))
}
for _, event := range events {
if event.Metadata["reason"] != string(reasonDataAdapter) {
t.Errorf("Expected init reason to be %s", reasonDataAdapter)
}
}
})
t.Run("able to fetch id list data from adapter and populate store without network", func(t *testing.T) {
InitializeWithOptions("secret-key", options)
defer ShutdownAndDangerouslyClearInstance()
user := User{UserID: "abc"}
value := CheckGate(user, "on_for_id_list")
if !value {
t.Errorf("Expected gate to return true")
}
})
}
func TestSaveToAdapter(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
if strings.Contains(req.URL.Path, "download_config_specs") {
bytes, _ := os.ReadFile("download_config_specs.json")
_, _ = res.Write(bytes)
}
if strings.Contains(req.URL.Path, "get_id_lists") {
baseURL := "http://" + req.Host
r := map[string]idList{
"list_1": {Name: "list_1", Size: 20, URL: baseURL + "/list_1", CreationTime: 0, FileID: "123"},
}
v, _ := json.Marshal(r)
_, _ = res.Write(v)
}
if strings.Contains(req.URL.Path, "list_1") {
_, _ = res.Write([]byte("+ungWv48B\n+Ngi8oeRO\n"))
}
}))
dataAdapter := dataAdapterExample{store: make(map[string]string)}
options := &Options{
DataAdapter: &dataAdapter,
API: testServer.URL,
Environment: Environment{Tier: "test"},
OutputLoggerOptions: getOutputLoggerOptionsForTest(t),
StatsigLoggerOptions: getStatsigLoggerOptionsForTest(t),
IDListSyncInterval: 100 * time.Millisecond,
ConfigSyncInterval: 100 * time.Millisecond,
}
InitializeWithOptions("secret-key", options)
defer ShutdownAndDangerouslyClearInstance()
t.Run("updates adapter with newer config spec values from network", func(t *testing.T) {
waitForCondition(t, func() bool {
return dataAdapter.Get(CONFIG_SPECS_KEY) != ""
})
specString := dataAdapter.Get(CONFIG_SPECS_KEY)
specs := downloadConfigSpecResponse{}
err := json.Unmarshal([]byte(specString), &specs)
if err != nil {
t.Errorf("Error parsing data adapter values")
}
if !contains_spec(specs.FeatureGates, "always_on_gate", "feature_gate") {
t.Errorf("Expected data adapter to have downloaded gates")
}
if !contains_spec(specs.DynamicConfigs, "test_config", "dynamic_config") {
t.Errorf("Expected data adapter to have downloaded configs")
}
if !contains_spec(specs.LayerConfigs, "a_layer", "dynamic_config") {
t.Errorf("Expected data adapter to have downloaded layers")
}
})
t.Run("updates adapter with newer id list values from network", func(t *testing.T) {
waitForCondition(t, func() bool {
return dataAdapter.Get(ID_LISTS_KEY) != "" && dataAdapter.Get(fmt.Sprintf("%s::%s", ID_LISTS_KEY, "list_1")) != ""
})
idListsString := dataAdapter.Get(ID_LISTS_KEY)
list1String := dataAdapter.Get(fmt.Sprintf("%s::%s", ID_LISTS_KEY, "list_1"))
list1Bytes := []byte(list1String)
var idLists map[string]idList
err := json.Unmarshal([]byte(idListsString), &idLists)
if err != nil {
t.Errorf("Error parsing data adapter values")
}
if len(idLists) != 1 {
t.Errorf("Expected data adapter to have list_1")
}
if idLists["list_1"].Size != 20 {
t.Errorf("Expected list_1 to have size 20, received %d", idLists["list_1"].Size)
}
if idLists["list_1"].FileID != "123" {
t.Errorf("Expected list_1 to have file ID 123")
}
if len(list1Bytes) != 20 {
t.Errorf("Expected list_1 to have 20 bytes, received %d", len(list1Bytes))
}
if !strings.Contains(list1String, "+ungWv48B\n") || !strings.Contains(list1String, "+Ngi8oeRO\n") {
// the list should be exactly +ungWv48B\n+Ngi8oeRO\n. Will fix in the future, patching this test for now so it's not flakey
t.Errorf("Expected list_1 to contain ids: ungWv48B, Ngi8oeRO, received %v", strings.Split(list1String, "\n"))
}
})
}
func TestAdapterWithPolling(t *testing.T) {
dcs_bytes, _ := os.ReadFile("download_config_specs.json")
idlists_bytes, _ := os.ReadFile("test_data/get_id_lists.json")
idlist_bytes, _ := os.ReadFile("test_data/list_1.txt")
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
if strings.Contains(req.URL.Path, "download_config_specs") {
_, _ = res.Write(dcs_bytes)
}
}))
dataAdapter := dataAdapterWithPollingExample{store: make(map[string]string)}
dataAdapter.Set(CONFIG_SPECS_KEY, string(dcs_bytes))
dataAdapter.Set(ID_LISTS_KEY, string(idlists_bytes))
dataAdapter.Set(fmt.Sprintf("%s::%s", ID_LISTS_KEY, "list_1"), string(idlist_bytes))
options := &Options{
DataAdapter: &dataAdapter,
API: testServer.URL,
Environment: Environment{Tier: "test"},
ConfigSyncInterval: 100 * time.Millisecond,
IDListSyncInterval: 100 * time.Millisecond,
OutputLoggerOptions: getOutputLoggerOptionsForTest(t),
StatsigLoggerOptions: getStatsigLoggerOptionsForTest(t),
}
InitializeWithOptions("secret-key", options)
defer ShutdownAndDangerouslyClearInstance()
t.Run("updating adapter also updates statsig store", func(t *testing.T) {
user := User{UserID: "abc"}
value := CheckGate(user, "on_for_id_list")
if !value {
t.Errorf("Expected on_for_id_list to return true")
}
idlists_updated_bytes, _ := os.ReadFile("test_data/get_id_lists_updated.json")
idlist_updated_bytes, _ := os.ReadFile("test_data/list_1_updated.txt")
dataAdapter.Set(fmt.Sprintf("%s::%s", ID_LISTS_KEY, "list_1"), string(idlist_updated_bytes))
dataAdapter.Set(ID_LISTS_KEY, string(idlists_updated_bytes))
waitForConditionWithMessage(t, func() bool {
return !CheckGate(user, "on_for_id_list")
}, "Expected on_for_id_list to return false")
user = User{UserID: "statsig_user", Email: "[email protected]"}
value = CheckGate(user, "always_on_gate")
if !value {
t.Errorf("Expected always_on_gate to return true")
}
dataAdapter.clearStore(CONFIG_SPECS_KEY)
waitForConditionWithMessage(t, func() bool {
return !CheckGate(user, "always_on_gate")
}, "Expected always_on_gate to return false")
})
}
func TestIncorrectlyImplementedAdapter(t *testing.T) {
events := []Event{}
testServer := getTestServer(testServerOptions{
dcsOnline: true,
onLogEvent: func(newEvents []map[string]interface{}) {
for _, newEvent := range newEvents {
eventTyped := convertToExposureEvent(newEvent)
events = append(events, eventTyped)
}
},
})
dataAdapter := brokenDataAdapterExample{}
options := &Options{
DataAdapter: dataAdapter,
API: testServer.URL,
Environment: Environment{Tier: "test"},
OutputLoggerOptions: getOutputLoggerOptionsForTest(t),
StatsigLoggerOptions: getStatsigLoggerOptionsForTest(t),
}
stderrLogs := swallow_stderr(func() {
InitializeWithOptions("secret-key", options)
})
if stderrLogs == "" {
t.Errorf("Expected output to stderr")
}
user := User{UserID: "statsig_user", Email: "[email protected]"}
t.Run("recover and finish initialize if adapter panics", func(t *testing.T) {
value := CheckGate(user, "always_on_gate")
if !value {
t.Errorf("Expected gate to return true")
}
config := GetConfig(user, "test_config")
if config.GetString("string", "") != "statsig" {
t.Errorf("Expected config to return statsig")
}
layer := GetLayer(user, "a_layer")
if layer.GetString("experiment_param", "") != "control" {
t.Errorf("Expected layer param to return control")
}
ShutdownAndDangerouslyClearInstance() // shutdown here to flush event queue
if len(events) != 3 {
t.Errorf("Should receive exactly 3 log_event. Got %d", len(events))
}
for _, event := range events {
if event.Metadata["reason"] != string(reasonNetwork) {
t.Errorf("Expected init reason to be %s", reasonNetwork)
}
}
})
}
func swallow_stderr(task func()) string {
stderr := os.Stderr
r, w, _ := os.Pipe()
os.Stderr = w
task()
w.Close()
var buf bytes.Buffer
_, _ = io.Copy(&buf, r)
os.Stderr = stderr
return buf.String()
}
func contains_spec(specs []configSpec, name string, specType string) bool {
for _, e := range specs {
if e.Name == name && e.Type == specType {
return true
}
}
return false
}