go.etcd.io/etcd@v3.3.27+incompatible/clientv3/ctx_test.go (about) 1 // Copyright 2020 The etcd Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package clientv3 16 17 import ( 18 "context" 19 "reflect" 20 "testing" 21 22 "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes" 23 "github.com/coreos/etcd/version" 24 "google.golang.org/grpc/metadata" 25 ) 26 27 func TestMetadataWithRequireLeader(t *testing.T) { 28 ctx := context.TODO() 29 md, ok := metadata.FromOutgoingContext(ctx) 30 if ok { 31 t.Fatal("expected no outgoing metadata ctx key") 32 } 33 34 // add a conflicting key with some other value 35 md = metadata.Pairs(rpctypes.MetadataRequireLeaderKey, "invalid") 36 // add a key, and expect not be overwritten 37 metadataSet(md, "hello", "1", "2") 38 ctx = metadata.NewOutgoingContext(ctx, md) 39 40 // expect overwrites but still keep other keys 41 ctx = WithRequireLeader(ctx) 42 md, ok = metadata.FromOutgoingContext(ctx) 43 if !ok { 44 t.Fatal("expected outgoing metadata ctx key") 45 } 46 if ss := metadataGet(md, rpctypes.MetadataRequireLeaderKey); !reflect.DeepEqual(ss, []string{rpctypes.MetadataHasLeader}) { 47 t.Fatalf("unexpected metadata for %q %v", rpctypes.MetadataRequireLeaderKey, ss) 48 } 49 if ss := metadataGet(md, "hello"); !reflect.DeepEqual(ss, []string{"1", "2"}) { 50 t.Fatalf("unexpected metadata for 'hello' %v", ss) 51 } 52 } 53 54 func TestMetadataWithClientAPIVersion(t *testing.T) { 55 ctx := withVersion(WithRequireLeader(context.TODO())) 56 57 md, ok := metadata.FromOutgoingContext(ctx) 58 if !ok { 59 t.Fatal("expected outgoing metadata ctx key") 60 } 61 if ss := metadataGet(md, rpctypes.MetadataRequireLeaderKey); !reflect.DeepEqual(ss, []string{rpctypes.MetadataHasLeader}) { 62 t.Fatalf("unexpected metadata for %q %v", rpctypes.MetadataRequireLeaderKey, ss) 63 } 64 if ss := metadataGet(md, rpctypes.MetadataClientAPIVersionKey); !reflect.DeepEqual(ss, []string{version.APIVersion}) { 65 t.Fatalf("unexpected metadata for %q %v", rpctypes.MetadataClientAPIVersionKey, ss) 66 } 67 }