...

Source file src/k8s.io/component-base/metrics/http_test.go

Documentation: k8s.io/component-base/metrics

     1  /*
     2  Copyright 2020 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package metrics
    18  
    19  import (
    20  	"io"
    21  	"net/http"
    22  	"net/http/httptest"
    23  	"testing"
    24  
    25  	apimachineryversion "k8s.io/apimachinery/pkg/version"
    26  )
    27  
    28  func TestResetHandler(t *testing.T) {
    29  	currentVersion := apimachineryversion.Info{
    30  		Major:      "1",
    31  		Minor:      "17",
    32  		GitVersion: "v1.17.1-alpha-1.12345",
    33  	}
    34  	registry := newKubeRegistry(currentVersion)
    35  	resetHandler := HandlerWithReset(registry, HandlerOpts{})
    36  	testCases := []struct {
    37  		desc         string
    38  		method       string
    39  		expectedBody string
    40  	}{
    41  		{
    42  			desc:         "Should return empty body on a get",
    43  			method:       http.MethodGet,
    44  			expectedBody: "",
    45  		},
    46  		{
    47  			desc:         "Should return 'metrics reset' in the body on a delete",
    48  			method:       http.MethodDelete,
    49  			expectedBody: "metrics reset\n",
    50  		},
    51  	}
    52  	for _, tc := range testCases {
    53  		t.Run(tc.desc, func(t *testing.T) {
    54  			req, err := http.NewRequest(tc.method, "http://sample.com/metrics", nil)
    55  			if err != nil {
    56  				t.Fatalf("Error creating http request")
    57  			}
    58  			rec := httptest.NewRecorder()
    59  			resetHandler.ServeHTTP(rec, req)
    60  			body, err := io.ReadAll(rec.Result().Body)
    61  			if err != nil {
    62  				t.Fatalf("Error reading response body")
    63  			}
    64  			if string(body) != tc.expectedBody {
    65  				t.Errorf("Got '%s' as the response body, but want '%v'", body, tc.expectedBody)
    66  			}
    67  		})
    68  	}
    69  }
    70  

View as plain text