-
Hi! I've configured Prometheus Middleware with custom metric as shown in the example. I've tried to mock echo with this Middleware in the tests but it looks like it doesn't work the way I expect it to work and middleware is being initialised for every test. func TestGetToken(t *testing.T) {
for _, tt := range []struct {
name string
client ClientStub
expectedStatus int
expectedBody string
}{
{
name: "successful token generation",
client: ClientStub{},
expectedStatus: http.StatusOK,
},
{
name: "unsuccessful token generation",
client: ClientStub{err: errors.New("error")},
expectedStatus: http.StatusInternalServerError,
},
} {
t.Run(tt.name, func(t *testing.T) {
// Setup
e := server.NewEchoServer()
req := httptest.NewRequest(http.MethodGet, "/token", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
logger := zaptest.NewLogger(t)
// init metrics
m := metrics.NewMetrics()
c.Set(metrics.CustomKeyMetrics, m)
p := prometheus.NewPrometheus(metrics.CustomKeyMetrics, nil, m.MetricList())
p.Use(e)
e.Use(m.AddCustomMetricsMiddleware)
h := GetToken(context.Background(), logger, &tt.client)
h(c)
// Assertions
assert.Equal(t, tt.expectedStatus, rec.Code)
t.Cleanup(func() {
e.Close()
})
})
}
} The test produces following errors in the logs:
Therefore it looks like middleware isn't properly isolated but I can't figure out how to do it. Can you advise? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is because Prometheus middleware own tests unregister these metrics like that at the end of test https://github.com/labstack/echo-contrib/blob/b6855c2b7d9745b7db2498623e89cae526b41f57/prometheus/prometheus_test.go#L15 p.s. Prometheus middleware repository is located here https://github.com/labstack/echo-contrib and issues/PR should be sent there. |
Beta Was this translation helpful? Give feedback.
This is because
middleware.NewPrometheus()
registers metrics into global register here https://github.com/labstack/echo-contrib/blob/b6855c2b7d9745b7db2498623e89cae526b41f57/prometheus/prometheus.go#L381Prometheus middleware own tests unregister these metrics like that at the end of test https://github.com/labstack/echo-contrib/blob/b6855c2b7d9745b7db2498623e89cae526b41f57/prometheus/prometheus_test.go#L15
p.s. Prometheus middleware repository is located here https://github.com/labstack/echo-contrib and issues/PR should be sent there.