github.com/eliastor/durgaform@v0.0.0-20220816172711-d0ab2d17673e/internal/durgaform/node_local_test.go (about) 1 package durgaform 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/eliastor/durgaform/internal/addrs" 13 "github.com/eliastor/durgaform/internal/configs" 14 "github.com/eliastor/durgaform/internal/configs/hcl2shim" 15 "github.com/eliastor/durgaform/internal/states" 16 ) 17 18 func TestNodeLocalExecute(t *testing.T) { 19 tests := []struct { 20 Value string 21 Want interface{} 22 Err bool 23 }{ 24 { 25 "hello!", 26 "hello!", 27 false, 28 }, 29 { 30 "", 31 "", 32 false, 33 }, 34 { 35 "Hello, ${local.foo}", 36 nil, 37 true, // self-referencing 38 }, 39 } 40 41 for _, test := range tests { 42 t.Run(test.Value, func(t *testing.T) { 43 expr, diags := hclsyntax.ParseTemplate([]byte(test.Value), "", hcl.Pos{Line: 1, Column: 1}) 44 if diags.HasErrors() { 45 t.Fatal(diags.Error()) 46 } 47 48 n := &NodeLocal{ 49 Addr: addrs.LocalValue{Name: "foo"}.Absolute(addrs.RootModuleInstance), 50 Config: &configs.Local{ 51 Expr: expr, 52 }, 53 } 54 ctx := &MockEvalContext{ 55 StateState: states.NewState().SyncWrapper(), 56 57 EvaluateExprResult: hcl2shim.HCL2ValueFromConfigValue(test.Want), 58 } 59 60 err := n.Execute(ctx, walkApply) 61 if (err != nil) != test.Err { 62 if err != nil { 63 t.Errorf("unexpected error: %s", err) 64 } else { 65 t.Errorf("successful Eval; want error") 66 } 67 } 68 69 ms := ctx.StateState.Module(addrs.RootModuleInstance) 70 gotLocals := ms.LocalValues 71 wantLocals := map[string]cty.Value{} 72 if test.Want != nil { 73 wantLocals["foo"] = hcl2shim.HCL2ValueFromConfigValue(test.Want) 74 } 75 76 if !reflect.DeepEqual(gotLocals, wantLocals) { 77 t.Errorf( 78 "wrong locals after Eval\ngot: %swant: %s", 79 spew.Sdump(gotLocals), spew.Sdump(wantLocals), 80 ) 81 } 82 }) 83 } 84 85 }