@@ -198,13 +198,48 @@ func (s) TestDelete(t *testing.T) {
198198 }
199199}
200200
201+ func (s ) TestFromIncomingContext (t * testing.T ) {
202+ md := Pairs (
203+ "X-My-Header-1" , "42" ,
204+ )
205+ // Verify that we lowercase if callers directly modify md
206+ md ["X-INCORRECT-UPPERCASE" ] = []string {"foo" }
207+ ctx := NewIncomingContext (context .Background (), md )
208+
209+ result , found := FromIncomingContext (ctx )
210+ if ! found {
211+ t .Fatal ("FromIncomingContext must return metadata" )
212+ }
213+ expected := MD {
214+ "x-my-header-1" : []string {"42" },
215+ "x-incorrect-uppercase" : []string {"foo" },
216+ }
217+ if ! reflect .DeepEqual (result , expected ) {
218+ t .Errorf ("FromIncomingContext returned %#v, expected %#v" , result , expected )
219+ }
220+
221+ // ensure modifying result does not modify the value in the context
222+ result ["new_key" ] = []string {"foo" }
223+ result ["x-my-header-1" ][0 ] = "mutated"
224+
225+ result2 , found := FromIncomingContext (ctx )
226+ if ! found {
227+ t .Fatal ("FromIncomingContext must return metadata" )
228+ }
229+ if ! reflect .DeepEqual (result2 , expected ) {
230+ t .Errorf ("FromIncomingContext after modifications returned %#v, expected %#v" , result2 , expected )
231+ }
232+ }
233+
201234func (s ) TestValueFromIncomingContext (t * testing.T ) {
202235 md := Pairs (
203236 "X-My-Header-1" , "42" ,
204237 "X-My-Header-2" , "43-1" ,
205238 "X-My-Header-2" , "43-2" ,
206239 "x-my-header-3" , "44" ,
207240 )
241+ // Verify that we lowercase if callers directly modify md
242+ md ["X-INCORRECT-UPPERCASE" ] = []string {"foo" }
208243 ctx := NewIncomingContext (context .Background (), md )
209244
210245 for _ , test := range []struct {
@@ -227,6 +262,10 @@ func (s) TestValueFromIncomingContext(t *testing.T) {
227262 key : "x-unknown" ,
228263 want : nil ,
229264 },
265+ {
266+ key : "x-incorrect-uppercase" ,
267+ want : []string {"foo" },
268+ },
230269 } {
231270 v := ValueFromIncomingContext (ctx , test .key )
232271 if ! reflect .DeepEqual (v , test .want ) {
@@ -348,8 +387,22 @@ func BenchmarkFromIncomingContext(b *testing.B) {
348387func BenchmarkValueFromIncomingContext (b * testing.B ) {
349388 md := Pairs ("X-My-Header-1" , "42" )
350389 ctx := NewIncomingContext (context .Background (), md )
351- b .ResetTimer ()
352- for n := 0 ; n < b .N ; n ++ {
353- ValueFromIncomingContext (ctx , "x-my-header-1" )
354- }
390+
391+ b .Run ("key-found" , func (b * testing.B ) {
392+ for n := 0 ; n < b .N ; n ++ {
393+ result := ValueFromIncomingContext (ctx , "x-my-header-1" )
394+ if len (result ) != 1 {
395+ b .Fatal ("ensures not optimized away" )
396+ }
397+ }
398+ })
399+
400+ b .Run ("key-not-found" , func (b * testing.B ) {
401+ for n := 0 ; n < b .N ; n ++ {
402+ result := ValueFromIncomingContext (ctx , "key-not-found" )
403+ if len (result ) != 0 {
404+ b .Fatal ("ensures not optimized away" )
405+ }
406+ }
407+ })
355408}
0 commit comments