github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/legacy/terraform/util_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package terraform
     5  
     6  import (
     7  	"fmt"
     8  	"reflect"
     9  	"testing"
    10  	"time"
    11  )
    12  
    13  func TestSemaphore(t *testing.T) {
    14  	s := NewSemaphore(2)
    15  	timer := time.AfterFunc(time.Second, func() {
    16  		panic("deadlock")
    17  	})
    18  	defer timer.Stop()
    19  
    20  	s.Acquire()
    21  	if !s.TryAcquire() {
    22  		t.Fatalf("should acquire")
    23  	}
    24  	if s.TryAcquire() {
    25  		t.Fatalf("should not acquire")
    26  	}
    27  	s.Release()
    28  	s.Release()
    29  
    30  	// This release should panic
    31  	defer func() {
    32  		r := recover()
    33  		if r == nil {
    34  			t.Fatalf("should panic")
    35  		}
    36  	}()
    37  	s.Release()
    38  }
    39  
    40  func TestStrSliceContains(t *testing.T) {
    41  	if strSliceContains(nil, "foo") {
    42  		t.Fatalf("Bad")
    43  	}
    44  	if strSliceContains([]string{}, "foo") {
    45  		t.Fatalf("Bad")
    46  	}
    47  	if strSliceContains([]string{"bar"}, "foo") {
    48  		t.Fatalf("Bad")
    49  	}
    50  	if !strSliceContains([]string{"bar", "foo"}, "foo") {
    51  		t.Fatalf("Bad")
    52  	}
    53  }
    54  
    55  func TestUniqueStrings(t *testing.T) {
    56  	cases := []struct {
    57  		Input    []string
    58  		Expected []string
    59  	}{
    60  		{
    61  			[]string{},
    62  			[]string{},
    63  		},
    64  		{
    65  			[]string{"x"},
    66  			[]string{"x"},
    67  		},
    68  		{
    69  			[]string{"a", "b", "c"},
    70  			[]string{"a", "b", "c"},
    71  		},
    72  		{
    73  			[]string{"a", "a", "a"},
    74  			[]string{"a"},
    75  		},
    76  		{
    77  			[]string{"a", "b", "a", "b", "a", "a"},
    78  			[]string{"a", "b"},
    79  		},
    80  		{
    81  			[]string{"c", "b", "a", "c", "b"},
    82  			[]string{"a", "b", "c"},
    83  		},
    84  	}
    85  
    86  	for i, tc := range cases {
    87  		t.Run(fmt.Sprintf("unique-%d", i), func(t *testing.T) {
    88  			actual := uniqueStrings(tc.Input)
    89  			if !reflect.DeepEqual(tc.Expected, actual) {
    90  				t.Fatalf("Expected: %q\nGot: %q", tc.Expected, actual)
    91  			}
    92  		})
    93  	}
    94  }