-
-
Notifications
You must be signed in to change notification settings - Fork 833
Expand file tree
/
Copy pathMockVMVirtualizationService.swift
More file actions
101 lines (87 loc) · 2.85 KB
/
MockVMVirtualizationService.swift
File metadata and controls
101 lines (87 loc) · 2.85 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
import Foundation
import Virtualization
@testable import lume
@MainActor
final class MockVMVirtualizationService: VMVirtualizationService {
private(set) var currentState: VZVirtualMachine.State = .stopped
private(set) var startCallCount = 0
private(set) var stopCallCount = 0
private(set) var pauseCallCount = 0
private(set) var resumeCallCount = 0
var state: VZVirtualMachine.State {
currentState
}
private var _shouldFailNextOperation = false
private var _operationError: Error = VMError.internalError("Mock operation failed")
nonisolated func configure(shouldFail: Bool, error: Error = VMError.internalError("Mock operation failed")) async {
await setConfiguration(shouldFail: shouldFail, error: error)
}
@MainActor
private func setConfiguration(shouldFail: Bool, error: Error) {
_shouldFailNextOperation = shouldFail
_operationError = error
}
func start() async throws {
startCallCount += 1
if _shouldFailNextOperation {
throw _operationError
}
currentState = .running
}
func stop() async throws {
stopCallCount += 1
if _shouldFailNextOperation {
throw _operationError
}
currentState = .stopped
}
func pause() async throws {
pauseCallCount += 1
if _shouldFailNextOperation {
throw _operationError
}
currentState = .paused
}
func resume() async throws {
resumeCallCount += 1
if _shouldFailNextOperation {
throw _operationError
}
currentState = .running
}
func getVirtualMachine() -> Any {
return "mock_vm"
}
private var guestStopContinuation: CheckedContinuation<Error?, Never>?
private var pendingGuestStopResult: Error??
func waitForGuestStop() async -> Error? {
if let result = pendingGuestStopResult {
pendingGuestStopResult = nil
currentState = .stopped
return result
}
return await withCheckedContinuation { continuation in
guestStopContinuation = continuation
}
}
/// Simulate a normal guest shutdown.
func simulateGuestStop() {
currentState = .stopped
if let continuation = guestStopContinuation {
guestStopContinuation = nil
continuation.resume(returning: nil)
} else {
pendingGuestStopResult = .some(nil)
}
}
/// Simulate a guest crash with the given error.
func simulateGuestError(_ error: Error) {
currentState = .stopped
if let continuation = guestStopContinuation {
guestStopContinuation = nil
continuation.resume(returning: error)
} else {
pendingGuestStopResult = .some(error)
}
}
}