...
1 package api
2
3 import (
4 "fmt"
5 "net/http"
6 "net/http/httptest"
7 "net/url"
8 "testing"
9
10 "github.com/go-test/deep"
11 "github.com/julienschmidt/httprouter"
12 "github.com/linkerd/linkerd2/controller/k8s"
13 "github.com/sirupsen/logrus"
14 )
15
16 func TestHandleTap(t *testing.T) {
17 expectations := []struct {
18 req *http.Request
19 params httprouter.Params
20 code int
21 header http.Header
22 body string
23 }{
24 {
25 req: &http.Request{
26 URL: &url.URL{
27 Path: "/apis",
28 },
29 },
30 code: http.StatusBadRequest,
31 header: http.Header{"Content-Type": []string{"application/json"}},
32 body: `{"error":"invalid path: \"/apis\""}`,
33 },
34 {
35 req: &http.Request{
36 URL: &url.URL{
37 Path: "/apis/tap.linkerd.io/v1alpha1/watch/namespaces/foo/tap",
38 },
39 },
40 code: http.StatusForbidden,
41 header: http.Header{"Content-Type": []string{"application/json"}},
42 body: `{"error":"tap authorization failed (not authorized to access namespaces.tap.linkerd.io), visit https://linkerd.io/tap-rbac for more information"}`,
43 },
44 }
45
46 for i, exp := range expectations {
47 exp := exp
48
49 t.Run(fmt.Sprintf("%d handle the tap request", i), func(t *testing.T) {
50 k8sAPI, err := k8s.NewFakeAPI()
51 if err != nil {
52 t.Fatalf("NewFakeAPI returned an error: %s", err)
53 }
54
55 h := &handler{
56 k8sAPI: k8sAPI,
57 log: logrus.WithField("test", t.Name()),
58 }
59 recorder := httptest.NewRecorder()
60 h.handleTap(recorder, exp.req, exp.params)
61
62 if recorder.Code != exp.code {
63 t.Errorf("Unexpected code: %d, expected: %d", recorder.Code, exp.code)
64 }
65 if diff := deep.Equal(recorder.Header(), exp.header); diff != nil {
66 t.Errorf("Unexpected header: %v", diff)
67 }
68 if recorder.Body.String() != exp.body {
69 t.Errorf("Unexpected body: %s, expected: %s", recorder.Body.String(), exp.body)
70 }
71 })
72 }
73 }
74
View as plain text