From 92b2adf33e47db012494a0b0b60b984a3bcfc4dc Mon Sep 17 00:00:00 2001 From: qingliu Date: Sun, 5 Mar 2023 15:26:20 +0800 Subject: [PATCH] Add exact comparison for events For those who are writing unit tests for the first time, they may instinctively copy the event information from the error message. However, if the error message contains special characters that are not properly escaped, the unit test will fail. This requires the user to examine the source code to understand they reason For the failure. With this optimization, it could be more beginner-friendly. --- pkg/reconciler/events/k8sevent/event_test.go | 36 ++++++++++++++++++++ pkg/reconciler/events/k8sevent/events.go | 5 +++ 2 files changed, 41 insertions(+) diff --git a/pkg/reconciler/events/k8sevent/event_test.go b/pkg/reconciler/events/k8sevent/event_test.go index 650b64bf275..f5c446696b5 100644 --- a/pkg/reconciler/events/k8sevent/event_test.go +++ b/pkg/reconciler/events/k8sevent/event_test.go @@ -134,6 +134,42 @@ func TestEmitK8sEventsOnConditions(t *testing.T) { Status: corev1.ConditionFalse, }, wantEvents: []string{"Warning Failed "}, + }, { + name: "match wildcard events through escaping", + before: nil, + after: &apis.Condition{ + Type: apis.ConditionSucceeded, + Status: corev1.ConditionFalse, + Message: "contains a * character", + }, + wantEvents: []string{"Warning Failed contains a \\* character"}, + }, { + name: "match wildcard events literally", + before: nil, + after: &apis.Condition{ + Type: apis.ConditionSucceeded, + Status: corev1.ConditionFalse, + Message: "contains a * character", + }, + wantEvents: []string{"Warning Failed contains a * character"}, + }, { + name: "match contains parenthesis events through escaping", + before: nil, + after: &apis.Condition{ + Type: apis.ConditionSucceeded, + Status: corev1.ConditionFalse, + Message: "contains (parenthesis)", + }, + wantEvents: []string{"Warning Failed contains \\(parenthesis\\)"}, + }, { + name: "match contains parenthesis events through literally", + before: nil, + after: &apis.Condition{ + Type: apis.ConditionSucceeded, + Status: corev1.ConditionFalse, + Message: "contains (parenthesis)", + }, + wantEvents: []string{"Warning Failed contains (parenthesis)"}, }} for _, ts := range testcases { diff --git a/pkg/reconciler/events/k8sevent/events.go b/pkg/reconciler/events/k8sevent/events.go index c4de6c6d554..d6d2401d4b5 100644 --- a/pkg/reconciler/events/k8sevent/events.go +++ b/pkg/reconciler/events/k8sevent/events.go @@ -54,6 +54,11 @@ func eventsFromChannel(c chan string, wantEvents []string) error { case event := <-c: foundEvents = append(foundEvents, event) wantEvent := wantEvents[ii] + // If the event is an exact match, there is no need to use regular expressions for matching. + // This can avoid the need to escape special characters, such as *, in the event to match. + if wantEvent == event { + continue + } matching, err := regexp.MatchString(wantEvent, event) if err == nil { if !matching {