Skip to content

Commit

Permalink
hclwrite: Fix incorrect test TestTokenGenerateConsistency
Browse files Browse the repository at this point in the history
This test is aiming to verify that the tokens produced by TokensForValue
when given a map or object value will stay consistent with the tokens
produced by the lower-level TokensForObject function under future
maintenence.

However, since cty object types and maps don't preserve attribute/element
order, the result from TokensFromValue is always a lexical sort of the
attribute names or keys. TokensForObject is intentionally more flexible
by allowing the caller to control the order of the generated attributes,
but that means that we expect consistency only if the caller provides the
attributes in lexical order.

This test therefore now provides the TokensForObject argument in the
expected order to make this test valid. Previously one of the test cases
would fail 50% of the time due to the attributes being written out in
reverse order.
  • Loading branch information
apparentlymart committed Feb 15, 2022
1 parent 9a303ab commit 0ffd64d
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion hclwrite/generate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package hclwrite
import (
"bytes"
"math/big"
"sort"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -848,7 +849,20 @@ func TestTokenGenerateConsistency(t *testing.T) {
fromMapValue := TokensForValue(mapVal)
fromObjectValue := TokensForValue(cty.ObjectVal(test.attrs))
attrTokens := make([]ObjectAttrTokens, 0, len(test.attrs))
for k, v := range test.attrs {

// TokensForValue always writes the keys/attributes in cty's
// standard iteration order, but TokensForObject gives the
// caller direct control of the ordering. The result is
// therefore consistent only if the given attributes are
// pre-sorted into the same iteration order, which is a lexical
// sort by attribute name.
keys := make([]string, 0, len(test.attrs))
for k := range test.attrs {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := test.attrs[k]
attrTokens = append(attrTokens, ObjectAttrTokens{
Name: TokensForIdentifier(k),
Value: TokensForValue(v),
Expand Down

0 comments on commit 0ffd64d

Please sign in to comment.