40 lines
1.8 KiB
Go
40 lines
1.8 KiB
Go
package metrics_test
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/longpeng/configcenter/internal/metrics"
|
|
memory_store "github.com/longpeng/configcenter/internal/store/memory"
|
|
)
|
|
|
|
func TestHTTPDurationHistogram(t *testing.T) {
|
|
collector := metrics.New()
|
|
collector.ObserveHTTP(http.MethodGet, "GET /v1/config", http.StatusOK, 12*time.Millisecond)
|
|
collector.ObserveHTTP(http.MethodGet, "GET /v1/config", http.StatusOK, 300*time.Millisecond)
|
|
|
|
recorder := httptest.NewRecorder()
|
|
collector.Handler(memory_store.New(false)).ServeHTTP(recorder, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/metrics", nil))
|
|
if recorder.Code != http.StatusOK {
|
|
t.Fatalf("unexpected metrics status: %d", recorder.Code)
|
|
}
|
|
body := recorder.Body.String()
|
|
assertMetric(t, body, `configcenter_http_request_duration_seconds_bucket{method="GET",route="GET /v1/config",status="200",le="0.005"} 0`)
|
|
assertMetric(t, body, `configcenter_http_request_duration_seconds_bucket{method="GET",route="GET /v1/config",status="200",le="0.025"} 1`)
|
|
assertMetric(t, body, `configcenter_http_request_duration_seconds_bucket{method="GET",route="GET /v1/config",status="200",le="0.5"} 2`)
|
|
assertMetric(t, body, `configcenter_http_request_duration_seconds_bucket{method="GET",route="GET /v1/config",status="200",le="+Inf"} 2`)
|
|
assertMetric(t, body, `configcenter_http_request_duration_seconds_sum{method="GET",route="GET /v1/config",status="200"} 0.312000`)
|
|
assertMetric(t, body, `configcenter_http_request_duration_seconds_count{method="GET",route="GET /v1/config",status="200"} 2`)
|
|
}
|
|
|
|
func assertMetric(t *testing.T, body, expected string) {
|
|
t.Helper()
|
|
if !strings.Contains(body, expected+"\n") {
|
|
t.Fatalf("missing metric %q in:\n%s", expected, body)
|
|
}
|
|
}
|