kv_test.go 2.2 KB

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