google.golang.org/grpc@v1.62.1/internal/metadata/metadata_test.go (about) 1 /* 2 * 3 * Copyright 2020 gRPC authors. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 * 17 */ 18 19 package metadata 20 21 import ( 22 "errors" 23 "reflect" 24 "testing" 25 26 "github.com/google/go-cmp/cmp" 27 "google.golang.org/grpc/attributes" 28 "google.golang.org/grpc/metadata" 29 "google.golang.org/grpc/resolver" 30 ) 31 32 func TestGet(t *testing.T) { 33 tests := []struct { 34 name string 35 addr resolver.Address 36 want metadata.MD 37 }{ 38 { 39 name: "not set", 40 addr: resolver.Address{}, 41 want: nil, 42 }, 43 { 44 name: "not set", 45 addr: resolver.Address{ 46 Attributes: attributes.New(mdKey, mdValue(metadata.Pairs("k", "v"))), 47 }, 48 want: metadata.Pairs("k", "v"), 49 }, 50 } 51 for _, tt := range tests { 52 t.Run(tt.name, func(t *testing.T) { 53 if got := Get(tt.addr); !cmp.Equal(got, tt.want) { 54 t.Errorf("Get() = %v, want %v", got, tt.want) 55 } 56 }) 57 } 58 } 59 60 func TestSet(t *testing.T) { 61 tests := []struct { 62 name string 63 addr resolver.Address 64 md metadata.MD 65 }{ 66 { 67 name: "unset before", 68 addr: resolver.Address{}, 69 md: metadata.Pairs("k", "v"), 70 }, 71 { 72 name: "set before", 73 addr: resolver.Address{ 74 Attributes: attributes.New(mdKey, mdValue(metadata.Pairs("bef", "ore"))), 75 }, 76 md: metadata.Pairs("k", "v"), 77 }, 78 } 79 for _, tt := range tests { 80 t.Run(tt.name, func(t *testing.T) { 81 newAddr := Set(tt.addr, tt.md) 82 newMD := Get(newAddr) 83 if !cmp.Equal(newMD, tt.md) { 84 t.Errorf("md after Set() = %v, want %v", newMD, tt.md) 85 } 86 }) 87 } 88 } 89 90 func TestValidate(t *testing.T) { 91 for _, test := range []struct { 92 md metadata.MD 93 want error 94 }{ 95 { 96 md: map[string][]string{string(rune(0x19)): {"testVal"}}, 97 want: errors.New("header key \"\\x19\" contains illegal characters not in [0-9a-z-_.]"), 98 }, 99 { 100 md: map[string][]string{"test": {string(rune(0x19))}}, 101 want: errors.New("header key \"test\" contains value with non-printable ASCII characters"), 102 }, 103 { 104 md: map[string][]string{"": {"valid"}}, 105 want: errors.New("there is an empty key in the header"), 106 }, 107 { 108 md: map[string][]string{"test-bin": {string(rune(0x19))}}, 109 want: nil, 110 }, 111 } { 112 err := Validate(test.md) 113 if !reflect.DeepEqual(err, test.want) { 114 t.Errorf("validating metadata which is %v got err :%v, want err :%v", test.md, err, test.want) 115 } 116 } 117 }