github.com/anchore/syft@v1.38.2/syft/source/snapsource/snap_source_test.go (about) 1 package snapsource 2 3 import ( 4 "crypto" 5 "fmt" 6 "testing" 7 8 "github.com/spf13/afero" 9 "github.com/stretchr/testify/assert" 10 "github.com/stretchr/testify/require" 11 12 "github.com/anchore/go-homedir" 13 "github.com/anchore/stereoscope/pkg/image" 14 ) 15 16 func TestNewFromLocal(t *testing.T) { 17 tests := []struct { 18 name string 19 cfg Config 20 setup func(fs afero.Fs) 21 wantRequest string 22 wantErr assert.ErrorAssertionFunc 23 }{ 24 { 25 name: "local file exists", 26 cfg: Config{ 27 Request: "/test/local.snap", 28 DigestAlgorithms: []crypto.Hash{crypto.SHA256}, 29 }, 30 setup: func(fs afero.Fs) { 31 require.NoError(t, createMockSquashfsFile(fs, "/test/local.snap")) 32 }, 33 wantRequest: "/test/local.snap", 34 }, 35 { 36 name: "resolve home dir exists", 37 cfg: Config{ 38 Request: "~/test/local.snap", 39 DigestAlgorithms: []crypto.Hash{crypto.SHA256}, 40 }, 41 wantErr: assert.Error, 42 wantRequest: func() string { 43 homeDir, err := homedir.Expand("~/test/local.snap") 44 require.NoError(t, err, "failed to expand home directory") 45 require.NotContains(t, homeDir, "~") 46 return homeDir 47 }(), 48 }, 49 { 50 name: "local file with architecture specified", 51 cfg: Config{ 52 Request: "/test/local.snap", 53 Platform: &image.Platform{ 54 Architecture: "arm64", 55 }, 56 }, 57 setup: func(fs afero.Fs) { 58 require.NoError(t, createMockSquashfsFile(fs, "/test/local.snap")) 59 }, 60 wantErr: func(t assert.TestingT, err error, msgAndArgs ...interface{}) bool { 61 return assert.Error(t, err, msgAndArgs...) && assert.Contains(t, err.Error(), "architecture cannot be specified for local snap files", msgAndArgs...) 62 }, 63 wantRequest: "/test/local.snap", 64 }, 65 } 66 for _, tt := range tests { 67 t.Run(tt.name, func(t *testing.T) { 68 if tt.wantErr == nil { 69 tt.wantErr = assert.NoError 70 } 71 tt.cfg.fs = afero.NewMemMapFs() // Use an in-memory filesystem for testing 72 if tt.setup != nil { 73 tt.setup(tt.cfg.fs) 74 } 75 got, err := getLocalSnapFile(&tt.cfg) 76 tt.wantErr(t, err, fmt.Sprintf("NewFromLocal(%v)", tt.cfg)) 77 assert.Equal(t, tt.wantRequest, tt.cfg.Request, "expected request path to match") 78 if err != nil { 79 require.Nil(t, got, "expected nil source on error") 80 return 81 } 82 require.NotNil(t, got, "expected non-nil source on success") 83 84 }) 85 } 86 }