github.com/hashicorp/packer@v1.14.3/provisioner/hcp-sbom/provisioner_test.go (about)

     1  package hcp_sbom
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/google/go-cmp/cmp"
     7  	"github.com/google/go-cmp/cmp/cmpopts"
     8  	"github.com/hashicorp/packer-plugin-sdk/template/interpolate"
     9  )
    10  
    11  func TestConfigPrepare(t *testing.T) {
    12  	tests := []struct {
    13  		name               string
    14  		inputConfig        map[string]interface{}
    15  		interpolateContext interpolate.Context
    16  		expectConfig       *Config
    17  		expectError        bool
    18  	}{
    19  		{
    20  			"empty config, should error without a source",
    21  			map[string]interface{}{},
    22  			interpolate.Context{},
    23  			nil,
    24  			true,
    25  		},
    26  		{
    27  			"config with full context for interpolation: success",
    28  			map[string]interface{}{
    29  				"source": "{{ .Name }}",
    30  			},
    31  			interpolate.Context{
    32  				Data: &struct {
    33  					Name string
    34  				}{
    35  					Name: "testInterpolate",
    36  				},
    37  			},
    38  			&Config{
    39  				Source: "testInterpolate",
    40  			},
    41  			false,
    42  		},
    43  		{
    44  			// Note: this will look weird to reviewers, but is actually
    45  			// expected for the moment.
    46  			// Refer to the comment in `Prepare` for context as to WHY
    47  			// this cannot be considered an error.
    48  			"config with sbom name as interpolated value, without it in context, replace with a placeholder",
    49  			map[string]interface{}{
    50  				"source":    "test",
    51  				"sbom_name": "{{ .Name }}",
    52  			},
    53  			interpolate.Context{},
    54  			&Config{
    55  				Source:   "test",
    56  				SbomName: "<no value>",
    57  			},
    58  			false,
    59  		},
    60  	}
    61  
    62  	for _, tt := range tests {
    63  		t.Run(tt.name, func(t *testing.T) {
    64  			prov := &Provisioner{}
    65  			prov.config.ctx = tt.interpolateContext
    66  			err := prov.Prepare(tt.inputConfig)
    67  			if err != nil && !tt.expectError {
    68  				t.Fatalf("configuration unexpectedly failed to prepare: %s", err)
    69  			}
    70  
    71  			if err == nil && tt.expectError {
    72  				t.Fatalf("configuration succeeded to prepare, but should have failed")
    73  			}
    74  
    75  			if err != nil {
    76  				t.Logf("config had error %q", err)
    77  				return
    78  			}
    79  
    80  			diff := cmp.Diff(prov.config, *tt.expectConfig, cmpopts.IgnoreUnexported(Config{}))
    81  			if diff != "" {
    82  				t.Errorf("configuration returned by `Prepare` is different from what was expected: %s", diff)
    83  			}
    84  		})
    85  	}
    86  }