From 3f41213f8446eec91dc4844e8d288ce1ca867844 Mon Sep 17 00:00:00 2001 From: lou-lan Date: Mon, 3 Mar 2025 17:52:30 +0800 Subject: [PATCH] Update getFinalOwner method to handle not found error Signed-off-by: lou-lan --- pkg/podownercache/pod_owner_cache.go | 4 ++ pkg/podownercache/pod_owner_cache_test.go | 45 +++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/pkg/podownercache/pod_owner_cache.go b/pkg/podownercache/pod_owner_cache.go index 9504704616..3e1b473afd 100644 --- a/pkg/podownercache/pod_owner_cache.go +++ b/pkg/podownercache/pod_owner_cache.go @@ -152,6 +152,10 @@ func (s *PodOwnerCache) getFinalOwner(obj metav1.Object) (*OwnerInfo, error) { logger.Sugar().Debugf("forbidden to get owner of pod %s/%s", obj.GetNamespace(), obj.GetName()) return nil, nil } + if errors.IsNotFound(err) { + logger.Sugar().Debugf("owner not found for pod %s/%s", obj.GetNamespace(), obj.GetName()) + return nil, nil + } return nil, err } diff --git a/pkg/podownercache/pod_owner_cache_test.go b/pkg/podownercache/pod_owner_cache_test.go index 79281d7451..044141217c 100644 --- a/pkg/podownercache/pod_owner_cache_test.go +++ b/pkg/podownercache/pod_owner_cache_test.go @@ -223,3 +223,48 @@ func TestGetFinalOwnerForbidden(t *testing.T) { t.Fatalf("expected ownerInfo to be nil, got %v", ownerInfo) } } + +// MockNotFoundClient is a custom mock implementation of the client.Reader interface +type MockNotFoundClient struct{} + +func (m *MockNotFoundClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + return errors.NewNotFound(schema.GroupResource{Group: "apps", Resource: "replicasets"}, key.Name) +} + +func (m *MockNotFoundClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { + return nil +} + +// TestGetFinalOwnerNotFound tests the getFinalOwner method when the Get call returns a not found error. +func TestGetFinalOwnerNotFound(t *testing.T) { + logger = logutils.Logger.Named("PodOwnerCache") + + mockClient := &MockNotFoundClient{} + cache := &PodOwnerCache{ + ctx: context.Background(), + apiReader: mockClient, + } + + // Create a mock pod object + pod := &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-pod", + Namespace: "test-ns", + OwnerReferences: []metav1.OwnerReference{ + { + APIVersion: "apps/v1", + Kind: "ReplicaSet", + Name: "test-rs", + }, + }, + }, + } + + ownerInfo, err := cache.getFinalOwner(pod) + if err != nil { + t.Fatalf("expected no error, got %v", err) + } + if ownerInfo != nil { + t.Fatalf("expected ownerInfo to be nil, got %v", ownerInfo) + } +}