github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/lang/blocktoattr/fixup_bench_test.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package blocktoattr 5 6 import ( 7 "testing" 8 9 "github.com/hashicorp/hcl/v2" 10 "github.com/hashicorp/hcl/v2/hcldec" 11 "github.com/hashicorp/hcl/v2/hclsyntax" 12 "github.com/terramate-io/tf/configs/configschema" 13 "github.com/zclconf/go-cty/cty" 14 ) 15 16 func ambiguousNestedBlock(nesting int) *configschema.NestedBlock { 17 ret := &configschema.NestedBlock{ 18 Nesting: configschema.NestingList, 19 Block: configschema.Block{ 20 Attributes: map[string]*configschema.Attribute{ 21 "a": {Type: cty.String, Required: true}, 22 "b": {Type: cty.String, Optional: true}, 23 }, 24 }, 25 } 26 if nesting > 0 { 27 ret.BlockTypes = map[string]*configschema.NestedBlock{ 28 "nested0": ambiguousNestedBlock(nesting - 1), 29 "nested1": ambiguousNestedBlock(nesting - 1), 30 "nested2": ambiguousNestedBlock(nesting - 1), 31 "nested3": ambiguousNestedBlock(nesting - 1), 32 "nested4": ambiguousNestedBlock(nesting - 1), 33 "nested5": ambiguousNestedBlock(nesting - 1), 34 "nested6": ambiguousNestedBlock(nesting - 1), 35 "nested7": ambiguousNestedBlock(nesting - 1), 36 "nested8": ambiguousNestedBlock(nesting - 1), 37 "nested9": ambiguousNestedBlock(nesting - 1), 38 } 39 } 40 return ret 41 } 42 43 func schemaWithAmbiguousNestedBlock(nesting int) *configschema.Block { 44 return &configschema.Block{ 45 BlockTypes: map[string]*configschema.NestedBlock{ 46 "maybe_block": ambiguousNestedBlock(nesting), 47 }, 48 } 49 } 50 51 const configForFixupBlockAttrsBenchmark = ` 52 maybe_block { 53 a = "hello" 54 b = "world" 55 nested0 { 56 a = "the" 57 nested1 { 58 a = "deeper" 59 nested2 { 60 a = "we" 61 nested3 { 62 a = "go" 63 b = "inside" 64 } 65 } 66 } 67 } 68 } 69 ` 70 71 func configBodyForFixupBlockAttrsBenchmark() hcl.Body { 72 f, diags := hclsyntax.ParseConfig([]byte(configForFixupBlockAttrsBenchmark), "", hcl.Pos{Line: 1, Column: 1}) 73 if diags.HasErrors() { 74 panic("test configuration is invalid") 75 } 76 return f.Body 77 } 78 79 func BenchmarkFixUpBlockAttrs(b *testing.B) { 80 for i := 0; i < b.N; i++ { 81 b.StopTimer() 82 body := configBodyForFixupBlockAttrsBenchmark() 83 schema := schemaWithAmbiguousNestedBlock(5) 84 b.StartTimer() 85 86 spec := schema.DecoderSpec() 87 fixedBody := FixUpBlockAttrs(body, schema) 88 val, diags := hcldec.Decode(fixedBody, spec, nil) 89 if diags.HasErrors() { 90 b.Fatal("diagnostics during decoding", diags) 91 } 92 if !val.Type().IsObjectType() { 93 b.Fatal("result is not an object") 94 } 95 blockVal := val.GetAttr("maybe_block") 96 if !blockVal.Type().IsListType() || blockVal.LengthInt() != 1 { 97 b.Fatal("result has wrong value for 'maybe_block'") 98 } 99 } 100 }