返回 DeepSeek-Reasonix
gate_test.go
根目录 / internal / agent / gate_test.go
1 package agent
2
3 import (
4 "context"
5 "encoding/json"
6 "reasonix/internal/event"
7 "strings"
8 "testing"
9
10 "reasonix/internal/provider"
11 "reasonix/internal/tool"
12 )
13
14 // stubGate denies any call whose tool name is in deny; everything else allows.
15 type stubGate struct {
16 deny map[string]bool
17 checked []string
18 }
19
20 func (g *stubGate) Check(ctx context.Context, toolName string, args json.RawMessage, readOnly bool) (bool, string, error) {
21 g.checked = append(g.checked, toolName)
22 if g.deny[toolName] {
23 return false, "denied by test policy", nil
24 }
25 return true, "", nil
26 }
27
28 // TestGateBlocksDeniedCall proves executeOne consults the permission gate: a
29 // denied tool returns a "blocked:" result plus a notice and never runs, while an
30 // allowed tool runs normally.
31 func TestGateBlocksDeniedCall(t *testing.T) {
32 reg := tool.NewRegistry()
33 reg.Add(fakeTool{name: "bash", readOnly: false})
34 reg.Add(fakeTool{name: "read_file", readOnly: true})
35
36 g := &stubGate{deny: map[string]bool{"bash": true}}
37 a := New(nil, reg, NewSession(""), Options{Gate: g}, event.Discard)
38
39 blocked := a.executeOne(context.Background(), provider.ToolCall{Name: "bash", Arguments: `{"command":"rm -rf /"}`})
40 if !strings.HasPrefix(blocked.output, "blocked:") {
41 t.Errorf("denied call result = %q, want a 'blocked:' result", blocked.output)
42 }
43 if !blocked.blocked || blocked.errMsg == "" {
44 t.Errorf("denied call should surface a user-facing block notice, got %+v", blocked)
45 }
46
47 ok := a.executeOne(context.Background(), provider.ToolCall{Name: "read_file", Arguments: `{"path":"/a"}`})
48 if !strings.Contains(ok.output, "done") {
49 t.Errorf("allowed call should run, got %q", ok.output)
50 }
51
52 if len(g.checked) != 2 {
53 t.Errorf("gate consulted %d times, want 2 (%v)", len(g.checked), g.checked)
54 }
55 }
56
57 // TestNilGateRunsEverything confirms gating is opt-in: with no gate wired, a
58 // writer call runs unimpeded (backward-compatible default).
59 func TestNilGateRunsEverything(t *testing.T) {
60 reg := tool.NewRegistry()
61 reg.Add(fakeTool{name: "write_file", readOnly: false})
62
63 a := New(nil, reg, NewSession(""), Options{}, event.Discard) // no Gate
64 out := a.executeOne(context.Background(), provider.ToolCall{Name: "write_file", Arguments: `{"path":"/a"}`})
65 if strings.HasPrefix(out.output, "blocked:") {
66 t.Errorf("nil gate should not block: %q", out.output)
67 }
68 }
69
69 lines GO