Files
opentf/internal/tofu/node_local_test.go
Martin Atkins 868dc2f01b hcl2shim: Split out legacy subset
Due to some past confusion about the purpose of this package, it has grown
to include a confusing mix of currently-viable code and legacy support
code from the move to HCL 2. This has in turn caused confusion about which
parts of this package _should_ be used for new code.

To help clarify that distinction we'll move the legacy support code into
a package under the "legacy" directory, which is also where most of its
callers live.

There are unfortunately still some callers to these outside of the legacy
tree, but the vast majority are either old tests written before HCL 2
adoption or helper code used only by those tests. The one dubious exception
is the use in ResourceInstanceObjectSrc.Decode, which makes a best effort
to shim flatmap as a concession to the fact that not all state-loading
codepaths are able to run the provider state upgrade function that would
normally be responsible for the flatmap-to-JSON conversion, which is
explained in a new comment inline.

Signed-off-by: Martin Atkins <mart@degeneration.co.uk>
2025-07-10 08:13:25 -07:00

91 lines
1.9 KiB
Go

// Copyright (c) The OpenTofu Authors
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2023 HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package tofu
import (
"reflect"
"testing"
"github.com/davecgh/go-spew/spew"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
"github.com/opentofu/opentofu/internal/addrs"
"github.com/opentofu/opentofu/internal/configs"
"github.com/opentofu/opentofu/internal/legacy/hcl2shim"
"github.com/opentofu/opentofu/internal/states"
)
func TestNodeLocalExecute(t *testing.T) {
tests := []struct {
Value string
Want interface{}
Err bool
}{
{
"hello!",
"hello!",
false,
},
{
"",
"",
false,
},
{
"Hello, ${local.foo}",
nil,
true, // self-referencing
},
}
for _, test := range tests {
t.Run(test.Value, func(t *testing.T) {
expr, diags := hclsyntax.ParseTemplate([]byte(test.Value), "", hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
t.Fatal(diags.Error())
}
n := &NodeLocal{
Addr: addrs.LocalValue{Name: "foo"}.Absolute(addrs.RootModuleInstance),
Config: &configs.Local{
Expr: expr,
},
}
evalCtx := &MockEvalContext{
StateState: states.NewState().SyncWrapper(),
EvaluateExprResult: hcl2shim.HCL2ValueFromConfigValue(test.Want),
}
err := n.Execute(t.Context(), evalCtx, walkApply)
if (err != nil) != test.Err {
if err != nil {
t.Errorf("unexpected error: %s", err)
} else {
t.Errorf("successful Eval; want error")
}
}
ms := evalCtx.StateState.Module(addrs.RootModuleInstance)
gotLocals := ms.LocalValues
wantLocals := map[string]cty.Value{}
if test.Want != nil {
wantLocals["foo"] = hcl2shim.HCL2ValueFromConfigValue(test.Want)
}
if !reflect.DeepEqual(gotLocals, wantLocals) {
t.Errorf(
"wrong locals after Eval\ngot: %swant: %s",
spew.Sdump(gotLocals), spew.Sdump(wantLocals),
)
}
})
}
}