github.com/zppinho/prow@v0.0.0-20240510014325-1738badeb017/pkg/metrics/metrics_test.go (about) 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 "context" 21 "net/http" 22 "net/http/httptest" 23 "testing" 24 25 "sigs.k8s.io/prow/pkg/config" 26 "sigs.k8s.io/prow/pkg/flagutil" 27 "sigs.k8s.io/prow/pkg/interrupts" 28 ) 29 30 type fakeListenAndServer struct { 31 ctx context.Context 32 server *httptest.Server 33 } 34 35 func (fls *fakeListenAndServer) ListenAndServe() error { 36 defer fls.server.Close() 37 // Already listening and serving 38 <-fls.ctx.Done() 39 return http.ErrServerClosed 40 } 41 42 func (fls *fakeListenAndServer) Shutdown(ctx context.Context) error { 43 return fls.server.Config.Shutdown(ctx) 44 } 45 46 func (fls *fakeListenAndServer) CreateServer(handler http.Handler) interrupts.ListenAndServer { 47 fls.server = httptest.NewServer(handler) 48 return fls 49 } 50 51 func TestExposeMetrics(t *testing.T) { 52 ctx, cancel := context.WithCancel(context.Background()) 53 defer cancel() 54 fls := fakeListenAndServer{ctx: ctx} 55 56 ExposeMetricsWithRegistry("my-component", config.PushGateway{}, flagutil.DefaultMetricsPort, nil, fls.CreateServer) 57 resp, err := http.Get(fls.server.URL + "/metrics") 58 if err != nil { 59 t.Fatalf("failed getting metrics: %v", err) 60 } 61 if resp.StatusCode != http.StatusOK { 62 t.Errorf("resonse status was not 200 but %d", resp.StatusCode) 63 } 64 }