kv_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. "net"
  17. "testing"
  18. "time"
  19. "github.com/coreos/etcd/clientv3"
  20. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  21. "github.com/coreos/etcd/integration"
  22. "github.com/coreos/etcd/pkg/testutil"
  23. "golang.org/x/net/context"
  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. }
  46. type kvproxyTestServer struct {
  47. kp *kvProxy
  48. server *grpc.Server
  49. l net.Listener
  50. }
  51. func (kts *kvproxyTestServer) close() {
  52. kts.server.Stop()
  53. kts.l.Close()
  54. kts.kp.Close()
  55. }
  56. func newKVProxyServer(endpoints []string, t *testing.T) *kvproxyTestServer {
  57. cfg := clientv3.Config{
  58. Endpoints: endpoints,
  59. DialTimeout: 5 * time.Second,
  60. }
  61. client, err := clientv3.New(cfg)
  62. if err != nil {
  63. t.Fatal(err)
  64. }
  65. kvp := NewKvProxy(client)
  66. kvts := &kvproxyTestServer{
  67. kp: kvp,
  68. }
  69. var opts []grpc.ServerOption
  70. kvts.server = grpc.NewServer(opts...)
  71. pb.RegisterKVServer(kvts.server, kvts.kp)
  72. kvts.l, err = net.Listen("tcp", "127.0.0.1:0")
  73. if err != nil {
  74. t.Fatal(err)
  75. }
  76. go kvts.server.Serve(kvts.l)
  77. return kvts
  78. }