Skip to content

Commit 703abc6

Browse files
authored
test: format rendered test definitions (#975)
This change ensure that the test logs have a clean output when printing the rendered Terraform definition.
1 parent ce0b299 commit 703abc6

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

internal/testtemplate/template.go

+29-3
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,16 @@ import (
66
"math/rand"
77
"os"
88
"path/filepath"
9+
"slices"
910
"strconv"
1011
"strings"
1112
"sync"
1213
"testing"
1314
"text/template"
1415
"time"
16+
17+
hcl "github.com/hashicorp/hcl/v2"
18+
hclwrite "github.com/hashicorp/hcl/v2/hclwrite"
1519
)
1620

1721
var rng *rand.Rand
@@ -133,9 +137,31 @@ func (ts *Manager) Render(t *testing.T, args ...interface{}) string {
133137
buf.WriteString("\n")
134138
}
135139

136-
hcl := strings.TrimSpace(buf.String())
137-
t.Logf("\n\nHCL:\n%s\n", addLineNumbers(hcl))
138-
return hcl
140+
definition := buf.String()
141+
142+
{
143+
// Remove empty lines
144+
lines := strings.Split(definition, "\n")
145+
lines = slices.DeleteFunc(lines, func(line string) bool { return strings.TrimSpace(line) == "" })
146+
definition = strings.Join(lines, "\n")
147+
}
148+
149+
{
150+
// Format HCL files
151+
buf := bytes.NewBuffer(nil)
152+
file, diags := hclwrite.ParseConfig([]byte(definition), "testing.tf", hcl.InitialPos)
153+
if diags.HasErrors() {
154+
t.Fatal(diags.Error())
155+
}
156+
if _, err := file.WriteTo(buf); err != nil {
157+
t.Fatal(err)
158+
}
159+
definition = buf.String()
160+
}
161+
162+
t.Logf("\n\nHCL:\n%s\n", addLineNumbers(definition))
163+
164+
return definition
139165
}
140166

141167
func parseTmplGlob(t *testing.T, root *template.Template, prefix, glob string) {

0 commit comments

Comments
 (0)