k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/cmd/gotemplate/gotemplate_test.go (about) 1 /* 2 Copyright 2021 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "bytes" 21 "os" 22 "path" 23 "strings" 24 "syscall" 25 "testing" 26 27 "github.com/stretchr/testify/assert" 28 "github.com/stretchr/testify/require" 29 ) 30 31 func TestGenerate(t *testing.T) { 32 noFileErr := os.PathError{Op: "open", Path: "no-such-file.txt", Err: syscall.Errno(syscall.ENOENT)} 33 for name, tt := range map[string]struct { 34 in string 35 data map[string]string 36 files map[string]string 37 expected string 38 expectedErr string 39 }{ 40 "missing-file": { 41 in: `{{include "no-such-file.txt"}}`, 42 expectedErr: noFileErr.Error(), 43 }, 44 "data": { 45 in: `{{.Hello}} {{.World}}`, 46 data: map[string]string{"Hello": "world", "World": "hello"}, 47 expected: "world hello", 48 }, 49 "include": { 50 in: `{{include "test.txt" | indent 2}}`, 51 files: map[string]string{"test.txt": "hello\nworld"}, 52 expected: "hello\n world", 53 }, 54 } { 55 cwd, err := os.Getwd() 56 require.NoError(t, err) 57 58 t.Run(name, func(t *testing.T) { 59 tmp := t.TempDir() 60 for fileName, fileContent := range tt.files { 61 err := os.WriteFile(path.Join(tmp, fileName), []byte(fileContent), 0666) 62 require.NoError(t, err, "create input file") 63 } 64 defer os.Chdir(cwd) 65 require.NoError(t, os.Chdir(tmp), "change into tmp directory") 66 in := strings.NewReader(tt.in) 67 var out bytes.Buffer 68 err := generate(in, &out, tt.data) 69 if tt.expectedErr == "" { 70 require.NoError(t, err, "expand template") 71 require.Equal(t, tt.expected, out.String()) 72 } else { 73 require.Contains(t, err.Error(), tt.expectedErr) 74 } 75 }) 76 } 77 } 78 79 func TestIndent(t *testing.T) { 80 for name, tt := range map[string]struct { 81 numSpaces int 82 content string 83 expected string 84 }{ 85 "empty": { 86 numSpaces: 10, 87 content: "", 88 expected: "", 89 }, 90 "trailing-newline": { 91 numSpaces: 2, 92 content: "hello\nworld\n", 93 expected: "hello\n world\n ", 94 }, 95 "no-trailing-newline": { 96 numSpaces: 1, 97 content: "hello\nworld", 98 expected: "hello\n world", 99 }, 100 "zero-indent": { 101 numSpaces: 0, 102 content: "hello\nworld", 103 expected: "hello\nworld", 104 }, 105 } { 106 t.Run(name, func(t *testing.T) { 107 assert.Equal(t, tt.expected, indent(tt.numSpaces, tt.content)) 108 }) 109 } 110 }