Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/regtest/e2e_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 regtest
6
7 import (
8 "bytes"
9 "encoding/json"
10 "fmt"
11 "log"
12 "os"
13 "path/filepath"
14 "reflect"
15 "runtime"
16 "strings"
17 "testing"
18
19 "golang.org/x/telemetry/counter"
20 "golang.org/x/telemetry/internal/config"
21 icounter "golang.org/x/telemetry/internal/counter"
22 "golang.org/x/telemetry/internal/telemetry"
23 "golang.org/x/telemetry/internal/testenv"
24 )
25
26 func TestRunProg(t *testing.T) {
27 testenv.SkipIfUnsupportedPlatform(t)
28 testenv.MustHaveExec(t)
29 prog1 := NewProgram(t, "prog1", func() int {
30 fmt.Println("FuncB")
31 return 0
32 })
33 prog2 := NewProgram(t, "prog2", func() int {
34 fmt.Println("FuncC")
35 return 1
36 })
37 telemetryDir := t.TempDir()
38 if out, err := RunProg(t, telemetryDir, prog1); err != nil || !bytes.Contains(out, []byte("FuncB")) || bytes.Contains(out, []byte("FuncC")) {
39 t.Errorf("first RunProg = (%s, %v), want FuncB' and succeed", out, err)
40 }
41 t.Run("in subtest", func(t *testing.T) {
42 if out, err := RunProg(t, telemetryDir, prog2); err == nil || bytes.Contains(out, []byte("FuncB")) || !bytes.Contains(out, []byte("FuncC")) {
43 t.Errorf("second RunProg = (%s, %v), want 'FuncC' and fail", out, err)
44 }
45 })
46 }
47
48 func programIncCounters() int {
49 counter.Inc("counter")
50 counter.Inc("counter:surprise")
51 counter.New("gopls/editor:expected").Inc()
52 counter.New("gopls/editor:surprise").Inc()
53 counter.NewStack("stack/expected", 1).Inc()
54 counter.NewStack("stack-surprise", 1).Inc()
55 return 0
56 }
57
58 func TestE2E_off(t *testing.T) {
59 testenv.SkipIfUnsupportedPlatform(t)
60 testenv.MustHaveExec(t)
61 log.Printf("GOOS=%s GOARCH=%s", runtime.GOOS, runtime.GOARCH)
62
63 prog := NewProgram(t, "prog", programIncCounters)
64 tests := []struct {
65 mode string // if empty, don't set the mode
66 wantLocalDir bool
67 }{
68 {"", true},
69 {"local", true},
70 {"on", true},
71 {"off", false},
72 }
73
74 for _, test := range tests {
75 t.Run(fmt.Sprintf("mode=%s", test.mode), func(t *testing.T) {
76 dir := telemetry.NewDir(t.TempDir())
77 if test.mode != "" {
78 if err := dir.SetMode(test.mode); err != nil {
79 t.Fatalf("SetMode failed: %v", err)
80 }
81 }
82 out, err := RunProg(t, dir.Dir(), prog)
83 if err != nil {
84 t.Fatalf("program failed unexpectedly (%v)\n%s", err, out)
85 }
86 _, err = os.Stat(dir.LocalDir())
87 if err != nil && !os.IsNotExist(err) {
88 t.Fatalf("os.Stat(%q): unexpected error: %v", dir.LocalDir(), err)
89 }
90 if gotLocalDir := err == nil; gotLocalDir != test.wantLocalDir {
91 t.Errorf("got /local dir: %v, want %v; out:\n%s", gotLocalDir, test.wantLocalDir, string(out))
92 }
93 })
94 }
95 }
96
97 func TestE2E(t *testing.T) {
98 testenv.SkipIfUnsupportedPlatform(t)
99 testenv.MustHaveExec(t)
100 programIncCounters := NewProgram(t, "prog", programIncCounters)
101 telemetryDir := t.TempDir()
102 goVers, progPath, progVers := ProgramInfo(t)
103
104 out, err := RunProg(t, telemetryDir, programIncCounters)
105 if err != nil {
106 t.Fatalf("program failed unexpectedly (%v)\n%s", err, out)
107 }
108
109 // TODO: retrieve config through a module proxy so we test internal/configstore code path.
110 cfg := &telemetry.UploadConfig{
111 GOOS: []string{runtime.GOOS},
112 GOARCH: []string{runtime.GOARCH},
113 GoVersion: []string{goVers},
114 Programs: []*telemetry.ProgramConfig{
115 {
116 Name: progPath,
117 Versions: []string{progVers},
118 Counters: []telemetry.CounterConfig{
119 {Name: "counter", Rate: 1},
120 {Name: "gopls/editor:{expected, other}", Rate: 1},
121 },
122 Stacks: []telemetry.CounterConfig{
123 {Name: "stack/expected", Rate: 1, Depth: 1},
124 },
125 },
126 },
127 }
128
129 // TODO: check if weekday file exists.
130
131 // TODO: test upload path.
132 // - change the global clock (maybe internal/clock package?)
133 // - start an upload server
134 // - Run(t, telemetryDir, func() int { upload.Run(...) })
135 // - check if the upload server received expected data
136 // - check if the local and upload directories in the expected state
137
138 uploaded, notUploaded, err := parseCounters(cfg, telemetryDir)
139 if err != nil {
140 t.Fatalf("failed to simulate upload: %v", err)
141 }
142
143 wantUpload := map[string]uint64{
144 "counter": 1,
145 "gopls/editor:expected": 1,
146 "stack/expected\n": 1, // prefix of the stack counter name + "\n". see parseCounters.
147 }
148 testCounterUploadStatus(t, uploaded, wantUpload, false)
149
150 wantNotUpload := map[string]uint64{
151 "counter:surprise": 1,
152 "gopls/editor:surprise": 1,
153 "stack-surprise\n": 1, // prefix of the stack counter name + "\n". see parseCounters.
154 }
155 testCounterUploadStatus(t, notUploaded, wantNotUpload, true)
156 }
157
158 // testCounterUploadStatus checks if got and want counter maps match.
159 // If allowUnexpected is true, it checks if got is a superset of want.
160 func testCounterUploadStatus(t *testing.T, got, want map[string]uint64, allowUnexpected bool) {
161 t.Helper()
162
163 seen := got
164 if allowUnexpected {
165 // filter out unexpected counters from got, for comparison.
166 m := make(map[string]uint64, len(want))
167 for k, v := range got {
168 if _, ok := want[k]; ok {
169 m[k] = v
170 }
171 }
172 seen = m
173 }
174 if !reflect.DeepEqual(seen, want) {
175 // TODO(hyangah) implement diff or copy Go project's internal/diff for pretty printing of diff.
176 // Or, move internal/regtest to the godev module where we can depend on go-cmp.
177 t.Errorf("unmet expectation:\ngot %v\nwant %v", stringify(got), stringify(want))
178 }
179 }
180
181 func stringify(a any) string {
182 encoded, err := json.MarshalIndent(a, "\t", " ")
183 if err != nil {
184 return fmt.Sprintf("unmarshallable - %v", err)
185 }
186 return string(encoded)
187 }
188
189 // parseCounters reads all counter files in the local telemetry directory, and
190 // returns all observed counters grouped by whether the counter names are included
191 // in the specified configuration.
192 // For simplicity in the comparison code, the returned maps represent a stack counter
193 // with its counter name prefix and "\n". For example, if there are "stackcounter\npkg.F:..."
194 // and "stackcounter\npkg.G:..", "stackcounter\n" will hold the sum of those counters.
195 func parseCounters(uc *telemetry.UploadConfig, telemetryDir string) (uploadable, notUploadable map[string]uint64, _ error) {
196 cfg := config.NewConfig(uc)
197 localDir := filepath.Join(telemetryDir, "local")
198 entries, err := os.ReadDir(localDir)
199 if err != nil {
200 return nil, nil, err
201 }
202 uploadable, notUploadable = make(map[string]uint64), make(map[string]uint64)
203 for _, entry := range entries {
204 if entry.IsDir() || filepath.Ext(entry.Name()) != ".count" {
205 continue
206 }
207 data, err := os.ReadFile(filepath.Join(localDir, entry.Name()))
208 if err != nil { // ignore unreadable file.
209 continue
210 }
211 // TODO(hyangah): how about exposing "Parse" to public for testing? (i.e. countertest.Parse)?
212 parsed, err := icounter.Parse(entry.Name(), data)
213 if err != nil { // ignore unparsable file
214 continue
215 }
216 // The following is temporary until the upload package implements the exact same logic.
217 // TODO(hyangah): replace with the shared logic between the uploader and the local viewer.
218 maybeUploadable := true &&
219 cfg.HasGOOS(parsed.Meta["GOOS"]) &&
220 cfg.HasGOARCH(parsed.Meta["GOARCH"]) &&
221 cfg.HasGoVersion(parsed.Meta["GoVersion"]) &&
222 cfg.HasProgram(parsed.Meta["Program"]) &&
223 cfg.HasVersion(parsed.Meta["Program"], parsed.Meta["Version"])
224
225 for k, v := range parsed.Count {
226 counterPrefix, _, isStackCounter := strings.Cut(k, "\n")
227 isUploadable := maybeUploadable
228 key := k
229 if isStackCounter {
230 isUploadable = isUploadable && cfg.HasStack(parsed.Meta["Program"], counterPrefix)
231 key = counterPrefix + "\n"
232 } else {
233 isUploadable = isUploadable && cfg.HasCounter(parsed.Meta["Program"], k)
234 }
235 if isUploadable {
236 uploadable[key] = uploadable[key] + v
237 } else {
238 notUploadable[key] = notUploadable[key] + v
239 }
240 }
241 }
242 return uploadable, notUploadable, nil
243 }