forked from osteele/liquid
-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine_test.go
94 lines (83 loc) · 2.56 KB
/
engine_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package liquid
import (
"bytes"
"fmt"
"io"
"testing"
"github.com/stretchr/testify/require"
)
var emptyBindings = map[string]interface{}{}
// There's a lot more tests in the filters and tags sub-packages.
// This collects a minimal set for testing end-to-end.
var liquidTests = []struct{ in, expected string }{
{`{{ page.title }}`, "Introduction"},
{`{% if x %}true{% endif %}`, "true"},
{`{{ "upper" | upcase }}`, "UPPER"},
}
var testBindings = map[string]interface{}{
"x": 123,
"ar": []string{"first", "second", "third"},
"page": map[string]interface{}{
"title": "Introduction",
},
}
func TestEngine_ParseAndRenderString(t *testing.T) {
engine := NewEngine()
for i, test := range liquidTests {
t.Run(fmt.Sprint(i+1), func(t *testing.T) {
out, err := engine.ParseAndRenderString(test.in, testBindings)
require.NoErrorf(t, err, test.in)
require.Equalf(t, test.expected, out, test.in)
})
}
}
func TestEngine_ParseAndRenderString_ptr_to_hash(t *testing.T) {
params := map[string]interface{}{
"message": &map[string]interface{}{
"Text": "hello",
},
}
engine := NewEngine()
template := "{{ message.Text }}"
str, err := engine.ParseAndRenderString(template, params)
require.NoError(t, err)
require.Equal(t, "hello", str)
}
type testStruct struct{ Text string }
func TestEngine_ParseAndRenderString_struct(t *testing.T) {
params := map[string]interface{}{
"message": testStruct{
Text: "hello",
},
}
engine := NewEngine()
template := "{{ message.Text }}"
str, err := engine.ParseAndRenderString(template, params)
require.NoError(t, err)
require.Equal(t, "hello", str)
}
func TestEngine_ParseAndRender_errors(t *testing.T) {
_, err := NewEngine().ParseAndRenderString("{{ syntax error }}", emptyBindings)
require.Error(t, err)
_, err = NewEngine().ParseAndRenderString("{% if %}", emptyBindings)
require.Error(t, err)
_, err = NewEngine().ParseAndRenderString("{% undefined_tag %}", emptyBindings)
require.Error(t, err)
_, err = NewEngine().ParseAndRenderString("{% a | undefined_filter %}", emptyBindings)
require.Error(t, err)
}
func BenchmarkEngine_Parse(b *testing.B) {
engine := NewEngine()
buf := new(bytes.Buffer)
for i := 0; i < 1000; i++ {
io.WriteString(buf, `if{% if true %}true{% elsif %}elsif{% else %}else{% endif %}`)
io.WriteString(buf, `loop{% for item in array %}loop{% break %}{% endfor %}`)
io.WriteString(buf, `case{% case value %}{% when a %}{% when b %{% endcase %}`)
io.WriteString(buf, `expr{{ a and b }}{{ a add: b }}`)
}
s := buf.Bytes()
b.ResetTimer()
for i := 0; i < b.N; i++ {
engine.ParseTemplate(s)
}
}