Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/common-go/log/handler_test.go
2498 views
1
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package log
6
7
import (
8
"bytes"
9
"net/http"
10
"net/http/httptest"
11
"strings"
12
"testing"
13
)
14
15
func TestLevelHandler(t *testing.T) {
16
tests := []struct {
17
Name string
18
Method string
19
Body []byte
20
Expectation string
21
Error string
22
}{
23
{"report default level", http.MethodGet, nil, `{"level": "info"}`, ""},
24
{"change level to info", http.MethodPost, []byte(`{"level": "info"}`), `{"level": "info"}`, ""},
25
{"change level to debug", http.MethodPut, []byte(`{"level": "debug"}`), `{"level": "debug"}`, ""},
26
{"invalid level", http.MethodPost, []byte(`{"level": "something invalid"}`), "", `not a valid logrus Level: "something invalid"`},
27
{"invalid method", http.MethodDelete, nil, "", "DELETE unsupported"},
28
{"empty body", http.MethodPost, []byte(""), "", "invalid request"},
29
{"invalid json", http.MethodPost, []byte("{"), "", "cannot decode request: unexpected end of JSON input"},
30
}
31
32
for _, test := range tests {
33
t.Run(test.Name, func(t *testing.T) {
34
req, err := http.NewRequest(test.Method, "/debug/level", bytes.NewReader(test.Body))
35
if err != nil {
36
t.Fatal(err)
37
}
38
39
rr := httptest.NewRecorder()
40
handler := http.HandlerFunc(LevelHandler)
41
42
handler.ServeHTTP(rr, req)
43
44
if test.Error == "" {
45
if rr.Body.String() != test.Expectation {
46
t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), test.Expectation)
47
}
48
49
return
50
}
51
52
if rr.Code == http.StatusOK {
53
t.Errorf("handler returned should not return StatusOK")
54
return
55
}
56
57
msg := strings.ReplaceAll(rr.Body.String(), "\n", "")
58
if msg != test.Error {
59
t.Errorf(`handler returned wrong error: got '%v' want '%v'`, msg, test.Error)
60
}
61
})
62
}
63
}
64
65