github.com/lineaje-labs/syft@v0.98.1-0.20231227153149-9e393f60ff1b/syft/pkg/cataloger/generic/cataloger_test.go (about) 1 package generic 2 3 import ( 4 "fmt" 5 "io" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 "github.com/stretchr/testify/require" 10 11 "github.com/anchore/syft/syft/artifact" 12 "github.com/anchore/syft/syft/file" 13 "github.com/anchore/syft/syft/pkg" 14 ) 15 16 func Test_Cataloger(t *testing.T) { 17 allParsedPaths := make(map[string]bool) 18 parser := func(resolver file.Resolver, env *Environment, reader file.LocationReadCloser) ([]pkg.Package, []artifact.Relationship, error) { 19 allParsedPaths[reader.Path()] = true 20 contents, err := io.ReadAll(reader) 21 require.NoError(t, err) 22 23 if len(contents) == 0 { 24 return nil, nil, nil 25 } 26 27 p := pkg.Package{ 28 Name: string(contents), 29 Locations: file.NewLocationSet(reader.Location), 30 } 31 r := artifact.Relationship{ 32 From: p, 33 To: p, 34 Type: artifact.ContainsRelationship, 35 } 36 37 return []pkg.Package{p}, []artifact.Relationship{r}, nil 38 } 39 40 upstream := "some-other-cataloger" 41 42 expectedSelection := []string{"test-fixtures/last/path.txt", "test-fixtures/another-path.txt", "test-fixtures/a-path.txt", "test-fixtures/empty.txt"} 43 resolver := file.NewMockResolverForPaths(expectedSelection...) 44 cataloger := NewCataloger(upstream). 45 WithParserByPath(parser, "test-fixtures/another-path.txt", "test-fixtures/last/path.txt"). 46 WithParserByGlobs(parser, "**/a-path.txt", "**/empty.txt") 47 48 actualPkgs, relationships, err := cataloger.Catalog(resolver) 49 assert.NoError(t, err) 50 51 expectedPkgs := make(map[string]pkg.Package) 52 for _, path := range expectedSelection { 53 require.True(t, allParsedPaths[path]) 54 if path == "test-fixtures/empty.txt" { 55 continue // note: empty.txt won't become a package 56 } 57 expectedPkgs[path] = pkg.Package{ 58 FoundBy: upstream, 59 Name: fmt.Sprintf("%s file contents!", path), 60 } 61 } 62 63 assert.Len(t, allParsedPaths, len(expectedSelection)) 64 assert.Len(t, actualPkgs, len(expectedPkgs)) 65 assert.Len(t, relationships, len(actualPkgs)) 66 67 for _, p := range actualPkgs { 68 ls := p.Locations.ToSlice() 69 require.NotEmpty(t, ls) 70 ref := ls[0] 71 exP, ok := expectedPkgs[ref.RealPath] 72 if !ok { 73 t.Errorf("missing expected pkg: ref=%+v", ref) 74 continue 75 } 76 77 // assigned by the generic cataloger 78 if p.FoundBy != exP.FoundBy { 79 t.Errorf("bad upstream: %s", p.FoundBy) 80 } 81 82 // assigned by the parser 83 if exP.Name != p.Name { 84 t.Errorf("bad contents mapping: %+v", p.Locations) 85 } 86 } 87 }