github.com/kastenhq/syft@v0.0.0-20230821225854-0710af25cdbe/syft/formats/syftjson/decoder_test.go (about) 1 package syftjson 2 3 import ( 4 "bytes" 5 "errors" 6 "fmt" 7 "strings" 8 "testing" 9 10 "github.com/go-test/deep" 11 "github.com/stretchr/testify/assert" 12 13 "github.com/kastenhq/syft/syft/formats/internal/testutils" 14 ) 15 16 func TestEncodeDecodeCycle(t *testing.T) { 17 testImage := "image-simple" 18 originalSBOM := testutils.ImageInput(t, testImage) 19 20 var buf bytes.Buffer 21 assert.NoError(t, encoder(&buf, originalSBOM)) 22 23 actualSBOM, err := decoder(bytes.NewReader(buf.Bytes())) 24 assert.NoError(t, err) 25 26 for _, d := range deep.Equal(originalSBOM.Source, actualSBOM.Source) { 27 if strings.HasSuffix(d, "<nil slice> != []") { 28 // semantically the same 29 continue 30 } 31 t.Errorf("metadata difference: %+v", d) 32 } 33 34 actualPackages := actualSBOM.Artifacts.Packages.Sorted() 35 for idx, p := range originalSBOM.Artifacts.Packages.Sorted() { 36 if !assert.Equal(t, p.Name, actualPackages[idx].Name) { 37 t.Errorf("different package at idx=%d: %s vs %s", idx, p.Name, actualPackages[idx].Name) 38 continue 39 } 40 41 for _, d := range deep.Equal(p, actualPackages[idx]) { 42 if strings.Contains(d, ".VirtualPath: ") { 43 // location.Virtual path is not exposed in the json output 44 continue 45 } 46 if strings.HasSuffix(d, "<nil slice> != []") { 47 // semantically the same 48 continue 49 } 50 t.Errorf("package difference (%s): %+v", p.Name, d) 51 } 52 } 53 } 54 55 func TestOutOfDateParser(t *testing.T) { 56 tests := []struct { 57 name string 58 documentVersion string 59 parserVersion string 60 want error 61 }{{ 62 name: "no warning when doc version is older", 63 documentVersion: "1.0.9", 64 parserVersion: "3.1.0", 65 }, { 66 name: "warning when parser is older", 67 documentVersion: "4.3.2", 68 parserVersion: "3.1.0", 69 want: fmt.Errorf("document has schema version %s, but parser has older schema version (%s)", "4.3.2", "3.1.0"), 70 }, { 71 name: "warning when document version is unparseable", 72 documentVersion: "some-nonsense", 73 parserVersion: "3.1.0", 74 want: fmt.Errorf("error comparing document schema version with parser schema version: %w", errors.New("Invalid Semantic Version")), 75 }, { 76 name: "warning when parser version is unparseable", 77 documentVersion: "7.1.0", 78 parserVersion: "some-nonsense", 79 want: fmt.Errorf("error comparing document schema version with parser schema version: %w", errors.New("Invalid Semantic Version")), 80 }} 81 82 for _, tt := range tests { 83 t.Run(tt.name, func(t *testing.T) { 84 got := checkSupportedSchema(tt.documentVersion, tt.parserVersion) 85 assert.Equal(t, tt.want, got) 86 }) 87 } 88 }