kubeform.dev/terraform-backend-sdk@v0.0.0-20220310143633-45f07fe731c5/communicator/communicator_test.go (about) 1 package communicator 2 3 import ( 4 "context" 5 "errors" 6 "io" 7 "net" 8 "testing" 9 "time" 10 11 "github.com/zclconf/go-cty/cty" 12 ) 13 14 func TestCommunicator_new(t *testing.T) { 15 cfg := map[string]cty.Value{ 16 "type": cty.StringVal("telnet"), 17 "host": cty.StringVal("127.0.0.1"), 18 } 19 20 if _, err := New(cty.ObjectVal(cfg)); err == nil { 21 t.Fatalf("expected error with telnet") 22 } 23 24 cfg["type"] = cty.StringVal("ssh") 25 if _, err := New(cty.ObjectVal(cfg)); err != nil { 26 t.Fatalf("err: %v", err) 27 } 28 29 cfg["type"] = cty.StringVal("winrm") 30 if _, err := New(cty.ObjectVal(cfg)); err != nil { 31 t.Fatalf("err: %v", err) 32 } 33 } 34 func TestRetryFunc(t *testing.T) { 35 origMax := maxBackoffDelay 36 maxBackoffDelay = time.Second 37 origStart := initialBackoffDelay 38 initialBackoffDelay = 10 * time.Millisecond 39 40 defer func() { 41 maxBackoffDelay = origMax 42 initialBackoffDelay = origStart 43 }() 44 45 // succeed on the third try 46 errs := []error{io.EOF, &net.OpError{Err: errors.New("ERROR")}, nil} 47 count := 0 48 49 ctx, cancel := context.WithTimeout(context.Background(), time.Second) 50 defer cancel() 51 52 err := Retry(ctx, func() error { 53 if count >= len(errs) { 54 return errors.New("failed to stop after nil error") 55 } 56 57 err := errs[count] 58 count++ 59 60 return err 61 }) 62 63 if count != 3 { 64 t.Fatal("retry func should have been called 3 times") 65 } 66 67 if err != nil { 68 t.Fatal(err) 69 } 70 } 71 72 func TestRetryFuncBackoff(t *testing.T) { 73 origMax := maxBackoffDelay 74 maxBackoffDelay = time.Second 75 origStart := initialBackoffDelay 76 initialBackoffDelay = 100 * time.Millisecond 77 78 defer func() { 79 maxBackoffDelay = origMax 80 initialBackoffDelay = origStart 81 }() 82 83 count := 0 84 85 ctx, cancel := context.WithTimeout(context.Background(), time.Second) 86 defer cancel() 87 88 Retry(ctx, func() error { 89 count++ 90 return io.EOF 91 }) 92 93 if count > 4 { 94 t.Fatalf("retry func failed to backoff. called %d times", count) 95 } 96 }