From 4fa8c9c06dd1438df6e975e4461c8ca8921884dc Mon Sep 17 00:00:00 2001 From: Shreyas Goenka Date: Tue, 23 May 2023 19:15:20 +0200 Subject: [PATCH] added test for gen file --- libs/template/execute.go | 1 - libs/template/execute_test.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/libs/template/execute.go b/libs/template/execute.go index 82f80c52..6096ccc0 100644 --- a/libs/template/execute.go +++ b/libs/template/execute.go @@ -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) diff --git a/libs/template/execute_test.go b/libs/template/execute_test.go index 906c886a..55ac03a2 100644 --- a/libs/template/execute_test.go +++ b/libs/template/execute_test.go @@ -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())) +}