opentofu/internal/tofu/validate_selfref_test.go

112 lines
2.1 KiB
Go
Raw Normal View History

// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
2023-09-20 07:16:53 -05:00
package tofu
2017-01-25 23:00:45 -06:00
import (
"fmt"
"testing"
"github.com/opentofu/opentofu/internal/configs/configschema"
"github.com/opentofu/opentofu/internal/providers"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hcltest"
"github.com/opentofu/opentofu/internal/addrs"
"github.com/zclconf/go-cty/cty"
2017-01-25 23:00:45 -06:00
)
func TestValidateSelfRef(t *testing.T) {
rAddr := addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: "aws_instance",
Name: "foo",
}
tests := []struct {
Name string
Addr addrs.Referenceable
Expr hcl.Expression
Err bool
2017-01-25 23:00:45 -06:00
}{
{
"no references at all",
rAddr,
hcltest.MockExprLiteral(cty.StringVal("bar")),
2017-01-25 23:00:45 -06:00
false,
},
{
"non self reference",
rAddr,
hcltest.MockExprTraversalSrc("aws_instance.bar.id"),
2017-01-25 23:00:45 -06:00
false,
},
{
"self reference",
rAddr,
hcltest.MockExprTraversalSrc("aws_instance.foo.id"),
2017-01-25 23:00:45 -06:00
true,
},
{
"self reference other index",
rAddr,
hcltest.MockExprTraversalSrc("aws_instance.foo[4].id"),
2017-01-25 23:00:45 -06:00
false,
},
{
"self reference same index",
rAddr.Instance(addrs.IntKey(4)),
hcltest.MockExprTraversalSrc("aws_instance.foo[4].id"),
2017-01-25 23:00:45 -06:00
true,
},
{
"self reference whole",
rAddr.Instance(addrs.IntKey(4)),
hcltest.MockExprTraversalSrc("aws_instance.foo"),
2017-01-25 23:00:45 -06:00
true,
},
}
for i, test := range tests {
t.Run(fmt.Sprintf("%d-%s", i, test.Name), func(t *testing.T) {
body := hcltest.MockBody(&hcl.BodyContent{
Attributes: hcl.Attributes{
"foo": {
Name: "foo",
Expr: test.Expr,
},
},
})
2017-01-25 23:00:45 -06:00
2023-07-06 09:35:33 -05:00
ps := providers.ProviderSchema{
ResourceTypes: map[string]providers.Schema{
"aws_instance": {
Block: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"foo": {
Type: cty.String,
Required: true,
},
},
},
},
},
}
diags := validateSelfRef(test.Addr, body, ps)
if diags.HasErrors() != test.Err {
if test.Err {
t.Errorf("unexpected success; want error")
} else {
t.Errorf("unexpected error\n\n%s", diags.Err())
}
2017-01-25 23:00:45 -06:00
}
})
}
}