diff --git a/array.go b/array.go index c1314d2f9..6fab712c2 100644 --- a/array.go +++ b/array.go @@ -168,6 +168,9 @@ func (a *Array) Value(index int) *Value { return newValue(opChain, nil) } + if index < 0 { + index = len(a.value) + index + } if index < 0 || index >= len(a.value) { opChain.fail(AssertionFailure{ Type: AssertInRange, @@ -208,6 +211,9 @@ func (a *Array) HasValue(index int, value interface{}) *Array { return a } + if index < 0 { + index = len(a.value) + index + } if index < 0 || index >= len(a.value) { opChain.fail(AssertionFailure{ Type: AssertInRange, @@ -262,6 +268,9 @@ func (a *Array) NotHasValue(index int, value interface{}) *Array { return a } + if index < 0 { + index = len(a.value) + index + } if index < 0 || index >= len(a.value) { opChain.fail(AssertionFailure{ Type: AssertInRange, diff --git a/array_test.go b/array_test.go index cad656e95..201d443ba 100644 --- a/array_test.go +++ b/array_test.go @@ -351,7 +351,21 @@ func TestArray_Getters(t *testing.T) { innerValue.chain.assert(t, success) }) - t.Run("value out of range", func(t *testing.T) { + t.Run("value negative", func(t *testing.T) { + reporter := newMockReporter(t) + + data := []interface{}{"foo", 123.0} + + value := NewArray(reporter, data) + + innerValue := value.Value(-1) + assert.Equal(t, 123.0, innerValue.Raw()) + + value.chain.assert(t, success) + innerValue.chain.assert(t, success) + }) + + t.Run("value out of range (positive)", func(t *testing.T) { reporter := newMockReporter(t) data := []interface{}{"foo", 123.0} @@ -364,6 +378,20 @@ func TestArray_Getters(t *testing.T) { value.chain.assert(t, failure) innerValue.chain.assert(t, failure) }) + + t.Run("value out of range (negative)", func(t *testing.T) { + reporter := newMockReporter(t) + + data := []interface{}{"foo", 123.0} + + value := NewArray(reporter, data) + + innerValue := value.Value(-3) + assert.NotNil(t, innerValue) + + value.chain.assert(t, failure) + innerValue.chain.assert(t, failure) + }) } func TestArray_IsEmpty(t *testing.T) { @@ -1426,6 +1454,20 @@ func TestArray_HasValue(t *testing.T) { wantHasValue: success, wantNotHasValue: failure, }, + { + name: "negative index check", + array: []interface{}{ + 123, + []interface{}{"456", 789}, + map[string]interface{}{ + "a": "b", + }, + }, + index: -3, + value: 123, + wantHasValue: success, + wantNotHasValue: failure, + }, { name: "out of bounds check", array: []interface{}{