-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinuxkit_test.go
More file actions
786 lines (613 loc) · 20.9 KB
/
linuxkit_test.go
File metadata and controls
786 lines (613 loc) · 20.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
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
package container
import (
"context"
"os"
"os/exec"
"path/filepath"
"testing"
"time"
"dappco.re/go/core/io"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// MockHypervisor is a mock implementation for testing.
type MockHypervisor struct {
name string
available bool
buildErr error
lastImage string
lastOpts *HypervisorOptions
commandToRun string
}
func NewMockHypervisor() *MockHypervisor {
return &MockHypervisor{
name: "mock",
available: true,
commandToRun: "echo",
}
}
func (m *MockHypervisor) Name() string {
return m.name
}
func (m *MockHypervisor) Available() bool {
return m.available
}
func (m *MockHypervisor) BuildCommand(ctx context.Context, image string, opts *HypervisorOptions) (*exec.Cmd, error) {
m.lastImage = image
m.lastOpts = opts
if m.buildErr != nil {
return nil, m.buildErr
}
// Return a simple command that exits quickly
return exec.CommandContext(ctx, m.commandToRun, "test"), nil
}
// newTestManager creates a LinuxKitManager with mock hypervisor for testing.
// Uses manual temp directory management to avoid race conditions with t.TempDir cleanup.
func newTestManager(t *testing.T) (*LinuxKitManager, *MockHypervisor, string) {
tmpDir, err := os.MkdirTemp("", "linuxkit-test-*")
require.NoError(t, err)
// Manual cleanup that handles race conditions with state file writes
t.Cleanup(func() {
// Give any pending file operations time to complete
time.Sleep(10 * time.Millisecond)
_ = os.RemoveAll(tmpDir)
})
statePath := filepath.Join(tmpDir, "containers.json")
state, err := LoadState(statePath)
require.NoError(t, err)
mock := NewMockHypervisor()
manager := NewLinuxKitManagerWithHypervisor(io.Local, state, mock)
return manager, mock, tmpDir
}
func TestNewLinuxKitManagerWithHypervisor_Good(t *testing.T) {
tmpDir := t.TempDir()
statePath := filepath.Join(tmpDir, "containers.json")
state, _ := LoadState(statePath)
mock := NewMockHypervisor()
manager := NewLinuxKitManagerWithHypervisor(io.Local, state, mock)
assert.NotNil(t, manager)
assert.Equal(t, state, manager.State())
assert.Equal(t, mock, manager.Hypervisor())
}
func TestLinuxKitManager_Run_Good_Detached(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
// Create a test image file
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that runs briefly then exits
mock.commandToRun = "sleep"
ctx := context.Background()
opts := RunOptions{
Name: "test-vm",
Detach: true,
Memory: 512,
CPUs: 2,
}
container, err := manager.Run(ctx, imagePath, opts)
require.NoError(t, err)
assert.NotEmpty(t, container.ID)
assert.Equal(t, "test-vm", container.Name)
assert.Equal(t, imagePath, container.Image)
assert.Equal(t, StatusRunning, container.Status)
assert.Greater(t, container.PID, 0)
assert.Equal(t, 512, container.Memory)
assert.Equal(t, 2, container.CPUs)
// Verify hypervisor was called with correct options
assert.Equal(t, imagePath, mock.lastImage)
assert.Equal(t, 512, mock.lastOpts.Memory)
assert.Equal(t, 2, mock.lastOpts.CPUs)
// Clean up - stop the container
time.Sleep(100 * time.Millisecond)
}
func TestLinuxKitManager_Run_Good_DefaultValues(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := filepath.Join(tmpDir, "test.qcow2")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
ctx := context.Background()
opts := RunOptions{Detach: true}
container, err := manager.Run(ctx, imagePath, opts)
require.NoError(t, err)
// Check defaults were applied
assert.Equal(t, 1024, mock.lastOpts.Memory)
assert.Equal(t, 1, mock.lastOpts.CPUs)
assert.Equal(t, 2222, mock.lastOpts.SSHPort)
// Name should default to first 8 chars of ID
assert.Equal(t, container.ID[:8], container.Name)
// Wait for the mock process to complete to avoid temp dir cleanup issues
time.Sleep(50 * time.Millisecond)
}
func TestLinuxKitManager_Run_Bad_ImageNotFound(t *testing.T) {
manager, _, _ := newTestManager(t)
ctx := context.Background()
opts := RunOptions{Detach: true}
_, err := manager.Run(ctx, "/nonexistent/image.iso", opts)
assert.Error(t, err)
assert.Contains(t, err.Error(), "image not found")
}
func TestLinuxKitManager_Run_Bad_UnsupportedFormat(t *testing.T) {
manager, _, tmpDir := newTestManager(t)
imagePath := filepath.Join(tmpDir, "test.txt")
err := os.WriteFile(imagePath, []byte("not an image"), 0644)
require.NoError(t, err)
ctx := context.Background()
opts := RunOptions{Detach: true}
_, err = manager.Run(ctx, imagePath, opts)
assert.Error(t, err)
assert.Contains(t, err.Error(), "unsupported image format")
}
func TestLinuxKitManager_Stop_Good(t *testing.T) {
manager, _, _ := newTestManager(t)
// Add a fake running container with a non-existent PID
// The Stop function should handle this gracefully
container := &Container{
ID: "abc12345",
Status: StatusRunning,
PID: 999999, // Non-existent PID
StartedAt: time.Now(),
}
_ = manager.State().Add(container)
ctx := context.Background()
err := manager.Stop(ctx, "abc12345")
// Stop should succeed (process doesn't exist, so container is marked stopped)
assert.NoError(t, err)
// Verify the container status was updated
c, ok := manager.State().Get("abc12345")
assert.True(t, ok)
assert.Equal(t, StatusStopped, c.Status)
}
func TestLinuxKitManager_Stop_Bad_NotFound(t *testing.T) {
manager, _, _ := newTestManager(t)
ctx := context.Background()
err := manager.Stop(ctx, "nonexistent")
assert.Error(t, err)
assert.Contains(t, err.Error(), "container not found")
}
func TestLinuxKitManager_Stop_Bad_NotRunning(t *testing.T) {
_, _, tmpDir := newTestManager(t)
statePath := filepath.Join(tmpDir, "containers.json")
state, err := LoadState(statePath)
require.NoError(t, err)
manager := NewLinuxKitManagerWithHypervisor(io.Local, state, NewMockHypervisor())
container := &Container{
ID: "abc12345",
Status: StatusStopped,
}
_ = state.Add(container)
ctx := context.Background()
err = manager.Stop(ctx, "abc12345")
assert.Error(t, err)
assert.Contains(t, err.Error(), "not running")
}
func TestLinuxKitManager_List_Good(t *testing.T) {
_, _, tmpDir := newTestManager(t)
statePath := filepath.Join(tmpDir, "containers.json")
state, err := LoadState(statePath)
require.NoError(t, err)
manager := NewLinuxKitManagerWithHypervisor(io.Local, state, NewMockHypervisor())
_ = state.Add(&Container{ID: "aaa11111", Status: StatusStopped})
_ = state.Add(&Container{ID: "bbb22222", Status: StatusStopped})
ctx := context.Background()
containers, err := manager.List(ctx)
require.NoError(t, err)
assert.Len(t, containers, 2)
}
func TestLinuxKitManager_List_Good_VerifiesRunningStatus(t *testing.T) {
_, _, tmpDir := newTestManager(t)
statePath := filepath.Join(tmpDir, "containers.json")
state, err := LoadState(statePath)
require.NoError(t, err)
manager := NewLinuxKitManagerWithHypervisor(io.Local, state, NewMockHypervisor())
// Add a "running" container with a fake PID that doesn't exist
_ = state.Add(&Container{
ID: "abc12345",
Status: StatusRunning,
PID: 999999, // PID that almost certainly doesn't exist
})
ctx := context.Background()
containers, err := manager.List(ctx)
require.NoError(t, err)
assert.Len(t, containers, 1)
// Status should have been updated to stopped since PID doesn't exist
assert.Equal(t, StatusStopped, containers[0].Status)
}
func TestLinuxKitManager_Logs_Good(t *testing.T) {
manager, _, tmpDir := newTestManager(t)
// Create a log file manually
logsDir := filepath.Join(tmpDir, "logs")
require.NoError(t, os.MkdirAll(logsDir, 0755))
container := &Container{ID: "abc12345"}
_ = manager.State().Add(container)
// Override the default logs dir for testing by creating the log file
// at the expected location
logContent := "test log content\nline 2\n"
logPath, err := LogPath("abc12345")
require.NoError(t, err)
require.NoError(t, os.MkdirAll(filepath.Dir(logPath), 0755))
require.NoError(t, os.WriteFile(logPath, []byte(logContent), 0644))
ctx := context.Background()
reader, err := manager.Logs(ctx, "abc12345", false)
require.NoError(t, err)
defer func() { _ = reader.Close() }()
buf := make([]byte, 1024)
n, _ := reader.Read(buf)
assert.Equal(t, logContent, string(buf[:n]))
}
func TestLinuxKitManager_Logs_Bad_NotFound(t *testing.T) {
manager, _, _ := newTestManager(t)
ctx := context.Background()
_, err := manager.Logs(ctx, "nonexistent", false)
assert.Error(t, err)
assert.Contains(t, err.Error(), "container not found")
}
func TestLinuxKitManager_Logs_Bad_NoLogFile(t *testing.T) {
manager, _, _ := newTestManager(t)
// Use a unique ID that won't have a log file
uniqueID, err := GenerateID()
require.NoError(t, err)
container := &Container{ID: uniqueID}
_ = manager.State().Add(container)
ctx := context.Background()
reader, err := manager.Logs(ctx, uniqueID, false)
// If logs existed somehow, clean up the reader
if reader != nil {
_ = reader.Close()
}
assert.Error(t, err)
if err != nil {
assert.Contains(t, err.Error(), "no logs available")
}
}
func TestLinuxKitManager_Exec_Bad_NotFound(t *testing.T) {
manager, _, _ := newTestManager(t)
ctx := context.Background()
err := manager.Exec(ctx, "nonexistent", []string{"ls"})
assert.Error(t, err)
assert.Contains(t, err.Error(), "container not found")
}
func TestLinuxKitManager_Exec_Bad_NotRunning(t *testing.T) {
manager, _, _ := newTestManager(t)
container := &Container{ID: "abc12345", Status: StatusStopped}
_ = manager.State().Add(container)
ctx := context.Background()
err := manager.Exec(ctx, "abc12345", []string{"ls"})
assert.Error(t, err)
assert.Contains(t, err.Error(), "not running")
}
func TestDetectImageFormat_Good(t *testing.T) {
tests := []struct {
path string
format ImageFormat
}{
{"/path/to/image.iso", FormatISO},
{"/path/to/image.ISO", FormatISO},
{"/path/to/image.qcow2", FormatQCOW2},
{"/path/to/image.QCOW2", FormatQCOW2},
{"/path/to/image.vmdk", FormatVMDK},
{"/path/to/image.raw", FormatRaw},
{"/path/to/image.img", FormatRaw},
{"image.iso", FormatISO},
}
for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
assert.Equal(t, tt.format, DetectImageFormat(tt.path))
})
}
}
func TestDetectImageFormat_Bad_Unknown(t *testing.T) {
tests := []string{
"/path/to/image.txt",
"/path/to/image",
"noextension",
"/path/to/image.docx",
}
for _, path := range tests {
t.Run(path, func(t *testing.T) {
assert.Equal(t, FormatUnknown, DetectImageFormat(path))
})
}
}
func TestQemuHypervisor_Name_Good(t *testing.T) {
q := NewQemuHypervisor()
assert.Equal(t, "qemu", q.Name())
}
func TestQemuHypervisor_BuildCommand_Good(t *testing.T) {
q := NewQemuHypervisor()
ctx := context.Background()
opts := &HypervisorOptions{
Memory: 2048,
CPUs: 4,
SSHPort: 2222,
Ports: map[int]int{8080: 80},
Detach: true,
}
cmd, err := q.BuildCommand(ctx, "/path/to/image.iso", opts)
require.NoError(t, err)
assert.NotNil(t, cmd)
// Check command path
assert.Contains(t, cmd.Path, "qemu")
// Check that args contain expected values
args := cmd.Args
assert.Contains(t, args, "-m")
assert.Contains(t, args, "2048")
assert.Contains(t, args, "-smp")
assert.Contains(t, args, "4")
assert.Contains(t, args, "-nographic")
}
func TestLinuxKitManager_Logs_Good_Follow(t *testing.T) {
manager, _, _ := newTestManager(t)
// Create a unique container ID
uniqueID, err := GenerateID()
require.NoError(t, err)
container := &Container{ID: uniqueID}
_ = manager.State().Add(container)
// Create a log file at the expected location
logPath, err := LogPath(uniqueID)
require.NoError(t, err)
require.NoError(t, os.MkdirAll(filepath.Dir(logPath), 0755))
// Write initial content
err = os.WriteFile(logPath, []byte("initial log content\n"), 0644)
require.NoError(t, err)
// Create a cancellable context
ctx, cancel := context.WithCancel(context.Background())
// Get the follow reader
reader, err := manager.Logs(ctx, uniqueID, true)
require.NoError(t, err)
// Cancel the context to stop the follow
cancel()
// Read should return EOF after context cancellation
buf := make([]byte, 1024)
_, readErr := reader.Read(buf)
// After context cancel, Read should return EOF
assert.Equal(t, "EOF", readErr.Error())
// Close the reader
assert.NoError(t, reader.Close())
}
func TestFollowReader_Read_Good_WithData(t *testing.T) {
tmpDir := t.TempDir()
logPath := filepath.Join(tmpDir, "test.log")
// Create log file with content
content := "test log line 1\ntest log line 2\n"
err := os.WriteFile(logPath, []byte(content), 0644)
require.NoError(t, err)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
reader, err := newFollowReader(ctx, io.Local, logPath)
require.NoError(t, err)
defer func() { _ = reader.Close() }()
// The followReader seeks to end, so we need to append more content
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY, 0644)
require.NoError(t, err)
_, err = f.WriteString("new line\n")
require.NoError(t, err)
require.NoError(t, f.Close())
// Give the reader time to poll
time.Sleep(150 * time.Millisecond)
buf := make([]byte, 1024)
n, err := reader.Read(buf)
if err == nil {
assert.Greater(t, n, 0)
}
}
func TestFollowReader_Read_Good_ContextCancel(t *testing.T) {
tmpDir := t.TempDir()
logPath := filepath.Join(tmpDir, "test.log")
// Create log file
err := os.WriteFile(logPath, []byte("initial content\n"), 0644)
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
reader, err := newFollowReader(ctx, io.Local, logPath)
require.NoError(t, err)
// Cancel the context
cancel()
// Read should return EOF
buf := make([]byte, 1024)
_, readErr := reader.Read(buf)
assert.Equal(t, "EOF", readErr.Error())
_ = reader.Close()
}
func TestFollowReader_Close_Good(t *testing.T) {
tmpDir := t.TempDir()
logPath := filepath.Join(tmpDir, "test.log")
err := os.WriteFile(logPath, []byte("content\n"), 0644)
require.NoError(t, err)
ctx := context.Background()
reader, err := newFollowReader(ctx, io.Local, logPath)
require.NoError(t, err)
err = reader.Close()
assert.NoError(t, err)
// Reading after close should fail or return EOF
buf := make([]byte, 1024)
_, readErr := reader.Read(buf)
assert.Error(t, readErr)
}
func TestNewFollowReader_Bad_FileNotFound(t *testing.T) {
ctx := context.Background()
_, err := newFollowReader(ctx, io.Local, "/nonexistent/path/to/file.log")
assert.Error(t, err)
}
func TestLinuxKitManager_Run_Bad_BuildCommandError(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
// Create a test image file
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Configure mock to return an error
mock.buildErr = assert.AnError
ctx := context.Background()
opts := RunOptions{Detach: true}
_, err = manager.Run(ctx, imagePath, opts)
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to build hypervisor command")
}
func TestLinuxKitManager_Run_Good_Foreground(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
// Create a test image file
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use echo which exits quickly
mock.commandToRun = "echo"
ctx := context.Background()
opts := RunOptions{
Name: "test-foreground",
Detach: false, // Run in foreground
Memory: 512,
CPUs: 1,
}
container, err := manager.Run(ctx, imagePath, opts)
require.NoError(t, err)
assert.NotEmpty(t, container.ID)
assert.Equal(t, "test-foreground", container.Name)
// Foreground process should have completed
assert.Equal(t, StatusStopped, container.Status)
}
func TestLinuxKitManager_Stop_Good_ContextCancelled(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
// Create a test image file
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that takes a long time
mock.commandToRun = "sleep"
// Start a container
ctx := context.Background()
opts := RunOptions{
Name: "test-cancel",
Detach: true,
}
container, err := manager.Run(ctx, imagePath, opts)
require.NoError(t, err)
// Ensure cleanup happens regardless of test outcome
t.Cleanup(func() {
_ = manager.Stop(context.Background(), container.ID)
})
// Create a context that's already cancelled
cancelCtx, cancel := context.WithCancel(context.Background())
cancel()
// Stop with cancelled context
err = manager.Stop(cancelCtx, container.ID)
// Should return context error
assert.Error(t, err)
assert.Equal(t, context.Canceled, err)
}
func TestIsProcessRunning_Good_ExistingProcess(t *testing.T) {
// Use our own PID which definitely exists
running := isProcessRunning(os.Getpid())
assert.True(t, running)
}
func TestIsProcessRunning_Bad_NonexistentProcess(t *testing.T) {
// Use a PID that almost certainly doesn't exist
running := isProcessRunning(999999)
assert.False(t, running)
}
func TestLinuxKitManager_Run_Good_WithPortsAndVolumes(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
ctx := context.Background()
opts := RunOptions{
Name: "test-ports",
Detach: true,
Memory: 512,
CPUs: 1,
SSHPort: 2223,
Ports: map[int]int{8080: 80, 443: 443},
Volumes: map[string]string{"/host/data": "/container/data"},
}
container, err := manager.Run(ctx, imagePath, opts)
require.NoError(t, err)
assert.NotEmpty(t, container.ID)
assert.Equal(t, map[int]int{8080: 80, 443: 443}, container.Ports)
assert.Equal(t, 2223, mock.lastOpts.SSHPort)
assert.Equal(t, map[string]string{"/host/data": "/container/data"}, mock.lastOpts.Volumes)
time.Sleep(50 * time.Millisecond)
}
func TestFollowReader_Read_Bad_ReaderError(t *testing.T) {
tmpDir := t.TempDir()
logPath := filepath.Join(tmpDir, "test.log")
// Create log file
err := os.WriteFile(logPath, []byte("content\n"), 0644)
require.NoError(t, err)
ctx := context.Background()
reader, err := newFollowReader(ctx, io.Local, logPath)
require.NoError(t, err)
// Close the underlying file to cause read errors
_ = reader.file.Close()
// Read should return an error
buf := make([]byte, 1024)
_, readErr := reader.Read(buf)
assert.Error(t, readErr)
}
func TestLinuxKitManager_Run_Bad_StartError(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that doesn't exist to cause Start() to fail
mock.commandToRun = "/nonexistent/command/that/does/not/exist"
ctx := context.Background()
opts := RunOptions{
Name: "test-start-error",
Detach: true,
}
_, err = manager.Run(ctx, imagePath, opts)
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to start VM")
}
func TestLinuxKitManager_Run_Bad_ForegroundStartError(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that doesn't exist to cause Start() to fail
mock.commandToRun = "/nonexistent/command/that/does/not/exist"
ctx := context.Background()
opts := RunOptions{
Name: "test-foreground-error",
Detach: false,
}
_, err = manager.Run(ctx, imagePath, opts)
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to start VM")
}
func TestLinuxKitManager_Run_Good_ForegroundWithError(t *testing.T) {
manager, mock, tmpDir := newTestManager(t)
imagePath := filepath.Join(tmpDir, "test.iso")
err := os.WriteFile(imagePath, []byte("fake image"), 0644)
require.NoError(t, err)
// Use a command that exits with error
mock.commandToRun = "false" // false command exits with code 1
ctx := context.Background()
opts := RunOptions{
Name: "test-foreground-exit-error",
Detach: false,
}
container, err := manager.Run(ctx, imagePath, opts)
require.NoError(t, err) // Run itself should succeed
// Container should be in error state since process exited with error
assert.Equal(t, StatusError, container.Status)
}
func TestLinuxKitManager_Stop_Good_ProcessExitedWhileRunning(t *testing.T) {
manager, _, _ := newTestManager(t)
// Add a "running" container with a process that has already exited
// This simulates the race condition where process exits between status check
// and signal send
container := &Container{
ID: "test1234",
Status: StatusRunning,
PID: 999999, // Non-existent PID
StartedAt: time.Now(),
}
_ = manager.State().Add(container)
ctx := context.Background()
err := manager.Stop(ctx, "test1234")
// Stop should succeed gracefully
assert.NoError(t, err)
// Container should be stopped
c, ok := manager.State().Get("test1234")
assert.True(t, ok)
assert.Equal(t, StatusStopped, c.Status)
}