10 "github.com/docker/docker/client/session/filesync"
11 "github.com/stretchr/testify/assert"
12 "golang.org/x/net/context"
15 func TestFSCache(t *testing.T) {
16 tmpDir, err := ioutil.TempDir("", "fscache")
18 defer os.RemoveAll(tmpDir)
20 backend := NewNaiveCacheBackend(filepath.Join(tmpDir, "backend"))
25 GCPolicy: GCPolicy{MaxSize: 15, MaxKeepDuration: time.Hour},
28 fscache, err := NewFSCache(opt)
33 err = fscache.RegisterTransport("test", &testTransport{})
36 src1, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo", "data", "bar"})
39 dt, err := ioutil.ReadFile(filepath.Join(src1.Root(), "foo"))
41 assert.Equal(t, string(dt), "data")
43 // same id doesn't recalculate anything
44 src2, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo", "data2", "bar"})
46 assert.Equal(t, src1.Root(), src2.Root())
48 dt, err = ioutil.ReadFile(filepath.Join(src1.Root(), "foo"))
50 assert.Equal(t, string(dt), "data")
51 assert.Nil(t, src2.Close())
53 src3, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo2", "data2", "bar"})
55 assert.NotEqual(t, src1.Root(), src3.Root())
57 dt, err = ioutil.ReadFile(filepath.Join(src3.Root(), "foo2"))
59 assert.Equal(t, string(dt), "data2")
61 s, err := fscache.DiskUsage()
63 assert.Equal(t, s, int64(0))
65 assert.Nil(t, src3.Close())
67 s, err = fscache.DiskUsage()
69 assert.Equal(t, s, int64(5))
71 // new upload with the same shared key shoutl overwrite
72 src4, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo3", "data3", "bar"})
74 assert.NotEqual(t, src1.Root(), src3.Root())
76 dt, err = ioutil.ReadFile(filepath.Join(src3.Root(), "foo3"))
78 assert.Equal(t, string(dt), "data3")
79 assert.Equal(t, src4.Root(), src3.Root())
80 assert.Nil(t, src4.Close())
82 s, err = fscache.DiskUsage()
84 assert.Equal(t, s, int64(10))
86 // this one goes over the GC limit
87 src5, err := fscache.SyncFrom(context.TODO(), &testIdentifier{"foo4", "datadata", "baz"})
89 assert.Nil(t, src5.Close())
92 time.Sleep(100 * time.Millisecond)
94 // only last insertion after GC
95 s, err = fscache.DiskUsage()
97 assert.Equal(t, s, int64(8))
99 // prune deletes everything
100 released, err := fscache.Prune()
102 assert.Equal(t, released, uint64(8))
104 s, err = fscache.DiskUsage()
106 assert.Equal(t, s, int64(0))
109 type testTransport struct {
112 func (t *testTransport) Copy(ctx context.Context, id RemoteIdentifier, dest string, cs filesync.CacheUpdater) error {
113 testid := id.(*testIdentifier)
114 return ioutil.WriteFile(filepath.Join(dest, testid.filename), []byte(testid.data), 0600)
117 type testIdentifier struct {
123 func (t *testIdentifier) Key() string {
126 func (t *testIdentifier) SharedKey() string {
129 func (t *testIdentifier) Transport() string {