github.com/docker/docker-ce@v17.12.1-ce-rc2+incompatible/components/cli/templates/templates_test.go (about) 1 package templates 2 3 import ( 4 "bytes" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 // GitHub #32120 11 func TestParseJSONFunctions(t *testing.T) { 12 tm, err := Parse(`{{json .Ports}}`) 13 assert.NoError(t, err) 14 15 var b bytes.Buffer 16 assert.NoError(t, tm.Execute(&b, map[string]string{"Ports": "0.0.0.0:2->8/udp"})) 17 want := "\"0.0.0.0:2->8/udp\"" 18 assert.Equal(t, want, b.String()) 19 } 20 21 func TestParseStringFunctions(t *testing.T) { 22 tm, err := Parse(`{{join (split . ":") "/"}}`) 23 assert.NoError(t, err) 24 25 var b bytes.Buffer 26 assert.NoError(t, tm.Execute(&b, "text:with:colon")) 27 want := "text/with/colon" 28 assert.Equal(t, want, b.String()) 29 } 30 31 func TestNewParse(t *testing.T) { 32 tm, err := NewParse("foo", "this is a {{ . }}") 33 assert.NoError(t, err) 34 35 var b bytes.Buffer 36 assert.NoError(t, tm.Execute(&b, "string")) 37 want := "this is a string" 38 assert.Equal(t, want, b.String()) 39 } 40 41 func TestParseTruncateFunction(t *testing.T) { 42 source := "tupx5xzf6hvsrhnruz5cr8gwp" 43 44 testCases := []struct { 45 template string 46 expected string 47 }{ 48 { 49 template: `{{truncate . 5}}`, 50 expected: "tupx5", 51 }, 52 { 53 template: `{{truncate . 25}}`, 54 expected: "tupx5xzf6hvsrhnruz5cr8gwp", 55 }, 56 { 57 template: `{{truncate . 30}}`, 58 expected: "tupx5xzf6hvsrhnruz5cr8gwp", 59 }, 60 { 61 template: `{{pad . 3 3}}`, 62 expected: " tupx5xzf6hvsrhnruz5cr8gwp ", 63 }, 64 } 65 66 for _, testCase := range testCases { 67 tm, err := Parse(testCase.template) 68 assert.NoError(t, err) 69 70 t.Run("Non Empty Source Test with template: "+testCase.template, func(t *testing.T) { 71 var b bytes.Buffer 72 assert.NoError(t, tm.Execute(&b, source)) 73 assert.Equal(t, testCase.expected, b.String()) 74 }) 75 76 t.Run("Empty Source Test with template: "+testCase.template, func(t *testing.T) { 77 var c bytes.Buffer 78 assert.NoError(t, tm.Execute(&c, "")) 79 assert.Equal(t, "", c.String()) 80 }) 81 82 t.Run("Nil Source Test with template: "+testCase.template, func(t *testing.T) { 83 var c bytes.Buffer 84 assert.Error(t, tm.Execute(&c, nil)) 85 assert.Equal(t, "", c.String()) 86 }) 87 } 88 }