From ea7b9f8da9ab931ee31b9666f855fde646d311d8 Mon Sep 17 00:00:00 2001 From: Elara6331 Date: Fri, 23 Feb 2024 22:15:43 -0800 Subject: [PATCH] Add tests for negative indices --- salix.go | 2 +- structs_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/salix.go b/salix.go index dfc2a4f..ede93ce 100644 --- a/salix.go +++ b/salix.go @@ -432,7 +432,7 @@ func (t *Template) getIndex(i ast.Index, local map[string]any) (any, error) { if intIndex < 0 { intIndex = rval.Len() + intIndex 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) } else if intIndex < rval.Len() { diff --git a/structs_test.go b/structs_test.go index 787a00b..6c09fff 100644 --- a/structs_test.go +++ b/structs_test.go @@ -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) { testSlice := []any{} 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) { testSlice := []any{} tmpl := testTmpl(t)