88 "testing"
99 "time"
1010
11+ dto "github.com/prometheus/client_model/go"
1112 "github.com/prometheus/common/expfmt"
1213 "github.com/prometheus/common/model"
1314 api "k8s.io/api/core/v1"
@@ -121,9 +122,11 @@ func testEndpoints(t *testing.T, client *kubernetes.Clientset, slices bool) {
121122 expectBucketsDelta = map [int ]uint64 {}
122123 }
123124
124- // create the expected bucket values by adding deltas to the base state buckets
125- if _ , ok := base [metricName ]; ok {
126- for i , bucket := range base [metricName ].Metric [0 ].Histogram .Bucket {
125+ // create the expected bucket values by adding deltas to the base state buckets.
126+ // Look up headless_with_selector explicitly — cluster_ip is now also recorded and
127+ // sorts first alphabetically, so Metric[0] is no longer reliable.
128+ if baseMetric := metricByServiceKind (base [metricName ], "headless_with_selector" ); baseMetric != nil {
129+ for i , bucket := range baseMetric .Histogram .Bucket {
127130 expectBuckets = append (expectBuckets , expectBucket {i , * bucket .CumulativeCount + expectBucketsDelta [i ]})
128131 }
129132 }
@@ -138,14 +141,34 @@ func testEndpoints(t *testing.T, client *kubernetes.Clientset, slices bool) {
138141 if _ , ok := got [metricName ]; ! ok {
139142 t .Fatalf ("Did not find '%v' in scraped metrics." , metricName )
140143 }
144+ gotMetric := metricByServiceKind (got [metricName ], "headless_with_selector" )
145+ if gotMetric == nil {
146+ t .Fatalf ("Did not find headless_with_selector service_kind in '%v'" , metricName )
147+ }
141148 for _ , eb := range expectBuckets {
142- count := * got [ metricName ]. Metric [ 0 ] .Histogram .Bucket [eb .n ].CumulativeCount
149+ count := * gotMetric .Histogram .Bucket [eb .n ].CumulativeCount
143150 if count != eb .count {
144151 t .Errorf ("In bucket %v, expected %v, got %v" , eb .n , eb .count , count )
145152 }
146153 }
147154}
148155
156+ // metricByServiceKind returns the first dto.Metric in the family whose
157+ // service_kind label matches the given value, or nil if not found.
158+ func metricByServiceKind (family * dto.MetricFamily , serviceKind string ) * dto.Metric {
159+ if family == nil {
160+ return nil
161+ }
162+ for _ , m := range family .Metric {
163+ for _ , l := range m .Label {
164+ if l .GetName () == "service_kind" && l .GetValue () == serviceKind {
165+ return m
166+ }
167+ }
168+ }
169+ return nil
170+ }
171+
149172func addUpdateEndpoints (t * testing.T , client * kubernetes.Clientset ) {
150173 subset1 := []api.EndpointSubset {{
151174 Addresses : []api.EndpointAddress {{IP : "1.2.3.6" , Hostname : "foo" }},
0 commit comments