1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-26 21:34:44 +01:00
liquid/expressions/parser_test.go

67 lines
1.5 KiB
Go
Raw Normal View History

2017-07-14 02:18:23 +02:00
package expressions
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
2017-07-12 20:25:41 +02:00
var parseTests = []struct {
in string
expect interface{}
}{
2017-07-19 15:42:01 +02:00
{`true`, true},
{`false`, false},
{`nil`, nil},
{`2`, 2},
{`"s"`, "s"},
{`a`, 1},
{`obj.prop`, 2},
{`a | add: b`, 3},
{`1 == 1`, true},
{`1 != 1`, false},
{`true and true`, true},
2017-07-06 05:25:03 +02:00
}
var parseErrorTests = []struct{ in, expected string }{
2017-07-19 00:39:38 +02:00
{"a syntax error", "syntax error"},
{`%assign a`, "syntax error"},
{`%assign a 3`, "syntax error"},
{`%cycle 'a' 'b'`, "syntax error"},
{`%loop a in in`, "syntax error"},
{`%when a b`, "syntax error"},
}
2017-07-19 15:42:01 +02:00
// Since the parser returns funcs, there's no easy way to test them except evaluation
2017-07-06 05:25:03 +02:00
func TestParse(t *testing.T) {
cfg := NewConfig()
2017-07-19 15:42:01 +02:00
cfg.AddFilter("add", func(a, b int) int { return a + b })
ctx := NewContext(map[string]interface{}{
"a": 1,
"b": 2,
"obj": map[string]int{"prop": 2},
}, cfg)
2017-07-06 05:25:03 +02:00
for i, test := range parseTests {
t.Run(fmt.Sprintf("%02d", i+1), func(t *testing.T) {
expr, err := Parse(test.in)
require.NoError(t, err, test.in)
_ = expr
2017-07-06 05:25:03 +02:00
value, err := expr.Evaluate(ctx)
require.NoError(t, err, test.in)
2017-07-12 20:25:41 +02:00
require.Equal(t, test.expect, value, test.in)
2017-07-06 05:25:03 +02:00
})
}
}
func TestParse_errors(t *testing.T) {
for i, test := range parseErrorTests {
2017-06-30 22:13:18 +02:00
t.Run(fmt.Sprintf("%02d", i+1), func(t *testing.T) {
expr, err := Parse(test.in)
require.Nilf(t, expr, test.in)
require.Errorf(t, err, test.in, test.in)
require.Containsf(t, err.Error(), test.expected, test.in)
})
}
}