-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathe2e_test.go
More file actions
407 lines (363 loc) · 14.1 KB
/
Copy pathe2e_test.go
File metadata and controls
407 lines (363 loc) · 14.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
package server_test
// End-to-end tests for the MCP tool surface — the contract AI agents actually
// hit. The existing server_test.go (package server) exercises internal helper
// methods against hand-built stores; this file instead spins up the real
// engine+server over an in-memory MCP transport and drives each registered tool
// through the wire (JSON args in, CallToolResult out), so the tool handlers,
// arg unmarshaling, name resolution, and result rendering are all covered.
//
// Fixtures are shared with the engine golden tests (../engine/testdata/repos).
// We use go_sample because the Go extractor is stdlib-based and its fact graph
// is small and stable: modules ".", "pkg/a", "pkg/b"; symbols "..main",
// "pkg/a.Alpha", "pkg/b.Beta"; with a deliberate pkg/a<->pkg/b import cycle.
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/enola-labs/enola/internal/config"
"github.com/enola-labs/enola/pkg/bootstrap"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
// expectedTools is the OSS MCP tool surface. If a tool is added or renamed,
// this list (and the per-tool coverage below) should move with it.
var expectedTools = []string{
"generate_snapshot",
"query_facts",
"explore",
"show_symbol",
"traverse",
"find_path",
"impact_analysis",
"coverage_report",
}
// session bundles a connected client and the temp repo the server was pointed at.
type session struct {
cs *mcp.ClientSession
repo string
}
// startInMemory wires bootstrap.NewEngine + NewServer to an in-memory transport
// and returns a connected client session plus a fresh temp copy of go_sample.
func startInMemory(t *testing.T) *session {
t.Helper()
eng, cfg := newTestEngine(t)
s := connect(t, eng, cfg)
s.repo = copyTree(t, filepath.Join("..", "engine", "testdata", "repos", "go_sample"), t.TempDir())
return s
}
// newTestEngine builds a bootstrap engine with all OSS plugins and a config that
// falls back to defaults (no config file on disk).
func newTestEngine(t *testing.T) (*bootstrap.Engine, *config.Config) {
t.Helper()
eng, cfg, err := bootstrap.NewEngine(bootstrap.Options{
ConfigPath: filepath.Join(t.TempDir(), "no-such-config.yaml"),
})
if err != nil {
t.Fatalf("bootstrap.NewEngine: %v", err)
}
return eng, cfg
}
// connect wires the given engine into an MCP server over an in-memory transport
// and returns a connected client session.
func connect(t *testing.T, eng *bootstrap.Engine, cfg *config.Config) *session {
t.Helper()
ctx := context.Background()
srv, err := bootstrap.NewServer(eng, cfg)
if err != nil {
t.Fatalf("bootstrap.NewServer: %v", err)
}
serverT, clientT := mcp.NewInMemoryTransports()
if _, err := srv.MCP().Connect(ctx, serverT, nil); err != nil {
t.Fatalf("server Connect: %v", err)
}
client := mcp.NewClient(&mcp.Implementation{Name: "enola-test", Version: "0"}, nil)
cs, err := client.Connect(ctx, clientT, nil)
if err != nil {
t.Fatalf("client Connect: %v", err)
}
t.Cleanup(func() { _ = cs.Close() })
return &session{cs: cs}
}
// call invokes a tool and fails the test on transport error (a transport error
// is distinct from a tool-level IsError, which several assertions check for).
func (s *session) call(t *testing.T, name string, args map[string]any) *mcp.CallToolResult {
t.Helper()
res, err := s.cs.CallTool(context.Background(), &mcp.CallToolParams{Name: name, Arguments: args})
if err != nil {
t.Fatalf("CallTool(%s) transport error: %v", name, err)
}
return res
}
// text concatenates the text content of a tool result.
func text(res *mcp.CallToolResult) string {
var sb strings.Builder
for _, c := range res.Content {
if tc, ok := c.(*mcp.TextContent); ok {
sb.WriteString(tc.Text)
}
}
return sb.String()
}
// snapshot runs generate_snapshot against the session's temp repo so the
// server's engine is populated before the other tools are exercised.
func (s *session) snapshot(t *testing.T) {
t.Helper()
res := s.call(t, "generate_snapshot", map[string]any{"repo_path": s.repo})
if res.IsError {
t.Fatalf("generate_snapshot returned error: %s", text(res))
}
if !strings.Contains(text(res), "Facts:") {
t.Fatalf("generate_snapshot summary missing 'Facts:'; got:\n%s", text(res))
}
}
func TestE2E_ListTools(t *testing.T) {
s := startInMemory(t)
res, err := s.cs.ListTools(context.Background(), nil)
if err != nil {
t.Fatalf("ListTools: %v", err)
}
got := map[string]bool{}
for _, tool := range res.Tools {
got[tool.Name] = true
}
for _, name := range expectedTools {
if !got[name] {
t.Errorf("expected tool %q to be registered; registered: %v", name, keys(got))
}
}
}
func TestE2E_GenerateAndQuery(t *testing.T) {
s := startInMemory(t)
s.snapshot(t)
// query_facts(kind=module) must surface the fixture's modules.
out := text(s.call(t, "query_facts", map[string]any{"kind": "module"}))
for _, mod := range []string{"pkg/a", "pkg/b"} {
if !strings.Contains(out, mod) {
t.Errorf("query_facts(kind=module) missing %q; got:\n%s", mod, out)
}
}
// kinds= batch filter is OR within the dimension.
out = text(s.call(t, "query_facts", map[string]any{"kinds": []string{"symbol"}, "output_mode": "names"}))
if !strings.Contains(out, "Alpha") || !strings.Contains(out, "Beta") {
t.Errorf("query_facts(kinds=[symbol]) missing known symbols; got:\n%s", out)
}
}
func TestE2E_ShowSymbol(t *testing.T) {
s := startInMemory(t)
s.snapshot(t)
out := text(s.call(t, "show_symbol", map[string]any{"name": "Alpha", "context_lines": 10}))
if !strings.Contains(out, "Alpha") {
t.Errorf("show_symbol(Alpha) missing symbol name; got:\n%s", out)
}
if !strings.Contains(out, "a.go") {
t.Errorf("show_symbol(Alpha) missing source file reference; got:\n%s", out)
}
}
func TestE2E_Explore(t *testing.T) {
s := startInMemory(t)
s.snapshot(t)
res := s.call(t, "explore", map[string]any{"focus": "pkg/a"})
if res.IsError {
t.Fatalf("explore(pkg/a) errored: %s", text(res))
}
if !strings.Contains(text(res), "Alpha") {
t.Errorf("explore(pkg/a) should mention symbol Alpha; got:\n%s", text(res))
}
}
func TestE2E_Traverse(t *testing.T) {
s := startInMemory(t)
s.snapshot(t)
// pkg/b imports pkg/a, so traversing reverse from pkg/a must reach pkg/b.
out := text(s.call(t, "traverse", map[string]any{
"start": "pkg/a", "direction": "reverse", "output_mode": "compact",
}))
if !strings.Contains(out, "pkg/b") {
t.Errorf("traverse(reverse, pkg/a) should reach pkg/b; got:\n%s", out)
}
}
func TestE2E_FindPath(t *testing.T) {
s := startInMemory(t)
s.snapshot(t)
// Positive: main calls Alpha, so a forward path exists.
res := s.call(t, "find_path", map[string]any{"from": "..main", "to": "pkg/a.Alpha"})
if res.IsError {
t.Fatalf("find_path(main -> Alpha) errored: %s", text(res))
}
if !strings.Contains(text(res), "Alpha") {
t.Errorf("find_path(main -> Alpha) should report a path through Alpha; got:\n%s", text(res))
}
// Negative: Beta only reaches Alpha/Beta (the cycle), never main, so there
// is no forward path. This must be a graceful "no path" answer, not an error.
res = s.call(t, "find_path", map[string]any{"from": "pkg/b.Beta", "to": "..main"})
if res.IsError {
t.Fatalf("find_path with no route should not be a tool error; got:\n%s", text(res))
}
if !strings.Contains(strings.ToLower(text(res)), "no path") {
t.Errorf("find_path(Beta -> main) should report no path; got:\n%s", text(res))
}
}
func TestE2E_ImpactAnalysis(t *testing.T) {
s := startInMemory(t)
s.snapshot(t)
// main and Beta both call Alpha, so changing Alpha impacts 2 dependents.
// Summary mode reports the count + hotspot modules; compact mode names them.
out := text(s.call(t, "impact_analysis", map[string]any{"target": "pkg/a.Alpha"}))
if !strings.Contains(out, "2 total") {
t.Errorf("impact_analysis(Alpha) should report 2 dependents; got:\n%s", out)
}
out = text(s.call(t, "impact_analysis", map[string]any{"target": "pkg/a.Alpha", "output_mode": "compact"}))
if !strings.Contains(out, "Beta") {
t.Errorf("impact_analysis(Alpha, compact) should list Beta as a dependent; got:\n%s", out)
}
}
func TestE2E_CoverageReport(t *testing.T) {
s := startInMemory(t)
s.snapshot(t)
// coverage_report is registered in OSS; on a single Go repo it should return
// a non-error report (its content varies, so we only assert it succeeds).
res := s.call(t, "coverage_report", map[string]any{})
if res.IsError {
t.Fatalf("coverage_report errored: %s", text(res))
}
if strings.TrimSpace(text(res)) == "" {
t.Errorf("coverage_report returned empty output")
}
}
// TestE2E_RequiredArgValidation checks that tools with required arguments fail
// (as a tool error or a transport error) when the required arg is omitted,
// rather than silently succeeding.
func TestE2E_RequiredArgValidation(t *testing.T) {
s := startInMemory(t)
s.snapshot(t)
cases := []struct {
tool string
args map[string]any
}{
{"explore", map[string]any{}},
{"traverse", map[string]any{}},
{"find_path", map[string]any{"from": "pkg/a"}}, // missing "to"
{"impact_analysis", map[string]any{}},
{"show_symbol", map[string]any{}},
}
for _, c := range cases {
t.Run(c.tool, func(t *testing.T) {
res, err := s.cs.CallTool(context.Background(), &mcp.CallToolParams{Name: c.tool, Arguments: c.args})
if err != nil {
return // transport-level rejection is an acceptable failure mode
}
if !res.IsError {
t.Errorf("%s with missing required arg should be an error; got:\n%s", c.tool, text(res))
}
})
}
}
// writeSnapshotToDisk indexes repo with a throwaway engine and writes its
// artifacts (including .enola/facts.jsonl) to disk, simulating a workspace that
// already has a prior snapshot on disk for AutoLoadSnapshot to pick up.
func writeSnapshotToDisk(t *testing.T, repo string) {
t.Helper()
eng, _ := newTestEngine(t)
if _, err := eng.GenerateSnapshot(context.Background(), repo, false); err != nil {
t.Fatalf("prep GenerateSnapshot(%s): %v", repo, err)
}
if err := eng.WriteArtifacts(repo); err != nil {
t.Fatalf("prep WriteArtifacts(%s): %v", repo, err)
}
}
// TestE2E_AutoLoadedSnapshotResetOnFreshGenerate is a regression test for the
// bug where a snapshot auto-loaded at startup caused the first
// generate_snapshot(append=false) to silently switch to append mode, carrying
// the auto-loaded repo forward as a stale service node. A non-append call must
// discard the auto-loaded state and index only the requested repo.
func TestE2E_AutoLoadedSnapshotResetOnFreshGenerate(t *testing.T) {
// repoA: a fixture whose snapshot we pre-write to disk so AutoLoadSnapshot
// picks it up at startup. ts_sample gives a distinct repo label from repoB.
repoA := copyTree(t, filepath.Join("..", "engine", "testdata", "repos", "ts_sample"), t.TempDir())
writeSnapshotToDisk(t, repoA)
// Build an engine pointed at repoA and auto-load its snapshot, exactly as the
// server does on startup in a pre-populated workspace.
eng, cfg := newTestEngine(t)
cfg.Repo = repoA
bootstrap.AutoLoadSnapshot(eng, cfg)
if eng.Store().Count() == 0 {
t.Fatalf("expected AutoLoadSnapshot to populate the store from %s", repoA)
}
s := connect(t, eng, cfg)
// First generate_snapshot, for a DIFFERENT repo, with no append. It must reset.
repoB := copyTree(t, filepath.Join("..", "engine", "testdata", "repos", "go_sample"), t.TempDir())
res := s.call(t, "generate_snapshot", map[string]any{"repo_path": repoB})
if res.IsError {
t.Fatalf("generate_snapshot(repoB) errored: %s", text(res))
}
if out := text(res); strings.Contains(out, "Multi-repo mode active") || strings.Contains(out, "auto-enabled") {
t.Errorf("non-append generate_snapshot over auto-loaded state must not enter append mode; got:\n%s", out)
}
// coverage_report must report no service nodes (single-repo) — the stale
// repoA service must be gone.
if cov := text(s.call(t, "coverage_report", map[string]any{})); !strings.Contains(cov, "No service nodes") {
t.Errorf("expected no service nodes after fresh single-repo snapshot; got:\n%s", cov)
}
// repoA's facts must have been discarded entirely.
repoALabel := filepath.Base(repoA)
if q := text(s.call(t, "query_facts", map[string]any{"kind": "service"})); strings.Contains(q, repoALabel) {
t.Errorf("expected repoA (%s) to be discarded, but it still appears as a service node; got:\n%s", repoALabel, q)
}
}
// TestE2E_MultiRepoAppendStillAccumulates guards against the session-flag gate
// over-resetting: a genuine multi-repo flow (first snapshot resets, then
// append=true) must still accumulate both repos as service nodes.
func TestE2E_MultiRepoAppendStillAccumulates(t *testing.T) {
s := startInMemory(t)
s.snapshot(t) // go_sample, first snapshot (no append): resets, marks session
repoB := copyTree(t, filepath.Join("..", "engine", "testdata", "repos", "ts_sample"), t.TempDir())
res := s.call(t, "generate_snapshot", map[string]any{"repo_path": repoB, "append": true})
if res.IsError {
t.Fatalf("append generate_snapshot errored: %s", text(res))
}
if !strings.Contains(text(res), "Multi-repo mode active") {
t.Errorf("append=true should report multi-repo mode; got:\n%s", text(res))
}
cov := text(s.call(t, "coverage_report", map[string]any{}))
for _, label := range []string{"go_sample", "ts_sample"} {
if !strings.Contains(cov, label) {
t.Errorf("coverage_report should list service %q after append; got:\n%s", label, cov)
}
}
}
func keys(m map[string]bool) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
return out
}
// copyTree recursively copies src into a fresh subdir of dstParent and returns
// the new root. Kept local to this package (the engine golden harness has its
// own copy) so the e2e tests stay self-contained.
func copyTree(t *testing.T, src, dstParent string) string {
t.Helper()
dst := filepath.Join(dstParent, filepath.Base(src))
if err := os.MkdirAll(dst, 0o755); err != nil {
t.Fatalf("mkdir %s: %v", dst, err)
}
entries, err := os.ReadDir(src)
if err != nil {
t.Fatalf("read fixture dir %s: %v", src, err)
}
for _, e := range entries {
sp := filepath.Join(src, e.Name())
if e.IsDir() {
copyTree(t, sp, dst)
continue
}
data, err := os.ReadFile(sp)
if err != nil {
t.Fatalf("read %s: %v", sp, err)
}
if err := os.WriteFile(filepath.Join(dst, e.Name()), data, 0o644); err != nil {
t.Fatalf("write: %v", err)
}
}
return dst
}