@@ -16,12 +16,14 @@ import XCTest
16
16
import SwiftFoundation
17
17
import SwiftXCTest
18
18
#endif
19
+ import Dispatch
19
20
20
21
class TestNSOperationQueue : XCTestCase {
21
22
static var allTests : [ ( String , ( TestNSOperationQueue ) -> ( ) throws -> Void ) ] {
22
23
return [
23
24
( " test_OperationPriorities " , test_OperationPriorities) ,
24
- ( " test_OperationCount " , test_OperationCount)
25
+ ( " test_OperationCount " , test_OperationCount) ,
26
+ ( " test_AsyncOperation " , test_AsyncOperation)
25
27
]
26
28
}
27
29
@@ -65,4 +67,75 @@ class TestNSOperationQueue : XCTestCase {
65
67
XCTAssertEqual ( msgOperations [ 2 ] , " Operation2 executed " )
66
68
XCTAssertEqual ( msgOperations [ 3 ] , " Operation4 executed " )
67
69
}
70
+
71
+ func test_AsyncOperation( ) {
72
+ let operation = AsyncOperation ( )
73
+ XCTAssertFalse ( operation. isExecuting)
74
+ XCTAssertFalse ( operation. isFinished)
75
+
76
+ operation. start ( )
77
+
78
+ while !operation. isFinished {
79
+ // wait until the operation finishes
80
+ XCTAssertTrue ( operation. isExecuting)
81
+ XCTAssertFalse ( operation. isFinished)
82
+ }
83
+
84
+ XCTAssertFalse ( operation. isExecuting)
85
+ XCTAssertTrue ( operation. isFinished)
86
+ }
87
+ }
88
+
89
+ class AsyncOperation : Operation {
90
+
91
+ private let queue = DispatchQueue ( label: " async.operation.queue " )
92
+
93
+ private var _executing = false
94
+ private var _finished = false
95
+
96
+ override internal( set) var isExecuting : Bool {
97
+ get {
98
+ return _executing
99
+ }
100
+ set {
101
+ if _executing != newValue {
102
+ willChangeValue ( forKey: " isExecuting " )
103
+ _executing = newValue
104
+ didChangeValue ( forKey: " isExecuting " )
105
+ }
106
+ }
107
+ }
108
+
109
+ override internal( set) var isFinished : Bool {
110
+ get {
111
+ return _finished
112
+ }
113
+ set {
114
+ if _finished != newValue {
115
+ willChangeValue ( forKey: " isFinished " )
116
+ _finished = newValue
117
+ didChangeValue ( forKey: " isFinished " )
118
+ }
119
+ }
120
+ }
121
+
122
+ override var isAsynchronous : Bool {
123
+ return true
124
+ }
125
+
126
+ override func start( ) {
127
+ if isCancelled {
128
+ isFinished = true
129
+ return
130
+ }
131
+
132
+ isExecuting = true
133
+
134
+ queue. async {
135
+ sleep ( 1 )
136
+ self . isExecuting = false
137
+ self . isFinished = true
138
+ }
139
+ }
140
+
68
141
}
0 commit comments