From 0ffd64deae73e7bd14d0e8b1dbe9388d2e2e55c6 Mon Sep 17 00:00:00 2001 From: Martin Atkins Date: Tue, 15 Feb 2022 13:29:17 -0800 Subject: hclwrite: Fix incorrect test TestTokenGenerateConsistency 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. --- hclwrite/generate_test.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'hclwrite') diff --git a/hclwrite/generate_test.go b/hclwrite/generate_test.go index a3df844..06fa094 100644 --- a/hclwrite/generate_test.go +++ b/hclwrite/generate_test.go @@ -3,6 +3,7 @@ package hclwrite import ( "bytes" "math/big" + "sort" "testing" "github.com/google/go-cmp/cmp" @@ -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), -- cgit v1.2.3