|
| 1 | +package prometheus |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/kimdre/doco-cd/internal/config" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "strings" |
| 8 | + "testing" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/prometheus/client_golang/prometheus/promhttp" |
| 12 | +) |
| 13 | + |
| 14 | +// TestServe tests the metrics endpoint serving functionality. |
| 15 | +func TestServe(t *testing.T) { |
| 16 | + expectedStatusCode := 200 |
| 17 | + expectedContentType := "text/plain; version=0.0.4; charset=utf-8; escaping=underscores" |
| 18 | + |
| 19 | + appConfig, err := config.GetAppConfig() |
| 20 | + if err != nil { |
| 21 | + t.Fatalf("Failed to get app config: %v", err) |
| 22 | + } |
| 23 | + |
| 24 | + AppInfo.WithLabelValues("test", appConfig.LogLevel, time.Now().Format(time.RFC3339)).Set(1) |
| 25 | + |
| 26 | + req, err := http.NewRequest("GET", MetricsPath, nil) |
| 27 | + if err != nil { |
| 28 | + t.Fatal(err) |
| 29 | + } |
| 30 | + |
| 31 | + rr := httptest.NewRecorder() |
| 32 | + |
| 33 | + handler := promhttp.Handler() |
| 34 | + handler.ServeHTTP(rr, req) |
| 35 | + |
| 36 | + if status := rr.Code; status != expectedStatusCode { |
| 37 | + t.Errorf("Expected status code %d, got %d", expectedStatusCode, status) |
| 38 | + } |
| 39 | + |
| 40 | + if contentType := rr.Header().Get("Content-Type"); contentType != expectedContentType { |
| 41 | + t.Errorf("Expected Content-Type %s, got %s", expectedContentType, contentType) |
| 42 | + } |
| 43 | + |
| 44 | + // Check if the response body is not empty |
| 45 | + if rr.Body.Len() == 0 { |
| 46 | + t.Error("Expected non-empty response body, got empty") |
| 47 | + } |
| 48 | + |
| 49 | + // Check if the response body contains the expected metrics |
| 50 | + if !strings.Contains(rr.Body.String(), "doco_cd_info") { |
| 51 | + t.Error("Expected response body to contain 'doco_cd_info' metric, but it does not") |
| 52 | + } |
| 53 | +} |
0 commit comments