github.com/hashicorp/hcl/v2@v2.20.0/ext/transform/transform_test.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package transform 5 6 import ( 7 "testing" 8 9 "reflect" 10 11 "github.com/hashicorp/hcl/v2" 12 "github.com/hashicorp/hcl/v2/hcltest" 13 "github.com/zclconf/go-cty/cty" 14 ) 15 16 // Assert that deepWrapper implements Body 17 var deepWrapperIsBody hcl.Body = deepWrapper{} 18 19 func TestDeep(t *testing.T) { 20 21 testTransform := TransformerFunc(func(body hcl.Body) hcl.Body { 22 _, remain, diags := body.PartialContent(&hcl.BodySchema{ 23 Blocks: []hcl.BlockHeaderSchema{ 24 { 25 Type: "remove", 26 }, 27 }, 28 }) 29 30 return BodyWithDiagnostics(remain, diags) 31 }) 32 33 src := hcltest.MockBody(&hcl.BodyContent{ 34 Attributes: hcltest.MockAttrs(map[string]hcl.Expression{ 35 "true": hcltest.MockExprLiteral(cty.True), 36 }), 37 Blocks: []*hcl.Block{ 38 { 39 Type: "remove", 40 Body: hcl.EmptyBody(), 41 }, 42 { 43 Type: "child", 44 Body: hcltest.MockBody(&hcl.BodyContent{ 45 Blocks: []*hcl.Block{ 46 { 47 Type: "remove", 48 }, 49 }, 50 }), 51 }, 52 }, 53 }) 54 55 wrapped := Deep(src, testTransform) 56 57 rootContent, diags := wrapped.Content(&hcl.BodySchema{ 58 Attributes: []hcl.AttributeSchema{ 59 { 60 Name: "true", 61 }, 62 }, 63 Blocks: []hcl.BlockHeaderSchema{ 64 { 65 Type: "child", 66 }, 67 }, 68 }) 69 if len(diags) != 0 { 70 t.Errorf("unexpected diagnostics for root content") 71 for _, diag := range diags { 72 t.Logf("- %s", diag) 73 } 74 } 75 76 wantAttrs := hcltest.MockAttrs(map[string]hcl.Expression{ 77 "true": hcltest.MockExprLiteral(cty.True), 78 }) 79 if !reflect.DeepEqual(rootContent.Attributes, wantAttrs) { 80 t.Errorf("wrong root attributes\ngot: %#v\nwant: %#v", rootContent.Attributes, wantAttrs) 81 } 82 83 if got, want := len(rootContent.Blocks), 1; got != want { 84 t.Fatalf("wrong number of root blocks %d; want %d", got, want) 85 } 86 if got, want := rootContent.Blocks[0].Type, "child"; got != want { 87 t.Errorf("wrong block type %s; want %s", got, want) 88 } 89 90 childBlock := rootContent.Blocks[0] 91 childContent, diags := childBlock.Body.Content(&hcl.BodySchema{}) 92 if len(diags) != 0 { 93 t.Errorf("unexpected diagnostics for child content") 94 for _, diag := range diags { 95 t.Logf("- %s", diag) 96 } 97 } 98 99 if len(childContent.Attributes) != 0 { 100 t.Errorf("unexpected attributes in child content; want empty content") 101 } 102 if len(childContent.Blocks) != 0 { 103 t.Errorf("unexpected blocks in child content; want empty content") 104 } 105 }