github.com/kastenhq/syft@v0.0.0-20230821225854-0710af25cdbe/test/integration/convert_test.go (about) 1 package integration 2 3 import ( 4 "context" 5 "fmt" 6 "os" 7 "testing" 8 9 "github.com/stretchr/testify/require" 10 11 "github.com/kastenhq/syft/cmd/syft/cli/convert" 12 "github.com/kastenhq/syft/internal/config" 13 "github.com/kastenhq/syft/syft/formats" 14 "github.com/kastenhq/syft/syft/formats/cyclonedxjson" 15 "github.com/kastenhq/syft/syft/formats/cyclonedxxml" 16 "github.com/kastenhq/syft/syft/formats/spdxjson" 17 "github.com/kastenhq/syft/syft/formats/spdxtagvalue" 18 "github.com/kastenhq/syft/syft/formats/syftjson" 19 "github.com/kastenhq/syft/syft/formats/table" 20 "github.com/kastenhq/syft/syft/sbom" 21 "github.com/kastenhq/syft/syft/source" 22 ) 23 24 // TestConvertCmd tests if the converted SBOM is a valid document according 25 // to spec. 26 // TODO: This test can, but currently does not, check the converted SBOM content. It 27 // might be useful to do that in the future, once we gather a better understanding of 28 // what users expect from the convert command. 29 func TestConvertCmd(t *testing.T) { 30 tests := []struct { 31 name string 32 format sbom.Format 33 }{ 34 { 35 name: "syft-json", 36 format: syftjson.Format(), 37 }, 38 { 39 name: "spdx-json", 40 format: spdxjson.Format(), 41 }, 42 { 43 name: "spdx-tag-value", 44 format: spdxtagvalue.Format(), 45 }, 46 { 47 name: "cyclonedx-json", 48 format: cyclonedxjson.Format(), 49 }, 50 { 51 name: "cyclonedx-xml", 52 format: cyclonedxxml.Format(), 53 }, 54 } 55 for _, test := range tests { 56 t.Run(test.name, func(t *testing.T) { 57 syftSbom, _ := catalogFixtureImage(t, "image-pkg-coverage", source.SquashedScope, nil) 58 syftFormat := syftjson.Format() 59 60 syftFile, err := os.CreateTemp("", "test-convert-sbom-") 61 require.NoError(t, err) 62 defer func() { 63 _ = os.Remove(syftFile.Name()) 64 }() 65 66 err = syftFormat.Encode(syftFile, syftSbom) 67 require.NoError(t, err) 68 69 formatFile, err := os.CreateTemp("", "test-convert-sbom-") 70 require.NoError(t, err) 71 defer func() { 72 _ = os.Remove(syftFile.Name()) 73 }() 74 75 ctx := context.Background() 76 app := &config.Application{ 77 Outputs: []string{fmt.Sprintf("%s=%s", test.format.ID().String(), formatFile.Name())}, 78 } 79 80 // stdout reduction of test noise 81 rescue := os.Stdout // keep backup of the real stdout 82 os.Stdout, _ = os.OpenFile(os.DevNull, os.O_APPEND|os.O_WRONLY, os.ModeAppend) 83 defer func() { 84 os.Stdout = rescue 85 }() 86 87 err = convert.Run(ctx, app, []string{syftFile.Name()}) 88 require.NoError(t, err) 89 contents, err := os.ReadFile(formatFile.Name()) 90 require.NoError(t, err) 91 92 formatFound := formats.Identify(contents) 93 if test.format.ID() == table.ID { 94 require.Nil(t, formatFound) 95 return 96 } 97 require.Equal(t, test.format.ID(), formatFound.ID()) 98 }) 99 } 100 }