Skip to content

Commit

Permalink
wip: test http handler CT generation
Browse files Browse the repository at this point in the history
Signed-off-by: Arthur Silva Sens <arthur.sens@coralogix.com>
  • Loading branch information
ArthurSens committed Aug 1, 2023
1 parent 74691a1 commit 7453af0
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
3 changes: 3 additions & 0 deletions prometheus/promhttp/http.go
Expand Up @@ -379,6 +379,9 @@ type HandlerOpts struct {
// NOTE: This feature is experimental and not covered by OpenMetrics or Prometheus
// exposition format.
ProcessStartTime time.Time
// If true, Counters, Summaries and Histograms will be exposed with additional
// information about the timestamp when a particular timeseries was first initialized.
EnableCreatedTimestamps bool
}

// gzipAccepted returns whether the client will accept gzip-encoded content.
Expand Down
56 changes: 56 additions & 0 deletions prometheus/promhttp/http_test.go
Expand Up @@ -17,6 +17,7 @@ import (
"bytes"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
Expand All @@ -25,6 +26,7 @@ import (
"time"

dto "github.com/prometheus/client_model/go"
"google.golang.org/protobuf/proto"

"github.com/prometheus/client_golang/prometheus"
)
Expand Down Expand Up @@ -331,3 +333,57 @@ func TestHandlerTimeout(t *testing.T) {

close(c.Block) // To not leak a goroutine.
}

func TestHandlerWithCreatedTimestamps(t *testing.T) {
testCases := []struct {
testName string
enableCreatedTimestamps bool
}{
{
testName: "Created timestamps enabled",
enableCreatedTimestamps: true,
},
{
testName: "Created timestamps disabled",
enableCreatedTimestamps: false,
},
}

for _, tc := range testCases {
tc := tc
t.Run(tc.testName, func(t *testing.T) {
reg := prometheus.NewRegistry()
handler := HandlerFor(reg, HandlerOpts{EnableCreatedTimestamps: true})
w := httptest.NewRecorder()
counter := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "test",
Help: "help test",
}, []string{"label"})
reg.MustRegister(counter)
counter.WithLabelValues("test1").Inc()
counter.WithLabelValues("test2").Add(2)
request, _ := http.NewRequest("GET", "/", nil)
request.Header.Add("Accept", "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.8")

handler.ServeHTTP(w, request)
rsp := w.Result()
body, err := io.ReadAll(rsp.Body)
if err != nil {
t.Errorf("Error reading response body: %s", err.Error())
}

var mf = dto.MetricFamily{}
if err := proto.Unmarshal(body, &mf); err != nil {
t.Errorf("Error unmarshaling response: %s", err.Error())
}

if tc.enableCreatedTimestamps && mf.Metric[0].Counter.CreatedTimestamp == nil {
t.Error("expected created timestamp, but there isn't")
}

if !tc.enableCreatedTimestamps && mf.Metric[0].Counter.CreatedTimestamp != nil {
t.Error("Did not expected created timestamp, but there is")
}
})
}
}

0 comments on commit 7453af0

Please sign in to comment.