forked from anomalyco/opencode-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_update_test.go
More file actions
491 lines (423 loc) · 12.9 KB
/
config_update_test.go
File metadata and controls
491 lines (423 loc) · 12.9 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
package opencode
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
)
func TestConfigUpdate_Success(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPatch {
t.Errorf("Expected PATCH method, got %s", r.Method)
}
if r.URL.Path != "/config" {
t.Errorf("Expected path /config, got %s", r.URL.Path)
}
// Verify request body
var received Config
if err := json.NewDecoder(r.Body).Decode(&received); err != nil {
t.Fatalf("Failed to decode request body: %v", err)
}
if received.Model != "anthropic/claude-sonnet-4" {
t.Errorf("Expected model anthropic/claude-sonnet-4, got %s", received.Model)
}
if received.Theme != "dark" {
t.Errorf("Expected theme dark, got %s", received.Theme)
}
// Return updated config
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(Config{
Model: "anthropic/claude-sonnet-4",
Theme: "dark",
})
}))
defer server.Close()
client, err := NewClient(WithBaseURL(server.URL))
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
params := &ConfigUpdateParams{
Config: ConfigPatch{
Model: strPtr("anthropic/claude-sonnet-4"),
Theme: strPtr("dark"),
},
}
result, err := client.Config.Update(context.Background(), params)
if err != nil {
t.Fatalf("Update failed: %v", err)
}
if result.Model != "anthropic/claude-sonnet-4" {
t.Errorf("Expected model anthropic/claude-sonnet-4, got %s", result.Model)
}
if result.Theme != "dark" {
t.Errorf("Expected theme dark, got %s", result.Theme)
}
}
func TestConfigUpdate_WithDirectoryQueryParam(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPatch {
t.Errorf("Expected PATCH method, got %s", r.Method)
}
if r.URL.Path != "/config" {
t.Errorf("Expected path /config, got %s", r.URL.Path)
}
// Verify query param
if r.URL.Query().Get("directory") != "/workspace/project" {
t.Errorf("Expected directory query param /workspace/project, got %s", r.URL.Query().Get("directory"))
}
// Verify request body
var received Config
if err := json.NewDecoder(r.Body).Decode(&received); err != nil {
t.Fatalf("Failed to decode request body: %v", err)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(Config{
Model: "openai/gpt-4",
})
}))
defer server.Close()
client, err := NewClient(WithBaseURL(server.URL))
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
dir := "/workspace/project"
params := &ConfigUpdateParams{
Config: ConfigPatch{
Model: strPtr("openai/gpt-4"),
},
Directory: &dir,
}
result, err := client.Config.Update(context.Background(), params)
if err != nil {
t.Fatalf("Update failed: %v", err)
}
if result.Model != "openai/gpt-4" {
t.Errorf("Expected model openai/gpt-4, got %s", result.Model)
}
}
func TestConfigUpdate_NilParams(t *testing.T) {
client, err := NewClient()
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
_, err = client.Config.Update(context.Background(), nil)
if err == nil {
t.Fatal("Expected error for nil params, got nil")
}
if !errors.Is(err, ErrParamsRequired) {
t.Errorf("Expected error 'params is required', got %s", err.Error())
}
}
func TestConfigUpdate_ServerError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error": "internal server error"}`))
}))
defer server.Close()
client, err := NewClient(WithBaseURL(server.URL))
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
params := &ConfigUpdateParams{
Config: ConfigPatch{
Model: strPtr("anthropic/claude-sonnet-4"),
},
}
_, err = client.Config.Update(context.Background(), params)
if err == nil {
t.Fatal("expected error for server error, got nil")
}
var apiErr *APIError
if !errors.As(err, &apiErr) {
t.Fatalf("expected *APIError, got %T", err)
}
if apiErr.StatusCode != http.StatusInternalServerError {
t.Errorf("expected status %d, got %d", http.StatusInternalServerError, apiErr.StatusCode)
}
}
func TestConfigUpdate_InvalidJSON(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{invalid json`))
}))
defer server.Close()
client, err := NewClient(WithBaseURL(server.URL))
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
params := &ConfigUpdateParams{
Config: ConfigPatch{
Model: strPtr("anthropic/claude-sonnet-4"),
},
}
_, err = client.Config.Update(context.Background(), params)
if err == nil {
t.Fatal("Expected error for invalid JSON, got nil")
}
}
func TestConfigUpdate_UnionTypeRoundTrip(t *testing.T) {
mcpJSON := `{"type":"local","command":["/usr/bin/mcp-server"],"enabled":true,"environment":{"NODE_ENV":"production"}}`
var mcp ConfigMcp
if err := json.Unmarshal([]byte(mcpJSON), &mcp); err != nil {
t.Fatalf("unmarshal ConfigMcp: %v", err)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var received map[string]json.RawMessage
if err := json.NewDecoder(r.Body).Decode(&received); err != nil {
t.Fatalf("decode request body: %v", err)
}
mcpRaw, ok := received["mcp"]
if !ok {
t.Fatal("expected mcp field in request body")
}
var mcpMap map[string]json.RawMessage
if err := json.Unmarshal(mcpRaw, &mcpMap); err != nil {
t.Fatalf("unmarshal mcp map: %v", err)
}
serverRaw, ok := mcpMap["test-server"]
if !ok {
t.Fatal("expected test-server key in mcp map")
}
var entry map[string]interface{}
if err := json.Unmarshal(serverRaw, &entry); err != nil {
t.Fatalf("unmarshal mcp entry: %v", err)
}
if entry["type"] != "local" {
t.Errorf("expected type local, got %v", entry["type"])
}
cmd, ok := entry["command"].([]interface{})
if !ok || len(cmd) != 1 || cmd[0] != "/usr/bin/mcp-server" {
t.Errorf("unexpected command: %v", entry["command"])
}
// Echo back the config
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(Config{})
}))
defer server.Close()
client, err := NewClient(WithBaseURL(server.URL))
if err != nil {
t.Fatalf("create client: %v", err)
}
params := &ConfigUpdateParams{
Config: ConfigPatch{
Mcp: map[string]ConfigMcp{
"test-server": mcp,
},
},
}
_, err = client.Config.Update(context.Background(), params)
if err != nil {
t.Fatalf("Update failed: %v", err)
}
}
func TestConfigUpdateParams_MarshalJSON(t *testing.T) {
params := ConfigUpdateParams{
Config: ConfigPatch{
Model: strPtr("anthropic/claude-sonnet-4"),
Theme: strPtr("dark"),
Autoupdate: boolPtr(true),
},
Directory: nil,
}
data, err := json.Marshal(params)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
var decoded map[string]any
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("Unmarshal failed: %v", err)
}
if decoded["model"] != "anthropic/claude-sonnet-4" {
t.Errorf("Expected model anthropic/claude-sonnet-4, got %v", decoded["model"])
}
if decoded["theme"] != "dark" {
t.Errorf("Expected theme dark, got %v", decoded["theme"])
}
if decoded["autoupdate"] != true {
t.Errorf("Expected autoupdate true, got %v", decoded["autoupdate"])
}
}
func TestConfigUpdateParams_MarshalJSON_OmitsUnsetFields(t *testing.T) {
params := ConfigUpdateParams{
Config: ConfigPatch{
Theme: strPtr("dark"),
},
}
data, err := json.Marshal(params)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
var raw map[string]interface{}
if err := json.Unmarshal(data, &raw); err != nil {
t.Fatalf("Unmarshal into map failed: %v", err)
}
if raw["theme"] != "dark" {
t.Errorf("Expected theme=dark, got %v", raw["theme"])
}
if _, ok := raw["autoshare"]; ok {
t.Error("Unset bool 'autoshare' should be omitted from PATCH body")
}
if _, ok := raw["autoupdate"]; ok {
t.Error("Unset bool 'autoupdate' should be omitted from PATCH body")
}
if _, ok := raw["snapshot"]; ok {
t.Error("Unset bool 'snapshot' should be omitted from PATCH body")
}
if _, ok := raw["model"]; ok {
t.Error("Unset string 'model' should be omitted from PATCH body")
}
if _, ok := raw["mode"]; ok {
t.Error("Deprecated field 'mode' should be omitted from PATCH body")
}
// Nil pointer struct fields must be omitted from PATCH body to avoid
// the server interpreting zero-value sub-fields as intentional updates.
for _, key := range []string{"agent", "keybinds", "permission", "tui", "watcher", "experimental"} {
if _, ok := raw[key]; ok {
t.Errorf("Nil struct field %q should be omitted from PATCH body", key)
}
}
}
func TestConfigUpdateParams_MarshalJSON_OmitsUnsetPermissionBash(t *testing.T) {
params := ConfigUpdateParams{
Config: ConfigPatch{
Permission: &ConfigPermission{
Edit: ConfigPermissionEditAllow,
Webfetch: ConfigPermissionWebfetchAsk,
},
},
}
data, err := json.Marshal(params)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
var raw map[string]interface{}
if err := json.Unmarshal(data, &raw); err != nil {
t.Fatalf("Unmarshal into map failed: %v", err)
}
permissionRaw, ok := raw["permission"].(map[string]interface{})
if !ok {
t.Fatalf("Expected permission object, got %T", raw["permission"])
}
if _, ok := permissionRaw["bash"]; ok {
t.Error("Unset union field 'permission.bash' should be omitted from PATCH body")
}
if permissionRaw["edit"] != string(ConfigPermissionEditAllow) {
t.Errorf("Expected permission.edit=%q, got %v", ConfigPermissionEditAllow, permissionRaw["edit"])
}
if permissionRaw["webfetch"] != string(ConfigPermissionWebfetchAsk) {
t.Errorf("Expected permission.webfetch=%q, got %v", ConfigPermissionWebfetchAsk, permissionRaw["webfetch"])
}
}
func TestConfigUpdateParams_MarshalJSON_OmitsEmptyMcpMapAfterPruning(t *testing.T) {
params := ConfigUpdateParams{
Config: ConfigPatch{
Mcp: map[string]ConfigMcp{
"srv": {},
},
},
}
data, err := json.Marshal(params)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
var raw map[string]interface{}
if err := json.Unmarshal(data, &raw); err != nil {
t.Fatalf("Unmarshal into map failed: %v", err)
}
if _, ok := raw["mcp"]; ok {
t.Fatalf("Expected mcp to be omitted when all entries are pruned, got %v", raw["mcp"])
}
}
func TestConfigUpdateParams_MarshalJSON_OmitsEmptyLspMapAfterPruning(t *testing.T) {
params := ConfigUpdateParams{
Config: ConfigPatch{
Lsp: map[string]ConfigLsp{
"tsserver": {},
},
},
}
data, err := json.Marshal(params)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
var raw map[string]interface{}
if err := json.Unmarshal(data, &raw); err != nil {
t.Fatalf("Unmarshal into map failed: %v", err)
}
if _, ok := raw["lsp"]; ok {
t.Fatalf("Expected lsp to be omitted when all entries are pruned, got %v", raw["lsp"])
}
}
func TestConfigUpdateParams_MarshalJSON_IncludesExplicitFalseValues(t *testing.T) {
params := ConfigUpdateParams{
Config: ConfigPatch{
Autoshare: boolPtr(false),
Autoupdate: boolPtr(false),
Snapshot: boolPtr(false),
},
}
data, err := json.Marshal(params)
if err != nil {
t.Fatalf("MarshalJSON failed: %v", err)
}
var raw map[string]interface{}
if err := json.Unmarshal(data, &raw); err != nil {
t.Fatalf("Unmarshal into map failed: %v", err)
}
if value, ok := raw["autoshare"]; !ok || value != false {
t.Fatalf("Expected autoshare=false in payload, got %v", raw["autoshare"])
}
if value, ok := raw["autoupdate"]; !ok || value != false {
t.Fatalf("Expected autoupdate=false in payload, got %v", raw["autoupdate"])
}
if value, ok := raw["snapshot"]; !ok || value != false {
t.Fatalf("Expected snapshot=false in payload, got %v", raw["snapshot"])
}
}
func TestConfigUpdateParams_URLQuery(t *testing.T) {
tests := []struct {
name string
params ConfigUpdateParams
expectDir string
hasDir bool
}{
{
name: "with directory",
params: ConfigUpdateParams{
Config: ConfigPatch{Model: strPtr("test")},
Directory: ptrString("/test/dir"),
},
expectDir: "/test/dir",
hasDir: true,
},
{
name: "without directory",
params: ConfigUpdateParams{
Config: ConfigPatch{Model: strPtr("test")},
Directory: nil,
},
hasDir: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
vals, err := tt.params.URLQuery()
if err != nil {
t.Fatalf("URLQuery failed: %v", err)
}
if tt.hasDir {
if vals.Get("directory") != tt.expectDir {
t.Errorf("Expected directory %s, got %s", tt.expectDir, vals.Get("directory"))
}
} else {
if vals.Has("directory") {
t.Error("Expected no directory param, but it was present")
}
}
})
}
}
func boolPtr(v bool) *bool { return &v }
func strPtr(v string) *string { return &v }