@@ -16,12 +16,14 @@ import XCTest
1616import SwiftFoundation
1717import SwiftXCTest
1818#endif
19+ import Dispatch
1920
2021class TestNSOperationQueue : XCTestCase {
2122 static var allTests : [ ( String , ( TestNSOperationQueue ) -> ( ) throws -> Void ) ] {
2223 return [
2324 ( " test_OperationPriorities " , test_OperationPriorities) ,
24- ( " test_OperationCount " , test_OperationCount)
25+ ( " test_OperationCount " , test_OperationCount) ,
26+ ( " test_AsyncOperation " , test_AsyncOperation)
2527 ]
2628 }
2729
@@ -65,4 +67,75 @@ class TestNSOperationQueue : XCTestCase {
6567 XCTAssertEqual ( msgOperations [ 2 ] , " Operation2 executed " )
6668 XCTAssertEqual ( msgOperations [ 3 ] , " Operation4 executed " )
6769 }
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+
68141}
0 commit comments