Debian Codegraph @

tools/antithesis-go-toolexec/runtime_edges_test.go

raw
1 package main
2
3 // End-to-end runtime edge tests for the -toolexec front end.
4 //
5 // These reuse the fixtures TestRuntimeEdges already curates for the whole-tree
6 // instrumentor and drive them through a real `go build -toolexec=antithesis-go-toolexec`
7 // instead. Regenerating the fixtures with
8 //
9 // go test ./scanners/coverage/instrumentor -run TestRuntimeEdges -update
10 //
11 // updates the expectations for both front ends at once.
12
13 import (
14 "encoding/json"
15 "errors"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "strconv"
20 "strings"
21 "testing"
22
23 qt "github.com/go-quicktest/qt"
24 )
25
26 // runtimeEdgesDir holds the fixtures, which live with the instrumentor whose
27 // behavior they describe.
28 const runtimeEdgesDir = "../antithesis-go-instrumentor/scanners/coverage/instrumentor/testdata/runtime_edges"
29
30 // The recorder module shadows the SDK import path that instrumented code calls
31 // into, so that every Notify lands somewhere observable. The real SDK cannot be
32 // used here: without a loaded library its notifications go nowhere, and with one
33 // they would be absorbed by coverage leases rather than reported individually.
34 const (
35 recorderGoMod = `module github.com/antithesishq/antithesis-sdk-go
36
37 go 1.24
38 `
39
40 recorderInstrumentation = `package instrumentation
41
42 import (
43 "fmt"
44 "os"
45 )
46
47 // Module mirrors the shape the generated registration file expects. Notify
48 // prints the module's symbol table and the module-local edge id, in call order,
49 // with nothing suppressed. The symbol table is needed because edge ids restart
50 // at 1 in every package, so an id alone does not identify an edge.
51 type Module struct{ symbolTable string }
52
53 func RegisterModule(symbolTable string, edgeCount int) *Module {
54 return &Module{symbolTable: symbolTable}
55 }
56
57 func (m *Module) Notify(edge int) {
58 fmt.Fprintf(os.Stdout, "%s\t%d\n", m.symbolTable, edge)
59 }
60 `
61 )
62
63 type toolexecEdgeCase struct {
64 Args []string `json:"args"`
65 Edges []int `json:"edges"`
66 }
67
68 type toolexecEdgeCases struct {
69 Cases []toolexecEdgeCase `json:"cases"`
70 }
71
72 func TestRuntimeEdgesToolexec(t *testing.T) {
73 if testing.Short() {
74 t.Skip("builds a wrapper binary and one program per case")
75 }
76
77 programs, err := filepath.Glob(filepath.Join(runtimeEdgesDir, "*/program.go"))
78 qt.Assert(t, qt.IsNil(err))
79 qt.Assert(t, qt.IsTrue(len(programs) > 0))
80
81 for _, program := range programs {
82 caseDir := filepath.Dir(program)
83 t.Run(filepath.Base(caseDir), func(t *testing.T) {
84 t.Parallel()
85
86 var cases toolexecEdgeCases
87 body, err := os.ReadFile(filepath.Join(caseDir, "cases.json"))
88 qt.Assert(t, qt.IsNil(err))
89 qt.Assert(t, qt.IsNil(json.Unmarshal(body, &cases)))
90
91 binary, symbolRows := buildInstrumented(t, caseDir, program)
92
93 // The same edges must fire, in the same order, as the whole-tree
94 // instrumentor produces for this program.
95 for _, c := range cases.Cases {
96 qt.Check(t, qt.DeepEquals(runForEdges(t, binary, c.Args), c.Edges),
97 qt.Commentf("argv %q", c.Args))
98 }
99
100 // And they must describe the same source spans. Only the rows are
101 // compared: the header names the module, which is per-package here
102 // and per-program there.
103 want, err := os.ReadFile(filepath.Join(caseDir, "expected.sym.tsv"))
104 qt.Assert(t, qt.IsNil(err))
105 qt.Check(t, qt.DeepEquals(symbolRows, symbolTableRows(string(want))))
106 })
107 }
108 }
109
110 // writeRecorderModuleTo materializes the module that shadows the SDK.
111 func writeRecorderModuleTo(dir string) error {
112 if err := os.MkdirAll(filepath.Join(dir, "instrumentation"), 0o755); err != nil {
113 return err
114 }
115 if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(recorderGoMod), 0o644); err != nil {
116 return err
117 }
118 return os.WriteFile(
119 filepath.Join(dir, "instrumentation", "instrumentation.go"), []byte(recorderInstrumentation), 0o644)
120 }
121
122 // buildInstrumented assembles a temporary module around one fixture program,
123 // builds it through the wrapper, and returns the binary along with the rows of
124 // the symbol table that was produced.
125 func buildInstrumented(t *testing.T, caseDir, program string) (string, []string) {
126 t.Helper()
127 dir := t.TempDir()
128
129 // The program does not import the SDK -- instrumentation is what introduces
130 // that dependency -- so the requirement is stated here and satisfied by the
131 // recorder. Left untidied on purpose: `go mod tidy` would drop it.
132 goMod := "module edgetest\n\ngo 1.24\n\nrequire github.com/antithesishq/antithesis-sdk-go v0.0.0\n\n" +
133 "replace github.com/antithesishq/antithesis-sdk-go => " + sharedRecorder + "\n"
134 qt.Assert(t, qt.IsNil(os.WriteFile(filepath.Join(dir, "go.mod"), []byte(goMod), 0o644)))
135
136 source, err := os.ReadFile(program)
137 qt.Assert(t, qt.IsNil(err))
138 qt.Assert(t, qt.IsNil(os.WriteFile(filepath.Join(dir, "program.go"), source, 0o644)))
139 copyEmbedAssets(t, caseDir, dir)
140
141 symbolsDir := filepath.Join(dir, "symbols")
142 binary := filepath.Join(dir, "prog")
143 build := exec.Command("go", "build", "-toolexec="+sharedToolexec, "-o", binary, ".")
144 build.Dir = dir
145 // These programs carry no assertions, and the recorder deliberately does not
146 // provide the assert package.
147 build.Env = buildEnv(symbolsDir, "edgetest", "ANTITHESIS_SKIP_CATALOG=1")
148 if out, err := build.CombinedOutput(); err != nil {
149 t.Fatalf("building the instrumented program failed: %v\n%s", err, out)
150 }
151
152 tables := tablesForModule(t, symbolsDir, dir)
153 qt.Assert(t, qt.HasLen(tables, 1))
154 body, err := os.ReadFile(tables[0])
155 qt.Assert(t, qt.IsNil(err))
156 return binary, symbolTableRows(string(body))
157 }
158
159 // runForEdges runs the instrumented program and returns the edge ids it printed.
160 func runForEdges(t *testing.T, binary string, args []string) []int {
161 t.Helper()
162 command := exec.Command(binary, args...)
163 command.Dir = filepath.Dir(binary)
164 out, err := command.Output()
165 if err != nil {
166 stderr := ""
167 var exitErr *exec.ExitError
168 if errors.As(err, &exitErr) {
169 stderr = string(exitErr.Stderr)
170 }
171 t.Fatalf("running %s %q failed: %v\n%s", filepath.Base(binary), args, err, stderr)
172 }
173 // Empty rather than nil: a fixture expecting no edges unmarshals to an empty
174 // slice, and DeepEquals distinguishes the two.
175 edges := []int{}
176 for _, notification := range recorded(t, out) {
177 edges = append(edges, notification.edge)
178 }
179 return edges
180 }
181
182 // notification is one line of recorder output: which module fired, and which of
183 // its edges.
184 type notification struct {
185 symbolTable string
186 edge int
187 }
188
189 func recorded(t *testing.T, out []byte) []notification {
190 t.Helper()
191 var notifications []notification
192 for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
193 if line == "" {
194 continue
195 }
196 table, id, found := strings.Cut(line, "\t")
197 qt.Assert(t, qt.IsTrue(found), qt.Commentf("malformed recorder line %q", line))
198 edge, err := strconv.Atoi(id)
199 qt.Assert(t, qt.IsNil(err), qt.Commentf("non-integer edge %q", id))
200 notifications = append(notifications, notification{symbolTable: table, edge: edge})
201 }
202 return notifications
203 }
204
205 // symbolTableRows returns a symbol table's data rows with the file column reduced
206 // to a base name, so tables written from different directories compare equal.
207 func symbolTableRows(table string) []string {
208 var rows []string
209 for _, line := range strings.Split(table, "\n") {
210 if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, "file\t") {
211 continue
212 }
213 columns := strings.Split(line, "\t")
214 columns[0] = filepath.Base(columns[0])
215 rows = append(rows, strings.Join(columns, "\t"))
216 }
217 return rows
218 }
219
220 func copyEmbedAssets(t *testing.T, caseDir, dir string) {
221 t.Helper()
222 entries, err := os.ReadDir(caseDir)
223 qt.Assert(t, qt.IsNil(err))
224 for _, entry := range entries {
225 switch {
226 case entry.IsDir(), entry.Name() == "program.go",
227 entry.Name() == "cases.json", entry.Name() == "expected.sym.tsv":
228 continue
229 }
230 body, err := os.ReadFile(filepath.Join(caseDir, entry.Name()))
231 qt.Assert(t, qt.IsNil(err))
232 qt.Assert(t, qt.IsNil(os.WriteFile(filepath.Join(dir, entry.Name()), body, 0o644)))
233 }
234 }