...
1
16
17 package events
18
19 import (
20 "context"
21 "reflect"
22 "testing"
23
24 "github.com/google/go-cmp/cmp"
25 eventsv1 "k8s.io/api/events/v1"
26 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
27 "k8s.io/client-go/kubernetes/fake"
28 "k8s.io/klog/v2/ktesting"
29 )
30
31 func TestRecordEventToSink(t *testing.T) {
32 nonIsomorphicEvent := eventsv1.Event{
33 ObjectMeta: metav1.ObjectMeta{
34 Name: "test",
35 Namespace: metav1.NamespaceDefault,
36 },
37 Series: nil,
38 }
39
40 isomorphicEvent := *nonIsomorphicEvent.DeepCopy()
41 isomorphicEvent.Series = &eventsv1.EventSeries{Count: 2}
42
43 testCases := []struct {
44 name string
45 eventsToRecord []eventsv1.Event
46 expectedRecordedEvent eventsv1.Event
47 }{
48 {
49 name: "record one Event",
50 eventsToRecord: []eventsv1.Event{
51 nonIsomorphicEvent,
52 },
53 expectedRecordedEvent: nonIsomorphicEvent,
54 },
55 {
56 name: "record one Event followed by an isomorphic one",
57 eventsToRecord: []eventsv1.Event{
58 nonIsomorphicEvent,
59 isomorphicEvent,
60 },
61 expectedRecordedEvent: isomorphicEvent,
62 },
63 {
64 name: "record one isomorphic Event before the original",
65 eventsToRecord: []eventsv1.Event{
66 isomorphicEvent,
67 nonIsomorphicEvent,
68 },
69 expectedRecordedEvent: isomorphicEvent,
70 },
71 {
72 name: "record one isomorphic Event without one already existing",
73 eventsToRecord: []eventsv1.Event{
74 isomorphicEvent,
75 },
76 expectedRecordedEvent: isomorphicEvent,
77 },
78 }
79
80 for _, tc := range testCases {
81 t.Run(tc.name, func(t *testing.T) {
82 _, ctx := ktesting.NewTestContext(t)
83 kubeClient := fake.NewSimpleClientset()
84 eventSink := &EventSinkImpl{Interface: kubeClient.EventsV1()}
85
86 for _, ev := range tc.eventsToRecord {
87 recordEvent(ctx, eventSink, &ev)
88 }
89
90 recordedEvents, err := kubeClient.EventsV1().Events(metav1.NamespaceDefault).List(context.TODO(), metav1.ListOptions{})
91 if err != nil {
92 t.Errorf("expected to be able to list Events from fake client")
93 }
94
95 if len(recordedEvents.Items) != 1 {
96 t.Errorf("expected one Event to be recorded, found: %d", len(recordedEvents.Items))
97 }
98
99 recordedEvent := recordedEvents.Items[0]
100 if !reflect.DeepEqual(recordedEvent, tc.expectedRecordedEvent) {
101 t.Errorf("expected to have recorded Event: %#+v, got: %#+v\n diff: %s", tc.expectedRecordedEvent, recordedEvent, cmp.Diff(tc.expectedRecordedEvent, recordedEvent))
102 }
103 })
104 }
105 }
106
View as plain text