Skip to content

Commit

Permalink
Add exact comparison for events
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
l-qing committed Mar 7, 2023
1 parent 771fb66 commit 92b2adf
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
36 changes: 36 additions & 0 deletions pkg/reconciler/events/k8sevent/event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 5 additions & 0 deletions pkg/reconciler/events/k8sevent/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 92b2adf

Please sign in to comment.