github.com/hashicorp/terraform-plugin-sdk@v1.17.2/terraform/eval_local_test.go (about) 1 package terraform 2 3 import ( 4 "reflect" 5 "testing" 6 7 "github.com/davecgh/go-spew/spew" 8 "github.com/hashicorp/hcl/v2" 9 "github.com/hashicorp/hcl/v2/hclsyntax" 10 "github.com/zclconf/go-cty/cty" 11 12 "github.com/hashicorp/terraform-plugin-sdk/internal/addrs" 13 "github.com/hashicorp/terraform-plugin-sdk/internal/configs/hcl2shim" 14 "github.com/hashicorp/terraform-plugin-sdk/internal/states" 15 ) 16 17 func TestEvalLocal_impl(t *testing.T) { 18 var _ EvalNode = new(EvalLocal) 19 } 20 21 func TestEvalLocal(t *testing.T) { 22 tests := []struct { 23 Value string 24 Want interface{} 25 Err bool 26 }{ 27 { 28 "hello!", 29 "hello!", 30 false, 31 }, 32 { 33 "", 34 "", 35 false, 36 }, 37 { 38 "Hello, ${local.foo}", 39 nil, 40 true, // self-referencing 41 }, 42 } 43 44 for _, test := range tests { 45 t.Run(test.Value, func(t *testing.T) { 46 expr, diags := hclsyntax.ParseTemplate([]byte(test.Value), "", hcl.Pos{Line: 1, Column: 1}) 47 if diags.HasErrors() { 48 t.Fatal(diags.Error()) 49 } 50 51 n := &EvalLocal{ 52 Addr: addrs.LocalValue{Name: "foo"}, 53 Expr: expr, 54 } 55 ctx := &MockEvalContext{ 56 StateState: states.NewState().SyncWrapper(), 57 58 EvaluateExprResult: hcl2shim.HCL2ValueFromConfigValue(test.Want), 59 } 60 61 _, err := n.Eval(ctx) 62 if (err != nil) != test.Err { 63 if err != nil { 64 t.Errorf("unexpected error: %s", err) 65 } else { 66 t.Errorf("successful Eval; want error") 67 } 68 } 69 70 ms := ctx.StateState.Module(addrs.RootModuleInstance) 71 gotLocals := ms.LocalValues 72 wantLocals := map[string]cty.Value{} 73 if test.Want != nil { 74 wantLocals["foo"] = hcl2shim.HCL2ValueFromConfigValue(test.Want) 75 } 76 77 if !reflect.DeepEqual(gotLocals, wantLocals) { 78 t.Errorf( 79 "wrong locals after Eval\ngot: %swant: %s", 80 spew.Sdump(gotLocals), spew.Sdump(wantLocals), 81 ) 82 } 83 }) 84 } 85 86 }