Debian Codegraph @

gopls/internal/telemetry/telemetry_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 //go:build !openbsd && !js && !wasip1 && !solaris && !android && !386
6
7 package telemetry_test
8
9 import (
10 "context"
11 "errors"
12 "os"
13 "strconv"
14 "strings"
15 "testing"
16 "time"
17
18 "golang.org/x/telemetry/counter"
19 "golang.org/x/telemetry/counter/countertest" // requires go1.21+
20 "golang.org/x/tools/gopls/internal/protocol"
21 "golang.org/x/tools/gopls/internal/protocol/command"
22 "golang.org/x/tools/gopls/internal/telemetry"
23 . "golang.org/x/tools/gopls/internal/test/integration"
24 "golang.org/x/tools/gopls/internal/util/bug"
25 )
26
27 func TestMain(m *testing.M) {
28 tmp, err := os.MkdirTemp("", "gopls-telemetry-test-counters")
29 if err != nil {
30 panic(err)
31 }
32 countertest.Open(tmp)
33 code := Main(m)
34 os.RemoveAll(tmp) // ignore error (cleanup fails on Windows; golang/go#68243)
35 os.Exit(code)
36 }
37
38 func TestTelemetry(t *testing.T) {
39 var (
40 goversion = ""
41 editor = "vscode" // We set ClientName("Visual Studio Code") below.
42 )
43
44 // Run gopls once to determine the Go version.
45 WithOptions(
46 Modes(Default),
47 ).Run(t, "", func(_ *testing.T, env *Env) {
48 goversion = strconv.Itoa(env.GoVersion())
49 })
50
51 // counters that should be incremented once per session
52 sessionCounters := []*counter.Counter{
53 counter.New("gopls/client:" + editor),
54 counter.New("gopls/goversion:1." + goversion),
55 counter.New("fwd/vscode/linter:a"),
56 counter.New("gopls/gotoolchain:local"),
57 }
58 initialCounts := make([]uint64, len(sessionCounters))
59 for i, c := range sessionCounters {
60 count, err := countertest.ReadCounter(c)
61 if err != nil {
62 continue // counter db not open, or counter not found
63 }
64 initialCounts[i] = count
65 }
66
67 // Verify that a properly configured session gets notified of a bug on the
68 // server.
69 WithOptions(
70 Modes(Default), // must be in-process to receive the bug report below
71 Settings{"showBugReports": true},
72 ClientName("Visual Studio Code"),
73 EnvVars{
74 "GOTOOLCHAIN": "local", // so that the local counter is incremented
75 },
76 ).Run(t, "", func(_ *testing.T, env *Env) {
77 goversion = strconv.Itoa(env.GoVersion())
78 addForwardedCounters(env, []string{"vscode/linter:a"}, []int64{1})
79 const desc = "got a bug"
80
81 // This will increment a counter named something like:
82 //
83 // `gopls/bug
84 // golang.org/x/tools/gopls/internal/util/bug.report:+35
85 // golang.org/x/tools/gopls/internal/util/bug.Report:=68
86 // golang.org/x/tools/gopls/internal/telemetry_test.TestTelemetry.func2:+4
87 // golang.org/x/tools/gopls/internal/test/integration.(*Runner).Run.func1:+87
88 // testing.tRunner:+150
89 // runtime.goexit:+0`
90 //
91 bug.Report(desc) // want a stack counter with the trace starting from here.
92
93 env.Await(ShownMessage(desc))
94 })
95
96 // gopls/editor:client
97 // gopls/goversion:1.x
98 // fwd/vscode/linter:a
99 // gopls/gotoolchain:local
100 for i, c := range sessionCounters {
101 want := initialCounts[i] + 1
102 got, err := countertest.ReadCounter(c)
103 if err != nil || got != want {
104 t.Errorf("ReadCounter(%q) = (%v, %v), want (%v, nil)", c.Name(), got, err, want)
105 t.Logf("Current timestamp = %v", time.Now().UTC())
106 }
107 }
108
109 // gopls/bug
110 bugcount := bug.BugReportCount
111 counts, err := countertest.ReadStackCounter(bugcount)
112 if err != nil {
113 t.Fatalf("ReadStackCounter(bugreportcount) failed - %v", err)
114 }
115 if len(counts) != 1 || !hasEntry(counts, t.Name(), 1) {
116 t.Errorf("read stackcounter(%q) = (%#v, %v), want one entry", "gopls/bug", counts, err)
117 t.Logf("Current timestamp = %v", time.Now().UTC())
118 }
119 }
120
121 func TestSettingTelemetry(t *testing.T) {
122 // counters that should be incremented by each session
123 sessionCounters := []*counter.Counter{
124 counter.New("gopls/setting/diagnosticsDelay"),
125 counter.New("gopls/setting/staticcheck:true"),
126 counter.New("gopls/setting/noSemanticString:true"),
127 counter.New("gopls/setting/analyses/deprecated:false"),
128 }
129
130 initialCounts := make([]uint64, len(sessionCounters))
131 for i, c := range sessionCounters {
132 count, err := countertest.ReadCounter(c)
133 if err != nil {
134 continue // counter db not open, or counter not found
135 }
136 initialCounts[i] = count
137 }
138
139 // Run gopls.
140 WithOptions(
141 Modes(Default),
142 Settings{
143 "staticcheck": true,
144 "analyses": map[string]bool{
145 "deprecated": false,
146 },
147 "diagnosticsDelay": "0s",
148 "noSemanticString": true,
149 },
150 ).Run(t, "", func(_ *testing.T, env *Env) {
151 })
152
153 for i, c := range sessionCounters {
154 count, err := countertest.ReadCounter(c)
155 if err != nil {
156 t.Errorf("ReadCounter(%q) failed: %v", c.Name(), err)
157 continue
158 }
159 if count <= initialCounts[i] {
160 t.Errorf("ReadCounter(%q) = %d, want > %d", c.Name(), count, initialCounts[i])
161 }
162 }
163 }
164
165 func addForwardedCounters(env *Env, names []string, values []int64) {
166 args, err := command.MarshalArgs(command.AddTelemetryCountersArgs{
167 Names: names, Values: values,
168 })
169 if err != nil {
170 env.TB.Fatal(err)
171 }
172 var res error
173 env.ExecuteCommand(&protocol.ExecuteCommandParams{
174 Command: command.AddTelemetryCounters.String(),
175 Arguments: args,
176 }, &res)
177 if res != nil {
178 env.TB.Errorf("%v failed - %v", command.AddTelemetryCounters, res)
179 }
180 }
181
182 func hasEntry(counts map[string]uint64, pattern string, want uint64) bool {
183 for k, v := range counts {
184 if strings.Contains(k, pattern) && v == want {
185 return true
186 }
187 }
188 return false
189 }
190
191 func TestLatencyCounter(t *testing.T) {
192 const operation = "TestLatencyCounter" // a unique operation name
193
194 stop := telemetry.StartLatencyTimer(operation)
195 stop(context.Background(), nil)
196
197 for isError, want := range map[bool]uint64{false: 1, true: 0} {
198 if got := totalLatencySamples(t, operation, isError); got != want {
199 t.Errorf("totalLatencySamples(operation=%v, isError=%v) = %d, want %d", operation, isError, got, want)
200 }
201 }
202 }
203
204 func TestLatencyCounter_Error(t *testing.T) {
205 const operation = "TestLatencyCounter_Error" // a unique operation name
206
207 stop := telemetry.StartLatencyTimer(operation)
208 stop(context.Background(), errors.New("bad"))
209
210 for isError, want := range map[bool]uint64{false: 0, true: 1} {
211 if got := totalLatencySamples(t, operation, isError); got != want {
212 t.Errorf("totalLatencySamples(operation=%v, isError=%v) = %d, want %d", operation, isError, got, want)
213 }
214 }
215 }
216
217 func TestLatencyCounter_Cancellation(t *testing.T) {
218 const operation = "TestLatencyCounter_Cancellation"
219
220 stop := telemetry.StartLatencyTimer(operation)
221 ctx, cancel := context.WithCancel(context.Background())
222 cancel()
223 stop(ctx, nil)
224
225 for isError, want := range map[bool]uint64{false: 0, true: 0} {
226 if got := totalLatencySamples(t, operation, isError); got != want {
227 t.Errorf("totalLatencySamples(operation=%v, isError=%v) = %d, want %d", operation, isError, got, want)
228 }
229 }
230 }
231
232 func totalLatencySamples(t *testing.T, operation string, isError bool) uint64 {
233 var total uint64
234 telemetry.ForEachLatencyCounter(operation, isError, func(c *counter.Counter) {
235 count, err := countertest.ReadCounter(c)
236 if err != nil {
237 t.Errorf("ReadCounter(%s) failed: %v", c.Name(), err)
238 } else {
239 total += count
240 }
241 })
242 return total
243 }
244
245 func TestLatencyInstrumentation(t *testing.T) {
246 const files = `
247 -- go.mod --
248 module mod.test/a
249 go 1.18
250 -- a.go --
251 package a
252
253 func _() {
254 x := 0
255 _ = x
256 }
257 `
258
259 // Verify that a properly configured session gets notified of a bug on the
260 // server.
261 WithOptions(
262 Modes(Default), // must be in-process to receive the bug report below
263 ).Run(t, files, func(_ *testing.T, env *Env) {
264 env.OpenFile("a.go")
265 before := totalLatencySamples(t, "completion", false)
266 loc := env.RegexpSearch("a.go", "()x")
267 for i := 0; i < 10; i++ {
268 env.Completion(loc)
269 }
270 after := totalLatencySamples(t, "completion", false)
271 if after-before < 10 {
272 t.Errorf("after 10 completions, completion counter went from %d to %d", before, after)
273 }
274 })
275 }