Skip to content

Commit

Permalink
Add tests for File
Browse files Browse the repository at this point in the history
  • Loading branch information
minamijoyo committed Apr 4, 2022
1 parent 0975f76 commit 6526c3f
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
6 changes: 6 additions & 0 deletions tfwrite/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ func NewFile(file *hclwrite.File) *File {
return &File{raw: file}
}

// NewEmptyFile creates a new file with an empty body.
func NewEmptyFile() *File {
file := hclwrite.NewEmptyFile()
return NewFile(file)
}

// Raw returns a raw object for hclwrite.
func (f *File) Raw() *hclwrite.File {
return f.raw
Expand Down
91 changes: 91 additions & 0 deletions tfwrite/file_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package tfwrite

import (
"testing"

"github.com/google/go-cmp/cmp"
)

func TestFileFindResourcesByType(t *testing.T) {
cases := []struct {
desc string
src string
resourceType string
want string
ok bool
}{
{
desc: "simple",
src: `
resource "foo_test" "example1" {}
resource "foo_test" "example2" {}
resource "foo_bar" "example1" {}
data "foo_test" "example1" {}
`,
resourceType: "foo_test",
want: `
resource "foo_test" "example1" {}
resource "foo_test" "example2" {}
`,
ok: true,
},
}

for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
f := parseTestFile(t, tc.src)
resources := f.FindResourcesByType(tc.resourceType)

newFile := NewEmptyFile()
for _, r := range resources {
newFile.AppendResource(r)
}

got := printTestFile(t, newFile)
if diff := cmp.Diff(got, tc.want); diff != "" {
t.Fatalf("got:\n%s\nwant:\n%s\ndiff:\n%s", got, tc.want, diff)
}
})
}
}

func TestFileAppendResource(t *testing.T) {
cases := []struct {
desc string
src string
resourceType string
resourceName string
want string
ok bool
}{
{
desc: "simple",
src: `
resource "foo_test" "example1" {}
`,
resourceType: "foo_test",
resourceName: "example2",
want: `
resource "foo_test" "example1" {}
resource "foo_test" "example2" {
}
`,
ok: true,
},
}

for _, tc := range cases {
t.Run(tc.desc, func(t *testing.T) {
f := parseTestFile(t, tc.src)
r := NewEmptyResource(tc.resourceType, tc.resourceName)
f.AppendResource(r)

got := printTestFile(t, f)
if diff := cmp.Diff(got, tc.want); diff != "" {
t.Fatalf("got:\n%s\nwant:\n%s\ndiff:\n%s", got, tc.want, diff)
}
})
}
}

0 comments on commit 6526c3f

Please sign in to comment.