Debian Codegraph @

gopls/internal/filecache/filecache_test.go

raw symbols SCIP
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package filecache_test
6
7 // This file defines tests of the API of the filecache package.
8 //
9 // Some properties (e.g. garbage collection) cannot be exercised
10 // through the API, so this test does not attempt to do so.
11
12 import (
13 "bytes"
14 cryptorand "crypto/rand"
15 "fmt"
16 "log"
17 mathrand "math/rand"
18 "os"
19 "os/exec"
20 "strconv"
21 "strings"
22 "testing"
23
24 "golang.org/x/sync/errgroup"
25 "golang.org/x/tools/gopls/internal/filecache"
26 "golang.org/x/tools/internal/testenv"
27 )
28
29 func TestBasics(t *testing.T) {
30 const kind = "TestBasics"
31 key := uniqueKey() // never used before
32 value := []byte("hello")
33
34 // Get of a never-seen key returns not found.
35 if _, err := filecache.Get(kind, key, filecache.Bytes); err != filecache.ErrNotFound {
36 if strings.Contains(err.Error(), "operation not supported") ||
37 strings.Contains(err.Error(), "not implemented") {
38 t.Skipf("skipping: %v", err)
39 }
40 t.Errorf("Get of random key returned err=%q, want not found", err)
41 }
42
43 // Set of a never-seen key and a small value succeeds.
44 if err := filecache.Set(kind, key, value); err != nil {
45 t.Errorf("Set failed: %v", err)
46 }
47
48 // Get of the key returns a copy of the value.
49 if got, err := filecache.Get(kind, key, filecache.Bytes); err != nil {
50 t.Errorf("Get after Set failed: %v", err)
51 } else if string(got) != string(value) {
52 t.Errorf("Get after Set returned different value: got %q, want %q", got, value)
53 }
54
55 // The kind is effectively part of the key.
56 if _, err := filecache.Get("different-kind", key, filecache.Bytes); err != filecache.ErrNotFound {
57 t.Errorf("Get with wrong kind returned err=%q, want not found", err)
58 }
59 }
60
61 // TestConcurrency exercises concurrent access to the same entry.
62 func TestConcurrency(t *testing.T) {
63 if os.Getenv("GO_BUILDER_NAME") == "plan9-arm" {
64 t.Skip(`skipping on plan9-arm builder due to golang/go#58748: failing with 'mount rpc error'`)
65 }
66 const kind = "TestConcurrency"
67 key := uniqueKey()
68 const N = 100 // concurrency level
69
70 // Construct N distinct values, each larger
71 // than a typical 4KB OS file buffer page.
72 var values [N][8192]byte
73 for i := range values {
74 if _, err := mathrand.Read(values[i][:]); err != nil {
75 t.Fatalf("rand: %v", err)
76 }
77 }
78
79 // get calls Get and verifies that the cache entry
80 // matches one of the values passed to Set.
81 get := func(mustBeFound bool) error {
82 got, err := filecache.Get(kind, key, filecache.Bytes)
83 if err != nil {
84 if err == filecache.ErrNotFound && !mustBeFound {
85 return nil // not found
86 }
87 return err
88 }
89 for _, want := range values {
90 if bytes.Equal(want[:], got) {
91 return nil // a match
92 }
93 }
94 return fmt.Errorf("Get returned a value that was never Set")
95 }
96
97 // Perform N concurrent calls to Set and Get.
98 // All sets must succeed.
99 // All gets must return nothing, or one of the Set values;
100 // there is no third possibility.
101 var group errgroup.Group
102 for i := range values {
103 group.Go(func() error { return filecache.Set(kind, key, values[i][:]) })
104 group.Go(func() error { return get(false) })
105 }
106 if err := group.Wait(); err != nil {
107 if strings.Contains(err.Error(), "operation not supported") ||
108 strings.Contains(err.Error(), "not implemented") {
109 t.Skipf("skipping: %v", err)
110 }
111 t.Fatal(err)
112 }
113
114 // A final Get must report one of the values that was Set.
115 if err := get(true); err != nil {
116 t.Fatalf("final Get failed: %v", err)
117 }
118 }
119
120 const (
121 testIPCKind = "TestIPC"
122 testIPCValueA = "hello"
123 testIPCValueB = "world"
124 )
125
126 // TestIPC exercises interprocess communication through the cache.
127 // It calls Set(A) in the parent, { Get(A); Set(B) } in the child
128 // process, then Get(B) in the parent.
129 func TestIPC(t *testing.T) {
130 testenv.NeedsExec(t)
131
132 keyA := uniqueKey()
133 keyB := uniqueKey()
134 value := []byte(testIPCValueA)
135
136 // Set keyA.
137 if err := filecache.Set(testIPCKind, keyA, value); err != nil {
138 if strings.Contains(err.Error(), "operation not supported") {
139 t.Skipf("skipping: %v", err)
140 }
141 t.Fatalf("Set: %v", err)
142 }
143
144 // Call ipcChild in a child process,
145 // passing it the keys in the environment
146 // (quoted, to avoid NUL termination of C strings).
147 // It will Get(A) then Set(B).
148 cmd := exec.Command(os.Args[0], os.Args[1:]...)
149 cmd.Env = append(os.Environ(),
150 "ENTRYPOINT=ipcChild",
151 fmt.Sprintf("KEYA=%q", keyA),
152 fmt.Sprintf("KEYB=%q", keyB))
153 cmd.Stdout = os.Stderr
154 cmd.Stderr = os.Stderr
155 if err := cmd.Run(); err != nil {
156 t.Fatal(err)
157 }
158
159 // Verify keyB.
160 got, err := filecache.Get(testIPCKind, keyB, filecache.Bytes)
161 if err != nil {
162 t.Fatal(err)
163 }
164 if string(got) != "world" {
165 t.Fatalf("Get(keyB) = %q, want %q", got, "world")
166 }
167 }
168
169 // We define our own main function so that portions of
170 // some tests can run in a separate (child) process.
171 func TestMain(m *testing.M) {
172 switch os.Getenv("ENTRYPOINT") {
173 case "ipcChild":
174 ipcChild()
175 default:
176 os.Exit(m.Run())
177 }
178 }
179
180 // ipcChild is the portion of TestIPC that runs in a child process.
181 func ipcChild() {
182 getenv := func(name string) (key [32]byte) {
183 s, _ := strconv.Unquote(os.Getenv(name))
184 copy(key[:], []byte(s))
185 return
186 }
187
188 // Verify key A.
189 got, err := filecache.Get(testIPCKind, getenv("KEYA"), filecache.Bytes)
190 if err != nil || string(got) != testIPCValueA {
191 log.Fatalf("child: Get(key) = %q, %v; want %q", got, err, testIPCValueA)
192 }
193
194 // Set key B.
195 if err := filecache.Set(testIPCKind, getenv("KEYB"), []byte(testIPCValueB)); err != nil {
196 log.Fatalf("child: Set(keyB) failed: %v", err)
197 }
198 }
199
200 // uniqueKey returns a key that has never been used before.
201 func uniqueKey() (key [32]byte) {
202 if _, err := cryptorand.Read(key[:]); err != nil {
203 log.Fatalf("rand: %v", err)
204 }
205 return
206 }
207
208 func BenchmarkUncontendedGet(b *testing.B) {
209 const kind = "BenchmarkUncontendedGet"
210 key := uniqueKey()
211
212 var value [8192]byte
213 if _, err := mathrand.Read(value[:]); err != nil {
214 b.Fatalf("rand: %v", err)
215 }
216 if err := filecache.Set(kind, key, value[:]); err != nil {
217 b.Fatal(err)
218 }
219
220 b.SetBytes(int64(len(value)))
221
222 var group errgroup.Group
223 group.SetLimit(50)
224 for b.Loop() {
225 group.Go(func() error {
226 _, err := filecache.Get(kind, key, filecache.Bytes)
227 return err
228 })
229 }
230 if err := group.Wait(); err != nil {
231 b.Fatal(err)
232 }
233 }
234
235 // These two benchmarks are asymmetric: the one for Get imposes a
236 // modest bound on concurrency (50) whereas the one for Set imposes a
237 // much higher concurrency (1000) to test the implementation's
238 // self-imposed bound.
239
240 func BenchmarkUncontendedSet(b *testing.B) {
241 const kind = "BenchmarkUncontendedSet"
242 key := uniqueKey()
243 var value [8192]byte
244
245 const P = 1000 // parallelism
246 b.SetBytes(P * int64(len(value)))
247
248 for b.Loop() {
249 // Perform P concurrent calls to Set. All must succeed.
250 var group errgroup.Group
251 for range [P]bool{} {
252 group.Go(func() error {
253 return filecache.Set(kind, key, value[:])
254 })
255 }
256 if err := group.Wait(); err != nil {
257 if strings.Contains(err.Error(), "operation not supported") ||
258 strings.Contains(err.Error(), "not implemented") {
259 b.Skipf("skipping: %v", err)
260 }
261 b.Fatal(err)
262 }
263 }
264 }