forked from movio/bramble
-
Notifications
You must be signed in to change notification settings - Fork 0
/
instrumentation_test.go
99 lines (85 loc) · 2.12 KB
/
instrumentation_test.go
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
package bramble
import (
"context"
"encoding/json"
"io"
"testing"
"time"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
func collectLogEvent(t *testing.T, f func()) map[string]interface{} {
t.Helper()
r, w := io.Pipe()
defer r.Close()
logger := log.StandardLogger()
prevOut := logger.Out
prevFmt := logger.Formatter
logger.SetOutput(w)
logger.SetFormatter(&log.JSONFormatter{})
t.Cleanup(func() {
logger.SetOutput(prevOut)
logger.SetFormatter(prevFmt)
})
go func() {
defer w.Close()
f()
}()
var obj map[string]interface{}
err := json.NewDecoder(r).Decode(&obj)
assert.NoError(t, err)
return obj
}
func collectEventFromContext(ctx context.Context, t *testing.T, f func(*event)) map[string]interface{} {
t.Helper()
return collectLogEvent(t, func() {
e := getEvent(ctx)
f(e)
if e != nil {
e.finish()
}
})
}
func TestDropsField(t *testing.T) {
AddField(context.TODO(), "val", "test")
assert.True(t, true)
}
func TestEventLogOnFinish(t *testing.T) {
ctx, _ := startEvent(context.TODO(), "test")
output := collectEventFromContext(ctx, t, func(*event) {
AddField(ctx, "val", "test")
})
assert.Equal(t, "test", output["val"])
}
func TestAddMultipleToEventOnContext(t *testing.T) {
ctx, _ := startEvent(context.TODO(), "test")
output := collectEventFromContext(ctx, t, func(*event) {
AddFields(ctx, EventFields{
"gizmo": "foo",
"gimmick": "bar",
})
})
assert.Equal(t, "foo", output["gizmo"])
assert.Equal(t, "bar", output["gimmick"])
}
func TestEventMeasurement(t *testing.T) {
start := time.Now()
ctx, _ := startEvent(context.TODO(), "test")
output := collectEventFromContext(ctx, t, func(*event) {
time.Sleep(time.Microsecond)
})
if ts, ok := output["timestamp"].(string); ok {
timestamp, err := time.Parse(time.RFC3339Nano, ts)
assert.NoError(t, err)
assert.WithinDuration(t, start, timestamp, time.Second)
} else {
assert.Fail(t, "missing timestamp")
}
if dur, ok := output["duration"].(string); ok {
duration, err := time.ParseDuration(dur)
assert.NoError(t, err)
assert.True(t, duration > 0)
} else {
assert.Fail(t, "missing duration")
}
}