Add tests for negative indices

This commit is contained in:
Elara 2024-02-23 22:15:43 -08:00
parent 110f050c1c
commit ea7b9f8da9
2 changed files with 40 additions and 1 deletions

View File

@ -432,7 +432,7 @@ func (t *Template) getIndex(i ast.Index, local map[string]any) (any, error) {
if intIndex < 0 { if intIndex < 0 {
intIndex = rval.Len() + intIndex intIndex = rval.Len() + intIndex
if intIndex < 0 { if intIndex < 0 {
return nil, ast.PosError(i, "%s: index out of range: %d (length %d)", valueToString(i), intIndex, rval.Len()) return nil, ast.PosError(i, "%s: index out of range: %d (length %d)", valueToString(i), rindex.Interface(), rval.Len())
} }
out = rval.Index(intIndex) out = rval.Index(intIndex)
} else if intIndex < rval.Len() { } else if intIndex < rval.Len() {

View File

@ -33,6 +33,28 @@ func TestSliceGetIndex(t *testing.T) {
} }
} }
func TestSliceGetNegativeIndex(t *testing.T) {
testSlice := []any{1, "2", 3.0}
tmpl := testTmpl(t)
// test[-2]
ast := ast.Index{
Value: ast.Ident{Value: "test", Position: testPos(t)},
Index: ast.Integer{Value: -2, Position: testPos(t)},
Position: testPos(t),
}
val, err := tmpl.getIndex(ast, map[string]any{"test": testSlice})
if err != nil {
t.Fatalf("getIndex error: %s", err)
}
if val != testSlice[len(testSlice)-2] {
t.Errorf("Expected %q, got %q", "2", val)
}
}
func TestSliceGetIndexOutOfRange(t *testing.T) { func TestSliceGetIndexOutOfRange(t *testing.T) {
testSlice := []any{} testSlice := []any{}
tmpl := testTmpl(t) tmpl := testTmpl(t)
@ -50,6 +72,23 @@ func TestSliceGetIndexOutOfRange(t *testing.T) {
} }
} }
func TestSliceGetNegativeIndexOutOfRange(t *testing.T) {
testSlice := []any{0, 1, 2, 3}
tmpl := testTmpl(t)
// test[-5]
ast := ast.Index{
Value: ast.Ident{Value: "test", Position: testPos(t)},
Index: ast.Integer{Value: -5, Position: testPos(t)},
Position: testPos(t),
}
_, err := tmpl.getIndex(ast, map[string]any{"test": testSlice})
if err == nil {
t.Errorf("Expected error, got nil")
}
}
func TestSliceGetIndexInvalidType(t *testing.T) { func TestSliceGetIndexInvalidType(t *testing.T) {
testSlice := []any{} testSlice := []any{}
tmpl := testTmpl(t) tmpl := testTmpl(t)