github.com/inspektor-gadget/inspektor-gadget@v0.28.1/pkg/container-collection/pubsub_test.go (about) 1 // Copyright 2019-2022 The Inspektor Gadget authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package containercollection 16 17 import ( 18 "testing" 19 20 types "github.com/inspektor-gadget/inspektor-gadget/pkg/types" 21 ) 22 23 func TestPubSub(t *testing.T) { 24 p := NewGadgetPubSub() 25 if p == nil { 26 t.Fatalf("Failed to create new pubsub") 27 } 28 29 var event PubSubEvent 30 done := make(chan struct{}, 1) 31 counter := 0 32 key := "callback1" 33 callback := func(e PubSubEvent) { 34 event = e 35 counter++ 36 done <- struct{}{} 37 } 38 39 p.Subscribe(key, callback, nil) 40 41 p.Publish( 42 EventTypeRemoveContainer, 43 &Container{ 44 Runtime: RuntimeMetadata{ 45 BasicRuntimeMetadata: types.BasicRuntimeMetadata{ 46 ContainerID: "container1", 47 }, 48 }, 49 }, 50 ) 51 _, ok := <-done 52 if !ok { 53 t.Fatalf("Failed to receive event from callback") 54 } 55 56 if event.Type != EventTypeRemoveContainer { 57 t.Fatalf("Failed to receive correct event of type EVENT_TYPE_REMOVE_CONTAINER") 58 } 59 if event.Container.Runtime.ContainerID != "container1" { 60 t.Fatalf("Failed to receive correct event") 61 } 62 63 p.Unsubscribe(key) 64 p.Publish( 65 EventTypeRemoveContainer, 66 &Container{ 67 Runtime: RuntimeMetadata{ 68 BasicRuntimeMetadata: types.BasicRuntimeMetadata{ 69 ContainerID: "container2", 70 }, 71 }, 72 }, 73 ) 74 if counter != 1 { 75 t.Fatalf("Callback called too many times") 76 } 77 } 78 79 func TestPubSubVerifyPointerToContainer(t *testing.T) { 80 p := NewGadgetPubSub() 81 if p == nil { 82 t.Fatalf("Failed to create new pubsub") 83 } 84 85 c := &Container{ 86 Runtime: RuntimeMetadata{ 87 BasicRuntimeMetadata: types.BasicRuntimeMetadata{ 88 ContainerID: "container1", 89 }, 90 }, 91 } 92 93 var receivedC *Container 94 95 key := "callback1" 96 done := make(chan struct{}, 1) 97 callback := func(e PubSubEvent) { 98 receivedC = e.Container 99 done <- struct{}{} 100 } 101 102 p.Subscribe(key, callback, nil) 103 p.Publish(EventTypeAddContainer, c) 104 105 _, ok := <-done 106 if !ok { 107 t.Fatalf("Failed to receive event from callback") 108 } 109 110 p.Unsubscribe(key) 111 112 if receivedC != c { 113 t.Fatalf("Pointer doesn't correspond to original object") 114 } 115 }