github.com/nextlinux/gosbom@v0.81.1-0.20230627115839-1ff50c281391/schema/json/main_test.go (about) 1 package main 2 3 import ( 4 "reflect" 5 "sort" 6 "testing" 7 8 "github.com/google/go-cmp/cmp" 9 "github.com/nextlinux/gosbom/schema/json/internal" 10 "github.com/stretchr/testify/assert" 11 "github.com/stretchr/testify/require" 12 ) 13 14 func TestAllMetadataRepresented(t *testing.T) { 15 // this test checks that all the metadata types are represented in the currently generated ArtifactMetadataContainer struct 16 // such that PRs will reflect when there is drift from the implemented set of metadata types and the generated struct 17 // which controls the JSON schema content. 18 expected, err := internal.AllGosbomMetadataTypeNames() 19 require.NoError(t, err) 20 actual := allTypeNamesFromStruct(internal.ArtifactMetadataContainer{}) 21 if !assert.ElementsMatch(t, expected, actual) { 22 t.Errorf("metadata types not fully represented: \n%s", cmp.Diff(expected, actual)) 23 t.Log("did you add a new pkg.*Metadata type without updating the JSON schema?") 24 t.Log("if so, you need to update the schema version and regenerate the JSON schema (make generate-json-schema)") 25 } 26 } 27 28 func allTypeNamesFromStruct(instance any) []string { 29 // get all the type names from the struct (not recursively) 30 var typeNames []string 31 tt := reflect.TypeOf(instance) 32 for i := 0; i < tt.NumField(); i++ { 33 field := tt.Field(i) 34 typeNames = append(typeNames, field.Type.Name()) 35 } 36 sort.Strings(typeNames) 37 return typeNames 38 }