go.etcd.io/etcd@v3.3.27+incompatible/proxy/grpcproxy/kv_test.go (about) 1 // Copyright 2016 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 grpcproxy 16 17 import ( 18 "context" 19 "net" 20 "testing" 21 "time" 22 23 "github.com/coreos/etcd/clientv3" 24 pb "github.com/coreos/etcd/etcdserver/etcdserverpb" 25 "github.com/coreos/etcd/integration" 26 "github.com/coreos/etcd/pkg/testutil" 27 28 "google.golang.org/grpc" 29 ) 30 31 func TestKVProxyRange(t *testing.T) { 32 defer testutil.AfterTest(t) 33 34 clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1}) 35 defer clus.Terminate(t) 36 37 kvts := newKVProxyServer([]string{clus.Members[0].GRPCAddr()}, t) 38 defer kvts.close() 39 40 // create a client and try to get key from proxy. 41 cfg := clientv3.Config{ 42 Endpoints: []string{kvts.l.Addr().String()}, 43 DialTimeout: 5 * time.Second, 44 } 45 client, err := clientv3.New(cfg) 46 if err != nil { 47 t.Fatalf("err = %v, want nil", err) 48 } 49 _, err = client.Get(context.Background(), "foo") 50 if err != nil { 51 t.Fatalf("err = %v, want nil", err) 52 } 53 client.Close() 54 } 55 56 type kvproxyTestServer struct { 57 kp pb.KVServer 58 c *clientv3.Client 59 server *grpc.Server 60 l net.Listener 61 } 62 63 func (kts *kvproxyTestServer) close() { 64 kts.server.Stop() 65 kts.l.Close() 66 kts.c.Close() 67 } 68 69 func newKVProxyServer(endpoints []string, t *testing.T) *kvproxyTestServer { 70 cfg := clientv3.Config{ 71 Endpoints: endpoints, 72 DialTimeout: 5 * time.Second, 73 } 74 client, err := clientv3.New(cfg) 75 if err != nil { 76 t.Fatal(err) 77 } 78 79 kvp, _ := NewKvProxy(client) 80 81 kvts := &kvproxyTestServer{ 82 kp: kvp, 83 c: client, 84 } 85 86 var opts []grpc.ServerOption 87 kvts.server = grpc.NewServer(opts...) 88 pb.RegisterKVServer(kvts.server, kvts.kp) 89 90 kvts.l, err = net.Listen("tcp", "127.0.0.1:0") 91 if err != nil { 92 t.Fatal(err) 93 } 94 95 go kvts.server.Serve(kvts.l) 96 97 return kvts 98 }