gitlab.com/ignitionrobotics/web/ign-go@v1.0.0-rc4/monitoring_prometheus_test.go (about) 1 package ign 2 3 import ( 4 "github.com/gorilla/mux" 5 "github.com/jinzhu/gorm" 6 "github.com/stretchr/testify/suite" 7 "gitlab.com/ignitionrobotics/web/ign-go/monitoring" 8 "gitlab.com/ignitionrobotics/web/ign-go/monitoring/prometheus" 9 "net/http" 10 "net/http/httptest" 11 "testing" 12 ) 13 14 func TestMonitoringPrometheusTestSuite(t *testing.T) { 15 suite.Run(t, &MonitoringPrometheusTestSuite{}) 16 } 17 18 type MonitoringPrometheusTestSuite struct { 19 suite.Suite 20 monitoring monitoring.Provider 21 metricsRoute string 22 router *mux.Router 23 server *Server 24 } 25 26 func (suite *MonitoringPrometheusTestSuite) SetupSuite() { 27 suite.monitoring = prometheus.NewPrometheusProvider("") 28 suite.metricsRoute = suite.monitoring.MetricsRoute() 29 30 suite.server = &Server{ 31 HTTPPort: ":8000", 32 SSLport: ":4430", 33 monitoring: suite.monitoring, 34 } 35 36 // Prepare the router 37 suite.router = NewRouter() 38 // Test route 39 suite.server.ConfigureRouterWithRoutes("/", suite.router, Routes{ 40 { 41 Name: "test", 42 Description: "Test route.", 43 URI: "/test", 44 Headers: nil, 45 Methods: Methods{ 46 { 47 Type: "GET", 48 Description: "Test GET route.", 49 Handlers: FormatHandlers{ 50 { 51 Extension: "", 52 Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 53 // Set the body 54 _, err := w.Write([]byte("OK")) 55 56 // Set the status code 57 code := 200 58 if err != nil { 59 code = 500 60 } 61 w.WriteHeader(code) 62 }), 63 }, 64 }, 65 }, 66 }, 67 }, 68 }) 69 // SetRouter automatically configures the router with a monitoring route 70 suite.server.SetRouter(suite.router) 71 72 // Server needs to be initialized to prevent the logging middleware from panicking 73 gServer = suite.server 74 suite.server.Db = &gorm.DB{} 75 } 76 77 func (suite *MonitoringPrometheusTestSuite) TestMonitoringRouteExists() { 78 // Check that the route exists and returns successfully 79 match := &mux.RouteMatch{} 80 req, err := http.NewRequest("GET", suite.metricsRoute, nil) 81 suite.NoError(err) 82 83 suite.True(suite.router.Match(req, match)) 84 suite.NoError(match.MatchErr) 85 } 86 87 func (suite *MonitoringPrometheusTestSuite) TestMonitoringRoute() { 88 sendRequest := func(route string) *httptest.ResponseRecorder { 89 req, err := http.NewRequest("GET", route, nil) 90 suite.NoError(err) 91 w := httptest.NewRecorder() 92 93 suite.router.ServeHTTP(w, req) 94 95 suite.Equal(200, w.Code) 96 97 return w 98 } 99 responseBody := sendRequest("/test").Body.String() 100 suite.Equal("OK", responseBody) 101 responseBody = sendRequest("/test").Body.String() 102 suite.Equal("OK", responseBody) 103 104 responseBody = sendRequest("/metrics").Body.String() 105 suite.Contains(responseBody, "http_requests_total{status=\"200\"} 2") 106 suite.Contains(responseBody, "http_request_duration_seconds_count{method=\"GET\",path=\"test\",status=\"200\"} 2") 107 108 }