jobmetrics_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package metrics
  2. import (
  3. "testing"
  4. "github.com/opencost/opencost/core/pkg/clustercache"
  5. "github.com/prometheus/client_golang/prometheus"
  6. dto "github.com/prometheus/client_model/go"
  7. batchv1 "k8s.io/api/batch/v1"
  8. "k8s.io/apimachinery/pkg/types"
  9. )
  10. func TestKubeJobCollector_Collect(t *testing.T) {
  11. // Test with job that has no failures
  12. cache := &clustercache.MockClusterCache{
  13. Jobs: []*clustercache.Job{
  14. {
  15. Name: "test-job",
  16. Namespace: "default",
  17. UID: types.UID("test-job-uid"),
  18. Status: batchv1.JobStatus{Failed: 0},
  19. },
  20. },
  21. }
  22. collector := KubeJobCollector{
  23. KubeClusterCache: cache,
  24. metricsConfig: MetricsConfig{},
  25. }
  26. ch := make(chan prometheus.Metric, 10)
  27. go func() {
  28. collector.Collect(ch)
  29. close(ch)
  30. }()
  31. count := 0
  32. for range ch {
  33. count++
  34. }
  35. if count != 1 {
  36. t.Errorf("Expected 1 metric, got %d", count)
  37. }
  38. }
  39. func TestKubeJobStatusFailedMetric_Write(t *testing.T) {
  40. metric := newKubeJobStatusFailedMetric(
  41. "test-job",
  42. "default",
  43. "test-job-uid",
  44. "kube_job_status_failed",
  45. "",
  46. 0.0,
  47. )
  48. pbMetric := &dto.Metric{}
  49. err := metric.Write(pbMetric)
  50. if err != nil {
  51. t.Fatalf("Write failed: %v", err)
  52. }
  53. if pbMetric.Gauge == nil || *pbMetric.Gauge.Value != 0.0 {
  54. t.Error("Expected gauge value 0.0")
  55. }
  56. if len(pbMetric.Label) != 4 { // job_name + namespace + uid + reason
  57. t.Errorf("Expected 4 labels, got %d", len(pbMetric.Label))
  58. }
  59. // Verify UID label is present
  60. foundUID := false
  61. for _, label := range pbMetric.Label {
  62. if *label.Name == "uid" && *label.Value == "test-job-uid" {
  63. foundUID = true
  64. break
  65. }
  66. }
  67. if !foundUID {
  68. t.Error("Expected uid label not found")
  69. }
  70. }