github.com/skyscape-cloud-services/terraform@v0.9.2-0.20170609144644-7ece028a1747/terraform/util_test.go (about) 1 package terraform 2 3 import ( 4 "fmt" 5 "reflect" 6 "testing" 7 "time" 8 ) 9 10 func TestSemaphore(t *testing.T) { 11 s := NewSemaphore(2) 12 timer := time.AfterFunc(time.Second, func() { 13 panic("deadlock") 14 }) 15 defer timer.Stop() 16 17 s.Acquire() 18 if !s.TryAcquire() { 19 t.Fatalf("should acquire") 20 } 21 if s.TryAcquire() { 22 t.Fatalf("should not acquire") 23 } 24 s.Release() 25 s.Release() 26 27 // This release should panic 28 defer func() { 29 r := recover() 30 if r == nil { 31 t.Fatalf("should panic") 32 } 33 }() 34 s.Release() 35 } 36 37 func TestStrSliceContains(t *testing.T) { 38 if strSliceContains(nil, "foo") { 39 t.Fatalf("Bad") 40 } 41 if strSliceContains([]string{}, "foo") { 42 t.Fatalf("Bad") 43 } 44 if strSliceContains([]string{"bar"}, "foo") { 45 t.Fatalf("Bad") 46 } 47 if !strSliceContains([]string{"bar", "foo"}, "foo") { 48 t.Fatalf("Bad") 49 } 50 } 51 52 func TestUtilResourceProvider(t *testing.T) { 53 type testCase struct { 54 ResourceName string 55 Alias string 56 Expected string 57 } 58 59 tests := []testCase{ 60 { 61 // If no alias is provided, the first underscore-separated segment 62 // is assumed to be the provider name. 63 ResourceName: "aws_thing", 64 Alias: "", 65 Expected: "aws", 66 }, 67 { 68 // If we have more than one underscore then it's the first one that we'll use. 69 ResourceName: "aws_thingy_thing", 70 Alias: "", 71 Expected: "aws", 72 }, 73 { 74 // A provider can export a resource whose name is just the bare provider name, 75 // e.g. because the provider only has one resource and so any additional 76 // parts would be redundant. 77 ResourceName: "external", 78 Alias: "", 79 Expected: "external", 80 }, 81 { 82 // Alias always overrides the default extraction of the name 83 ResourceName: "aws_thing", 84 Alias: "tls.baz", 85 Expected: "tls.baz", 86 }, 87 } 88 89 for _, test := range tests { 90 got := resourceProvider(test.ResourceName, test.Alias) 91 if got != test.Expected { 92 t.Errorf( 93 "(%q, %q) produced %q; want %q", 94 test.ResourceName, test.Alias, 95 got, 96 test.Expected, 97 ) 98 } 99 } 100 } 101 102 func TestUniqueStrings(t *testing.T) { 103 cases := []struct { 104 Input []string 105 Expected []string 106 }{ 107 { 108 []string{}, 109 []string{}, 110 }, 111 { 112 []string{"x"}, 113 []string{"x"}, 114 }, 115 { 116 []string{"a", "b", "c"}, 117 []string{"a", "b", "c"}, 118 }, 119 { 120 []string{"a", "a", "a"}, 121 []string{"a"}, 122 }, 123 { 124 []string{"a", "b", "a", "b", "a", "a"}, 125 []string{"a", "b"}, 126 }, 127 { 128 []string{"c", "b", "a", "c", "b"}, 129 []string{"a", "b", "c"}, 130 }, 131 } 132 133 for i, tc := range cases { 134 t.Run(fmt.Sprintf("unique-%d", i), func(t *testing.T) { 135 actual := uniqueStrings(tc.Input) 136 if !reflect.DeepEqual(tc.Expected, actual) { 137 t.Fatalf("Expected: %q\nGot: %q", tc.Expected, actual) 138 } 139 }) 140 } 141 }