File: metric_test.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20231006.7918f67-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 6,492 kB
  • sloc: ansic: 1,900; objc: 276; sh: 272; asm: 48; makefile: 27
file content (75 lines) | stat: -rw-r--r-- 2,296 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package otel_test

import (
	"context"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/metric/metrictest"
	"go.opentelemetry.io/otel/metric/number"
	"golang.org/x/exp/event"
	"golang.org/x/exp/event/otel"
)

func TestMeter(t *testing.T) {
	ctx := context.Background()
	mp := metrictest.NewMeterProvider()
	mh := otel.NewMetricHandler(mp.Meter("test"))
	ctx = event.WithExporter(ctx, event.NewExporter(mh, nil))
	recordMetrics(ctx)

	lib := metrictest.Library{InstrumentationName: "test"}
	emptyLabels := map[attribute.Key]attribute.Value{}
	got := metrictest.AsStructs(mp.MeasurementBatches)
	want := []metrictest.Measured{
		{
			Name:    "golang.org/x/exp/event/otel_test/hits",
			Number:  number.NewInt64Number(8),
			Labels:  emptyLabels,
			Library: lib,
		},
		{
			Name:    "golang.org/x/exp/event/otel_test/temp",
			Number:  number.NewFloat64Number(-100),
			Labels:  map[attribute.Key]attribute.Value{"location": attribute.StringValue("Mare Imbrium")},
			Library: lib,
		},
		{
			Name:    "golang.org/x/exp/event/otel_test/latency",
			Number:  number.NewInt64Number(int64(1248 * time.Millisecond)),
			Labels:  emptyLabels,
			Library: lib,
		},
		{
			Name:    "golang.org/x/exp/event/otel_test/latency",
			Number:  number.NewInt64Number(int64(1255 * time.Millisecond)),
			Labels:  emptyLabels,
			Library: lib,
		},
	}

	if diff := cmp.Diff(want, got, cmp.Comparer(valuesEqual)); diff != "" {
		t.Errorf("mismatch (-want, got):\n%s", diff)
	}
}

func valuesEqual(v1, v2 attribute.Value) bool {
	return v1.AsInterface() == v2.AsInterface()
}

func recordMetrics(ctx context.Context) {
	c := event.NewCounter("hits", &event.MetricOptions{Description: "Earth meteorite hits"})
	g := event.NewFloatGauge("temp", &event.MetricOptions{Description: "moon surface temperature in Kelvin"})
	d := event.NewDuration("latency", &event.MetricOptions{Description: "Earth-moon comms lag, milliseconds"})

	c.Record(ctx, 8)
	g.Record(ctx, -100, event.String("location", "Mare Imbrium"))
	d.Record(ctx, 1248*time.Millisecond)
	d.Record(ctx, 1255*time.Millisecond)
}