From 7569bb176b19fc76938960f3aa31f7fa6bae01f1 Mon Sep 17 00:00:00 2001 From: Shivanth Date: Sat, 4 Jan 2025 21:18:48 +0100 Subject: [PATCH] fix tests --- prometheus/metric.go | 9 ++++++--- prometheus/metric_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/prometheus/metric.go b/prometheus/metric.go index c587ee83b..d8e3d2c13 100644 --- a/prometheus/metric.go +++ b/prometheus/metric.go @@ -186,10 +186,13 @@ func (m *withExemplarsMetric) Write(pb *dto.Metric) error { case pb.Counter != nil: pb.Counter.Exemplar = m.exemplars[len(m.exemplars)-1] case pb.Histogram != nil: - if *pb.Histogram.Schema > math.MinInt32 { - pb.Histogram.Exemplars = append(pb.Histogram.Exemplars, m.exemplars...) - } for _, e := range m.exemplars { + if pb.Histogram.Schema != nil { + if *pb.Histogram.Schema > math.MinInt32 && e.GetTimestamp() != nil { + pb.Histogram.Exemplars = append(pb.Histogram.Exemplars, e) + } + continue + } // pb.Histogram.Bucket are sorted by UpperBound. i := sort.Search(len(pb.Histogram.Bucket), func(i int) bool { return pb.Histogram.Bucket[i].GetUpperBound() >= e.GetValue() diff --git a/prometheus/metric_test.go b/prometheus/metric_test.go index 629aa4f84..afdec0ae0 100644 --- a/prometheus/metric_test.go +++ b/prometheus/metric_test.go @@ -16,10 +16,12 @@ package prometheus import ( "math" "testing" + "time" dto "github.com/prometheus/client_model/go" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" ) func TestBuildFQName(t *testing.T) { @@ -90,3 +92,29 @@ func TestWithExemplarsMetric(t *testing.T) { } }) } + +func TestWithExemplarsNativeHistogramMetric(t *testing.T) { + t.Run("histogram", func(t *testing.T) { + // Create a constant histogram from values we got from a 3rd party telemetry system. + h := MustNewConstNativeHistogram( + NewDesc("http_request_duration_seconds", "A histogram of the HTTP request durations.", nil, nil), + 10, 12.1, map[int]int64{1: 7, 2: 1, 3: 2}, map[int]int64{}, 0, 2, 0.2, time.Date( + 2009, 11, 17, 20, 34, 58, 651387237, time.UTC)) + m := &withExemplarsMetric{Metric: h, exemplars: []*dto.Exemplar{ + {Value: proto.Float64(2000.0), Timestamp: timestamppb.New(time.Date(2009, 11, 17, 20, 34, 58, 3243244, time.UTC))}, + }} + metric := dto.Metric{} + if err := m.Write(&metric); err != nil { + t.Fatal(err) + } + if want, got := 1, len(metric.GetHistogram().Exemplars); want != got { + t.Errorf("want %v, got %v", want, got) + } + + for _, b := range metric.GetHistogram().Bucket { + if b.Exemplar != nil { + t.Error("Not expecting exemplar for bucket") + } + } + }) +}