github.com/devseccon/trivy@v0.47.1-0.20231123133102-bd902a0bd996/pkg/fanal/walker/fs_test.go (about) 1 package walker_test 2 3 import ( 4 "errors" 5 "io" 6 "os" 7 "strings" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 "github.com/stretchr/testify/require" 12 13 "github.com/devseccon/trivy/pkg/fanal/analyzer" 14 "github.com/devseccon/trivy/pkg/fanal/walker" 15 ) 16 17 func TestDir_Walk(t *testing.T) { 18 type fields struct { 19 skipFiles []string 20 skipDirs []string 21 errCallback walker.ErrorCallback 22 } 23 tests := []struct { 24 name string 25 fields fields 26 rootDir string 27 analyzeFn walker.WalkFunc 28 wantErr string 29 }{ 30 { 31 name: "happy path", 32 rootDir: "testdata/fs", 33 analyzeFn: func(filePath string, info os.FileInfo, opener analyzer.Opener) error { 34 if filePath == "testdata/fs/bar" { 35 got, err := opener() 36 require.NoError(t, err) 37 38 b, err := io.ReadAll(got) 39 require.NoError(t, err) 40 41 assert.Equal(t, "bar", string(b)) 42 } 43 return nil 44 }, 45 }, 46 { 47 name: "skip file", 48 rootDir: "testdata/fs", 49 fields: fields{ 50 skipFiles: []string{"testdata/fs/bar"}, 51 }, 52 analyzeFn: func(filePath string, info os.FileInfo, opener analyzer.Opener) error { 53 if filePath == "testdata/fs/bar" { 54 assert.Fail(t, "skip files error", "%s should be skipped", filePath) 55 } 56 return nil 57 }, 58 }, 59 { 60 name: "skip dir", 61 rootDir: "testdata/fs/", 62 fields: fields{ 63 skipDirs: []string{"/testdata/fs/app"}, 64 }, 65 analyzeFn: func(filePath string, info os.FileInfo, opener analyzer.Opener) error { 66 if strings.HasPrefix(filePath, "testdata/fs/app") { 67 assert.Fail(t, "skip dirs error", "%s should be skipped", filePath) 68 } 69 return nil 70 }, 71 }, 72 { 73 name: "ignore all errors", 74 rootDir: "testdata/fs/nosuch", 75 fields: fields{ 76 errCallback: func(pathname string, err error) error { 77 return nil 78 }, 79 }, 80 analyzeFn: func(filePath string, info os.FileInfo, opener analyzer.Opener) error { 81 // Ignore errors 82 return nil 83 }, 84 }, 85 { 86 name: "sad path", 87 rootDir: "testdata/fs", 88 analyzeFn: func(filePath string, info os.FileInfo, opener analyzer.Opener) error { 89 return errors.New("error") 90 }, 91 wantErr: "failed to analyze file", 92 }, 93 } 94 for _, tt := range tests { 95 t.Run(tt.name, func(t *testing.T) { 96 w := walker.NewFS(tt.fields.skipFiles, tt.fields.skipDirs, 1, tt.fields.errCallback) 97 98 err := w.Walk(tt.rootDir, tt.analyzeFn) 99 if tt.wantErr != "" { 100 require.Error(t, err) 101 assert.Contains(t, err.Error(), tt.wantErr) 102 return 103 } 104 assert.NoError(t, err) 105 }) 106 } 107 }