added test for gen file

This commit is contained in:
Shreyas Goenka 2023-05-23 19:15:20 +02:00
parent 95d4da6dc0
commit 4fa8c9c06d
No known key found for this signature in database
GPG Key ID: 92A07DF49CCB0622
2 changed files with 34 additions and 1 deletions

View File

@ -27,7 +27,6 @@ func executeTemplate(config map[string]any, templateDefinition string) (string,
return result.String(), nil
}
// TODO: test this function
func generateFile(config map[string]any, pathTemplate, contentTemplate string, perm fs.FileMode) error {
// compute file content
fileContent, err := executeTemplate(config, contentTemplate)

View File

@ -1,6 +1,8 @@
package template
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
@ -32,3 +34,35 @@ Sheep wool is the best!
require.NoError(t, err)
assert.Equal(t, "\"1 items are made of wool\".\n\ncat wool is not too bad...\n\n", statement)
}
func TestGenerateFile(t *testing.T) {
tmp := t.TempDir()
pathTemplate := filepath.Join(tmp, "{{.Animal}}", "{{.Material}}", "foo", "{{.count}}.txt")
contentTemplate := `"{{.count}} items are made of {{.Material}}".
{{if eq .Animal "sheep" }}
Sheep wool is the best!
{{else}}
{{.Animal}} wool is not too bad...
{{end}}
`
err := generateFile(map[string]any{
"Material": "wool",
"count": 1,
"Animal": "cat",
}, pathTemplate, contentTemplate, 0444)
require.NoError(t, err)
// assert file exists
assert.FileExists(t, filepath.Join(tmp, "cat", "wool", "foo", "1.txt"))
// assert file content is created correctly
b, err := os.ReadFile(filepath.Join(tmp, "cat", "wool", "foo", "1.txt"))
require.NoError(t, err)
assert.Equal(t, "\"1 items are made of wool\".\n\t\n\tcat wool is not too bad...\n\t\n\t", string(b))
// assert file permissions are correctly assigned
stat, err := os.Stat(filepath.Join(tmp, "cat", "wool", "foo", "1.txt"))
require.NoError(t, err)
assert.Equal(t, uint(0444), uint(stat.Mode().Perm()))
}