Add tests for negative indices
This commit is contained in:
		
							
								
								
									
										2
									
								
								salix.go
									
									
									
									
									
								
							
							
						
						
									
										2
									
								
								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() { | ||||
|   | ||||
| @@ -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) | ||||
|   | ||||
		Reference in New Issue
	
	Block a user