-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexec_test.go
More file actions
273 lines (243 loc) · 7.51 KB
/
exec_test.go
File metadata and controls
273 lines (243 loc) · 7.51 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
package codex
import (
"context"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
)
func TestSerializeConfigOverrides(t *testing.T) {
t.Parallel()
overrides, err := serializeConfigOverrides(map[string]any{
"approval_policy": "never",
"sandbox_workspace_write": map[string]any{"network_access": true},
"retry_budget": 3,
"tool_rules": map[string]any{"allow": []any{"git status", "git diff"}},
})
if err != nil {
t.Fatalf("serializeConfigOverrides() error = %v", err)
}
expected := []string{
`approval_policy="never"`,
`sandbox_workspace_write.network_access=true`,
`retry_budget=3`,
`tool_rules.allow=["git status", "git diff"]`,
}
if !reflect.DeepEqual(overrides, expected) {
t.Fatalf("serializeConfigOverrides() = %#v, want %#v", overrides, expected)
}
}
func TestBuildCommandArgsResumeBeforeImages(t *testing.T) {
t.Parallel()
exec := NewCodexExec("codex", nil, nil)
args, err := exec.buildCommandArgs(CodexExecArgs{
Input: "hi",
ThreadID: "thread-id",
Images: []string{"img.png"},
})
if err != nil {
t.Fatalf("buildCommandArgs() error = %v", err)
}
resumeIndex := indexOf(args, "resume")
imageIndex := indexOf(args, "--image")
if resumeIndex == -1 || imageIndex == -1 || resumeIndex >= imageIndex {
t.Fatalf("resume/image ordering incorrect: %#v", args)
}
}
func TestBuildEnvOverrideDoesNotLeak(t *testing.T) {
t.Setenv("CODEX_ENV_SHOULD_NOT_LEAK", "leak")
env := buildEnv(map[string]string{"CUSTOM_ENV": "custom"}, "http://example.com", "test")
joined := strings.Join(env, "\n")
if strings.Contains(joined, "CODEX_ENV_SHOULD_NOT_LEAK=leak") {
t.Fatalf("buildEnv() leaked parent process env: %s", joined)
}
if !strings.Contains(joined, "CUSTOM_ENV=custom") {
t.Fatalf("buildEnv() missing custom env: %s", joined)
}
if !strings.Contains(joined, "OPENAI_BASE_URL=http://example.com") {
t.Fatalf("buildEnv() missing base url: %s", joined)
}
if !strings.Contains(joined, "CODEX_API_KEY=test") {
t.Fatalf("buildEnv() missing api key: %s", joined)
}
if !strings.Contains(joined, internalOriginatorEnv+"="+goSDKOriginator) {
t.Fatalf("buildEnv() missing originator: %s", joined)
}
}
func TestExecRunAndThreadRun(t *testing.T) {
t.Parallel()
fixture := newFixtureCodex(t, `#!/bin/sh
set -eu
for arg in "$@"; do printf '%s\n' "$arg"; done > "$ARGS_FILE"
env | sort > "$ENV_FILE"
cat > "$STDIN_FILE"
schema_path=""
prev=""
for arg in "$@"; do
if [ "$prev" = "--output-schema" ]; then
schema_path="$arg"
break
fi
prev="$arg"
done
if [ -n "$schema_path" ] && [ -f "$schema_path" ]; then
printf '%s' "present" > "$SCHEMA_CHECK_FILE"
fi
printf '%s\n' '{"type":"thread.started","thread_id":"thread_123"}'
printf '%s\n' '{"type":"turn.started"}'
printf '%s\n' '{"type":"item.completed","item":{"id":"item_1","type":"agent_message","text":"Hi!"}}'
printf '%s\n' '{"type":"turn.completed","usage":{"input_tokens":42,"cached_input_tokens":12,"output_tokens":5}}'
`)
client := New(CodexOptions{
CodexPathOverride: fixture.script,
BaseURL: "http://example.com",
APIKey: "test",
Config: map[string]any{
"approval_policy": "never",
},
Env: map[string]string{
"ARGS_FILE": fixture.argsFile,
"ENV_FILE": fixture.envFile,
"STDIN_FILE": fixture.stdinFile,
"SCHEMA_CHECK_FILE": fixture.schemaCheckFile,
},
})
thread := client.StartThread(ThreadOptions{
Model: "gpt-test-1",
SandboxMode: SandboxWorkspaceWrite,
ApprovalPolicy: ApprovalOnRequest,
WorkingDirectory: "/tmp/project",
AdditionalDirectories: []string{
"../backend",
"/tmp/shared",
},
})
result, err := thread.Run([]UserInput{
{Type: "text", Text: "Describe file changes"},
{Type: "text", Text: "Focus on impacted tests"},
{Type: "local_image", Path: "/tmp/first.png"},
{Type: "local_image", Path: "/tmp/second.jpg"},
}, TurnOptions{
Context: context.Background(),
OutputSchema: map[string]any{
"type": "object",
"properties": map[string]any{
"answer": map[string]any{"type": "string"},
},
},
})
if err != nil {
t.Fatalf("thread.Run() error = %v", err)
}
if thread.ID() != "thread_123" {
t.Fatalf("thread.ID() = %q, want %q", thread.ID(), "thread_123")
}
if result.FinalResponse != "Hi!" {
t.Fatalf("FinalResponse = %q, want %q", result.FinalResponse, "Hi!")
}
if result.Usage == nil || result.Usage.InputTokens != 42 || result.Usage.CachedInputTokens != 12 || result.Usage.OutputTokens != 5 {
t.Fatalf("Usage = %#v, want populated usage", result.Usage)
}
args := readLines(t, fixture.argsFile)
expectContainsPair(t, args, "--model", "gpt-test-1")
expectContainsPair(t, args, "--sandbox", "workspace-write")
expectContainsPair(t, args, "--cd", "/tmp/project")
expectContainsPair(t, args, "--config", `approval_policy="never"`)
expectContainsPair(t, args, "--config", `approval_policy="on-request"`)
expectContainsPair(t, args, "--add-dir", "../backend")
expectContainsPair(t, args, "--add-dir", "/tmp/shared")
if got := collectFollowingArgs(args, "--image"); !reflect.DeepEqual(got, []string{"/tmp/first.png", "/tmp/second.jpg"}) {
t.Fatalf("images = %#v", got)
}
stdin := strings.TrimSpace(readText(t, fixture.stdinFile))
if stdin != "Describe file changes\n\nFocus on impacted tests" {
t.Fatalf("stdin = %q", stdin)
}
if got := strings.TrimSpace(readText(t, fixture.schemaCheckFile)); got != "present" {
t.Fatalf("schema file was not present during exec, got %q", got)
}
schemaPath := valueAfter(args, "--output-schema")
if schemaPath == "" {
t.Fatal("missing --output-schema argument")
}
if _, err := os.Stat(schemaPath); !os.IsNotExist(err) {
t.Fatalf("schema file still exists after run: %s", schemaPath)
}
}
func indexOf(values []string, target string) int {
for i, value := range values {
if value == target {
return i
}
}
return -1
}
type fixtureCodex struct {
script string
argsFile string
envFile string
stdinFile string
schemaCheckFile string
}
func newFixtureCodex(t *testing.T, scriptBody string) fixtureCodex {
t.Helper()
dir := t.TempDir()
script := filepath.Join(dir, "fake-codex.sh")
argsFile := filepath.Join(dir, "args.txt")
envFile := filepath.Join(dir, "env.txt")
stdinFile := filepath.Join(dir, "stdin.txt")
schemaCheckFile := filepath.Join(dir, "schema.txt")
if err := os.WriteFile(script, []byte(scriptBody), 0o755); err != nil {
t.Fatalf("write script: %v", err)
}
return fixtureCodex{
script: script,
argsFile: argsFile,
envFile: envFile,
stdinFile: stdinFile,
schemaCheckFile: schemaCheckFile,
}
}
func readLines(t *testing.T, path string) []string {
t.Helper()
text := strings.TrimSpace(readText(t, path))
if text == "" {
return nil
}
return strings.Split(text, "\n")
}
func readText(t *testing.T, path string) string {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
return string(data)
}
func expectContainsPair(t *testing.T, args []string, key string, value string) {
t.Helper()
for i := 0; i+1 < len(args); i++ {
if args[i] == key && args[i+1] == value {
return
}
}
t.Fatalf("pair %q %q not found in %#v", key, value, args)
}
func collectFollowingArgs(args []string, key string) []string {
collected := make([]string, 0)
for i := 0; i+1 < len(args); i++ {
if args[i] == key {
collected = append(collected, args[i+1])
}
}
return collected
}
func valueAfter(args []string, key string) string {
for i := 0; i+1 < len(args); i++ {
if args[i] == key {
return args[i+1]
}
}
return ""
}