Debian Codegraph @

prometheus/utils_test.go

raw
1 // Copyright 2018 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 package prometheus_test
14
15 import (
16 "bytes"
17 "encoding/json"
18 "time"
19
20 dto "github.com/prometheus/client_model/go"
21 "google.golang.org/protobuf/encoding/protojson"
22 "google.golang.org/protobuf/proto"
23 "google.golang.org/protobuf/types/known/timestamppb"
24 )
25
26 // sanitizeMetric injects expected fake created timestamp value "1970-01-01T00:00:10Z",
27 // so we can compare it in examples. It modifies metric in-place, the returned pointer
28 // is for convenience.
29 func sanitizeMetric(metric *dto.Metric) *dto.Metric {
30 if metric.Counter != nil && metric.Counter.CreatedTimestamp != nil {
31 metric.Counter.CreatedTimestamp = timestamppb.New(time.Unix(10, 0))
32 }
33 if metric.Summary != nil && metric.Summary.CreatedTimestamp != nil {
34 metric.Summary.CreatedTimestamp = timestamppb.New(time.Unix(10, 0))
35 }
36 if metric.Histogram != nil && metric.Histogram.CreatedTimestamp != nil {
37 metric.Histogram.CreatedTimestamp = timestamppb.New(time.Unix(10, 0))
38 }
39 return metric
40 }
41
42 // sanitizeMetricFamily is like sanitizeMetric, but for multiple metrics.
43 func sanitizeMetricFamily(f *dto.MetricFamily) *dto.MetricFamily {
44 for _, m := range f.Metric {
45 sanitizeMetric(m)
46 }
47 return f
48 }
49
50 // toNormalizedJSON removes fake random space from proto JSON original marshaller.
51 // It is required, so we can compare proto messages in json format.
52 // Read more in https://github.com/golang/protobuf/issues/1121
53 func toNormalizedJSON(m proto.Message) string {
54 mAsJSON, err := protojson.Marshal(m)
55 if err != nil {
56 panic(err)
57 }
58
59 buffer := new(bytes.Buffer)
60 if err := json.Compact(buffer, mAsJSON); err != nil {
61 panic(err)
62 }
63 return buffer.String()
64 }