github.com/lineaje-labs/syft@v0.98.1-0.20231227153149-9e393f60ff1b/cmd/syft/cli/options/format_cyclonedx_json_test.go (about)

     1  package options
     2  
     3  import (
     4  	"reflect"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestFormatCyclonedxJSON_buildConfig(t *testing.T) {
    11  	// assert when building the config that we respond to all possible fields
    12  
    13  	ft := &FormatCyclonedxJSON{}
    14  	ft = setAllToNonZero(t, ft).(*FormatCyclonedxJSON)
    15  
    16  	subject := ft.buildConfig("Version")
    17  	assertExpectedValue(t, subject)
    18  }
    19  
    20  func setAllToNonZero(t testing.TB, structPtr any) any {
    21  	// set all fields on the struct to non-zero values
    22  	rt := reflect.TypeOf(structPtr)
    23  	if rt.Kind() != reflect.Ptr || rt.Elem().Kind() != reflect.Struct {
    24  		t.Fatal("expected a pointer to a struct")
    25  	}
    26  
    27  	rv := reflect.ValueOf(structPtr).Elem()
    28  	for i := 0; i < rt.Elem().NumField(); i++ {
    29  		val := getNonZeroExampleValue(t, rv.Field(i).Interface(), rt.Elem().Field(i).Name)
    30  		rv.Field(i).Set(reflect.ValueOf(val))
    31  	}
    32  	return structPtr
    33  }
    34  
    35  func getNonZeroExampleValue(t testing.TB, v any, name string) any {
    36  	switch v.(type) {
    37  	case bool:
    38  		return true
    39  	case *bool:
    40  		val := true
    41  		return &val
    42  	case string:
    43  		return name
    44  	}
    45  	t.Fatalf("unsupported type: %T", v)
    46  	return nil
    47  }
    48  
    49  func assertExpectedValue(t *testing.T, structTy any) {
    50  	rt := reflect.TypeOf(structTy)
    51  	rv := reflect.ValueOf(structTy)
    52  
    53  	for i := 0; i < rt.NumField(); i++ {
    54  		f := rt.Field(i)
    55  		fieldValue := rv.Field(i)
    56  
    57  		if fieldValue.Type().Kind() == reflect.String {
    58  			// use the field name as the expected value
    59  			assert.Equalf(t, f.Name, fieldValue.String(), "field %q value differs", f.Name)
    60  		} else {
    61  			// use the zero value for the type
    62  			if reflect.DeepEqual(fieldValue.Interface(), reflect.Zero(fieldValue.Type()).Interface()) {
    63  				t.Errorf("field '%s' is zero", f.Name)
    64  			}
    65  		}
    66  	}
    67  }