Debian Codegraph @

gopls/internal/test/integration/misc/prompt_test.go

raw symbols SCIP
1 // Copyright 2023 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 misc
6
7 import (
8 "fmt"
9 "os"
10 "path/filepath"
11 "regexp"
12 "strconv"
13 "testing"
14 "time"
15
16 "github.com/google/go-cmp/cmp"
17 "golang.org/x/telemetry/counter"
18 "golang.org/x/telemetry/counter/countertest"
19 "golang.org/x/tools/gopls/internal/protocol"
20 "golang.org/x/tools/gopls/internal/protocol/command"
21 "golang.org/x/tools/gopls/internal/server"
22 . "golang.org/x/tools/gopls/internal/test/integration"
23 )
24
25 // Test prompt file in old and new formats are handled as expected.
26 func TestTelemetryPrompt_PromptFile(t *testing.T) {
27 const src = `
28 -- go.mod --
29 module mod.com
30
31 go 1.12
32 -- main.go --
33 package main
34
35 func main() {}
36 `
37
38 defaultTelemetryStartTime := "1714521600" // 2024-05-01
39 defaultToken := "7"
40 samplesPerMille := "500"
41
42 testCases := []struct {
43 name, in, want string
44 wantPrompt bool
45 }{
46 {
47 name: "empty",
48 in: "",
49 want: "failed 1 1714521600 7",
50 wantPrompt: true,
51 },
52 {
53 name: "v0.15-format/invalid",
54 in: "pending",
55 want: "failed 1 1714521600 7",
56 wantPrompt: true,
57 },
58 {
59 name: "v0.15-format/pPending",
60 in: "pending 1",
61 want: "failed 2 1714521600 7",
62 wantPrompt: true,
63 },
64 {
65 name: "v0.15-format/pPending",
66 in: "failed 1",
67 want: "failed 2 1714521600 7",
68 wantPrompt: true,
69 },
70 {
71 name: "v0.15-format/pYes",
72 in: "yes 1",
73 want: "yes 1", // untouched since short-circuited
74 },
75 {
76 name: "v0.16-format/pNotReady",
77 in: "- 0 1714521600 1000",
78 want: "- 0 1714521600 1000",
79 },
80 {
81 name: "v0.16-format/pPending",
82 in: "pending 1 1714521600 1",
83 want: "failed 2 1714521600 1",
84 wantPrompt: true,
85 },
86 {
87 name: "v0.16-format/pFailed",
88 in: "failed 2 1714521600 1",
89 want: "failed 3 1714521600 1",
90 wantPrompt: true,
91 },
92 {
93 name: "v0.16-format/invalid",
94 in: "xxx 0 12345 678",
95 want: "failed 1 1714521600 7",
96 wantPrompt: true,
97 },
98 {
99 name: "v0.16-format/extra",
100 in: "- 0 1714521600 1000 7777 xxx",
101 want: "- 0 1714521600 1000", // drop extra
102 },
103 }
104 for _, tc := range testCases {
105 t.Run(tc.name, func(t *testing.T) {
106 modeFile := filepath.Join(t.TempDir(), "mode")
107 goplsConfigDir := t.TempDir()
108 promptDir := filepath.Join(goplsConfigDir, "prompt")
109 promptFile := filepath.Join(promptDir, "telemetry")
110
111 if err := os.MkdirAll(promptDir, 0777); err != nil {
112 t.Fatal(err)
113 }
114 if err := os.WriteFile(promptFile, []byte(tc.in), 0666); err != nil {
115 t.Fatal(err)
116 }
117 WithOptions(
118 Modes(Default), // no need to run this in all modes
119 EnvVars{
120 server.GoplsConfigDirEnvvar: goplsConfigDir,
121 server.FakeTelemetryModefileEnvvar: modeFile,
122 server.GoTelemetryGoplsClientStartTimeEnvvar: defaultTelemetryStartTime,
123 server.GoTelemetryGoplsClientTokenEnvvar: defaultToken,
124 server.FakeSamplesPerMille: samplesPerMille,
125 },
126 Settings{
127 "telemetryPrompt": true,
128 },
129 ).Run(t, src, func(t *testing.T, env *Env) {
130 expectation := ShownMessageRequest(".*Would you like to enable Go telemetry?")
131 if !tc.wantPrompt {
132 expectation = Not(expectation)
133 }
134 env.OnceMet(
135 CompletedWork(server.TelemetryPromptWorkTitle, 1, true),
136 expectation,
137 )
138 if got, err := os.ReadFile(promptFile); err != nil || string(got) != tc.want {
139 t.Fatalf("(%q) -> (%q, %v), want %q", tc.in, got, err, tc.want)
140 }
141 })
142 })
143 }
144 }
145
146 // Test that gopls prompts for telemetry only when it is supposed to.
147 func TestTelemetryPrompt_Conditions_Mode(t *testing.T) {
148 const src = `
149 -- go.mod --
150 module mod.com
151
152 go 1.12
153 -- main.go --
154 package main
155
156 func main() {
157 }
158 `
159
160 for _, enabled := range []bool{true, false} {
161 t.Run(fmt.Sprintf("telemetryPrompt=%v", enabled), func(t *testing.T) {
162 for _, initialMode := range []string{"", "local", "off", "on"} {
163 t.Run(fmt.Sprintf("initial_mode=%s", initialMode), func(t *testing.T) {
164 modeFile := filepath.Join(t.TempDir(), "mode")
165 if initialMode != "" {
166 if err := os.WriteFile(modeFile, []byte(initialMode), 0666); err != nil {
167 t.Fatal(err)
168 }
169 }
170 telemetryStartTime := time.Now().Add(-8 * 24 * time.Hour) // telemetry started a while ago
171 WithOptions(
172 Modes(Default), // no need to run this in all modes
173 EnvVars{
174 server.GoplsConfigDirEnvvar: t.TempDir(),
175 server.FakeTelemetryModefileEnvvar: modeFile,
176 server.GoTelemetryGoplsClientStartTimeEnvvar: strconv.FormatInt(telemetryStartTime.Unix(), 10),
177 server.GoTelemetryGoplsClientTokenEnvvar: "1", // always sample because samplingPerMille >= 1.
178 },
179 Settings{
180 "telemetryPrompt": enabled,
181 },
182 ).Run(t, src, func(t *testing.T, env *Env) {
183 wantPrompt := enabled && (initialMode == "" || initialMode == "local")
184 expectation := ShownMessageRequest(".*Would you like to enable Go telemetry?")
185 if !wantPrompt {
186 expectation = Not(expectation)
187 }
188 env.OnceMet(
189 CompletedWork(server.TelemetryPromptWorkTitle, 1, true),
190 expectation,
191 )
192 })
193 })
194 }
195 })
196 }
197 }
198
199 // Test that gopls prompts for telemetry only after instrumenting for a while, and
200 // when the token is within the range for sample.
201 func TestTelemetryPrompt_Conditions_StartTimeAndSamplingToken(t *testing.T) {
202 const src = `
203 -- go.mod --
204 module mod.com
205
206 go 1.12
207 -- main.go --
208 package main
209
210 func main() {
211 }
212 `
213 day := 24 * time.Hour
214 samplesPerMille := 50
215 for _, token := range []int{1, samplesPerMille, samplesPerMille + 1} {
216 wantSampled := token <= samplesPerMille
217 t.Run(fmt.Sprintf("to_sample=%t/tokens=%d", wantSampled, token), func(t *testing.T) {
218 for _, elapsed := range []time.Duration{8 * day, 1 * day, 0} {
219 telemetryStartTimeOrEmpty := ""
220 if elapsed > 0 {
221 telemetryStartTimeOrEmpty = strconv.FormatInt(time.Now().Add(-elapsed).Unix(), 10)
222 }
223 t.Run(fmt.Sprintf("elapsed=%s", elapsed), func(t *testing.T) {
224 modeFile := filepath.Join(t.TempDir(), "mode")
225 WithOptions(
226 Modes(Default), // no need to run this in all modes
227 EnvVars{
228 server.GoplsConfigDirEnvvar: t.TempDir(),
229 server.FakeTelemetryModefileEnvvar: modeFile,
230 server.GoTelemetryGoplsClientStartTimeEnvvar: telemetryStartTimeOrEmpty,
231 server.GoTelemetryGoplsClientTokenEnvvar: strconv.Itoa(token),
232 server.FakeSamplesPerMille: strconv.Itoa(samplesPerMille), // want token ∈ [1, 50] is always sampled.
233 },
234 Settings{
235 "telemetryPrompt": true,
236 },
237 ).Run(t, src, func(t *testing.T, env *Env) {
238 wantPrompt := wantSampled && elapsed > 7*day
239 expectation := ShownMessageRequest(".*Would you like to enable Go telemetry?")
240 if !wantPrompt {
241 expectation = Not(expectation)
242 }
243 env.OnceMet(
244 CompletedWork(server.TelemetryPromptWorkTitle, 1, true),
245 expectation,
246 )
247 })
248 })
249 }
250 })
251 }
252 }
253
254 // Test that responding to the telemetry prompt results in the expected state.
255 func TestTelemetryPrompt_Response(t *testing.T) {
256 if !countertest.SupportedPlatform {
257 t.Skip("requires counter support")
258 }
259
260 const src = `
261 -- go.mod --
262 module mod.com
263
264 go 1.12
265 -- main.go --
266 package main
267
268 func main() {
269 }
270 `
271
272 var (
273 acceptanceCounter = "gopls/telemetryprompt/accepted"
274 declinedCounter = "gopls/telemetryprompt/declined"
275 attempt1Counter = "gopls/telemetryprompt/attempts:1"
276 allCounters = []string{acceptanceCounter, declinedCounter, attempt1Counter}
277 )
278
279 // To avoid (but not prevent) the flakes encountered in golang/go#68659, we
280 // need to perform our first read before starting to increment counters.
281 //
282 // ReadCounter checks to see if the counter file needs to be rotated before
283 // reading. When files are rotated, all previous counts are lost. Calling
284 // ReadCounter here reduces the window for a flake due to this rotation (the
285 // file was originally was located during countertest.Open in TestMain).
286 //
287 // golang/go#71590 tracks the larger problems with the countertest library.
288 //
289 // (The counter name below is arbitrary.)
290 _, _ = countertest.ReadCounter(counter.New("issue68659"))
291
292 // We must increment counters in order for the initial reads below to
293 // succeed.
294 //
295 // TODO(rfindley): ReadCounter should simply return 0 for uninitialized
296 // counters.
297 for _, name := range allCounters {
298 counter.New(name).Inc()
299 }
300
301 readCounts := func(t *testing.T) map[string]uint64 {
302 t.Helper()
303 counts := make(map[string]uint64)
304 for _, name := range allCounters {
305 count, err := countertest.ReadCounter(counter.New(name))
306 if err != nil {
307 t.Fatalf("ReadCounter(%q) failed: %v", name, err)
308 }
309 counts[name] = count
310 }
311 return counts
312 }
313
314 tests := []struct {
315 name string // subtest name
316 response string // response to choose for the telemetry dialog
317 wantMode string // resulting telemetry mode
318 wantMsg string // substring contained in the follow-up popup (if empty, no popup is expected)
319 wantInc uint64 // expected 'prompt accepted' counter increment
320 wantCounts map[string]uint64
321 }{
322 {"yes", server.TelemetryYes, "on", "uploading is now enabled", 1, map[string]uint64{
323 acceptanceCounter: 1,
324 declinedCounter: 0,
325 attempt1Counter: 1,
326 }},
327 {"no", server.TelemetryNo, "", "", 0, map[string]uint64{
328 acceptanceCounter: 0,
329 declinedCounter: 1,
330 attempt1Counter: 1,
331 }},
332 {"empty", "", "", "", 0, map[string]uint64{
333 acceptanceCounter: 0,
334 declinedCounter: 0,
335 attempt1Counter: 1,
336 }},
337 }
338
339 for _, test := range tests {
340 t.Run(test.name, func(t *testing.T) {
341 initialCounts := readCounts(t)
342 modeFile := filepath.Join(t.TempDir(), "mode")
343 telemetryStartTime := time.Now().Add(-8 * 24 * time.Hour)
344 msgRE := regexp.MustCompile(".*Would you like to enable Go telemetry?")
345 respond := func(m *protocol.ShowMessageRequestParams) (*protocol.MessageActionItem, error) {
346 if msgRE.MatchString(m.Message) {
347 for _, item := range m.Actions {
348 if item.Title == test.response {
349 return &item, nil
350 }
351 }
352 if test.response != "" {
353 t.Errorf("action item %q not found", test.response)
354 }
355 }
356 return nil, nil
357 }
358 WithOptions(
359 Modes(Default), // no need to run this in all modes
360 EnvVars{
361 server.GoplsConfigDirEnvvar: t.TempDir(),
362 server.FakeTelemetryModefileEnvvar: modeFile,
363 server.GoTelemetryGoplsClientStartTimeEnvvar: strconv.FormatInt(telemetryStartTime.Unix(), 10),
364 server.GoTelemetryGoplsClientTokenEnvvar: "1", // always sample because samplingPerMille >= 1.
365 },
366 Settings{
367 "telemetryPrompt": true,
368 },
369 MessageResponder(respond),
370 ).Run(t, src, func(t *testing.T, env *Env) {
371 var postConditions []Expectation
372 if test.wantMsg != "" {
373 postConditions = append(postConditions, ShownMessage(test.wantMsg))
374 }
375 env.OnceMet(
376 CompletedWork(server.TelemetryPromptWorkTitle, 1, true),
377 postConditions...,
378 )
379 gotMode := ""
380 if contents, err := os.ReadFile(modeFile); err == nil {
381 gotMode = string(contents)
382 } else if !os.IsNotExist(err) {
383 t.Fatal(err)
384 }
385 if gotMode != test.wantMode {
386 t.Errorf("after prompt, mode=%s, want %s", gotMode, test.wantMode)
387 }
388
389 // We increment the acceptance counter when checking the prompt file
390 // before prompting, so start a second, transient gopls session and
391 // verify that the acceptance counter is incremented.
392 env2 := ConnectGoplsEnv(t, env.Ctx, env.Sandbox, env.Editor.Config(), env.Server)
393 env2.Await(CompletedWork(server.TelemetryPromptWorkTitle, 1, true))
394 if err := env2.Editor.Close(env2.Ctx); err != nil {
395 t.Errorf("closing second editor: %v", err)
396 }
397
398 gotCounts := readCounts(t)
399 for k := range gotCounts {
400 gotCounts[k] -= initialCounts[k]
401 }
402 if diff := cmp.Diff(test.wantCounts, gotCounts); diff != "" {
403 t.Errorf("counter mismatch (-want +got):\n%s", diff)
404 }
405 })
406 })
407 }
408 }
409
410 // Test that we stop asking about telemetry after the user ignores the question
411 // 5 times.
412 func TestTelemetryPrompt_GivingUp(t *testing.T) {
413 const src = `
414 -- go.mod --
415 module mod.com
416
417 go 1.12
418 -- main.go --
419 package main
420
421 func main() {
422 }
423 `
424
425 // For this test, we want to share state across gopls sessions.
426 modeFile := filepath.Join(t.TempDir(), "mode")
427 telemetryStartTime := time.Now().Add(-30 * 24 * time.Hour)
428 configDir := t.TempDir()
429
430 const maxPrompts = 5 // internal prompt limit defined by gopls
431
432 for i := range maxPrompts + 1 {
433 WithOptions(
434 Modes(Default), // no need to run this in all modes
435 EnvVars{
436 server.GoplsConfigDirEnvvar: configDir,
437 server.FakeTelemetryModefileEnvvar: modeFile,
438 server.GoTelemetryGoplsClientStartTimeEnvvar: strconv.FormatInt(telemetryStartTime.Unix(), 10),
439 server.GoTelemetryGoplsClientTokenEnvvar: "1", // always sample because samplingPerMille >= 1.
440 },
441 Settings{
442 "telemetryPrompt": true,
443 },
444 ).Run(t, src, func(t *testing.T, env *Env) {
445 wantPrompt := i < maxPrompts
446 expectation := ShownMessageRequest(".*Would you like to enable Go telemetry?")
447 if !wantPrompt {
448 expectation = Not(expectation)
449 }
450 env.OnceMet(
451 CompletedWork(server.TelemetryPromptWorkTitle, 1, true),
452 expectation,
453 )
454 })
455 }
456 }
457
458 // Test that gopls prompts for telemetry only when it is supposed to.
459 func TestTelemetryPrompt_Conditions_Command(t *testing.T) {
460 const src = `
461 -- go.mod --
462 module mod.com
463
464 go 1.12
465 -- main.go --
466 package main
467
468 func main() {
469 }
470 `
471 modeFile := filepath.Join(t.TempDir(), "mode")
472 telemetryStartTime := time.Now().Add(-8 * 24 * time.Hour)
473 WithOptions(
474 Modes(Default), // no need to run this in all modes
475 EnvVars{
476 server.GoplsConfigDirEnvvar: t.TempDir(),
477 server.FakeTelemetryModefileEnvvar: modeFile,
478 server.GoTelemetryGoplsClientStartTimeEnvvar: fmt.Sprintf("%d", telemetryStartTime.Unix()),
479 server.GoTelemetryGoplsClientTokenEnvvar: "1", // always sample because samplingPerMille >= 1.
480 },
481 Settings{
482 // off because we are testing
483 // if we can trigger the prompt with command.
484 "telemetryPrompt": false,
485 },
486 ).Run(t, src, func(t *testing.T, env *Env) {
487 cmd := command.NewMaybePromptForTelemetryCommand("prompt")
488 var err error
489 env.ExecuteCommand(&protocol.ExecuteCommandParams{
490 Command: cmd.Command,
491 }, &err)
492 if err != nil {
493 t.Fatal(err)
494 }
495 expectation := ShownMessageRequest(".*Would you like to enable Go telemetry?")
496 env.OnceMet(
497 CompletedWork(server.TelemetryPromptWorkTitle, 2, true),
498 expectation,
499 )
500 })
501 }