Path: blob/main/components/common-go/log/handler_test.go
2498 views
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package log56import (7"bytes"8"net/http"9"net/http/httptest"10"strings"11"testing"12)1314func TestLevelHandler(t *testing.T) {15tests := []struct {16Name string17Method string18Body []byte19Expectation string20Error string21}{22{"report default level", http.MethodGet, nil, `{"level": "info"}`, ""},23{"change level to info", http.MethodPost, []byte(`{"level": "info"}`), `{"level": "info"}`, ""},24{"change level to debug", http.MethodPut, []byte(`{"level": "debug"}`), `{"level": "debug"}`, ""},25{"invalid level", http.MethodPost, []byte(`{"level": "something invalid"}`), "", `not a valid logrus Level: "something invalid"`},26{"invalid method", http.MethodDelete, nil, "", "DELETE unsupported"},27{"empty body", http.MethodPost, []byte(""), "", "invalid request"},28{"invalid json", http.MethodPost, []byte("{"), "", "cannot decode request: unexpected end of JSON input"},29}3031for _, test := range tests {32t.Run(test.Name, func(t *testing.T) {33req, err := http.NewRequest(test.Method, "/debug/level", bytes.NewReader(test.Body))34if err != nil {35t.Fatal(err)36}3738rr := httptest.NewRecorder()39handler := http.HandlerFunc(LevelHandler)4041handler.ServeHTTP(rr, req)4243if test.Error == "" {44if rr.Body.String() != test.Expectation {45t.Errorf("handler returned unexpected body: got %v want %v", rr.Body.String(), test.Expectation)46}4748return49}5051if rr.Code == http.StatusOK {52t.Errorf("handler returned should not return StatusOK")53return54}5556msg := strings.ReplaceAll(rr.Body.String(), "\n", "")57if msg != test.Error {58t.Errorf(`handler returned wrong error: got '%v' want '%v'`, msg, test.Error)59}60})61}62}636465