...
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 package callctx
31
32 import (
33 "context"
34 "sync"
35 "testing"
36
37 "github.com/google/go-cmp/cmp"
38 )
39
40 func TestAll(t *testing.T) {
41 testCases := []struct {
42 name string
43 pairs []string
44 want map[string][]string
45 }{
46 {
47 name: "standard",
48 pairs: []string{"key", "value"},
49 want: map[string][]string{"key": {"value"}},
50 },
51 {
52 name: "multiple values",
53 pairs: []string{"key", "value", "key2", "value2"},
54 want: map[string][]string{"key": {"value"}, "key2": {"value2"}},
55 },
56 {
57 name: "multiple values with same key",
58 pairs: []string{"key", "value", "key", "value2"},
59 want: map[string][]string{"key": {"value", "value2"}},
60 },
61 }
62 for _, tc := range testCases {
63 ctx := context.Background()
64 ctx = SetHeaders(ctx, tc.pairs...)
65 got := HeadersFromContext(ctx)
66 if diff := cmp.Diff(tc.want, got); diff != "" {
67 t.Errorf("HeadersFromContext() mismatch (-want +got):\n%s", diff)
68 }
69 }
70 }
71
72 func TestSetHeaders_panics(t *testing.T) {
73 defer func() {
74 if r := recover(); r == nil {
75 t.Errorf("expected panic with odd key value pairs")
76 }
77 }()
78 ctx := context.Background()
79 SetHeaders(ctx, "1", "2", "3")
80 }
81
82 func TestSetHeaders_reuse(t *testing.T) {
83 c := SetHeaders(context.Background(), "key", "value1")
84 v1 := HeadersFromContext(c)
85 c = SetHeaders(c, "key", "value2")
86 v2 := HeadersFromContext(c)
87
88 if cmp.Diff(v2, v1) == "" {
89 t.Errorf("Second header set did not differ from first header set as expected")
90 }
91 }
92
93 func TestSetHeaders_race(t *testing.T) {
94 key := "key"
95 value := "value"
96 want := map[string][]string{
97 key: {value, value},
98 }
99
100
101 cctx := SetHeaders(context.Background(), key, value)
102
103
104
105 var wg sync.WaitGroup
106 for i := 0; i < 3; i++ {
107 wg.Add(1)
108 go func(ctx context.Context) {
109 defer wg.Done()
110 c := SetHeaders(ctx, key, value)
111 h := HeadersFromContext(c)
112
113
114
115
116 if diff := cmp.Diff(h, want); diff != "" {
117 t.Errorf("got(-),want(+):\n%s", diff)
118 }
119 }(cctx)
120 }
121 wg.Wait()
122 }
123
View as plain text