From d222f971e2f5f9518bb69772bfeb34c17e92abdc Mon Sep 17 00:00:00 2001 From: xieyuschen Date: Mon, 18 Mar 2024 22:28:38 +0800 Subject: [PATCH] demo: overflow case for counter --- prometheus/counter_test.go | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/prometheus/counter_test.go b/prometheus/counter_test.go index 3686199..2673e20 100644 --- a/prometheus/counter_test.go +++ b/prometheus/counter_test.go @@ -25,6 +25,50 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) +func TestCounterAddExcess(t *testing.T) { + now := time.Now() + counter := NewCounter(CounterOpts{ + Name: "test", + Help: "test help", + ConstLabels: Labels{"a": "1", "b": "2"}, + now: func() time.Time { return now }, + }).(*counter) + + counter.Add(1 << 63) + if expected, got := uint64(1<<63), counter.valInt; expected != got { + t.Errorf("Expected %d, got %d.", expected, got) + } + + counter.Add(1 << 63) + if expected, got := uint64(0), counter.valInt; expected == got { + t.Errorf("oops! overflow") + } + + m := &dto.Metric{} + counter.Write(m) + + expected := &dto.Metric{ + Label: []*dto.LabelPair{ + {Name: proto.String("a"), Value: proto.String("1")}, + {Name: proto.String("b"), Value: proto.String("2")}, + }, + Counter: &dto.Counter{ + Value: proto.Float64(1 << 64), + CreatedTimestamp: timestamppb.New(now), + }, + } + + if !proto.Equal(expected, m) { + t.Errorf("failed because the internal overflow") + } + + // verify the overflow case + expected.Counter.Value = proto.Float64(0) + if proto.Equal(expected, m) { + t.Errorf("verify the overflow case") + } +} + func TestCounterAdd(t *testing.T) { now := time.Now()