github.com/openshift-online/ocm-sdk-go@v0.1.473/testing/metrics.go (about) 1 /* 2 Copyright (c) 2021 Red Hat, Inc. 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 // This file types and functions useful for testing Prometheus metrics. 18 19 package testing 20 21 import ( 22 "io" 23 "net/http" 24 "strings" 25 26 "github.com/prometheus/client_golang/prometheus" 27 "github.com/prometheus/client_golang/prometheus/promhttp" 28 29 . "github.com/onsi/gomega" // nolint 30 . "github.com/onsi/gomega/ghttp" // nolint 31 ) 32 33 // MetricsServer is an HTTP server configured to return Prometheus metrics. Don't create objects of 34 // this type directly, use the MakeMetricsServer function instead. 35 type MetricsServer struct { 36 server *Server 37 registry *prometheus.Registry 38 } 39 40 // NewMetricsServer creates a metrics server. 41 func NewMetricsServer() *MetricsServer { 42 // Create the registry: 43 registry := prometheus.NewPedanticRegistry() 44 45 // Create the server: 46 handler := promhttp.HandlerFor(registry, promhttp.HandlerOpts{}) 47 server := NewServer() 48 server.AppendHandlers(handler.ServeHTTP) 49 50 // Create and populate the object: 51 return &MetricsServer{ 52 server: server, 53 registry: registry, 54 } 55 } 56 57 // Metrics returns an array of strings containing the metrics available in this server. Each item in 58 // this array is a line in the Prometheus exposition format. This is intended to be used together 59 // with the MatchLine matcher. 60 func (s *MetricsServer) Metrics() []string { 61 response, err := http.Get(s.server.URL() + "/metrics") 62 Expect(err).ToNot(HaveOccurred()) 63 defer func() { 64 err = response.Body.Close() 65 Expect(err).ToNot(HaveOccurred()) 66 }() 67 data, err := io.ReadAll(response.Body) 68 Expect(err).ToNot(HaveOccurred()) 69 return strings.Split(string(data), "\n") 70 } 71 72 // Registry returns the registry that should be used to register metrics for this server. 73 func (s *MetricsServer) Registry() prometheus.Registerer { 74 return s.registry 75 } 76 77 // Close stops the server and releases the resources it uses. 78 func (s *MetricsServer) Close() { 79 s.server.Close() 80 } 81 82 // MatchLine succeeds if actual is an slice of strings that contains at least one items that matches 83 // the passed regular expression. 84 func MatchLine(regexp string, args ...interface{}) OmegaMatcher { 85 return ContainElement(MatchRegexp(regexp, args...)) 86 }