github.com/opentofu/opentofu@v1.7.1/internal/legacy/tofu/util_test.go (about)

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