github.com/kanishk98/terraform@v1.3.0-dev.0.20220917174235-661ca8088a6a/internal/terraform/evaluate_triggers_test.go (about) 1 package terraform 2 3 import ( 4 "testing" 5 6 "github.com/hashicorp/hcl/v2" 7 "github.com/hashicorp/hcl/v2/hclsyntax" 8 "github.com/hashicorp/terraform/internal/addrs" 9 "github.com/hashicorp/terraform/internal/instances" 10 "github.com/zclconf/go-cty/cty" 11 ) 12 13 func TestEvalReplaceTriggeredBy(t *testing.T) { 14 tests := map[string]struct { 15 // Raw config expression from within replace_triggered_by list. 16 // If this does not contains any count or each references, it should 17 // directly parse into the same *addrs.Reference. 18 expr string 19 20 // If the expression contains count or each, then we need to add 21 // repetition data, and the static string to parse into the desired 22 // *addrs.Reference 23 repData instances.RepetitionData 24 reference string 25 }{ 26 "single resource": { 27 expr: "test_resource.a", 28 }, 29 30 "resource instance attr": { 31 expr: "test_resource.a.attr", 32 }, 33 34 "resource instance index attr": { 35 expr: "test_resource.a[0].attr", 36 }, 37 38 "resource instance count": { 39 expr: "test_resource.a[count.index]", 40 repData: instances.RepetitionData{ 41 CountIndex: cty.NumberIntVal(0), 42 }, 43 reference: "test_resource.a[0]", 44 }, 45 "resource instance for_each": { 46 expr: "test_resource.a[each.key].attr", 47 repData: instances.RepetitionData{ 48 EachKey: cty.StringVal("k"), 49 }, 50 reference: `test_resource.a["k"].attr`, 51 }, 52 "resource instance for_each map attr": { 53 expr: "test_resource.a[each.key].attr[each.key]", 54 repData: instances.RepetitionData{ 55 EachKey: cty.StringVal("k"), 56 }, 57 reference: `test_resource.a["k"].attr["k"]`, 58 }, 59 } 60 61 for name, tc := range tests { 62 pos := hcl.Pos{Line: 1, Column: 1} 63 t.Run(name, func(t *testing.T) { 64 expr, hclDiags := hclsyntax.ParseExpression([]byte(tc.expr), "", pos) 65 if hclDiags.HasErrors() { 66 t.Fatal(hclDiags) 67 } 68 69 got, diags := evalReplaceTriggeredByExpr(expr, tc.repData) 70 if diags.HasErrors() { 71 t.Fatal(diags.Err()) 72 } 73 74 want := tc.reference 75 if want == "" { 76 want = tc.expr 77 } 78 79 // create the desired reference 80 traversal, travDiags := hclsyntax.ParseTraversalAbs([]byte(want), "", pos) 81 if travDiags.HasErrors() { 82 t.Fatal(travDiags) 83 } 84 ref, diags := addrs.ParseRef(traversal) 85 if diags.HasErrors() { 86 t.Fatal(diags.Err()) 87 } 88 89 if got.DisplayString() != ref.DisplayString() { 90 t.Fatalf("expected %q: got %q", ref.DisplayString(), got.DisplayString()) 91 } 92 }) 93 } 94 }