github.com/grahambrereton-form3/tilt@v0.10.18/internal/k8s/names_test.go (about)

     1  package k8s
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
     9  )
    10  
    11  type workload struct {
    12  	name                 string
    13  	kind                 string
    14  	namespace            string
    15  	group                string
    16  	expectedResourceName string
    17  }
    18  
    19  func TestUniqueResourceNames(t *testing.T) {
    20  	testCases := []struct {
    21  		testName  string
    22  		workloads []workload
    23  	}{
    24  		{"one workload, just name", []workload{
    25  			{"foo", "Deployment", "default", "", "foo"},
    26  		}},
    27  		{"one workload, same name", []workload{
    28  			{"foo", "Deployment", "default", "", "foo:deployment:default::0"},
    29  			{"foo", "Deployment", "default", "", "foo:deployment:default::1"},
    30  		}},
    31  		{"one workload, by name", []workload{
    32  			{"foo", "Deployment", "default", "", "foo"},
    33  			{"bar", "Deployment", "default", "", "bar"},
    34  		}},
    35  		{"two workloads, by kind", []workload{
    36  			{"foo", "Deployment", "default", "", "foo:deployment"},
    37  			{"foo", "CronJob", "default", "", "foo:cronjob"},
    38  		}},
    39  		{"two workloads, by namespace", []workload{
    40  			{"foo", "Deployment", "default", "", "foo:deployment:default"},
    41  			{"foo", "Deployment", "fission", "", "foo:deployment:fission"},
    42  		}},
    43  		{"two workloads, by group", []workload{
    44  			{"foo", "Deployment", "default", "a", "foo:deployment:default:a"},
    45  			{"foo", "Deployment", "default", "b", "foo:deployment:default:b"},
    46  		}},
    47  		{"three workloads, one by kind, two by namespace", []workload{
    48  			{"foo", "Deployment", "default", "a", "foo:deployment:default"},
    49  			{"foo", "Deployment", "fission", "b", "foo:deployment:fission"},
    50  			{"foo", "CronJob", "default", "b", "foo:cronjob"},
    51  		}},
    52  	}
    53  
    54  	for _, test := range testCases {
    55  		t.Run(test.testName, func(t *testing.T) {
    56  			var entities []K8sEntity
    57  			var expectedNames []string
    58  			for _, w := range test.workloads {
    59  				obj := unstructured.Unstructured{}
    60  				obj.SetName(w.name)
    61  				obj.SetNamespace(w.namespace)
    62  				obj.SetKind(w.kind)
    63  				obj.SetAPIVersion(fmt.Sprintf("%s/1.0", w.group))
    64  				entities = append(entities, NewK8sEntity(&obj))
    65  
    66  				expectedNames = append(expectedNames, w.expectedResourceName)
    67  			}
    68  
    69  			actualNames := UniqueNames(entities, 1)
    70  			assert.Equal(t, expectedNames, actualNames)
    71  		})
    72  	}
    73  }