client_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 clientv3
  15. import (
  16. "fmt"
  17. "testing"
  18. "time"
  19. "github.com/coreos/etcd/etcdserver"
  20. "github.com/coreos/etcd/pkg/testutil"
  21. "golang.org/x/net/context"
  22. "google.golang.org/grpc"
  23. )
  24. func TestDialTimeout(t *testing.T) {
  25. defer testutil.AfterTest(t)
  26. donec := make(chan error)
  27. go func() {
  28. // without timeout, grpc keeps redialing if connection refused
  29. cfg := Config{
  30. Endpoints: []string{"localhost:12345"},
  31. DialTimeout: 2 * time.Second}
  32. c, err := New(cfg)
  33. if c != nil || err == nil {
  34. t.Errorf("new client should fail")
  35. }
  36. donec <- err
  37. }()
  38. time.Sleep(10 * time.Millisecond)
  39. select {
  40. case err := <-donec:
  41. t.Errorf("dial didn't wait (%v)", err)
  42. default:
  43. }
  44. select {
  45. case <-time.After(5 * time.Second):
  46. t.Errorf("failed to timeout dial on time")
  47. case err := <-donec:
  48. if err != grpc.ErrClientConnTimeout {
  49. t.Errorf("unexpected error %v, want %v", err, grpc.ErrClientConnTimeout)
  50. }
  51. }
  52. }
  53. func TestDialNoTimeout(t *testing.T) {
  54. cfg := Config{Endpoints: []string{"127.0.0.1:12345"}}
  55. c, err := New(cfg)
  56. if c == nil || err != nil {
  57. t.Fatalf("new client with DialNoWait should succeed, got %v", err)
  58. }
  59. c.Close()
  60. }
  61. func TestIsHaltErr(t *testing.T) {
  62. if !isHaltErr(nil, fmt.Errorf("etcdserver: some etcdserver error")) {
  63. t.Errorf(`error prefixed with "etcdserver: " should be Halted by default`)
  64. }
  65. if isHaltErr(nil, etcdserver.ErrStopped) {
  66. t.Errorf("error %v should not halt", etcdserver.ErrStopped)
  67. }
  68. if isHaltErr(nil, etcdserver.ErrNoLeader) {
  69. t.Errorf("error %v should not halt", etcdserver.ErrNoLeader)
  70. }
  71. ctx, cancel := context.WithCancel(context.TODO())
  72. if isHaltErr(ctx, nil) {
  73. t.Errorf("no error and active context should not be Halted")
  74. }
  75. cancel()
  76. if !isHaltErr(ctx, nil) {
  77. t.Errorf("cancel on context should be Halted")
  78. }
  79. }