github.com/metasources/buildx@v0.0.0-20230418141019-7aa1459cedea/test/cli/spdx_json_schema_test.go (about) 1 package cli 2 3 import ( 4 "fmt" 5 "path" 6 "strings" 7 "testing" 8 9 "github.com/xeipuuv/gojsonschema" 10 11 "github.com/anchore/stereoscope/pkg/imagetest" 12 ) 13 14 // this is the path to the json schema directory relative to the root of the repo 15 const spdxJsonSchemaPath = "schema/spdx-json" 16 17 func TestSPDXJSONSchema(t *testing.T) { 18 imageFixture := func(t *testing.T) string { 19 fixtureImageName := "image-pkg-coverage" 20 imagetest.GetFixtureImage(t, "docker-archive", fixtureImageName) 21 tarPath := imagetest.GetFixtureImageTarPath(t, fixtureImageName) 22 return "docker-archive:" + tarPath 23 } 24 25 tests := []struct { 26 name string 27 subcommand string 28 args []string 29 fixture func(*testing.T) string 30 }{ 31 { 32 name: "packages:image:docker-archive:pkg-coverage", 33 subcommand: "packages", 34 args: []string{"-o", "spdx-json"}, 35 fixture: imageFixture, 36 }, 37 { 38 name: "packages:dir:pkg-coverage", 39 subcommand: "packages", 40 args: []string{"-o", "spdx-json"}, 41 fixture: func(t *testing.T) string { 42 return "dir:test-fixtures/image-pkg-coverage" 43 }, 44 }, 45 } 46 47 for _, test := range tests { 48 t.Run(test.name, func(t *testing.T) { 49 fixtureRef := test.fixture(t) 50 args := []string{ 51 test.subcommand, fixtureRef, "-q", 52 } 53 for _, a := range test.args { 54 args = append(args, a) 55 } 56 57 _, stdout, _ := runBuildx(t, nil, args...) 58 59 if len(strings.Trim(stdout, "\n ")) < 100 { 60 t.Fatalf("bad buildx output: %q", stdout) 61 } 62 63 validateSpdxJsonAgainstSchema(t, stdout) 64 }) 65 } 66 } 67 68 func validateSpdxJsonAgainstSchema(t testing.TB, json string) { 69 fullSchemaPath := path.Join(repoRoot(t), spdxJsonSchemaPath, fmt.Sprintf("spdx-schema-2.3.json")) 70 schemaLoader := gojsonschema.NewReferenceLoader(fmt.Sprintf("file://%s", fullSchemaPath)) 71 documentLoader := gojsonschema.NewStringLoader(json) 72 73 result, err := gojsonschema.Validate(schemaLoader, documentLoader) 74 if err != nil { 75 t.Fatal("unable to validate json schema:", err.Error()) 76 } 77 78 if !result.Valid() { 79 t.Errorf("failed json schema validation:") 80 t.Errorf("JSON:\n%s\n", json) 81 for _, desc := range result.Errors() { 82 t.Errorf(" - %s\n", desc) 83 } 84 } 85 }