forked from attic-labs/noms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fd_cache_test.go
113 lines (92 loc) · 2.48 KB
/
fd_cache_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Copyright 2017 Attic Labs, Inc. All rights reserved.
// Licensed under the Apache License, version 2.0:
// http://www.apache.org/licenses/LICENSE-2.0
package nbs
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"sync"
"testing"
"github.com/stretchr/testify/assert"
)
func TestFDCache(t *testing.T) {
dir := makeTempDir(t)
defer os.RemoveAll(dir)
paths := [3]string{}
for i := range paths {
name := fmt.Sprintf("file%d", i)
paths[i] = filepath.Join(dir, name)
err := ioutil.WriteFile(paths[i], []byte(name), 0644)
assert.NoError(t, err)
}
refNoError := func(fc *fdCache, p string, assert *assert.Assertions) *os.File {
f, err := fc.RefFile(p)
assert.NoError(err)
assert.NotNil(f)
return f
}
t.Run("ConcurrentOpen", func(t *testing.T) {
assert := assert.New(t)
concurrency := 3
fc := newFDCache(3)
defer fc.Drop()
trigger := make(chan struct{})
wg := sync.WaitGroup{}
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-trigger
fc.RefFile(paths[0])
}()
}
close(trigger)
wg.Wait()
present := fc.reportEntries()
if assert.Len(present, 1) {
ce := fc.cache[present[0]]
assert.EqualValues(concurrency, ce.refCount)
}
})
t.Run("NoEvictions", func(t *testing.T) {
assert := assert.New(t)
fc := newFDCache(2)
defer fc.Drop()
f := refNoError(fc, paths[0], assert)
f2 := refNoError(fc, paths[1], assert)
assert.NotEqual(f, f2)
dup := refNoError(fc, paths[0], assert)
assert.Equal(f, dup)
})
t.Run("Evictions", func(t *testing.T) {
assert := assert.New(t)
fc := newFDCache(1)
defer fc.Drop()
f0 := refNoError(fc, paths[0], assert)
f1 := refNoError(fc, paths[1], assert)
assert.NotEqual(f0, f1)
// f0 wasn't evicted, because that doesn't happen until UnrefFile()
dup := refNoError(fc, paths[0], assert)
assert.Equal(f0, dup)
expected := sort.StringSlice(paths[:2])
sort.Sort(expected)
assert.EqualValues(expected, fc.reportEntries())
// Unreffing f1 now should evict it
fc.UnrefFile(paths[1])
assert.EqualValues(paths[:1], fc.reportEntries())
// Bring f1 back so we can test multiple evictions in a row
f1 = refNoError(fc, paths[1], assert)
assert.NotEqual(f0, f1)
// After adding f3, we should be able to evict both f0 and f1
f2 := refNoError(fc, paths[2], assert)
assert.NotEqual(f0, f2)
assert.NotEqual(f1, f2)
fc.UnrefFile(paths[0])
fc.UnrefFile(paths[0])
fc.UnrefFile(paths[1])
assert.EqualValues(paths[2:], fc.reportEntries())
})
}