Expressions/threshold: Fix incorrect thresholds args length (#66859)

This commit is contained in:
Gilles De Mey 2023-04-20 11:42:34 +02:00 committed by GitHub
parent 82ac2bae5f
commit 350de3f3bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 77 additions and 3 deletions

View File

@ -30,6 +30,17 @@ var (
) )
func NewThresholdCommand(refID, referenceVar, thresholdFunc string, conditions []float64) (*ThresholdCommand, error) { 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{ return &ThresholdCommand{
RefID: refID, RefID: refID,
ReferenceVar: referenceVar, ReferenceVar: referenceVar,

View File

@ -8,9 +8,72 @@ import (
) )
func TestNewThresholdCommand(t *testing.T) { func TestNewThresholdCommand(t *testing.T) {
cmd, err := NewThresholdCommand("B", "A", "is_above", []float64{}) type testCase struct {
require.Nil(t, err) fn string
require.NotNil(t, cmd) 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) { func TestUnmarshalThresholdCommand(t *testing.T) {