-
Notifications
You must be signed in to change notification settings - Fork 601
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
hclwrite: Add (*Attribute).SetName() method
Reference: #340 Reference: #680 Similar to `(*hclwrite.Block).SetType()`, this new method enables in-place renaming of an attribute.
- Loading branch information
Showing
2 changed files
with
85 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
package hclwrite | ||
|
||
import ( | ||
"fmt" | ||
"reflect" | ||
"testing" | ||
|
||
"github.com/davecgh/go-spew/spew" | ||
"github.com/google/go-cmp/cmp" | ||
"github.com/hashicorp/hcl/v2" | ||
"github.com/hashicorp/hcl/v2/hclsyntax" | ||
) | ||
|
||
func TestAttributeSetName(t *testing.T) { | ||
t.Parallel() | ||
|
||
tests := []struct { | ||
src string | ||
oldName string | ||
newName string | ||
want Tokens | ||
}{ | ||
{ | ||
"old = 123", | ||
"old", | ||
"new", | ||
Tokens{ | ||
{ | ||
Type: hclsyntax.TokenIdent, | ||
Bytes: []byte(`new`), | ||
SpacesBefore: 0, | ||
}, | ||
{ | ||
Type: hclsyntax.TokenEqual, | ||
Bytes: []byte{'='}, | ||
SpacesBefore: 1, | ||
}, | ||
{ | ||
Type: hclsyntax.TokenNumberLit, | ||
Bytes: []byte(`123`), | ||
SpacesBefore: 1, | ||
}, | ||
{ | ||
Type: hclsyntax.TokenEOF, | ||
Bytes: []byte{}, | ||
SpacesBefore: 0, | ||
}, | ||
}, | ||
}, | ||
} | ||
|
||
for _, test := range tests { | ||
test := test | ||
|
||
t.Run(fmt.Sprintf("%s %s in %s", test.oldName, test.newName, test.src), func(t *testing.T) { | ||
t.Parallel() | ||
|
||
f, diags := ParseConfig([]byte(test.src), "", hcl.Pos{Line: 1, Column: 1}) | ||
|
||
if len(diags) != 0 { | ||
for _, diag := range diags { | ||
t.Logf("- %s", diag.Error()) | ||
} | ||
t.Fatalf("unexpected diagnostics") | ||
} | ||
|
||
attr := f.Body().GetAttribute(test.oldName) | ||
attr.SetName(test.newName) | ||
got := f.BuildTokens(nil) | ||
format(got) | ||
|
||
if !reflect.DeepEqual(got, test.want) { | ||
diff := cmp.Diff(test.want, got) | ||
t.Errorf("wrong result\ngot: %s\nwant: %s\ndiff:\n%s", spew.Sdump(got), spew.Sdump(test.want), diff) | ||
} | ||
}) | ||
} | ||
} |