-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathconfigserver_test.go
216 lines (191 loc) · 4.85 KB
/
configserver_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
package configcat
import (
"crypto/md5"
"crypto/rand"
"encoding/json"
"fmt"
"github.com/configcat/go-sdk/v9/configcatcache"
"net/http"
"net/http/httptest"
"os"
"sync"
"testing"
"time"
)
type configServer struct {
srv *httptest.Server
key string
t testing.TB
mu sync.Mutex
resp *configResponse
responses []configResponse
requestCount int
}
type configResponse struct {
status int
body string
sleep time.Duration
}
func newConfigServer(t testing.TB) *configServer {
return newConfigServerWithKey(t, randomSdkKey())
}
func randomSdkKey() string {
var seg1, seg2 [11]byte
rand.Read(seg1[:])
rand.Read(seg2[:])
return fmt.Sprintf("%x/%x", seg1, seg2)
}
func newConfigServerWithKey(t testing.TB, sdkKey string) *configServer {
srv := &configServer{
t: t,
}
srv.srv = httptest.NewServer(srv)
t.Cleanup(srv.srv.Close)
srv.key = sdkKey
return srv
}
// config returns a configuration suitable for creating
// a client that talks to the p.
func (srv *configServer) config() Config {
return Config{
SDKKey: srv.key,
BaseURL: srv.srv.URL,
Logger: newTestLogger(srv.t),
LogLevel: LogLevelError,
}
}
// setResponse sets the response that will be returned from the server.
func (srv *configServer) setResponse(response configResponse) {
srv.mu.Lock()
defer srv.mu.Unlock()
srv.resp = &response
}
func (srv *configServer) setResponseJSON(x interface{}) {
srv.setResponse(configResponse{
body: marshalJSON(x),
})
}
// allResponses returns all the responses that have been served over
// the lifetime of the server, excluding those that will have
// caused the test to fail.
func (srv *configServer) allResponses() []configResponse {
srv.mu.Lock()
defer srv.mu.Unlock()
return append([]configResponse(nil), srv.responses...)
}
func (srv *configServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "/configuration-files/"+srv.key+"/"+configcatcache.ConfigJSONName {
srv.t.Errorf("unexpected HTTP call: %s %s", req.Method, req.URL)
http.NotFound(w, req)
return
}
if req.Method != "GET" {
srv.t.Errorf("unexpected HTTP method: %s", req.Method)
http.Error(w, "only GET is allowed", http.StatusMethodNotAllowed)
return
}
srv.mu.Lock()
srv.requestCount++
resp0 := srv.resp
defer srv.mu.Unlock()
if resp0 == nil {
srv.t.Errorf("HTTP call with no response provided")
http.Error(w, "unexpected call", http.StatusInternalServerError)
return
}
resp := *resp0
time.Sleep(resp.sleep)
if resp.status == 0 {
w.Header().Set("Etag", etagOf(resp.body))
if req.Header.Get("If-None-Match") == etagOf(resp.body) {
resp.status = http.StatusNotModified
resp.body = ""
} else {
resp.status = http.StatusOK
}
}
w.WriteHeader(resp.status)
w.Write([]byte(resp.body))
// Record the response so that it's possible to check what went on behind the scenes later.
srv.responses = append(srv.responses, resp)
}
var (
readIntegrationTestKeysOnce sync.Once
integrationTestKeyContent map[string]json.RawMessage
)
func contentForIntegrationTestKey(key string) string {
readIntegrationTestKeysOnce.Do(func() {
data, err := os.ReadFile("resources/content-by-key.json")
if err != nil {
panic(err)
}
if err := json.Unmarshal(data, &integrationTestKeyContent); err != nil {
panic(err)
}
})
content, ok := integrationTestKeyContent[key]
if !ok {
panic(fmt.Errorf("integration test content for key %q not found", key))
}
return string(content)
}
func etagOf(content string) string {
return fmt.Sprintf("%x", md5.Sum([]byte(content)))
}
func marshalJSON(x interface{}) string {
data, err := json.Marshal(x)
if err != nil {
panic(err)
}
return string(data)
}
// testLogger implements the Logger interface by logging to the test.T
// instance.
type testLogger struct {
sync.RWMutex
t testing.TB
logs []string
}
func newTestLogger(t testing.TB) Logger {
return &testLogger{
t: t,
}
}
func (log *testLogger) Debugf(format string, args ...interface{}) {
log.Lock()
defer log.Unlock()
s := fmt.Sprintf("DEBUG: %s", fmt.Sprintf(format, args...))
log.logs = append(log.logs, s)
log.t.Log(s)
}
func (log *testLogger) Infof(format string, args ...interface{}) {
log.Lock()
defer log.Unlock()
s := fmt.Sprintf("INFO: %s", fmt.Sprintf(format, args...))
log.logs = append(log.logs, s)
log.t.Log(s)
}
func (log *testLogger) Warnf(format string, args ...interface{}) {
log.Lock()
defer log.Unlock()
s := fmt.Sprintf("WARN: %s", fmt.Sprintf(format, args...))
log.logs = append(log.logs, s)
log.t.Log(s)
}
func (log *testLogger) Errorf(format string, args ...interface{}) {
log.Lock()
defer log.Unlock()
s := fmt.Sprintf("ERROR: %s", fmt.Sprintf(format, args...))
log.logs = append(log.logs, s)
log.t.Log(s)
}
func (log *testLogger) Logs() []string {
log.RLock()
defer log.RUnlock()
return log.logs
}
func (log *testLogger) Clear() {
log.Lock()
defer log.Unlock()
log.logs = nil
}