Debian Codegraph @

debian/go/src/golang.org/x/telemetry/internal/regtest/regtest.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 provides helpers for end-to-end testing
6 // involving counter and upload packages.
7 package regtest
8
9 import (
10 "fmt"
11 "log"
12 "os"
13 "os/exec"
14 "runtime"
15 "runtime/debug"
16 "strings"
17 "testing"
18 "time"
19
20 "golang.org/x/telemetry/counter"
21 "golang.org/x/telemetry/counter/countertest"
22 internalcounter "golang.org/x/telemetry/internal/counter"
23 "golang.org/x/telemetry/internal/telemetry"
24 )
25
26 const (
27 telemetryDirEnvVar = "_COUNTERTEST_RUN_TELEMETRY_DIR"
28 asofEnvVar = "_COUNTERTEST_ASOF"
29 entryPointEnvVar = "_COUNTERTEST_ENTRYPOINT"
30 )
31
32 var (
33 telemetryDirEnvVarValue = os.Getenv(telemetryDirEnvVar)
34 asofEnvVarValue = os.Getenv(asofEnvVar)
35 entryPointEnvVarValue = os.Getenv(entryPointEnvVar)
36 )
37
38 // Program is a value that can be used to identify a program in the test.
39 type Program string
40
41 // NewProgram returns a Program value that can be used to identify a program
42 // to run by RunProg. The program must be registered with NewProgram before
43 // the first call to RunProg in the test function.
44 //
45 // RunProg runs this binary in a separate process with special environment
46 // variables that specify the entry point. When this binary runs with the
47 // environment variables that match the specified name, NewProgram calls
48 // the given fn and exits with the return value. Note that all the code
49 // before NewProgram is executed in both the main process and the subprocess.
50 func NewProgram(t *testing.T, name string, fn func() int) Program {
51 if telemetryDirEnvVarValue != "" && entryPointEnvVarValue == name {
52 // We are running the separate process that was spawned by RunProg.
53 fmt.Fprintf(os.Stderr, "running program %q\n", name)
54 if asofEnvVarValue != "" {
55 asof, err := time.Parse("2006-01-02", asofEnvVarValue)
56 if err != nil {
57 log.Fatalf("error parsing asof time %q: %v", asof, err)
58 }
59 fmt.Fprintf(os.Stderr, "setting counter time to %s\n", name)
60 internalcounter.CounterTime = func() time.Time {
61 return asof
62 }
63 }
64 countertest.Open(telemetryDirEnvVarValue)
65 os.Exit(fn())
66 }
67
68 testName, _, _ := strings.Cut(t.Name(), "/")
69 registered, ok := registeredPrograms[testName]
70 if !ok {
71 registered = make(map[string]bool)
72 }
73 if registered[name] {
74 t.Fatalf("program %q was already registered", name)
75 }
76 registered[name] = true
77 return Program(name)
78 }
79
80 // NewIncProgram returns a basic program that increments the given counters and
81 // exits with status 0.
82 func NewIncProgram(t *testing.T, name string, counters ...string) Program {
83 return NewProgram(t, name, func() int {
84 for _, c := range counters {
85 counter.Inc(c)
86 }
87 return 0
88 })
89 }
90
91 // registeredPrograms stores all registered program names to detect duplicate registrations.
92 var registeredPrograms = make(map[string]map[string]bool) // test name -> program name -> exist
93
94 // RunProg runs the program prog in a separate process with the specified
95 // telemetry directory. RunProg can be called multiple times in the same test,
96 // but all the programs must be registered with NewProgram before the first
97 // call to RunProg.
98 func RunProg(t *testing.T, telemetryDir string, prog Program) ([]byte, error) {
99 return RunProgAsOf(t, telemetryDir, time.Time{}, prog)
100 }
101
102 // RunProgAsOf is like RunProg, but executes the program as of a specific
103 // counter time.
104 func RunProgAsOf(t *testing.T, telemetryDir string, asof time.Time, prog Program) ([]byte, error) {
105 if telemetryDirEnvVarValue != "" {
106 fmt.Fprintf(os.Stderr, "unknown program %q\n %s %s", prog, telemetryDirEnvVarValue, entryPointEnvVarValue)
107 os.Exit(2)
108 }
109 testName, _, _ := strings.Cut(t.Name(), "/")
110 testBin, err := os.Executable()
111 if err != nil {
112 return nil, fmt.Errorf("cannot determine the current process's executable name: %v", err)
113 }
114
115 // Spawn a subprocess to run the 'prog' by setting telemetryDirEnvVar.
116 cmd := exec.Command(testBin, "-test.run", fmt.Sprintf("^%s$", testName))
117 cmd.Env = append(os.Environ(), telemetryDirEnvVar+"="+telemetryDir, entryPointEnvVar+"="+string(prog))
118 if !asof.IsZero() {
119 cmd.Env = append(cmd.Env, asofEnvVar+"="+asof.Format("2006-01-02"))
120 }
121 return cmd.CombinedOutput()
122 }
123
124 // ProgramInfo returns the go version, program name and version info the
125 // process would record in its counter file.
126 func ProgramInfo(t *testing.T) (goVersion, progPath, progVersion string) {
127 info, ok := debug.ReadBuildInfo()
128 if !ok {
129 t.Fatal("cannot read build info - it's likely this setup is unsupported by the counter package")
130 }
131 return telemetry.ProgramInfo(info)
132 }
133
134 // CreateTestUploadConfig creates a new upload config for the current program,
135 // permitting the given counters.
136 func CreateTestUploadConfig(t *testing.T, counterNames, stackCounterNames []string) *telemetry.UploadConfig {
137 goVersion, progPath, progVersion := ProgramInfo(t)
138 GOOS, GOARCH := runtime.GOOS, runtime.GOARCH
139 programConfig := &telemetry.ProgramConfig{
140 Name: progPath,
141 Versions: []string{progVersion},
142 }
143 for _, c := range counterNames {
144 programConfig.Counters = append(programConfig.Counters, telemetry.CounterConfig{Name: c, Rate: 1})
145 }
146 for _, c := range stackCounterNames {
147 programConfig.Stacks = append(programConfig.Stacks, telemetry.CounterConfig{Name: c, Rate: 1, Depth: 16})
148 }
149 return &telemetry.UploadConfig{
150 GOOS: []string{GOOS},
151 GOARCH: []string{GOARCH},
152 SampleRate: 1.0,
153 GoVersion: []string{goVersion},
154 Programs: []*telemetry.ProgramConfig{programConfig},
155 }
156 }