File: event_test.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20230522.2e198f4-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 6,404 kB
  • sloc: ansic: 1,900; objc: 276; sh: 272; asm: 48; makefile: 26
file content (348 lines) | stat: -rw-r--r-- 9,171 bytes parent folder | download | duplicates (2)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
// Copyright 2020 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.

//go:build !disable_events
// +build !disable_events

package event_test

import (
	"context"
	"errors"
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	"golang.org/x/exp/event"
	"golang.org/x/exp/event/adapter/logfmt"
	"golang.org/x/exp/event/eventtest"
)

var (
	l1      = event.Int64("l1", 1)
	l2      = event.Int64("l2", 2)
	l3      = event.Int64("l3", 3)
	counter = event.NewCounter("hits", nil)
	gauge   = event.NewFloatGauge("temperature", nil)
	latency = event.NewDuration("latency", nil)
	err     = errors.New("an error")
)

func TestCommon(t *testing.T) {
	for _, test := range []struct {
		method string
		events func(context.Context)
		expect []event.Event
	}{{
		method: "simple",
		events: func(ctx context.Context) { event.Log(ctx, "a message") },
		expect: []event.Event{{
			ID:     1,
			Kind:   event.LogKind,
			Labels: []event.Label{event.String("msg", "a message")},
		}},
	}, {
		method: "log 1",
		events: func(ctx context.Context) { event.Log(ctx, "a message", l1) },
		expect: []event.Event{{
			ID:     1,
			Kind:   event.LogKind,
			Labels: []event.Label{event.String("msg", "a message"), l1},
		}},
	}, {
		method: "log 2",
		events: func(ctx context.Context) { event.Log(ctx, "a message", l1, l2) },
		expect: []event.Event{{
			ID:     1,
			Kind:   event.LogKind,
			Labels: []event.Label{event.String("msg", "a message"), l1, l2},
		}},
	}, {
		method: "log 3",
		events: func(ctx context.Context) { event.Log(ctx, "a message", l1, l2, l3) },
		expect: []event.Event{{
			ID:     1,
			Kind:   event.LogKind,
			Labels: []event.Label{event.String("msg", "a message"), l1, l2, l3},
		}},
	}, {
		method: "logf",
		events: func(ctx context.Context) { event.Logf(ctx, "logf %s message", "to") },
		expect: []event.Event{{
			ID:     1,
			Kind:   event.LogKind,
			Labels: []event.Label{event.String("msg", "logf to message")},
		}},
	}, {
		method: "error",
		events: func(ctx context.Context) { event.Error(ctx, "failed", err, l1) },
		expect: []event.Event{{
			ID:   1,
			Kind: event.LogKind,
			Labels: []event.Label{
				event.String("msg", "failed"),
				event.Value("error", err),
				l1,
			},
		}},
	}, {
		method: "span",
		events: func(ctx context.Context) {
			ctx = event.Start(ctx, `span`)
			event.End(ctx)
		},
		expect: []event.Event{{
			ID:     1,
			Kind:   event.StartKind,
			Labels: []event.Label{event.String("name", "span")},
		}, {
			ID:     2,
			Parent: 1,
			Kind:   event.EndKind,
			Labels: []event.Label{},
		}},
	}, {
		method: "span nested",
		events: func(ctx context.Context) {
			ctx = event.Start(ctx, "parent")
			defer event.End(ctx)
			child := event.Start(ctx, "child")
			defer event.End(child)
			event.Log(child, "message")
		},
		expect: []event.Event{{
			ID:     1,
			Kind:   event.StartKind,
			Labels: []event.Label{event.String("name", "parent")},
		}, {
			ID:     2,
			Parent: 1,
			Kind:   event.StartKind,
			Labels: []event.Label{event.String("name", "child")},
		}, {
			ID:     3,
			Parent: 2,
			Kind:   event.LogKind,
			Labels: []event.Label{event.String("msg", "message")},
		}, {
			ID:     4,
			Parent: 2,
			Kind:   event.EndKind,
			Labels: []event.Label{},
		}, {
			ID:     5,
			Parent: 1,
			Kind:   event.EndKind,
			Labels: []event.Label{},
		}},
	}, {
		method: "counter",
		events: func(ctx context.Context) { counter.Record(ctx, 2, l1) },
		expect: []event.Event{{
			ID:   1,
			Kind: event.MetricKind,
			Labels: []event.Label{
				event.Int64("metricValue", 2),
				event.Value("metric", counter),
				l1,
			},
		}},
	}, {
		method: "gauge",
		events: func(ctx context.Context) { gauge.Record(ctx, 98.6, l1) },
		expect: []event.Event{{
			ID:   1,
			Kind: event.MetricKind,
			Labels: []event.Label{
				event.Float64("metricValue", 98.6),
				event.Value("metric", gauge),
				l1,
			},
		}},
	}, {
		method: "duration",
		events: func(ctx context.Context) { latency.Record(ctx, 3*time.Second, l1, l2) },
		expect: []event.Event{{
			ID:   1,
			Kind: event.MetricKind,
			Labels: []event.Label{
				event.Duration("metricValue", 3*time.Second),
				event.Value("metric", latency),
				l1, l2,
			},
		}},
	}, {
		method: "annotate",
		events: func(ctx context.Context) { event.Annotate(ctx, l1) },
		expect: []event.Event{{
			ID:     1,
			Labels: []event.Label{l1},
		}},
	}, {
		method: "annotate 2",
		events: func(ctx context.Context) { event.Annotate(ctx, l1, l2) },
		expect: []event.Event{{
			ID:     1,
			Labels: []event.Label{l1, l2},
		}},
	}, {
		method: "multiple events",
		events: func(ctx context.Context) {
			/*TODO: this is supposed to be using a cached target
			t := event.To(ctx)
			p := event.Prototype{}.As(event.LogKind)
			t.With(p).Int("myInt", 6).Message("my event").Send()
			t.With(p).String("myString", "some string value").Message("string event").Send()
			*/
			event.Log(ctx, "my event", event.Int64("myInt", 6))
			event.Log(ctx, "string event", event.String("myString", "some string value"))
		},
		expect: []event.Event{{
			ID:   1,
			Kind: event.LogKind,
			Labels: []event.Label{
				event.String("msg", "my event"),
				event.Int64("myInt", 6),
			},
		}, {
			ID:   2,
			Kind: event.LogKind,
			Labels: []event.Label{
				event.String("msg", "string event"),
				event.String("myString", "some string value"),
			},
		}},
	}} {
		t.Run(test.method, func(t *testing.T) {
			ctx, h := eventtest.NewCapture()
			test.events(ctx)
			if diff := cmp.Diff(test.expect, h.Got, eventtest.CmpOptions()...); diff != "" {
				t.Errorf("mismatch (-want, +got):\n%s", diff)
			}
		})
	}
}

