File: templates_test.go

package info (click to toggle)
docker.io 27.5.1%2Bdfsg4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 67,384 kB
  • sloc: sh: 5,847; makefile: 1,146; ansic: 664; python: 162; asm: 133
file content (91 lines) | stat: -rw-r--r-- 2,171 bytes parent folder | download | duplicates (10)
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
package templates

import (
	"bytes"
	"testing"

	"gotest.tools/v3/assert"
	is "gotest.tools/v3/assert/cmp"
)

// GitHub #32120
func TestParseJSONFunctions(t *testing.T) {
	tm, err := Parse(`{{json .Ports}}`)
	assert.NilError(t, err)

	var b bytes.Buffer
	assert.NilError(t, tm.Execute(&b, map[string]string{"Ports": "0.0.0.0:2->8/udp"}))
	want := "\"0.0.0.0:2->8/udp\""
	assert.Check(t, is.Equal(want, b.String()))
}

func TestParseStringFunctions(t *testing.T) {
	tm, err := Parse(`{{join (split . ":") "/"}}`)
	assert.NilError(t, err)

	var b bytes.Buffer
	assert.NilError(t, tm.Execute(&b, "text:with:colon"))
	want := "text/with/colon"
	assert.Check(t, is.Equal(want, b.String()))
}

func TestNewParse(t *testing.T) {
	tm, err := NewParse("foo", "this is a {{ . }}")
	assert.NilError(t, err)

	var b bytes.Buffer
	assert.NilError(t, tm.Execute(&b, "string"))
	want := "this is a string"
	assert.Check(t, is.Equal(want, b.String()))
}

func TestParseTruncateFunction(t *testing.T) {
	source := "tupx5xzf6hvsrhnruz5cr8gwp"

	testCases := []struct {
		template string
		expected string
	}{
		{
			template: `{{truncate . 5}}`,
			expected: "tupx5",
		},
		{
			template: `{{truncate . 25}}`,
			expected: "tupx5xzf6hvsrhnruz5cr8gwp",
		},
		{
			template: `{{truncate . 30}}`,
			expected: "tupx5xzf6hvsrhnruz5cr8gwp",
		},
		{
			template: `{{pad . 3 3}}`,
			expected: "   tupx5xzf6hvsrhnruz5cr8gwp   ",
		},
	}

	for _, testCase := range testCases {
		testCase := testCase

		tm, err := Parse(testCase.template)
		assert.NilError(t, err)

		t.Run("Non Empty Source Test with template: "+testCase.template, func(t *testing.T) {
			var b bytes.Buffer
			assert.NilError(t, tm.Execute(&b, source))
			assert.Check(t, is.Equal(testCase.expected, b.String()))
		})

		t.Run("Empty Source Test with template: "+testCase.template, func(t *testing.T) {
			var c bytes.Buffer
			assert.NilError(t, tm.Execute(&c, ""))
			assert.Check(t, is.Equal("", c.String()))
		})

		t.Run("Nil Source Test with template: "+testCase.template, func(t *testing.T) {
			var c bytes.Buffer
			assert.Check(t, tm.Execute(&c, nil) != nil)
			assert.Check(t, is.Equal("", c.String()))
		})
	}
}