github.com/graywolf-at-work-2/terraform-vendor@v1.4.5/internal/communicator/communicator_test.go (about)

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