1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package eventtest supports logging events to a test.
6 // You can use NewContext to create a context that knows how to deliver
7 // telemetry events back to the test.
8 // You must use this context or a derived one anywhere you want telemetry to be
9 // correctly routed back to the test it was constructed with.
10 // Any events delivered to a background context will be dropped.
12 // Importing this package will cause it to register a new global telemetry
13 // exporter that understands the special contexts returned by NewContext.
14 // This means you should not import this package if you are not going to call
24 "golang.org/x/tools/internal/event"
25 "golang.org/x/tools/internal/event/core"
26 "golang.org/x/tools/internal/event/export"
27 "golang.org/x/tools/internal/event/label"
31 e := &testExporter{buffer: &bytes.Buffer{}}
32 e.logger = export.LogWriter(e.buffer, false)
34 event.SetExporter(export.Spans(e.processEvent))
37 type testingKeyType int
39 const testingKey = testingKeyType(0)
41 // NewContext returns a context you should use for the active test.
42 func NewContext(ctx context.Context, t testing.TB) context.Context {
43 return context.WithValue(ctx, testingKey, t)
46 type testExporter struct {
52 func (w *testExporter) processEvent(ctx context.Context, ev core.Event, tm label.Map) context.Context {
55 // build our log message in buffer
56 result := w.logger(ctx, ev, tm)
57 v := ctx.Value(testingKey)
59 if w.buffer.Len() > 0 && v != nil {
60 v.(testing.TB).Log(w.buffer)