Debian Codegraph @

event/eventtest/eventtest.go

raw symbols SCIP
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.
4
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 package eventtest
11
12 import (
13 "context"
14 "os"
15 "testing"
16 "time"
17
18 "github.com/google/go-cmp/cmp"
19 "github.com/google/go-cmp/cmp/cmpopts"
20 "golang.org/x/exp/event"
21 "golang.org/x/exp/event/adapter/logfmt"
22 )
23
24 // NewContext returns a context you should use for the active test.
25 func NewContext(ctx context.Context, tb testing.TB) context.Context {
26 h := &testHandler{tb: tb}
27 return event.WithExporter(ctx, event.NewExporter(h, nil))
28 }
29
30 type testHandler struct {
31 tb testing.TB
32 printer logfmt.Printer
33 }
34
35 func (h *testHandler) Event(ctx context.Context, ev *event.Event) context.Context {
36 //TODO: choose between stdout and stderr based on the event
37 //TODO: decide if we should be calling h.tb.Fail()
38 h.printer.Event(os.Stdout, ev)
39 return ctx
40 }
41
42 var InitialTime = func() time.Time {
43 t, _ := time.Parse(logfmt.TimeFormat, "2020/03/05 14:27:48")
44 return t
45 }()
46
47 func ExporterOptions() *event.ExporterOptions {
48 nextTime := InitialTime
49 return &event.ExporterOptions{
50 Now: func() time.Time {
51 thisTime := nextTime
52 nextTime = nextTime.Add(time.Second)
53 return thisTime
54 },
55 }
56 }
57
58 func CmpOptions() []cmp.Option {
59 return []cmp.Option{
60 cmpopts.SortSlices(func(x, y event.Label) bool {
61 return x.Name < y.Name
62 }),
63 cmpopts.IgnoreFields(event.Event{}, "At", "ctx", "target", "labels"),
64 }
65 }