forked from kedacore/http-add-on
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain_test.go
271 lines (243 loc) · 5.94 KB
/
main_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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
appsv1 "k8s.io/api/apps/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/rand"
"github.com/kedacore/http-add-on/interceptor/config"
"github.com/kedacore/http-add-on/pkg/k8s"
kedanet "github.com/kedacore/http-add-on/pkg/net"
"github.com/kedacore/http-add-on/pkg/queue"
"github.com/kedacore/http-add-on/pkg/routing"
"github.com/kedacore/http-add-on/pkg/test"
)
func TestRunProxyServerCountMiddleware(t *testing.T) {
const (
ns = "testns"
port = 8080
host = "samplehost"
)
r := require.New(t)
ctx, done := context.WithCancel(
context.Background(),
)
defer done()
originHdl := kedanet.NewTestHTTPHandlerWrapper(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}),
)
originSrv, originURL, err := kedanet.StartTestServer(originHdl)
r.NoError(err)
defer originSrv.Close()
originPort, err := strconv.Atoi(originURL.Port())
r.NoError(err)
g, ctx := errgroup.WithContext(ctx)
q := queue.NewFakeCounter()
routingTable := routing.NewTable()
// set up a fake host that we can spoof
// when we later send request to the proxy,
// so that the proxy calculates a URL for that
// host that points to the (above) fake origin
// server.
r.NoError(routingTable.AddTarget(
host,
targetFromURL(
originURL,
originPort,
"testdepl",
),
))
timeouts := &config.Timeouts{}
waiterCh := make(chan struct{})
waitFunc := func(_ context.Context, _, _ string) (int, error) {
<-waiterCh
return 1, nil
}
g.Go(func() error {
return runProxyServer(
ctx,
logr.Discard(),
q,
waitFunc,
routingTable,
timeouts,
port,
)
})
// wait for server to start
time.Sleep(500 * time.Millisecond)
// make an HTTP request in the background
g.Go(func() error {
req, err := http.NewRequest(
"GET",
fmt.Sprintf(
"http://0.0.0.0:%d", port,
), nil,
)
if err != nil {
return err
}
req.Host = host
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf(
"unexpected status code: %d",
resp.StatusCode,
)
}
if resp.Header.Get("X-KEDA-HTTP-Cold-Start") != "false" {
return fmt.Errorf("expected X-KEDA-HTTP-Cold-Start false, but got %s", resp.Header.Get("X-KEDA-HTTP-Cold-Start"))
}
return nil
})
time.Sleep(100 * time.Millisecond)
select {
case hostAndCount := <-q.ResizedCh:
r.Equal(host, hostAndCount.Host)
r.Equal(+1, hostAndCount.Count)
case <-time.After(500 * time.Millisecond):
r.Fail("timeout waiting for +1 queue resize")
}
// tell the wait func to proceed
waiterCh <- struct{}{}
select {
case hostAndCount := <-q.ResizedCh:
r.Equal(host, hostAndCount.Host)
r.Equal(-1, hostAndCount.Count)
case <-time.After(2 * time.Second):
r.Fail("timeout waiting for -1 queue resize")
}
// check the queue to make sure all counts are at 0
countsPtr, err := q.Current()
r.NoError(err)
counts := countsPtr.Counts
r.Equal(1, len(counts))
_, foundHost := counts[host]
r.True(
foundHost,
"couldn't find host %s in the queue",
host,
)
r.Equal(0, counts[host])
done()
r.Error(g.Wait())
}
func TestRunAdminServerDeploymentsEndpoint(t *testing.T) {
const (
ns = "testns"
)
ctx := context.Background()
ctx, done := context.WithCancel(ctx)
defer done()
lggr := logr.Discard()
r := require.New(t)
port := rand.Intn(100) + 8000
const deplName = "testdeployment"
srvCfg := &config.Serving{}
timeoutCfg := &config.Timeouts{}
deplCache := k8s.NewFakeDeploymentCache()
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
return runAdminServer(
ctx,
lggr,
k8s.FakeConfigMapGetter{},
queue.NewFakeCounter(),
routing.NewTable(),
deplCache,
port,
srvCfg,
timeoutCfg,
)
})
time.Sleep(500 * time.Millisecond)
deplCache.Set(
ns,
deplName,
appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: deplName,
},
Spec: appsv1.DeploymentSpec{
Replicas: k8s.Int32P(123),
},
},
)
res, err := http.Get(fmt.Sprintf("http://0.0.0.0:%d/deployments", port))
r.NoError(err)
defer res.Body.Close()
r.Equal(200, res.StatusCode)
actual := map[string]int32{}
r.NoError(json.NewDecoder(res.Body).Decode(&actual))
expected := map[string]int32{}
for name, depl := range deplCache.CurrentDeployments() {
expected[name] = *depl.Spec.Replicas
}
r.Equal(expected, actual)
done()
r.Error(g.Wait())
}
func TestRunAdminServerConfig(t *testing.T) {
ctx := context.Background()
ctx, done := context.WithCancel(ctx)
defer done()
lggr := logr.Discard()
r := require.New(t)
const port = 8080
srvCfg := &config.Serving{}
timeoutCfg := &config.Timeouts{}
errgrp, ctx := errgroup.WithContext(ctx)
errgrp.Go(func() error {
return runAdminServer(
ctx,
lggr,
k8s.FakeConfigMapGetter{},
queue.NewFakeCounter(),
routing.NewTable(),
k8s.NewFakeDeploymentCache(),
port,
srvCfg,
timeoutCfg,
)
})
time.Sleep(500 * time.Millisecond)
urlStr := func(path string) string {
return fmt.Sprintf("http://0.0.0.0:%d/%s", port, path)
}
res, err := http.Get(urlStr("config"))
r.NoError(err)
defer res.Body.Close()
r.Equal(200, res.StatusCode)
bodyBytes, err := io.ReadAll(res.Body)
r.NoError(err)
decodedIfaces := map[string][]interface{}{}
r.NoError(json.Unmarshal(bodyBytes, &decodedIfaces))
r.Equal(1, len(decodedIfaces))
_, hasKey := decodedIfaces["configs"]
r.True(hasKey, "config body doesn't have 'configs' key")
configs := decodedIfaces["configs"]
r.Equal(2, len(configs))
retSrvCfg := &config.Serving{}
r.NoError(test.JSONRoundTrip(configs[0], retSrvCfg))
retTimeoutsCfg := &config.Timeouts{}
r.NoError(test.JSONRoundTrip(configs[1], retTimeoutsCfg))
r.Equal(*srvCfg, *retSrvCfg)
r.Equal(*timeoutCfg, *retTimeoutsCfg)
done()
r.Error(errgrp.Wait())
}