github.com/anchore/syft@v1.38.2/internal/cache/filesystem_test.go (about) 1 package cache 2 3 import ( 4 "fmt" 5 "io" 6 "net/url" 7 "os" 8 "path/filepath" 9 "strings" 10 "testing" 11 "time" 12 13 "github.com/stretchr/testify/require" 14 15 "github.com/anchore/syft/internal" 16 ) 17 18 func Test_filesystemCache(t *testing.T) { 19 dir := t.TempDir() 20 man, err := NewFromDir(dir, 1*time.Minute) 21 require.NoError(t, err) 22 23 cacheName := "test" 24 cacheVersion := "v1" 25 cache := man.GetCache(cacheName, cacheVersion) 26 27 cacheKey := "test-key" 28 contentsValue := "some contents to cache" 29 30 err = cache.Write(cacheKey, strings.NewReader(contentsValue)) 31 require.NoError(t, err) 32 33 rdr, err := cache.Read(cacheKey) 34 require.NoError(t, err) 35 defer internal.CloseAndLogError(rdr, cacheKey) 36 37 contents, err := io.ReadAll(rdr) 38 require.NoError(t, err) 39 require.Equal(t, contentsValue, string(contents)) 40 41 // check the contents were actually written to disk as expected 42 contents, err = os.ReadFile(filepath.Join(dir, cacheName, cacheVersion, cacheKey)) 43 require.NoError(t, err) 44 require.Equal(t, contentsValue, string(contents)) 45 46 _, err = cache.Read("otherKey") 47 require.ErrorIs(t, err, errNotFound) 48 } 49 50 func Test_makeDiskKey(t *testing.T) { 51 tests := []struct { 52 in string 53 expected string 54 }{ 55 { 56 in: "", 57 expected: "", 58 }, 59 { 60 in: ".", 61 expected: "%2E", 62 }, 63 { 64 in: "..", 65 expected: "%2E%2E", 66 }, 67 { 68 in: "github.com", 69 expected: "github.com", 70 }, 71 { 72 in: "../github.com", 73 expected: "%2E%2E/github.com", 74 }, 75 { 76 in: "github.com/../..", 77 expected: "github.com/%2E%2E/%2E%2E", 78 }, 79 { 80 in: "github.com/%2E../..", 81 expected: "github.com/%252E%2E%2E/%2E%2E", 82 }, 83 } 84 for _, test := range tests { 85 t.Run(test.in, func(t *testing.T) { 86 got := makeDiskKey(test.in) 87 // validate appropriate escaping 88 require.Equal(t, test.expected, got) 89 // also validate that unescaped string matches original 90 unescaped, err := url.QueryUnescape(got) 91 require.NoError(t, err) 92 require.Equal(t, test.in, unescaped) 93 }) 94 } 95 } 96 97 func Test_errors(t *testing.T) { 98 tmp := t.TempDir() 99 cache := filepath.Join(tmp, "cache") 100 // make a non-writable directory 101 require.NoError(t, os.MkdirAll(cache, 0500|os.ModeDir)) 102 // attempt to make cache in non-writable directory 103 dir := filepath.Join(cache, "dir") 104 _, err := NewFromDir(dir, time.Hour) 105 require.ErrorContains(t, err, fmt.Sprintf("unable to create directory at '%s':", dir)) 106 }