Skip to content

Commit

Permalink
json marshal for Extrema type, makefile typo fix
Browse files Browse the repository at this point in the history
  • Loading branch information
m-posluszny committed Jan 15, 2024
1 parent 5ed29d9 commit 4fb7a19
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ test-coverage: | $(GOCOVMERGE)
done; \
$(GOCOVMERGE) $$(find . -name coverage.out) > coverage.txt

# Adding a directory will include all benchmarks in that direcotry if a filter is not specified.
# Adding a directory will include all benchmarks in that directory if a filter is not specified.
BENCHMARK_TARGETS := sdk/trace
.PHONY: benchmark
benchmark: $(BENCHMARK_TARGETS:%=benchmark/%)
Expand Down
10 changes: 10 additions & 0 deletions sdk/metric/metricdata/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
package metricdata // import "go.opentelemetry.io/otel/sdk/metric/metricdata"

import (
"encoding/json"
"fmt"
"time"

"go.opentelemetry.io/otel/attribute"
Expand Down Expand Up @@ -211,6 +213,14 @@ type Extrema[N int64 | float64] struct {
valid bool
}

// MarshalJson converts the Extrema value to JSON number
func (e *Extrema[N]) MarshalJSON() ([]byte, error) {
if !e.valid {
return []byte("0"), nil
}
return []byte(json.Number(fmt.Sprint(e.value))), nil
}

// NewExtrema returns an Extrema set to v.
func NewExtrema[N int64 | float64](v N) Extrema[N] {
return Extrema[N]{value: v, valid: true}
Expand Down
22 changes: 22 additions & 0 deletions sdk/metric/metricdata/metricdatatest/assertion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package metricdatatest // import "go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest"

import (
"encoding/json"
"testing"
"time"

Expand Down Expand Up @@ -164,6 +165,8 @@ var (
minFloat64C = metricdata.NewExtrema(-1.)
minInt64C = metricdata.NewExtrema[int64](-1)

minFloat64D = metricdata.NewExtrema(-9.999999)

histogramDataPointInt64A = metricdata.HistogramDataPoint[int64]{
Attributes: attrA,
StartTime: startA,
Expand Down Expand Up @@ -1010,3 +1013,22 @@ func TestAssertAttributesFail(t *testing.T) {
}
assert.False(t, AssertHasAttributes(fakeT, sum, attribute.Bool("A", true)))
}

func AssertMarshal[N int64 | float64](t *testing.T, expected string, i *metricdata.Extrema[N]) {
t.Helper()

b, err := json.Marshal(i)
assert.NoError(t, err)
assert.Equal(t, expected, string(b))
}

func TestAssertMarshal(t *testing.T) {
AssertMarshal(t, "-1", &minFloat64A)
AssertMarshal(t, "3", &minFloat64B)
AssertMarshal(t, "-9.999999", &minFloat64D)
AssertMarshal(t, "99", &maxFloat64B)

AssertMarshal(t, "-1", &minInt64A)
AssertMarshal(t, "3", &minInt64B)
AssertMarshal(t, "99", &maxInt64B)
}

0 comments on commit 4fb7a19

Please sign in to comment.