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

pull/66929/head
Gilles De Mey 2 years ago committed by GitHub
parent 82ac2bae5f
commit 350de3f3bf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 11
      pkg/expr/threshold.go
  2. 69
      pkg/expr/threshold_test.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,

@ -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) {

Loading…
Cancel
Save