From 6d16cf2699102363c1d0867a58866a57cd198d1f Mon Sep 17 00:00:00 2001 From: William Wernert Date: Wed, 20 Mar 2024 13:10:39 -0400 Subject: [PATCH] Alerting: Marshal incoming json.RawMessage in diff (#84692) This will ensure the encoding is correct when comparing to the existing rule. --- pkg/services/ngalert/models/alert_rule.go | 6 +++++- pkg/services/ngalert/models/alert_rule_test.go | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/pkg/services/ngalert/models/alert_rule.go b/pkg/services/ngalert/models/alert_rule.go index 320d29386b5..d28ff8ecb70 100644 --- a/pkg/services/ngalert/models/alert_rule.go +++ b/pkg/services/ngalert/models/alert_rule.go @@ -346,7 +346,11 @@ func (alertRule *AlertRule) Diff(rule *AlertRule, ignore ...string) cmputil.Diff // json.RawMessage is a slice of bytes and therefore cmp's default behavior is to compare it by byte, which is not really useful var jsonCmp = cmp.Transformer("", func(in json.RawMessage) string { - return string(in) + b, err := json.Marshal(in) + if err != nil { + return string(in) + } + return string(b) }) ops = append( ops, diff --git a/pkg/services/ngalert/models/alert_rule_test.go b/pkg/services/ngalert/models/alert_rule_test.go index 32836ba4d67..22d2f65a9e6 100644 --- a/pkg/services/ngalert/models/alert_rule_test.go +++ b/pkg/services/ngalert/models/alert_rule_test.go @@ -656,6 +656,21 @@ func TestDiff(t *testing.T) { } }) + t.Run("should correctly detect no change with '<' and '>' in query", func(t *testing.T) { + old := query1 + new := query1 + old.Model = json.RawMessage(`{"field1": "$A \u003c 1"}`) + new.Model = json.RawMessage(`{"field1": "$A < 1"}`) + rule1.Data = []AlertQuery{old} + rule2.Data = []AlertQuery{new} + + diff := rule1.Diff(rule2) + assert.Nil(t, diff) + + // reset rule1 + rule1.Data = []AlertQuery{query1} + }) + t.Run("should detect new changes in array if too many fields changed", func(t *testing.T) { query2 := query1 query2.QueryType = "test"