io_test.go
 1  package util
 2  
 3  import (
 4  	"testing"
 5  
 6  	"github.com/stretchr/testify/assert"
 7  	"github.com/stretchr/testify/require"
 8  )
 9  
10  func TestUniqueName(t *testing.T) {
11  	type testCase struct {
12  		Name string
13  
14  		Input        string
15  		AlreadyExist []string
16  
17  		ExpectedUniqueName string
18  	}
19  
20  	validate := func(t *testing.T, tc *testCase) {
21  		t.Run(tc.Name, func(t *testing.T) {
22  			alreadyExist := make(map[string]bool, len(tc.AlreadyExist))
23  			for _, exists := range tc.AlreadyExist {
24  				alreadyExist[exists] = true
25  			}
26  
27  			actualUniqueName, err := UniqueName(tc.Input, func(candidate string) (bool, error) {
28  				return alreadyExist[candidate], nil
29  			})
30  			require.NoError(t, err)
31  			assert.Equal(t, tc.ExpectedUniqueName, actualUniqueName)
32  		})
33  	}
34  
35  	validate(t, &testCase{
36  		Name: "Already Unique",
37  
38  		Input: "foo",
39  
40  		ExpectedUniqueName: "foo",
41  	})
42  	validate(t, &testCase{
43  		Name: "Not Unique",
44  
45  		Input: "foo",
46  		AlreadyExist: []string{
47  			"foo",
48  		},
49  
50  		ExpectedUniqueName: "foo-0",
51  	})
52  	validate(t, &testCase{
53  		Name: "Multiple Outputs Exist",
54  
55  		Input: "foo",
56  		AlreadyExist: []string{
57  			"foo",
58  			"foo-0",
59  			"foo-1",
60  			"foo-2",
61  		},
62  
63  		ExpectedUniqueName: "foo-3",
64  	})
65  }