github.com/opentofu/opentofu@v1.7.1/internal/configs/hcl2shim/synth_body_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 hcl2shim
     7  
     8  import (
     9  	"testing"
    10  
    11  	"github.com/hashicorp/hcl/v2"
    12  	"github.com/zclconf/go-cty/cty"
    13  )
    14  
    15  func TestSynthBodyContent(t *testing.T) {
    16  	tests := map[string]struct {
    17  		Values    map[string]cty.Value
    18  		Schema    *hcl.BodySchema
    19  		DiagCount int
    20  	}{
    21  		"empty": {
    22  			Values:    map[string]cty.Value{},
    23  			Schema:    &hcl.BodySchema{},
    24  			DiagCount: 0,
    25  		},
    26  		"missing required attribute": {
    27  			Values: map[string]cty.Value{},
    28  			Schema: &hcl.BodySchema{
    29  				Attributes: []hcl.AttributeSchema{
    30  					{
    31  						Name:     "nonexist",
    32  						Required: true,
    33  					},
    34  				},
    35  			},
    36  			DiagCount: 1, // missing required attribute
    37  		},
    38  		"missing optional attribute": {
    39  			Values: map[string]cty.Value{},
    40  			Schema: &hcl.BodySchema{
    41  				Attributes: []hcl.AttributeSchema{
    42  					{
    43  						Name: "nonexist",
    44  					},
    45  				},
    46  			},
    47  			DiagCount: 0,
    48  		},
    49  		"extraneous attribute": {
    50  			Values: map[string]cty.Value{
    51  				"foo": cty.StringVal("unwanted"),
    52  			},
    53  			Schema:    &hcl.BodySchema{},
    54  			DiagCount: 1, // unsupported attribute
    55  		},
    56  	}
    57  
    58  	for name, test := range tests {
    59  		t.Run(name, func(t *testing.T) {
    60  			body := SynthBody("synth", test.Values)
    61  			_, diags := body.Content(test.Schema)
    62  			if got, want := len(diags), test.DiagCount; got != want {
    63  				t.Errorf("wrong number of diagnostics %d; want %d", got, want)
    64  				for _, diag := range diags {
    65  					t.Logf("- %s", diag)
    66  				}
    67  			}
    68  		})
    69  	}
    70  }