client_test.go 2.3 KB

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