github.com/opentofu/opentofu@v1.7.1/internal/tofu/node_local_test.go (about)

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