add vars2file method so we can set complex type variable by using varfile

This commit is contained in:
zjhe 2023-05-31 17:01:55 +08:00
Родитель 03dfdfb21b
Коммит 4133c0eced
4 изменённых файлов: 59 добавлений и 0 удалений

1
go.mod
Просмотреть файл

@ -15,6 +15,7 @@ require (
github.com/r3labs/diff/v3 v3.0.1
github.com/spf13/afero v1.9.5
github.com/stretchr/testify v1.8.3
github.com/thanhpk/randstr v1.0.6
github.com/timandy/routine v1.1.1
golang.org/x/mod v0.10.0
golang.org/x/oauth2 v0.8.0

2
go.sum
Просмотреть файл

@ -563,6 +563,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.3 h1:RP3t2pwF7cMEbC1dqtB6poj3niw/9gnV4Cjg5oW5gtY=
github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/thanhpk/randstr v1.0.6 h1:psAOktJFD4vV9NEVb3qkhRSMvYh4ORRaj1+w/hn4B+o=
github.com/thanhpk/randstr v1.0.6/go.mod h1:M/H2P1eNLZzlDwAzpkkkUvoyNNMbzRGhESZuEQk3r0U=
github.com/timandy/routine v1.1.1 h1:6/Z7qLFZj3GrzuRksBFzIG8YGUh8CLhjnnMePBQTrEI=
github.com/timandy/routine v1.1.1/go.mod h1:OZHPOKSvqL/ZvqXFkNZyit0xIVelERptYXdAHH00adQ=
github.com/tmccombs/hcl2json v0.3.3 h1:+DLNYqpWE0CsOQiEZu+OZm5ZBImake3wtITYxQ8uLFQ=

27
variable_file.go Normal file
Просмотреть файл

@ -0,0 +1,27 @@
package terraform_module_test_helper
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"github.com/thanhpk/randstr"
)
func VarsToFile(t *testing.T, vars map[string]any) string {
cleanPath := filepath.Clean(fmt.Sprintf("%s/terraform%s.tfvars.json", os.TempDir(), randstr.Hex(8)))
varFile, err := os.Create(cleanPath)
require.Nil(t, err)
c, err := json.Marshal(vars)
require.Nil(t, err)
_, err = varFile.Write(c)
require.Nil(t, err)
_ = varFile.Close()
varFilePath, err := filepath.Abs(cleanPath)
require.Nil(t, err)
return varFilePath
}

29
variable_file_test.go Normal file
Просмотреть файл

@ -0,0 +1,29 @@
package terraform_module_test_helper
import (
"encoding/json"
"github.com/gruntwork-io/go-commons/files"
"github.com/stretchr/testify/assert"
"os"
"testing"
)
func TestVarsToFile(t *testing.T) {
vars := make(map[string]any, 0)
vars["number"] = 1.0
vars["string"] = "hello"
vars["object"] = map[string]any {
"key": "value",
}
path := VarsToFile(t, vars)
defer func() {
_ = os.Remove(path)
}()
content, err := files.ReadFileAsString(path)
assert.NoError(t, err)
actual := make(map[string]any, 0)
err = json.Unmarshal([]byte(content), &actual)
assert.NoError(t, err)
assert.Equal(t, vars, actual)
}