github.com/anchore/syft@v1.4.2-0.20240516191711-1bec1fc5d397/test/cli/convert_cmd_test.go (about) 1 package cli 2 3 import ( 4 "fmt" 5 "strings" 6 "testing" 7 8 "github.com/stretchr/testify/require" 9 10 "github.com/anchore/syft/syft/format" 11 "github.com/anchore/syft/syft/format/cyclonedxjson" 12 "github.com/anchore/syft/syft/format/cyclonedxxml" 13 "github.com/anchore/syft/syft/format/spdxjson" 14 "github.com/anchore/syft/syft/format/spdxtagvalue" 15 "github.com/anchore/syft/syft/sbom" 16 ) 17 18 func TestConvertCmd(t *testing.T) { 19 assertions := []traitAssertion{ 20 assertInOutput("musl-utils"), 21 assertSuccessfulReturnCode, 22 } 23 24 tests := []struct { 25 from string 26 to string 27 expect sbom.FormatEncoder 28 }{ 29 {from: "syft-json", to: "spdx-tag-value", expect: mustEncoder(spdxtagvalue.NewFormatEncoderWithConfig(spdxtagvalue.DefaultEncoderConfig()))}, 30 {from: "syft-json", to: "spdx-json", expect: mustEncoder(spdxjson.NewFormatEncoderWithConfig(spdxjson.DefaultEncoderConfig()))}, 31 {from: "syft-json", to: "cyclonedx-json", expect: mustEncoder(cyclonedxjson.NewFormatEncoderWithConfig(cyclonedxjson.DefaultEncoderConfig()))}, 32 {from: "syft-json", to: "cyclonedx-xml", expect: mustEncoder(cyclonedxxml.NewFormatEncoderWithConfig(cyclonedxxml.DefaultEncoderConfig()))}, 33 } 34 35 for _, test := range tests { 36 t.Run(fmt.Sprintf("from %s to %s", test.from, test.to), func(t *testing.T) { 37 sbomArgs := []string{"dir:./test-fixtures/image-pkg-coverage", "-o", test.from} 38 cmd, stdout, stderr := runSyft(t, nil, sbomArgs...) 39 if cmd.ProcessState.ExitCode() != 0 { 40 t.Log("STDOUT:\n", stdout) 41 t.Log("STDERR:\n", stderr) 42 t.Log("COMMAND:", strings.Join(cmd.Args, " ")) 43 t.Fatalf("failure executing syft creating an sbom") 44 return 45 } 46 47 convertArgs := []string{"convert", "-", "-o", test.to} 48 cmd = getSyftCommand(t, convertArgs...) 49 50 cmd.Stdin = strings.NewReader(stdout) 51 stdout, stderr = runCommandObj(t, cmd, nil, false) 52 53 for _, traitFn := range assertions { 54 traitFn(t, stdout, stderr, cmd.ProcessState.ExitCode()) 55 } 56 logOutputOnFailure(t, cmd, stdout, stderr) 57 58 // let's make sure the output is valid relative to the expected format 59 foundID, _ := format.Identify(strings.NewReader(stdout)) 60 require.Equal(t, test.expect.ID(), foundID) 61 62 }) 63 } 64 } 65 66 func mustEncoder(enc sbom.FormatEncoder, err error) sbom.FormatEncoder { 67 if err != nil { 68 panic(err) 69 } 70 return enc 71 }