github.com/devseccon/trivy@v0.47.1-0.20231123133102-bd902a0bd996/pkg/fanal/walker/tar_test.go (about) 1 package walker_test 2 3 import ( 4 "errors" 5 "os" 6 "path/filepath" 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 TestLayerTar_Walk(t *testing.T) { 18 type fields struct { 19 skipFiles []string 20 skipDirs []string 21 } 22 tests := []struct { 23 name string 24 fields fields 25 inputFile string 26 analyzeFn walker.WalkFunc 27 wantOpqDirs []string 28 wantWhFiles []string 29 wantErr string 30 }{ 31 { 32 name: "happy path", 33 inputFile: filepath.Join("testdata", "test.tar"), 34 analyzeFn: func(filePath string, info os.FileInfo, opener analyzer.Opener) error { 35 return nil 36 }, 37 wantOpqDirs: []string{"etc/"}, 38 wantWhFiles: []string{"foo/foo"}, 39 }, 40 { 41 name: "skip file", 42 inputFile: filepath.Join("testdata", "test.tar"), 43 fields: fields{ 44 skipFiles: []string{"/app/myweb/index.html"}, 45 }, 46 analyzeFn: func(filePath string, info os.FileInfo, opener analyzer.Opener) error { 47 if filePath == "app/myweb/index.html" { 48 assert.Fail(t, "skip files error", "%s should be skipped", filePath) 49 } 50 return nil 51 }, 52 wantOpqDirs: []string{"etc/"}, 53 wantWhFiles: []string{"foo/foo"}, 54 }, 55 { 56 name: "skip dir", 57 inputFile: filepath.Join("testdata", "test.tar"), 58 fields: fields{ 59 skipDirs: []string{"/app"}, 60 }, 61 analyzeFn: func(filePath string, info os.FileInfo, opener analyzer.Opener) error { 62 if strings.HasPrefix(filePath, "app") { 63 assert.Fail(t, "skip dirs error", "%s should be skipped", filePath) 64 } 65 return nil 66 }, 67 wantOpqDirs: []string{"etc/"}, 68 wantWhFiles: []string{"foo/foo"}, 69 }, 70 { 71 name: "sad path", 72 inputFile: "testdata/test.tar", 73 analyzeFn: func(filePath string, info os.FileInfo, opener analyzer.Opener) error { 74 return errors.New("error") 75 }, 76 wantErr: "failed to analyze file", 77 }, 78 } 79 for _, tt := range tests { 80 t.Run(tt.name, func(t *testing.T) { 81 f, err := os.Open("testdata/test.tar") 82 require.NoError(t, err) 83 84 w := walker.NewLayerTar(tt.fields.skipFiles, tt.fields.skipDirs) 85 86 gotOpqDirs, gotWhFiles, err := w.Walk(f, tt.analyzeFn) 87 if tt.wantErr != "" { 88 require.Error(t, err) 89 assert.Contains(t, err.Error(), tt.wantErr) 90 return 91 } 92 assert.NoError(t, err) 93 assert.Equal(t, tt.wantOpqDirs, gotOpqDirs) 94 assert.Equal(t, tt.wantWhFiles, gotWhFiles) 95 }) 96 } 97 }