func ExampleLog() {
	ctx := event.WithExporter(context.Background(), event.NewExporter(logfmt.NewHandler(os.Stdout), eventtest.ExporterOptions()))
	event.Log(ctx, "my event", event.Int64("myInt", 6))
	event.Log(ctx, "error event", event.String("myString", "some string value"))
	// Output:
	// time="2020/03/05 14:27:48" myInt=6 msg="my event"
	// time="2020/03/05 14:27:49" myString="some string value" msg="error event"
}

func TestLogEventf(t *testing.T) {
	eventtest.TestBenchmark(t, eventPrint, eventLogf, eventtest.LogfOutput)
}

func TestLogEvent(t *testing.T) {
	eventtest.TestBenchmark(t, eventPrint, eventLog, eventtest.LogfmtOutput)
}

func TestTraceBuilder(t *testing.T) {
	// Verify that the context returned from the handler is also returned from Start,
	// and is the context passed to End.
	ctx := event.WithExporter(context.Background(), event.NewExporter(&testTraceHandler{t: t}, eventtest.ExporterOptions()))
	ctx = event.Start(ctx, "s")
	val := ctx.Value("x")
	if val != 1 {
		t.Fatal("context not returned from Start")
	}
	event.End(ctx)
}

type testTraceHandler struct {
	t *testing.T
}

func (t *testTraceHandler) Event(ctx context.Context, ev *event.Event) context.Context {
	switch ev.Kind {
	case event.StartKind:
		return context.WithValue(ctx, "x", 1)
	case event.EndKind:
		val := ctx.Value("x")
		if val != 1 {
			t.t.Fatal("Start context not passed to End")
		}
		return ctx
	default:
		return ctx
	}
}

func TestTraceDuration(t *testing.T) {
	// Verify that a trace can can emit a latency metric.
	dur := event.NewDuration("test", nil)
	want := time.Second

	check := func(t *testing.T, h *testTraceDurationHandler) {
		if !h.got.HasValue() {
			t.Fatal("no metric value")
		}
		got := h.got.Duration()
		if got != want {
			t.Fatalf("got %s, want %s", got, want)
		}
	}

	t.Run("returned builder", func(t *testing.T) {
		h := &testTraceDurationHandler{}
		ctx := event.WithExporter(context.Background(), event.NewExporter(h, eventtest.ExporterOptions()))
		ctx = event.Start(ctx, "s")
		time.Sleep(want)
		event.End(ctx, event.DurationMetric.Of(dur))
		check(t, h)
	})
	//TODO: come back and fix this
	t.Run("separate builder", func(t *testing.T) {
		h := &testTraceDurationHandler{}
		ctx := event.WithExporter(context.Background(), event.NewExporter(h, eventtest.ExporterOptions()))
		ctx = event.Start(ctx, "s")
		time.Sleep(want)
		event.End(ctx, event.DurationMetric.Of(dur))
		check(t, h)
	})
}

type testTraceDurationHandler struct {
	got event.Label
}

func (t *testTraceDurationHandler) Event(ctx context.Context, ev *event.Event) context.Context {
	for _, l := range ev.Labels {
		if l.Name == string(event.MetricVal) {
			t.got = l
		}
	}
	return ctx
}

func BenchmarkBuildContext(b *testing.B) {
	// How long does it take to deliver an event from a nested context?
	c := event.NewCounter("c", nil)
	for _, depth := range []int{1, 5, 7, 10} {
		b.Run(fmt.Sprintf("depth %d", depth), func(b *testing.B) {
			ctx := event.WithExporter(context.Background(), event.NewExporter(nopHandler{}, eventtest.ExporterOptions()))
			for i := 0; i < depth; i++ {
				ctx = context.WithValue(ctx, i, i)
			}
			b.Run("direct", func(b *testing.B) {
				for i := 0; i < b.N; i++ {
					c.Record(ctx, 1)
				}
			})
			/*TODO: work out how we do cached labels
			b.Run("cloned", func(b *testing.B) {
				bu := event.To(ctx)
				for i := 0; i < b.N; i++ {
					c.RecordTB(bu, 1).Name("foo").Send()
				}
			})
			*/
		})
	}
}