Skip to content

Commit a0743a3

Browse files
committed
Generate error when accessing string index of primitive
1 parent 468c296 commit a0743a3

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

Liquid.NET.Tests/Constants/MissingValueTests.cs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
using System;
2-
using System.Collections.Generic;
32
using System.Linq;
4-
using System.Text;
5-
using System.Threading.Tasks;
63
using Liquid.NET.Constants;
74
using NUnit.Framework;
85

@@ -55,6 +52,8 @@ public void It_Should_Display_An_Error_When_Dereferencing_Empty_Array(String var
5552

5653
}
5754

55+
56+
5857
[Test]
5958
public void It_Should_Display_Error_When_Dereferencing_Array_With_Non_Int()
6059
{
@@ -73,6 +72,26 @@ public void It_Should_Display_Error_When_Dereferencing_Array_With_Non_Int()
7372

7473
}
7574

75+
[Test]
76+
public void It_Should_Display_Error_When_Dereferencing_Primitive_With_Index()
77+
{
78+
// Arrange
79+
ITemplateContext ctx = new TemplateContext()
80+
.ErrorWhenValueMissing();
81+
ctx.DefineLocalVariable("e", LiquidString.Create("Hello"));
82+
83+
// Act
84+
var template = LiquidTemplate.Create("Result : {{ e.x }}");
85+
var result = template.LiquidTemplate.Render(ctx);
86+
87+
Assert.That(result.HasRenderingErrors, Is.True);
88+
var errorMessage = String.Join(",", result.RenderingErrors.Select(x => x.Message));
89+
// Assert
90+
Assert.That(errorMessage, Is.StringContaining("invalid string index: 'x'"));
91+
92+
}
93+
94+
7695
[Test]
7796
[TestCase("x")]
7897
[TestCase("e[1]")]

Liquid.NET/src/Constants/IndexDereferencer.cs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -147,14 +147,18 @@ private LiquidExpressionResult DoLookup(ITemplateContext ctx, LiquidString str,
147147
}
148148
else
149149
{
150-
var maybeIndexResult = ValueCaster.Cast<ILiquidValue, LiquidNumeric>(indexProperty);
151-
if (maybeIndexResult.IsError || !maybeIndexResult.SuccessResult.HasValue)
152-
{
153-
return LiquidExpressionResult.Error("invalid array index: " + propertyNameString);
150+
//var maybeIndexResult = ValueCaster.Cast<ILiquidValue, LiquidNumeric>(indexProperty);
151+
var numericIndexProperty = indexProperty as LiquidNumeric;
152+
153+
if (numericIndexProperty == null)
154+
{
155+
return ctx.Options.ErrorWhenValueMissing ?
156+
LiquidExpressionResult.Error("invalid string index: '" + propertyNameString + "'") :
157+
LiquidExpressionResult.Success(new None<ILiquidValue>());
154158
}
155159
else
156160
{
157-
index = maybeIndexResult.SuccessValue<LiquidNumeric>().IntValue;
161+
index = numericIndexProperty.IntValue;
158162
}
159163
}
160164

0 commit comments

Comments
 (0)