...
1 package webhook
2
3 import (
4 "bytes"
5 "context"
6 "crypto/tls"
7 "errors"
8 "net/http"
9 "net/http/httptest"
10 "reflect"
11 "testing"
12 "time"
13
14 "github.com/linkerd/linkerd2/controller/k8s"
15 )
16
17 var mockHTTPServer = &http.Server{
18 Addr: ":0",
19 ReadHeaderTimeout: 15 * time.Second,
20 TLSConfig: &tls.Config{
21 MinVersion: tls.VersionTLS12,
22 },
23 }
24
25 func TestServe(t *testing.T) {
26 t.Run("with empty http request body", func(t *testing.T) {
27 k8sAPI, err := k8s.NewFakeMetadataAPI(nil)
28 if err != nil {
29 panic(err)
30 }
31 testServer := getConfiguredServer(mockHTTPServer, k8sAPI, nil, nil)
32 in := bytes.NewReader(nil)
33 request := httptest.NewRequest(http.MethodGet, "/", in)
34
35 recorder := httptest.NewRecorder()
36 testServer.serve(recorder, request)
37
38 if recorder.Code != http.StatusOK {
39 t.Errorf("HTTP response status mismatch. Expected: %d. Actual: %d", http.StatusOK, recorder.Code)
40 }
41
42 if reflect.DeepEqual(recorder.Body.Bytes(), []byte("")) {
43 t.Errorf("Content mismatch. Expected HTTP response body to be empty %v", recorder.Body.Bytes())
44 }
45 })
46 }
47
48 func TestShutdown(t *testing.T) {
49 testServer := getConfiguredServer(mockHTTPServer, nil, nil, nil)
50
51 go func() {
52 if err := testServer.ListenAndServe(); err != nil {
53 if !errors.Is(err, http.ErrServerClosed) {
54 t.Errorf("Unexpected error: %s", err)
55 }
56 }
57 }()
58
59 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
60 defer cancel()
61 if err := testServer.Shutdown(ctx); err != nil {
62 t.Fatalf("Unexpected error: %s", err)
63 }
64 }
65
View as plain text