...
1
2
3
4 package flowcontrol
5
6 import (
7 "bytes"
8 "io"
9 "net/http"
10 "net/http/httptest"
11 "testing"
12 "time"
13
14 "context"
15
16 "github.com/stretchr/testify/assert"
17 flowcontrolapi "k8s.io/api/flowcontrol/v1beta2"
18 "k8s.io/client-go/rest"
19 "sigs.k8s.io/cli-utils/pkg/testutil"
20 )
21
22 func TestIsEnabled(t *testing.T) {
23 testCases := []struct {
24 name string
25 handler func(*http.Request) *http.Response
26 expectedEnabled bool
27 expectedError error
28 }{
29 {
30 name: "header found",
31 handler: func(req *http.Request) *http.Response {
32 defer req.Body.Close()
33 headers := http.Header{}
34 headers.Add(flowcontrolapi.ResponseHeaderMatchedFlowSchemaUID, "unused-uuid")
35
36 return &http.Response{
37 StatusCode: 200,
38 Header: headers,
39 Body: io.NopCloser(bytes.NewReader(nil)),
40 }
41 },
42 expectedEnabled: true,
43 },
44 {
45 name: "header not found",
46 handler: func(req *http.Request) *http.Response {
47 defer req.Body.Close()
48 return &http.Response{
49 StatusCode: 200,
50 Header: http.Header{},
51 Body: io.NopCloser(bytes.NewReader(nil)),
52 }
53 },
54 expectedEnabled: false,
55 },
56 }
57
58 for _, tc := range testCases {
59 t.Run(tc.name, func(t *testing.T) {
60 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
61 defer cancel()
62
63 handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
64 assert.Equal(t, "/livez/ping", req.URL.Path)
65 resp := tc.handler(req)
66 defer resp.Body.Close()
67 for k, vs := range resp.Header {
68 w.Header().Del(k)
69 for _, v := range vs {
70 w.Header().Add(k, v)
71 }
72 }
73 w.WriteHeader(resp.StatusCode)
74 _, err := io.Copy(w, resp.Body)
75 assert.NoError(t, err)
76 })
77
78 server := httptest.NewServer(handler)
79 defer server.Close()
80
81 cfg := &rest.Config{
82 Host: server.URL,
83 }
84
85 enabled, err := IsEnabled(ctx, cfg)
86 testutil.AssertEqual(t, tc.expectedError, err)
87 assert.Equal(t, tc.expectedEnabled, enabled)
88 })
89 }
90 }
91
View as plain text