jobmetrics_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. type mockJobCache struct {
  11. clustercache.ClusterCache
  12. jobs []*clustercache.Job
  13. }
  14. func (m mockJobCache) GetAllJobs() []*clustercache.Job {
  15. return m.jobs
  16. }
  17. func TestKubeJobCollector_Collect(t *testing.T) {
  18. // Test with job that has no failures
  19. cache := mockJobCache{
  20. jobs: []*clustercache.Job{
  21. {
  22. Name: "test-job",
  23. Namespace: "default",
  24. UID: types.UID("test-job-uid"),
  25. Status: batchv1.JobStatus{Failed: 0},
  26. },
  27. },
  28. }
  29. collector := KubeJobCollector{
  30. KubeClusterCache: cache,
  31. metricsConfig: MetricsConfig{},
  32. }
  33. ch := make(chan prometheus.Metric, 10)
  34. go func() {
  35. collector.Collect(ch)
  36. close(ch)
  37. }()
  38. count := 0
  39. for range ch {
  40. count++
  41. }
  42. if count != 1 {
  43. t.Errorf("Expected 1 metric, got %d", count)
  44. }
  45. }
  46. func TestKubeJobStatusFailedMetric_Write(t *testing.T) {
  47. metric := newKubeJobStatusFailedMetric(
  48. "test-job",
  49. "default",
  50. "test-job-uid",
  51. "kube_job_status_failed",
  52. "",
  53. 0.0,
  54. )
  55. pbMetric := &dto.Metric{}
  56. err := metric.Write(pbMetric)
  57. if err != nil {
  58. t.Fatalf("Write failed: %v", err)
  59. }
  60. if pbMetric.Gauge == nil || *pbMetric.Gauge.Value != 0.0 {
  61. t.Error("Expected gauge value 0.0")
  62. }
  63. if len(pbMetric.Label) != 4 { // job_name + namespace + uid + reason
  64. t.Errorf("Expected 4 labels, got %d", len(pbMetric.Label))
  65. }
  66. // Verify UID label is present
  67. foundUID := false
  68. for _, label := range pbMetric.Label {
  69. if *label.Name == "uid" && *label.Value == "test-job-uid" {
  70. foundUID = true
  71. break
  72. }
  73. }
  74. if !foundUID {
  75. t.Error("Expected uid label not found")
  76. }
  77. }