github.com/scottwinkler/terraform@v0.11.6-0.20180329211809-05143987aea8/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/hashicorp/terraform/terraform"
    12  )
    13  
    14  func TestCommunicator_new(t *testing.T) {
    15  	r := &terraform.InstanceState{
    16  		Ephemeral: terraform.EphemeralState{
    17  			ConnInfo: map[string]string{
    18  				"type": "telnet",
    19  			},
    20  		},
    21  	}
    22  	if _, err := New(r); err == nil {
    23  		t.Fatalf("expected error with telnet")
    24  	}
    25  
    26  	r.Ephemeral.ConnInfo["type"] = "ssh"
    27  	if _, err := New(r); err != nil {
    28  		t.Fatalf("err: %v", err)
    29  	}
    30  
    31  	r.Ephemeral.ConnInfo["type"] = "winrm"
    32  	if _, err := New(r); err != nil {
    33  		t.Fatalf("err: %v", err)
    34  	}
    35  }
    36  func TestRetryFunc(t *testing.T) {
    37  	origMax := maxBackoffDelay
    38  	maxBackoffDelay = time.Second
    39  	origStart := initialBackoffDelay
    40  	initialBackoffDelay = 10 * time.Millisecond
    41  
    42  	defer func() {
    43  		maxBackoffDelay = origMax
    44  		initialBackoffDelay = origStart
    45  	}()
    46  
    47  	// succeed on the third try
    48  	errs := []error{io.EOF, &net.OpError{Err: errors.New("ERROR")}, nil}
    49  	count := 0
    50  
    51  	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    52  	defer cancel()
    53  
    54  	err := Retry(ctx, func() error {
    55  		if count >= len(errs) {
    56  			return errors.New("failed to stop after nil error")
    57  		}
    58  
    59  		err := errs[count]
    60  		count++
    61  
    62  		return err
    63  	})
    64  
    65  	if count != 3 {
    66  		t.Fatal("retry func should have been called 3 times")
    67  	}
    68  
    69  	if err != nil {
    70  		t.Fatal(err)
    71  	}
    72  }
    73  
    74  func TestRetryFuncBackoff(t *testing.T) {
    75  	origMax := maxBackoffDelay
    76  	maxBackoffDelay = time.Second
    77  	origStart := initialBackoffDelay
    78  	initialBackoffDelay = 100 * time.Millisecond
    79  
    80  	defer func() {
    81  		maxBackoffDelay = origMax
    82  		initialBackoffDelay = origStart
    83  	}()
    84  
    85  	count := 0
    86  
    87  	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    88  	defer cancel()
    89  
    90  	Retry(ctx, func() error {
    91  		count++
    92  		return io.EOF
    93  	})
    94  
    95  	if count > 4 {
    96  		t.Fatalf("retry func failed to backoff. called %d times", count)
    97  	}
    98  }