-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsindoq_test.go
More file actions
532 lines (447 loc) · 12 KB
/
sindoq_test.go
File metadata and controls
532 lines (447 loc) · 12 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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
package sindoq
import (
"context"
"errors"
"testing"
"time"
"github.com/happyhackingspace/sindoq/internal/factory"
"github.com/happyhackingspace/sindoq/internal/provider"
"github.com/happyhackingspace/sindoq/pkg/executor"
"github.com/happyhackingspace/sindoq/pkg/fs"
)
// mockProvider implements provider.Provider for testing
type mockProvider struct {
name string
createErr error
instance *mockInstance
}
func (p *mockProvider) Name() string { return p.name }
func (p *mockProvider) Create(ctx context.Context, opts *provider.CreateOptions) (provider.Instance, error) {
if p.createErr != nil {
return nil, p.createErr
}
if p.instance == nil {
p.instance = &mockInstance{
id: "test-instance-123",
status: provider.StatusRunning,
}
}
return p.instance, nil
}
func (p *mockProvider) Capabilities() provider.Capabilities {
return provider.Capabilities{
SupportsStreaming: true,
SupportedLanguages: []string{"Python", "JavaScript", "Go"},
}
}
func (p *mockProvider) Validate(ctx context.Context) error { return nil }
func (p *mockProvider) Close() error { return nil }
// mockInstance implements provider.Instance for testing
type mockInstance struct {
id string
status provider.InstanceStatus
execResult *executor.ExecutionResult
execErr error
stopErr error
stopped bool
}
func (i *mockInstance) ID() string { return i.id }
func (i *mockInstance) Provider() string { return "mock" }
func (i *mockInstance) Status(ctx context.Context) (provider.InstanceStatus, error) {
return i.status, nil
}
func (i *mockInstance) Execute(ctx context.Context, code string, opts *executor.ExecutionOptions) (*executor.ExecutionResult, error) {
if i.execErr != nil {
return nil, i.execErr
}
if i.execResult != nil {
return i.execResult, nil
}
return &executor.ExecutionResult{
ExitCode: 0,
Stdout: "Hello, World!\n",
Language: opts.Language,
Duration: 100 * time.Millisecond,
}, nil
}
func (i *mockInstance) ExecuteStream(ctx context.Context, code string, opts *executor.ExecutionOptions, handler executor.StreamHandler) error {
_ = handler(&executor.StreamEvent{Type: executor.StreamStdout, Data: "Hello"})
_ = handler(&executor.StreamEvent{Type: executor.StreamComplete, ExitCode: 0})
return nil
}
func (i *mockInstance) RunCommand(ctx context.Context, cmd string, args []string) (*executor.CommandResult, error) {
return &executor.CommandResult{ExitCode: 0, Stdout: "ok"}, nil
}
func (i *mockInstance) FileSystem() fs.FileSystem { return nil }
func (i *mockInstance) Network() provider.Network { return nil }
func (i *mockInstance) Stop(ctx context.Context) error {
if i.stopErr != nil {
return i.stopErr
}
i.stopped = true
i.status = provider.StatusStopped
return nil
}
func setupMockProvider(t *testing.T) func() {
t.Helper()
mp := &mockProvider{name: "mock"}
factory.Register("mock", func(config any) (provider.Provider, error) {
return mp, nil
})
return func() {
factory.Unregister("mock")
}
}
func TestCreate(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx, WithProvider("mock"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
defer func() { _ = sb.Stop(ctx) }()
if sb.ID() == "" {
t.Error("ID() should not be empty")
}
if sb.Provider() != "mock" {
t.Errorf("Provider() = %q, want %q", sb.Provider(), "mock")
}
}
func TestCreateWithOptions(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx,
WithProvider("mock"),
WithTimeout(5*time.Minute),
WithRuntime("Python"),
)
if err != nil {
t.Fatalf("Create() error = %v", err)
}
defer func() { _ = sb.Stop(ctx) }()
if sb.ID() == "" {
t.Error("ID() should not be empty")
}
}
func TestCreateError(t *testing.T) {
mp := &mockProvider{name: "failing", createErr: errors.New("connection failed")}
factory.Register("failing", func(config any) (provider.Provider, error) {
return mp, nil
})
defer factory.Unregister("failing")
ctx := context.Background()
_, err := Create(ctx, WithProvider("failing"))
if err == nil {
t.Fatal("Create() should fail")
}
}
func TestCreateUnregisteredProvider(t *testing.T) {
ctx := context.Background()
_, err := Create(ctx, WithProvider("nonexistent"))
if err == nil {
t.Fatal("Create() should fail for unregistered provider")
}
}
func TestMustCreate(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
defer func() {
if r := recover(); r != nil {
t.Errorf("MustCreate() panicked unexpectedly: %v", r)
}
}()
sb := MustCreate(ctx, WithProvider("mock"))
defer func() { _ = sb.Stop(ctx) }()
if sb == nil {
t.Error("MustCreate() returned nil")
}
}
func TestMustCreatePanic(t *testing.T) {
ctx := context.Background()
defer func() {
if r := recover(); r == nil {
t.Error("MustCreate() should panic for unregistered provider")
}
}()
MustCreate(ctx, WithProvider("definitely-not-registered"))
}
func TestSandboxExecute(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx, WithProvider("mock"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
defer func() { _ = sb.Stop(ctx) }()
result, err := sb.Execute(ctx, `print("Hello")`, WithLanguage("Python"))
if err != nil {
t.Fatalf("Execute() error = %v", err)
}
if result.ExitCode != 0 {
t.Errorf("ExitCode = %d, want 0", result.ExitCode)
}
if result.Stdout == "" {
t.Error("Stdout should not be empty")
}
if result.Language != "Python" {
t.Errorf("Language = %q, want %q", result.Language, "Python")
}
}
func TestSandboxExecuteAutoDetect(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx, WithProvider("mock"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
defer func() { _ = sb.Stop(ctx) }()
// Python code should auto-detect
code := `import json
def main():
print(json.dumps({"hello": "world"}))
main()`
result, err := sb.Execute(ctx, code)
if err != nil {
t.Fatalf("Execute() error = %v", err)
}
if result.Language == "" {
t.Error("Language should be auto-detected")
}
}
func TestSandboxExecuteAfterStop(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx, WithProvider("mock"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
_ = sb.Stop(ctx)
_, err = sb.Execute(ctx, `print("Hello")`, WithLanguage("Python"))
if err == nil {
t.Error("Execute() should fail after Stop()")
}
if !errors.Is(err, ErrSandboxStopped) {
t.Errorf("error should be ErrSandboxStopped, got %v", err)
}
}
func TestSandboxExecuteAsync(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx, WithProvider("mock"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
defer func() { _ = sb.Stop(ctx) }()
results, err := sb.ExecuteAsync(ctx, `print("Hello")`, WithLanguage("Python"))
if err != nil {
t.Fatalf("ExecuteAsync() error = %v", err)
}
result := <-results
if result == nil {
t.Fatal("result should not be nil")
}
if result.ExitCode != 0 {
t.Errorf("ExitCode = %d, want 0", result.ExitCode)
}
}
func TestSandboxExecuteStream(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx, WithProvider("mock"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
defer func() { _ = sb.Stop(ctx) }()
var events []*executor.StreamEvent
err = sb.ExecuteStream(ctx, `print("Hello")`, func(e *executor.StreamEvent) error {
events = append(events, e)
return nil
}, WithLanguage("Python"))
if err != nil {
t.Fatalf("ExecuteStream() error = %v", err)
}
if len(events) == 0 {
t.Error("should receive stream events")
}
}
func TestSandboxRunCommand(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx, WithProvider("mock"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
defer func() { _ = sb.Stop(ctx) }()
result, err := sb.RunCommand(ctx, "ls", "-la")
if err != nil {
t.Fatalf("RunCommand() error = %v", err)
}
if result.ExitCode != 0 {
t.Errorf("ExitCode = %d, want 0", result.ExitCode)
}
}
func TestSandboxStatus(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx, WithProvider("mock"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
status, err := sb.Status(ctx)
if err != nil {
t.Fatalf("Status() error = %v", err)
}
if status != provider.StatusRunning {
t.Errorf("Status() = %v, want %v", status, provider.StatusRunning)
}
_ = sb.Stop(ctx)
status, err = sb.Status(ctx)
if err != nil {
t.Fatalf("Status() error = %v", err)
}
if status != provider.StatusStopped {
t.Errorf("Status() after stop = %v, want %v", status, provider.StatusStopped)
}
}
func TestSandboxStopIdempotent(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
sb, err := Create(ctx, WithProvider("mock"))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
// First stop
err = sb.Stop(ctx)
if err != nil {
t.Fatalf("Stop() error = %v", err)
}
// Second stop should be idempotent
err = sb.Stop(ctx)
if err != nil {
t.Fatalf("second Stop() error = %v", err)
}
}
func TestExecuteConvenience(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
// Use recognizable Python code for auto-detection
code := `import json
def main():
print(json.dumps({"hello": "world"}))
main()`
result, err := Execute(ctx, code, WithProvider("mock"))
if err != nil {
t.Fatalf("Execute() error = %v", err)
}
if result.ExitCode != 0 {
t.Errorf("ExitCode = %d, want 0", result.ExitCode)
}
}
func TestExecuteStreamConvenience(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
ctx := context.Background()
// Use recognizable Python code for auto-detection
code := `import json
def main():
print(json.dumps({"hello": "world"}))
main()`
var output string
err := ExecuteStream(ctx, code, func(e *executor.StreamEvent) error {
if e.Type == executor.StreamStdout {
output += e.Data
}
return nil
}, WithProvider("mock"))
if err != nil {
t.Fatalf("ExecuteStream() error = %v", err)
}
if output == "" {
t.Error("should receive output")
}
}
func TestListProviders(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
providers := ListProviders()
found := false
for _, p := range providers {
if p == "mock" {
found = true
break
}
}
if !found {
t.Error("ListProviders() should include mock provider")
}
}
func TestProviderCapabilities(t *testing.T) {
cleanup := setupMockProvider(t)
defer cleanup()
caps, err := ProviderCapabilities("mock")
if err != nil {
t.Fatalf("ProviderCapabilities() error = %v", err)
}
if !caps.SupportsStreaming {
t.Error("SupportsStreaming should be true")
}
}
func TestDetectLanguage(t *testing.T) {
tests := []struct {
code string
filename string
want string
}{
{`print("Hello")`, "main.py", "Python"},
{`console.log("Hello")`, "app.js", "JavaScript"},
{`package main`, "main.go", "Go"},
}
for _, tt := range tests {
t.Run(tt.want, func(t *testing.T) {
result := DetectLanguage(tt.code, tt.filename)
if result.Language != tt.want {
t.Errorf("DetectLanguage() = %q, want %q", result.Language, tt.want)
}
})
}
}
func TestSupportedLanguages(t *testing.T) {
langs := SupportedLanguages()
if len(langs) == 0 {
t.Error("SupportedLanguages() should not be empty")
}
foundPython := false
for _, lang := range langs {
if lang == "Python" {
foundPython = true
break
}
}
if !foundPython {
t.Error("SupportedLanguages() should include Python")
}
}
func TestGetRuntimeInfo(t *testing.T) {
info, ok := GetRuntimeInfo("Python")
if !ok {
t.Fatal("GetRuntimeInfo(Python) should succeed")
}
if info.Runtime == "" {
t.Error("Runtime should not be empty")
}
if info.DockerImage == "" {
t.Error("DockerImage should not be empty")
}
}