k8s.io/kubernetes@v1.29.3/pkg/kubelet/cm/containermap/container_map_test.go (about) 1 /* 2 Copyright 2017 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package containermap 18 19 import ( 20 "testing" 21 ) 22 23 func TestContainerMap(t *testing.T) { 24 testCases := []struct { 25 podUID string 26 containerNames []string 27 containerIDs []string 28 }{ 29 { 30 "fakePodUID", 31 []string{"fakeContainerName-1", "fakeContainerName-2"}, 32 []string{"fakeContainerID-1", "fakeContainerName-2"}, 33 }, 34 } 35 36 for _, tc := range testCases { 37 // Build a new containerMap from the testCases, checking proper 38 // addition, retrieval along the way. 39 cm := NewContainerMap() 40 for i := range tc.containerNames { 41 cm.Add(tc.podUID, tc.containerNames[i], tc.containerIDs[i]) 42 43 containerID, err := cm.GetContainerID(tc.podUID, tc.containerNames[i]) 44 if err != nil { 45 t.Errorf("error adding and retrieving containerID: %v", err) 46 } 47 if containerID != tc.containerIDs[i] { 48 t.Errorf("mismatched containerIDs %v, %v", containerID, tc.containerIDs[i]) 49 } 50 51 podUID, containerName, err := cm.GetContainerRef(containerID) 52 if err != nil { 53 t.Errorf("error retrieving container reference: %v", err) 54 } 55 if podUID != tc.podUID { 56 t.Errorf("mismatched pod UID %v, %v", tc.podUID, podUID) 57 } 58 if containerName != tc.containerNames[i] { 59 t.Errorf("mismatched container Name %v, %v", tc.containerNames[i], containerName) 60 } 61 } 62 63 // Remove all entries from the containerMap, checking proper removal of 64 // each along the way. 65 cm.Visit(func(podUID string, containerName string, containerID string) { 66 cm.RemoveByContainerID(containerID) 67 containerID, err := cm.GetContainerID(podUID, containerName) 68 if err == nil { 69 t.Errorf("unexpected retrieval of containerID after removal: %v", containerID) 70 } 71 72 cm.Add(podUID, containerName, containerID) 73 74 cm.RemoveByContainerRef(podUID, containerName) 75 id, cn, err := cm.GetContainerRef(containerID) 76 if err == nil { 77 t.Errorf("unexpected retrieval of container reference after removal: (%v, %v)", id, cn) 78 } 79 }) 80 81 // Verify containerMap now empty. 82 if len(cm) != 0 { 83 t.Errorf("unexpected entries still in containerMap: %v", cm) 84 } 85 } 86 }