github.com/hugorut/terraform@v1.1.3/src/terraform/validate_selfref_test.go (about)

     1  package terraform
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  
     7  	"github.com/hugorut/terraform/src/configs/configschema"
     8  
     9  	"github.com/hashicorp/hcl/v2"
    10  	"github.com/hashicorp/hcl/v2/hcltest"
    11  	"github.com/hugorut/terraform/src/addrs"
    12  	"github.com/zclconf/go-cty/cty"
    13  )
    14  
    15  func TestValidateSelfRef(t *testing.T) {
    16  	rAddr := addrs.Resource{
    17  		Mode: addrs.ManagedResourceMode,
    18  		Type: "aws_instance",
    19  		Name: "foo",
    20  	}
    21  
    22  	tests := []struct {
    23  		Name string
    24  		Addr addrs.Referenceable
    25  		Expr hcl.Expression
    26  		Err  bool
    27  	}{
    28  		{
    29  			"no references at all",
    30  			rAddr,
    31  			hcltest.MockExprLiteral(cty.StringVal("bar")),
    32  			false,
    33  		},
    34  
    35  		{
    36  			"non self reference",
    37  			rAddr,
    38  			hcltest.MockExprTraversalSrc("aws_instance.bar.id"),
    39  			false,
    40  		},
    41  
    42  		{
    43  			"self reference",
    44  			rAddr,
    45  			hcltest.MockExprTraversalSrc("aws_instance.foo.id"),
    46  			true,
    47  		},
    48  
    49  		{
    50  			"self reference other index",
    51  			rAddr,
    52  			hcltest.MockExprTraversalSrc("aws_instance.foo[4].id"),
    53  			false,
    54  		},
    55  
    56  		{
    57  			"self reference same index",
    58  			rAddr.Instance(addrs.IntKey(4)),
    59  			hcltest.MockExprTraversalSrc("aws_instance.foo[4].id"),
    60  			true,
    61  		},
    62  
    63  		{
    64  			"self reference whole",
    65  			rAddr.Instance(addrs.IntKey(4)),
    66  			hcltest.MockExprTraversalSrc("aws_instance.foo"),
    67  			true,
    68  		},
    69  	}
    70  
    71  	for i, test := range tests {
    72  		t.Run(fmt.Sprintf("%d-%s", i, test.Name), func(t *testing.T) {
    73  			body := hcltest.MockBody(&hcl.BodyContent{
    74  				Attributes: hcl.Attributes{
    75  					"foo": {
    76  						Name: "foo",
    77  						Expr: test.Expr,
    78  					},
    79  				},
    80  			})
    81  
    82  			ps := &ProviderSchema{
    83  				ResourceTypes: map[string]*configschema.Block{
    84  					"aws_instance": &configschema.Block{
    85  						Attributes: map[string]*configschema.Attribute{
    86  							"foo": {
    87  								Type:     cty.String,
    88  								Required: true,
    89  							},
    90  						},
    91  					},
    92  				},
    93  			}
    94  
    95  			diags := validateSelfRef(test.Addr, body, ps)
    96  			if diags.HasErrors() != test.Err {
    97  				if test.Err {
    98  					t.Errorf("unexpected success; want error")
    99  				} else {
   100  					t.Errorf("unexpected error\n\n%s", diags.Err())
   101  				}
   102  			}
   103  		})
   104  	}
   105  }