github.com/GuanceCloud/cliutils@v1.1.21/metrics/http_test.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 package metrics 7 8 import ( 9 "fmt" 10 "io" 11 "net/http" 12 "net/http/httptest" 13 "path/filepath" 14 T "testing" 15 16 "github.com/gin-gonic/gin" 17 "github.com/prometheus/client_golang/prometheus" 18 "github.com/prometheus/client_golang/prometheus/promhttp" 19 "github.com/stretchr/testify/assert" 20 ) 21 22 func TestRouteForGin(t *T.T) { 23 t.Run("gin", func(t *T.T) { 24 vec := prometheus.NewCounterVec( 25 prometheus.CounterOpts{ 26 Name: filepath.Base(t.Name()), 27 }, 28 []string{"api", "status"}, 29 ) 30 31 MustRegister(vec) 32 33 router := gin.New() 34 router.GET("/metrics", HTTPGinHandler(promhttp.HandlerOpts{})) 35 ts := httptest.NewServer(router) 36 defer ts.Close() 37 38 div := 10000.0 39 40 for i := 0; i < 1000; i++ { 41 switch i % 3 { 42 case 0: 43 vec.WithLabelValues("/v1/write/metric", "ok").Add(float64(i) / div) 44 case 1: 45 vec.WithLabelValues("/v1/write/logging", "ok").Add(float64(i) / div) 46 default: 47 vec.WithLabelValues("/v1/write/tracing", "ok").Add(float64(i) / div) 48 } 49 } 50 51 req, err := http.Get(fmt.Sprintf("%s/metrics", ts.URL)) 52 assert.NoError(t, err) 53 54 body, err := io.ReadAll(req.Body) 55 assert.NoError(t, err) 56 57 t.Logf("\n%s", string(body)) 58 }) 59 }