From a679f4ed10bfff49b4335f7db0799e47dd5ac648 Mon Sep 17 00:00:00 2001 From: Ryota Sakamoto Date: Sat, 15 Jun 2024 23:30:23 +0900 Subject: [PATCH] add cloudinit.Generate test --- pkg/cloudinit/generator.go | 14 ++++----- pkg/cloudinit/generator_test.go | 51 +++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 7 deletions(-) create mode 100644 pkg/cloudinit/generator_test.go diff --git a/pkg/cloudinit/generator.go b/pkg/cloudinit/generator.go index 5833ca3..359c8fc 100644 --- a/pkg/cloudinit/generator.go +++ b/pkg/cloudinit/generator.go @@ -2,7 +2,6 @@ package cloudinit import ( "bytes" - "fmt" "text/template" "github.com/goccy/go-yaml" @@ -26,17 +25,18 @@ func Generate(c Config, vars map[string]string) (string, error) { return "", err } - temp, err := template.New("cloud-config").Parse(buff.String()) + temp, err := template.New("cloud-config").Parse(`#cloud-config +package_update: true + +` + buff.String()) if err != nil { return "", err } - if err := temp.Execute(buff, vars); err != nil { + output := &bytes.Buffer{} + if err := temp.Execute(output, vars); err != nil { return "", err } - return fmt.Sprintf(`#cloud-config -package_update: true - -%s`, buff.String()), nil + return output.String(), nil } diff --git a/pkg/cloudinit/generator_test.go b/pkg/cloudinit/generator_test.go new file mode 100644 index 0000000..bf008e0 --- /dev/null +++ b/pkg/cloudinit/generator_test.go @@ -0,0 +1,51 @@ +package cloudinit_test + +import ( + "testing" + + "github.com/ryota-sakamoto/kubernetes-on-multipass/pkg/cloudinit" + "github.com/stretchr/testify/assert" +) + +func TestGenerate(t *testing.T) { + result, err := cloudinit.Generate(cloudinit.Config{ + Packages: []string{ + "git", + "vim", + }, + WriteFiles: []cloudinit.WriteFile{ + { + Content: `file {{ .Content }}`, + Path: "/opt/ok", + }, + { + Content: `echo ok`, + Path: "/use/bin/ok", + Permissions: "0755", + }, + }, + RunCmds: []string{ + "/use/bin/ok", + }, + }, map[string]string{ + "Content": "content", + }) + assert.NoError(t, err) + + expectedResult := `#cloud-config +package_update: true + +packages: +- git +- vim +write_files: +- path: /opt/ok + content: file content +- path: /use/bin/ok + content: echo ok + permissions: "0755" +runcmd: +- /use/bin/ok +` + assert.Equal(t, expectedResult, result) +}