github.com/grahambrereton-form3/tilt@v0.10.18/internal/k8s/owner_fetcher_test.go (about) 1 package k8s 2 3 import ( 4 "context" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 "golang.org/x/sync/errgroup" 9 appsv1 "k8s.io/api/apps/v1" 10 v1 "k8s.io/api/core/v1" 11 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 12 ) 13 14 func TestVisitOneParent(t *testing.T) { 15 kCli := &FakeK8sClient{} 16 ov := ProvideOwnerFetcher(kCli) 17 18 pod, rs := fakeOneParentChain() 19 kCli.InjectEntityByName(NewK8sEntity(rs)) 20 21 tree, err := ov.OwnerTreeOf(context.Background(), K8sEntity{Obj: pod}) 22 assert.NoError(t, err) 23 assert.Equal(t, `Pod:pod-a 24 ReplicaSet:rs-a`, tree.String()) 25 } 26 27 func TestVisitTwoParents(t *testing.T) { 28 kCli := &FakeK8sClient{} 29 ov := ProvideOwnerFetcher(kCli) 30 31 pod, rs, dep := fakeTwoParentChain() 32 kCli.InjectEntityByName(NewK8sEntity(rs), NewK8sEntity(dep)) 33 34 tree, err := ov.OwnerTreeOf(context.Background(), K8sEntity{Obj: pod}) 35 assert.NoError(t, err) 36 assert.Equal(t, `Pod:pod-a 37 ReplicaSet:rs-a 38 Deployment:dep-a`, tree.String()) 39 } 40 41 func TestOwnerFetcherParallelism(t *testing.T) { 42 kCli := &FakeK8sClient{} 43 ov := ProvideOwnerFetcher(kCli) 44 45 pod, rs := fakeOneParentChain() 46 kCli.InjectEntityByName(NewK8sEntity(rs)) 47 48 count := 30 49 g, ctx := errgroup.WithContext(context.Background()) 50 for i := 0; i < count; i++ { 51 g.Go(func() error { 52 _, err := ov.OwnerTreeOf(ctx, NewK8sEntity(pod)) 53 return err 54 }) 55 } 56 57 err := g.Wait() 58 assert.NoError(t, err) 59 assert.Equal(t, 1, kCli.getByReferenceCallCount) 60 } 61 62 func fakeOneParentChain() (*v1.Pod, *appsv1.ReplicaSet) { 63 pod := &v1.Pod{ 64 ObjectMeta: metav1.ObjectMeta{ 65 Name: "pod-a", 66 UID: "pod-a-uid", 67 OwnerReferences: []metav1.OwnerReference{ 68 { 69 APIVersion: "apps/v1", 70 Kind: "ReplicaSet", 71 Name: "rs-a", 72 UID: "rs-a-uid", 73 }, 74 }, 75 }, 76 } 77 rs := &appsv1.ReplicaSet{ 78 ObjectMeta: metav1.ObjectMeta{ 79 Name: "rs-a", 80 UID: "rs-a-uid", 81 }, 82 } 83 return pod, rs 84 } 85 86 func fakeTwoParentChain() (*v1.Pod, *appsv1.ReplicaSet, *appsv1.Deployment) { 87 pod := &v1.Pod{ 88 ObjectMeta: metav1.ObjectMeta{ 89 Name: "pod-a", 90 UID: "pod-a-uid", 91 OwnerReferences: []metav1.OwnerReference{ 92 { 93 APIVersion: "apps/v1", 94 Kind: "ReplicaSet", 95 Name: "rs-a", 96 UID: "rs-a-uid", 97 }, 98 }, 99 }, 100 } 101 rs := &appsv1.ReplicaSet{ 102 ObjectMeta: metav1.ObjectMeta{ 103 Name: "rs-a", 104 UID: "rs-a-uid", 105 OwnerReferences: []metav1.OwnerReference{ 106 { 107 APIVersion: "apps/v1", 108 Kind: "Deployment", 109 Name: "dep-a", 110 UID: "dep-a-uid", 111 }, 112 }, 113 }, 114 } 115 dep := &appsv1.Deployment{ 116 ObjectMeta: metav1.ObjectMeta{ 117 Name: "dep-a", 118 UID: "dep-a-uid", 119 }, 120 } 121 return pod, rs, dep 122 }