github.com/noqcks/syft@v0.0.0-20230920222752-a9e2c4e288e5/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  			args = append(args, test.args...)
    54  
    55  			_, stdout, _ := runSyft(t, nil, args...)
    56  
    57  			if len(strings.Trim(stdout, "\n ")) < 100 {
    58  				t.Fatalf("bad syft output: %q", stdout)
    59  			}
    60  
    61  			validateSpdxJsonAgainstSchema(t, stdout)
    62  		})
    63  	}
    64  }
    65  
    66  func validateSpdxJsonAgainstSchema(t testing.TB, json string) {
    67  	fullSchemaPath := path.Join(repoRoot(t), spdxJsonSchemaPath, fmt.Sprintf("spdx-schema-2.3.json"))
    68  	schemaLoader := gojsonschema.NewReferenceLoader(fmt.Sprintf("file://%s", fullSchemaPath))
    69  	documentLoader := gojsonschema.NewStringLoader(json)
    70  
    71  	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
    72  	if err != nil {
    73  		t.Fatal("unable to validate json schema:", err.Error())
    74  	}
    75  
    76  	if !result.Valid() {
    77  		t.Errorf("failed json schema validation:")
    78  		t.Errorf("JSON:\n%s\n", json)
    79  		for _, desc := range result.Errors() {
    80  			t.Errorf("  - %s\n", desc)
    81  		}
    82  	}
    83  }