Debian Codegraph @

tools/antithesis-go-instrumentor/e2e_test.go

raw
1 package main
2
3 import (
4 "io/fs"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "regexp"
9 "strings"
10 "testing"
11
12 qt "github.com/go-quicktest/qt"
13 )
14
15 func TestE2E(t *testing.T) {
16 t.Setenv("CGO_ENABLED", "0")
17
18 // Build the instrumentor binary.
19 instrumentorBin := filepath.Join(t.TempDir(), "instrumentor")
20 runCmd(t, ".", "go", "build", "-o", instrumentorBin, ".")
21
22 // Absolute path to the SDK repo root (sdk/go/repo).
23 sdkRoot, err := filepath.Abs(filepath.Join("..", ".."))
24 qt.Assert(t, qt.IsNil(err))
25
26 for _, be := range []struct {
27 name string
28 args []string
29 mainGolden string
30 }{
31 {"ast_rewriting", nil, "customer/main.go"},
32 {"source_editing", []string{"-source_editing"}, "customer/main.source_editing.go"},
33 } {
34 t.Run(be.name, func(t *testing.T) {
35 // Copy input fixture to a temp dir so we don't modify testdata, and
36 // rewrite the replace directive to use an absolute SDK path (the
37 // relative path in the checked-in go.mod won't resolve from a temp dir).
38 inputDir := filepath.Join(t.TempDir(), "input")
39 copyDir(t, "testdata/input", inputDir)
40 rewriteReplace(t, filepath.Join(inputDir, "go.mod"), sdkRoot)
41
42 // Run the instrumentor with -local_sdk_path so it works in
43 // sandboxed builds (e.g. Nix) where GOPROXY=off.
44 outputDir := filepath.Join(t.TempDir(), "output")
45 qt.Assert(t, qt.IsNil(os.MkdirAll(outputDir, 0755)))
46 args := append(append([]string{}, be.args...), "-local_sdk_path", sdkRoot, inputDir, outputDir)
47 runCmd(t, ".", instrumentorBin, args...)
48
49 expectedDir := "testdata/expected_output"
50
51 // Compare files that should match after normalization.
52 for _, f := range []struct{ actual, golden string }{
53 {"customer/main.go", be.mainGolden},
54 {"customer/go.mod", "customer/go.mod"},
55 {"notifier/notifier.go", "notifier/notifier.go"},
56 {"notifier/go.mod", "notifier/go.mod"},
57 } {
58 t.Run(f.actual, func(t *testing.T) {
59 expected, err := os.ReadFile(filepath.Join(expectedDir, f.golden))
60 qt.Assert(t, qt.IsNil(err))
61 actual, err := os.ReadFile(filepath.Join(outputDir, f.actual))
62 qt.Assert(t, qt.IsNil(err))
63 qt.Check(t, qt.Equals(
64 normalizeContent(string(actual)),
65 normalizeContent(string(expected)),
66 ))
67 })
68 }
69
70 // notifier/go.sum won't exist because we use the local sdk
71
72 // Compare symbol table (filename contains a content hash, so glob for it).
73 t.Run("symbols", func(t *testing.T) {
74 expectedFiles, err := filepath.Glob(filepath.Join(expectedDir, "symbols", "*.sym.tsv"))
75 qt.Assert(t, qt.IsNil(err))
76 qt.Assert(t, qt.HasLen(expectedFiles, 1))
77
78 actualFiles, err := filepath.Glob(filepath.Join(outputDir, "symbols", "*.sym.tsv"))
79 qt.Assert(t, qt.IsNil(err))
80 qt.Assert(t, qt.HasLen(actualFiles, 1))
81
82 expected, err := os.ReadFile(expectedFiles[0])
83 qt.Assert(t, qt.IsNil(err))
84 actual, err := os.ReadFile(actualFiles[0])
85 qt.Assert(t, qt.IsNil(err))
86
87 qt.Check(t, qt.Equals(
88 normalizeContent(string(actual)),
89 normalizeContent(string(expected)),
90 ))
91 })
92 })
93 }
94 }
95
96 func TestE2EMultiModule(t *testing.T) {
97 t.Setenv("CGO_ENABLED", "0")
98
99 instrumentorBin := filepath.Join(t.TempDir(), "instrumentor")
100 runCmd(t, ".", "go", "build", "-o", instrumentorBin, ".")
101
102 sdkRoot, err := filepath.Abs(filepath.Join("..", ".."))
103 qt.Assert(t, qt.IsNil(err))
104
105 inputDir := filepath.Join(t.TempDir(), "input")
106 copyDir(t, "testdata/input_multimodule", inputDir)
107 rewriteReplace(t, filepath.Join(inputDir, "go.mod"), sdkRoot)
108 rewriteReplace(t, filepath.Join(inputDir, "sub", "go.mod"), sdkRoot)
109
110 outputDir := filepath.Join(t.TempDir(), "output")
111 qt.Assert(t, qt.IsNil(os.MkdirAll(outputDir, 0755)))
112 runCmd(t, ".", instrumentorBin, "-local_sdk_path", sdkRoot, inputDir, outputDir)
113
114 t.Run("notifier_pinned_to_min", func(t *testing.T) {
115 got := readGoDirective(t, filepath.Join(outputDir, "notifier", "go.mod"))
116 qt.Check(t, qt.Equals(got, "1.24.0"))
117 qt.Check(t, qt.Equals(readToolchain(t, filepath.Join(outputDir, "notifier", "go.mod")), ""))
118 })
119
120 // The customer go.mod files (pre-tidy) must already carry the input's
121 // directives verbatim, since `go mod edit -print` does not modify them.
122 t.Run("customer_directives_preserved_pretidy", func(t *testing.T) {
123 qt.Check(t, qt.Equals(readGoDirective(t, filepath.Join(outputDir, "customer", "go.mod")), "1.24.7"))
124 qt.Check(t, qt.Equals(readToolchain(t, filepath.Join(outputDir, "customer", "go.mod")), "go1.24.8"))
125 qt.Check(t, qt.Equals(readGoDirective(t, filepath.Join(outputDir, "customer", "sub", "go.mod")), "1.24.3"))
126 })
127
128 // Strongest assertion: run `go mod tidy` on both customer modules after
129 // instrumentation and verify zero drift.
130 t.Run("post_tidy_zero_drift", func(t *testing.T) {
131 runCmdEnv(t, filepath.Join(outputDir, "customer"), []string{"GOFLAGS="}, "go", "mod", "tidy")
132 runCmdEnv(t, filepath.Join(outputDir, "customer", "sub"), []string{"GOFLAGS="}, "go", "mod", "tidy")
133
134 qt.Check(t, qt.Equals(readGoDirective(t, filepath.Join(outputDir, "customer", "go.mod")), "1.24.7"))
135 qt.Check(t, qt.Equals(readToolchain(t, filepath.Join(outputDir, "customer", "go.mod")), "go1.24.8"))
136 qt.Check(t, qt.Equals(readGoDirective(t, filepath.Join(outputDir, "customer", "sub", "go.mod")), "1.24.3"))
137 })
138
139 // `go build ./...` on each customer module proves the notifier and the
140 // instrumented customer code actually compile together — not just that
141 // their go.mods parse correctly.
142 t.Run("customer_builds", func(t *testing.T) {
143 runCmdEnv(t, filepath.Join(outputDir, "customer"), []string{"GOFLAGS="}, "go", "build", "./...")
144 runCmdEnv(t, filepath.Join(outputDir, "customer", "sub"), []string{"GOFLAGS="}, "go", "build", "./...")
145 })
146 }
147
148 // readGoDirective returns the value of the `go` directive in a go.mod file,
149 // or "" if absent. The match is intentionally simple — full modfile parsing
150 // would require importing the package we're testing.
151 func readGoDirective(t *testing.T, path string) string {
152 t.Helper()
153 data, err := os.ReadFile(path)
154 qt.Assert(t, qt.IsNil(err))
155 re := regexp.MustCompile(`(?m)^go (\S+)\s*$`)
156 m := re.FindStringSubmatch(string(data))
157 if len(m) < 2 {
158 return ""
159 }
160 return m[1]
161 }
162
163 // readToolchain returns the value of the `toolchain` directive in a go.mod
164 // file, or "" if absent.
165 func readToolchain(t *testing.T, path string) string {
166 t.Helper()
167 data, err := os.ReadFile(path)
168 qt.Assert(t, qt.IsNil(err))
169 re := regexp.MustCompile(`(?m)^toolchain (\S+)\s*$`)
170 m := re.FindStringSubmatch(string(data))
171 if len(m) < 2 {
172 return ""
173 }
174 return m[1]
175 }
176
177 // TestE2EDeepSubmodule covers ENG-3940: the instrumentor's
178 // PathFromBaseDirectory previously used a `filepath.Match` pattern of
179 // `baseDir/*`, which does not cross path separators. For any customer
180 // submodule nested two or more levels deep, the function fell through
181 // to returning the *absolute* path of the submodule, which the caller
182 // then joined onto the customer output dir — producing
183 // `customer/<input-abspath>/...` rather than `customer/<rel-path>/...`.
184 //
185 // The fixture has root + `tools/inner/` (level 2). After instrumentation
186 // we assert: (a) the modified go.mod is at `customer/tools/inner/go.mod`,
187 // (b) it contains the notifier `require` and `replace` lines, and
188 // (c) no stray `customer/<abs-path>/tools/inner/` directory exists.
189 //
190 // This test does NOT run `go mod tidy` post-instrumentation — directive
191 // drift caused by ONCALL-1121 (notifier `go.mod` poisoning) is being
192 // fixed separately, and conflating the two would muddy this test's
193 // signal. It focuses purely on file placement.
194 func TestE2EDeepSubmodule(t *testing.T) {
195 t.Setenv("CGO_ENABLED", "0")
196
197 instrumentorBin := filepath.Join(t.TempDir(), "instrumentor")
198 runCmd(t, ".", "go", "build", "-o", instrumentorBin, ".")
199
200 sdkRoot, err := filepath.Abs(filepath.Join("..", ".."))
201 qt.Assert(t, qt.IsNil(err))
202
203 inputDir := filepath.Join(t.TempDir(), "input")
204 copyDir(t, "testdata/input_deep_submodule", inputDir)
205 rewriteReplace(t, filepath.Join(inputDir, "go.mod"), sdkRoot)
206 rewriteReplace(t, filepath.Join(inputDir, "tools", "inner", "go.mod"), sdkRoot)
207
208 outputDir := filepath.Join(t.TempDir(), "output")
209 qt.Assert(t, qt.IsNil(os.MkdirAll(outputDir, 0755)))
210 runCmd(t, ".", instrumentorBin, "-local_sdk_path", sdkRoot, inputDir, outputDir)
211
212 // (a) The modified go.mod for the deep submodule must live at the
213 // correct relative path under customer/.
214 t.Run("deep_submodule_at_relative_path", func(t *testing.T) {
215 correctPath := filepath.Join(outputDir, "customer", "tools", "inner", "go.mod")
216 _, err := os.Stat(correctPath)
217 qt.Check(t, qt.IsNil(err), qt.Commentf("expected modified go.mod at %s", correctPath))
218 })
219
220 // (b) That go.mod must contain the notifier require + replace —
221 // proof that the instrumentor actually wrote it there (as opposed
222 // to CopyRecursiveDir just dropping in the unmodified input copy).
223 t.Run("deep_submodule_gomod_has_notifier", func(t *testing.T) {
224 correctPath := filepath.Join(outputDir, "customer", "tools", "inner", "go.mod")
225 data, err := os.ReadFile(correctPath)
226 qt.Assert(t, qt.IsNil(err))
227 s := string(data)
228 qt.Check(t, qt.IsTrue(strings.Contains(s, "antithesis.notifier/")),
229 qt.Commentf("go.mod missing antithesis.notifier require/replace; content:\n%s", s))
230 qt.Check(t, qt.IsTrue(strings.Contains(s, "replace antithesis.notifier/")),
231 qt.Commentf("go.mod missing antithesis.notifier replace; content:\n%s", s))
232 })
233
234 // (c) No `customer/<input-abspath>/...` mirror should exist. Walk
235 // customer/ and flag any directory whose path starts with what
236 // looks like an absolute input path (i.e. anything beginning with
237 // `customer/` + an absolute filesystem prefix).
238 t.Run("no_absolute_path_mirror", func(t *testing.T) {
239 customerDir := filepath.Join(outputDir, "customer")
240
241 // The pre-fix bug produced paths like
242 // `customer/tmp/.../input/tools/inner/`. Detect by looking for
243 // any directory under customer/ that contains an "input"
244 // segment (matching how t.TempDir names directories) — or more
245 // strictly, any directory whose path component starts with
246 // what would be an absolute root.
247 var offenders []string
248 _ = filepath.WalkDir(customerDir, func(path string, d fs.DirEntry, err error) error {
249 if err != nil || !d.IsDir() {
250 return nil
251 }
252 // The bug's signature: under `customer/` we'd see the
253 // instrumented input's absolute path replicated, e.g.
254 // `customer/tmp/...`. Absolute-path mirrors start with
255 // what was the first segment of the input abs path.
256 rel, _ := filepath.Rel(customerDir, path)
257 if rel == "." {
258 return nil
259 }
260 // Anything matching the leading segment of the temp dir
261 // (which contains the input fixture) is the bug.
262 parts := strings.Split(rel, string(filepath.Separator))
263 if len(parts) > 0 && (parts[0] == "tmp" || parts[0] == "home" || parts[0] == "build" || parts[0] == "private") {
264 offenders = append(offenders, rel)
265 }
266 return nil
267 })
268 qt.Check(t, qt.HasLen(offenders, 0),
269 qt.Commentf("path-doubling bug: found customer/<abs-path>/... directories: %v", offenders))
270 })
271 }
272
273 // runCmd runs a command and fails the test if it exits non-zero.
274 func runCmd(t *testing.T, dir string, name string, args ...string) {
275 t.Helper()
276 runCmdEnv(t, dir, nil, name, args...)
277 }
278
279 // runCmdEnv runs a command with additional env vars (formatted as "KEY=VAL";
280 // empty value clears the var). Fails the test if the command exits non-zero.
281 func runCmdEnv(t *testing.T, dir string, extraEnv []string, name string, args ...string) {
282 t.Helper()
283 cmd := exec.Command(name, args...)
284 cmd.Dir = dir
285 cmd.Env = append(os.Environ(), extraEnv...)
286 out, err := cmd.CombinedOutput()
287 qt.Assert(t, qt.IsNil(err), qt.Commentf("%s %s failed:\n%s", name, strings.Join(args, " "), out))
288 }
289
290 // copyDir recursively copies src to dst.
291 func copyDir(t *testing.T, src, dst string) {
292 t.Helper()
293 err := filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
294 if err != nil {
295 return err
296 }
297 rel, err := filepath.Rel(src, path)
298 if err != nil {
299 return err
300 }
301 target := filepath.Join(dst, rel)
302 if d.IsDir() {
303 return os.MkdirAll(target, 0755)
304 }
305 data, err := os.ReadFile(path)
306 if err != nil {
307 return err
308 }
309 return os.WriteFile(target, data, 0644)
310 })
311 qt.Assert(t, qt.IsNil(err))
312 }
313
314 // rewriteReplace rewrites the replace directive for the SDK to use an
315 // absolute path, so that go mod tidy works from any output location.
316 func rewriteReplace(t *testing.T, gomodPath, sdkRoot string) {
317 t.Helper()
318 data, err := os.ReadFile(gomodPath)
319 qt.Assert(t, qt.IsNil(err))
320
321 re := regexp.MustCompile(`(?m)^replace github\.com/antithesishq/antithesis-sdk-go => .+$`)
322 updated := re.ReplaceAllString(string(data),
323 "replace github.com/antithesishq/antithesis-sdk-go => "+sdkRoot)
324 if string(data) == updated {
325 t.Fatalf("replace directive not found in %s", gomodPath)
326 }
327 qt.Assert(t, qt.IsNil(os.WriteFile(gomodPath, []byte(updated), 0644)))
328 }
329
330 // Normalization regexes
331 var (
332 notifierHashRe = regexp.MustCompile(`z[0-9a-f]{12}\b`)
333 symbolHashRe = regexp.MustCompile(`go-[0-9a-f]{12}\b`)
334 sdkVersionRe = regexp.MustCompile(`antithesis-sdk-go v[\d.]+`)
335 absPathRe = regexp.MustCompile(`/[^\t\n]*/input/`)
336 instrumentorRe = regexp.MustCompile(`# instrumentor = .+`)
337 sdkReplaceRe = regexp.MustCompile(`(?m)^replace github\.com/antithesishq/antithesis-sdk-go => .+$`)
338 )
339
340 func normalizeContent(s string) string {
341 s = notifierHashRe.ReplaceAllString(s, "zHASH")
342 s = symbolHashRe.ReplaceAllString(s, "go-HASH")
343 s = sdkVersionRe.ReplaceAllString(s, "antithesis-sdk-go vX.Y.Z")
344 s = absPathRe.ReplaceAllString(s, "INPUT_DIR/")
345 s = instrumentorRe.ReplaceAllString(s, "# instrumentor = INSTRUMENTOR")
346 s = sdkReplaceRe.ReplaceAllString(s, "replace github.com/antithesishq/antithesis-sdk-go => SDK_ROOT")
347 return s
348 }