From 350de3f3bf8aab8e831deb453dfeab7501b88304 Mon Sep 17 00:00:00 2001 From: Gilles De Mey Date: Thu, 20 Apr 2023 11:42:34 +0200 Subject: [PATCH] Expressions/threshold: Fix incorrect thresholds args length (#66859) --- pkg/expr/threshold.go | 11 ++++++ pkg/expr/threshold_test.go | 69 ++++++++++++++++++++++++++++++++++++-- 2 files changed, 77 insertions(+), 3 deletions(-) diff --git a/pkg/expr/threshold.go b/pkg/expr/threshold.go index 3d3b4f3e65c..588cd65e30f 100644 --- a/pkg/expr/threshold.go +++ b/pkg/expr/threshold.go @@ -30,6 +30,17 @@ var ( ) func NewThresholdCommand(refID, referenceVar, thresholdFunc string, conditions []float64) (*ThresholdCommand, error) { + switch thresholdFunc { + case ThresholdIsOutsideRange, ThresholdIsWithinRange: + if len(conditions) < 2 { + return nil, fmt.Errorf("incorrect number of arguments: got %d but need 2", len(conditions)) + } + case ThresholdIsAbove, ThresholdIsBelow: + if len(conditions) < 1 { + return nil, fmt.Errorf("incorrect number of arguments: got %d but need 1", len(conditions)) + } + } + return &ThresholdCommand{ RefID: refID, ReferenceVar: referenceVar, diff --git a/pkg/expr/threshold_test.go b/pkg/expr/threshold_test.go index 9bb87144b2e..a903358a137 100644 --- a/pkg/expr/threshold_test.go +++ b/pkg/expr/threshold_test.go @@ -8,9 +8,72 @@ import ( ) func TestNewThresholdCommand(t *testing.T) { - cmd, err := NewThresholdCommand("B", "A", "is_above", []float64{}) - require.Nil(t, err) - require.NotNil(t, cmd) + type testCase struct { + fn string + args []float64 + shouldError bool + expectedError string + } + + cases := []testCase{ + { + fn: "gt", + args: []float64{0}, + shouldError: false, + }, + { + fn: "lt", + args: []float64{0}, + shouldError: false, + }, + { + fn: "within_range", + args: []float64{0, 1}, + shouldError: false, + }, + { + fn: "outside_range", + args: []float64{0, 1}, + shouldError: false, + }, + { + fn: "gt", + args: []float64{}, + shouldError: true, + expectedError: "incorrect number of arguments", + }, + { + fn: "lt", + args: []float64{}, + shouldError: true, + expectedError: "incorrect number of arguments", + }, + { + fn: "within_range", + args: []float64{0}, + shouldError: true, + expectedError: "incorrect number of arguments", + }, + { + fn: "outside_range", + args: []float64{0}, + shouldError: true, + expectedError: "incorrect number of arguments", + }, + } + + for _, tc := range cases { + cmd, err := NewThresholdCommand("B", "A", tc.fn, tc.args) + + if tc.shouldError { + require.Nil(t, cmd) + require.NotNil(t, err) + require.Contains(t, err.Error(), tc.expectedError) + } else { + require.Nil(t, err) + require.NotNil(t, cmd) + } + } } func TestUnmarshalThresholdCommand(t *testing.T) {