-
Notifications
You must be signed in to change notification settings - Fork 0
/
context_test.go
84 lines (66 loc) · 2.16 KB
/
context_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
package log
import (
"context"
. "github.com/onsi/ginkgo"
g "github.com/onsi/gomega" // gomega.Panic function collides with log.Panic
)
var _ = Describe("Context", func() {
Context("Context", func() {
It("should provide context with value", func() {
ctx := WithContext(context.Background())
g.Expect(ctx.Value(ContextKeyLogFields)).ToNot(g.BeNil())
})
It("should save field value in context", func() {
ctx := WithContext(context.Background(), MakeField("foo", 5))
fields := GetContextFields(ctx)
g.Expect(len(fields)).To(g.Equal(1))
g.Expect(fields["foo"]).To(g.Equal(5))
})
It("should push and pop fields", func() {
ctx := WithContext(context.Background(), MakeField("foo", 5))
fields := GetContextFields(ctx)
g.Expect(len(fields)).To(g.Equal(1))
g.Expect(fields["foo"]).To(g.Equal(5))
func1(ctx)
fields = GetContextFields(ctx)
g.Expect(len(fields)).To(g.Equal(1))
g.Expect(fields["foo"]).To(g.Equal(5))
// pop should be safe to call even beyond actual stack height
PopContextFields(ctx)
PopContextFields(ctx)
PopContextFields(ctx)
})
It("should safely ignore when context is not initialized", func() {
ctx := context.Background()
fields := GetContextFields(ctx)
g.Expect(len(fields)).To(g.Equal(0))
PushContextFields(ctx, MakeField("foo", 0))
PopContextFields(ctx)
ctx = context.WithValue(ctx, ContextKeyLogFields, "wrong")
PopContextFields(ctx)
PopContextFields(ctx)
})
})
})
func func1(ctx context.Context) {
PushContextFields(ctx, MakeField("bar", 6))
defer PopContextFields(ctx)
fields := GetContextFields(ctx)
g.Expect(len(fields)).To(g.Equal(2))
g.Expect(fields["foo"]).To(g.Equal(5))
g.Expect(fields["bar"]).To(g.Equal(6))
func2(ctx)
fields = GetContextFields(ctx)
g.Expect(len(fields)).To(g.Equal(2))
g.Expect(fields["foo"]).To(g.Equal(5))
g.Expect(fields["bar"]).To(g.Equal(6))
}
func func2(ctx context.Context) {
WithContext(ctx, MakeField("taz", 7))
defer PopContextFields(ctx)
fields := GetContextFields(ctx)
g.Expect(len(fields)).To(g.Equal(3))
g.Expect(fields["foo"]).To(g.Equal(5))
g.Expect(fields["bar"]).To(g.Equal(6))
g.Expect(fields["taz"]).To(g.Equal(7))
}